Merge
authorduke
Wed, 05 Jul 2017 19:00:49 +0200
changeset 18315 94696b2e0698
parent 18314 f7f6b997342b (current diff)
parent 18300 0711a535f874 (diff)
child 18349 1eb96c625ea1
Merge
hotspot/src/os_cpu/linux_sparc/vm/assembler_linux_sparc.cpp
hotspot/src/os_cpu/solaris_sparc/vm/assembler_solaris_sparc.cpp
jdk/make/sun/xawt/ToBin.java
jdk/makefiles/sun/awt/X11/ToBin.java
jdk/src/share/classes/sun/misc/FDBigInt.java
jdk/src/share/classes/sun/misc/Hashing.java
jdk/src/solaris/classes/sun/awt/X11/XIconInfo.java
jdk/src/solaris/classes/sun/awt/X11/security-icon-bw16.png
jdk/src/solaris/classes/sun/awt/X11/security-icon-bw24.png
jdk/src/solaris/classes/sun/awt/X11/security-icon-bw32.png
jdk/src/solaris/classes/sun/awt/X11/security-icon-bw48.png
jdk/src/solaris/classes/sun/awt/X11/security-icon-interim16.png
jdk/src/solaris/classes/sun/awt/X11/security-icon-interim24.png
jdk/src/solaris/classes/sun/awt/X11/security-icon-interim32.png
jdk/src/solaris/classes/sun/awt/X11/security-icon-interim48.png
jdk/src/solaris/classes/sun/awt/X11/security-icon-yellow16.png
jdk/src/solaris/classes/sun/awt/X11/security-icon-yellow24.png
jdk/src/solaris/classes/sun/awt/X11/security-icon-yellow32.png
jdk/src/solaris/classes/sun/awt/X11/security-icon-yellow48.png
jdk/test/java/lang/invoke/7196190/MHProxyTest.java
jdk/test/sun/misc/Hashing.java
--- a/.hgtags-top-repo	Mon Jun 24 14:26:58 2013 -0700
+++ b/.hgtags-top-repo	Wed Jul 05 19:00:49 2017 +0200
@@ -216,3 +216,4 @@
 3a36c926a7aafa9d4a892a45ef3678e87ad8359b jdk8-b92
 27c51c6e31c1ef36afa0e6efb031f9b13f26c12b jdk8-b93
 50d2bde060f2a9bbbe4da0c8986e20aca61f2e2e jdk8-b94
+785d07fe38901ecc1b7e0145e53e1c3da9361fee jdk8-b95
--- a/README-builds.html	Mon Jun 24 14:26:58 2013 -0700
+++ b/README-builds.html	Wed Jul 05 19:00:49 2017 +0200
@@ -355,12 +355,24 @@
                     </li>
                     <li>
                         Install a
-                        <a name="bootjdk">Bootstrap JDK</a>
-                        <br>
+                        <a name="bootjdk">Bootstrap JDK</a>.
                         All OpenJDK builds require access to a previously released
-                        JDK, this is often called a bootstrap JDK.
-                        Currently, for this JDK release we require
-                        JDK 7 Update 7 or newer.
+                        JDK called the <i>bootstrap JDK</i> or <i>boot JDK.</i>
+                        The general rule is that the bootstrap JDK
+                        must be an instance of the previous major
+                        release of the JDK. In addition, there may be
+                        a requirement to use a release at or beyond a
+                        particular update level.
+                        <br>&nbsp;<br>
+
+                        <b><i>Building JDK 8 requires use of a version
+                        of JDK 7 that is at Update 7 or newer. JDK 8
+                        developers should not use JDK 8 as the boot
+                        JDK, to ensure that JDK 8 dependencies are
+                        not introduced into the parts of the system
+                        that are built with JDK 7.</i></b>
+
+                        <br>&nbsp;<br>
                         The JDK 7 binaries can be downloaded from Oracle's 
                         <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html"
                            target="_blank">JDK 7 download site</a>.
--- a/common/makefiles/Main.gmk	Mon Jun 24 14:26:58 2013 -0700
+++ b/common/makefiles/Main.gmk	Wed Jul 05 19:00:49 2017 +0200
@@ -183,7 +183,7 @@
 test: images test-only
 test-only: start-make
 	@$(call TargetEnter)
-	@($(CD) $(SRC_ROOT)/test && $(BUILD_LOG_WRAPPER) $(MAKE) -j1 -k JT_HOME=$(JT_HOME) MAKEFLAGS= PRODUCT_HOME=$(JDK_IMAGE_DIR) JPRT_JAVA_HOME=$(JDK_IMAGE_DIR) ALT_OUTPUTDIR=$(OUTPUT_ROOT) $(TEST)) || true
+	@($(CD) $(SRC_ROOT)/test && $(BUILD_LOG_WRAPPER) $(MAKE) -j1 -k MAKEFLAGS= JT_HOME=$(JT_HOME) PRODUCT_HOME=$(JDK_IMAGE_DIR) JPRT_JAVA_HOME=$(JDK_IMAGE_DIR) ALT_OUTPUTDIR=$(OUTPUT_ROOT) CONCURRENCY=$(JOBS) $(TEST)) || true
 	@$(call TargetExit)
 
 # Stores the tips for each repository. This file is be used when constructing the jdk image and can be
@@ -192,7 +192,7 @@
 $(OUTPUT_ROOT)/source_tips: FRC
 	@$(MKDIR) -p $(@D)
 	@$(RM) $@
-	@$(if $(HG),$(call GetSourceTips),$(ECHO) "hg not installed" > $@)
+	@$(call GetSourceTips)
 
 
 # Remove everything, except the output from configure.
--- a/hotspot/.hgtags	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/.hgtags	Wed Jul 05 19:00:49 2017 +0200
@@ -351,3 +351,5 @@
 3c78a14da19d26d6937af5f98b97e2a21c653b04 hs25-b36
 1beed1f6f9edefe47ba8ed1355fbd3e7606b8288 jdk8-b94
 69689078dff8b21e6df30870464f5d736eebdf72 hs25-b37
+5d65c078cd0ac455aa5e58a09844c7acce54b487 jdk8-b95
+2cc5a9d1ba66dfdff578918b393c727bd9450210 hs25-b38
--- a/hotspot/make/hotspot_version	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/make/hotspot_version	Wed Jul 05 19:00:49 2017 +0200
@@ -35,7 +35,7 @@
 
 HS_MAJOR_VER=25
 HS_MINOR_VER=0
-HS_BUILD_NUMBER=37
+HS_BUILD_NUMBER=38
 
 JDK_MAJOR_VER=1
 JDK_MINOR_VER=8
--- a/hotspot/make/linux/makefiles/gcc.make	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/make/linux/makefiles/gcc.make	Wed Jul 05 19:00:49 2017 +0200
@@ -214,7 +214,7 @@
   WARNINGS_ARE_ERRORS += -Wno-return-type -Wno-empty-body
 endif
 
-WARNING_FLAGS = -Wpointer-arith -Wsign-compare -Wundef -Wunused-function
+WARNING_FLAGS = -Wpointer-arith -Wsign-compare -Wundef -Wunused-function -Wunused-value
 
 ifeq ($(USE_CLANG),)
   # Since GCC 4.3, -Wconversion has changed its meanings to warn these implicit
--- a/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -57,7 +57,6 @@
     fbp_op2   = 5,
     br_op2    = 2,
     bp_op2    = 1,
-    cb_op2    = 7, // V8
     sethi_op2 = 4
   };
 
@@ -145,7 +144,6 @@
     ldsh_op3     = 0x0a,
     ldx_op3      = 0x0b,
 
-    ldstub_op3   = 0x0d,
     stx_op3      = 0x0e,
     swap_op3     = 0x0f,
 
@@ -163,15 +161,6 @@
 
     prefetch_op3 = 0x2d,
 
-
-    ldc_op3      = 0x30,
-    ldcsr_op3    = 0x31,
-    lddc_op3     = 0x33,
-    stc_op3      = 0x34,
-    stcsr_op3    = 0x35,
-    stdcq_op3    = 0x36,
-    stdc_op3     = 0x37,
-
     casa_op3     = 0x3c,
     casxa_op3    = 0x3e,
 
@@ -574,17 +563,11 @@
   static void vis3_only() { assert( VM_Version::has_vis3(), "This instruction only works on SPARC with VIS3"); }
 
   // instruction only in v9
-  static void v9_only() { assert( VM_Version::v9_instructions_work(), "This instruction only works on SPARC V9"); }
-
-  // instruction only in v8
-  static void v8_only() { assert( VM_Version::v8_instructions_work(), "This instruction only works on SPARC V8"); }
+  static void v9_only() { } // do nothing
 
   // instruction deprecated in v9
   static void v9_dep()  { } // do nothing for now
 
-  // some float instructions only exist for single prec. on v8
-  static void v8_s_only(FloatRegisterImpl::Width w)  { if (w != FloatRegisterImpl::S)  v9_only(); }
-
   // v8 has no CC field
   static void v8_no_cc(CC cc)  { if (cc)  v9_only(); }
 
@@ -730,11 +713,6 @@
   inline void bp( Condition c, bool a, CC cc, Predict p, address d, relocInfo::relocType rt = relocInfo::none );
   inline void bp( Condition c, bool a, CC cc, Predict p, Label& L );
 
-  // pp 121 (V8)
-
-  inline void cb( Condition c, bool a, address d, relocInfo::relocType rt = relocInfo::none );
-  inline void cb( Condition c, bool a, Label& L );
-
   // pp 149
 
   inline void call( address d,  relocInfo::relocType rt = relocInfo::runtime_call_type );
@@ -775,8 +753,8 @@
 
   // pp 157
 
-  void fcmp(  FloatRegisterImpl::Width w, CC cc, FloatRegister s1, FloatRegister s2) { v8_no_cc(cc);  emit_int32( op(arith_op) | cmpcc(cc) | op3(fpop2_op3) | fs1(s1, w) | opf(0x50 + w) | fs2(s2, w)); }
-  void fcmpe( FloatRegisterImpl::Width w, CC cc, FloatRegister s1, FloatRegister s2) { v8_no_cc(cc);  emit_int32( op(arith_op) | cmpcc(cc) | op3(fpop2_op3) | fs1(s1, w) | opf(0x54 + w) | fs2(s2, w)); }
+  void fcmp(  FloatRegisterImpl::Width w, CC cc, FloatRegister s1, FloatRegister s2) { emit_int32( op(arith_op) | cmpcc(cc) | op3(fpop2_op3) | fs1(s1, w) | opf(0x50 + w) | fs2(s2, w)); }
+  void fcmpe( FloatRegisterImpl::Width w, CC cc, FloatRegister s1, FloatRegister s2) { emit_int32( op(arith_op) | cmpcc(cc) | op3(fpop2_op3) | fs1(s1, w) | opf(0x54 + w) | fs2(s2, w)); }
 
   // pp 159
 
@@ -794,21 +772,11 @@
 
   // pp 162
 
-  void fmov( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { v8_s_only(w);  emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x00 + w) | fs2(s, w)); }
-
-  void fneg( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { v8_s_only(w);  emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x04 + w) | fs2(s, w)); }
-
-  // page 144 sparc v8 architecture (double prec works on v8 if the source and destination registers are the same). fnegs is the only instruction available
-  // on v8 to do negation of single, double and quad precision floats.
+  void fmov( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x00 + w) | fs2(s, w)); }
 
-  void fneg( FloatRegisterImpl::Width w, FloatRegister sd ) { if (VM_Version::v9_instructions_work()) emit_int32( op(arith_op) | fd(sd, w) | op3(fpop1_op3) | opf(0x04 + w) | fs2(sd, w)); else emit_int32( op(arith_op) | fd(sd, w) | op3(fpop1_op3) |  opf(0x05) | fs2(sd, w)); }
-
-  void fabs( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { v8_s_only(w);  emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x08 + w) | fs2(s, w)); }
+  void fneg( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x04 + w) | fs2(s, w)); }
 
-  // page 144 sparc v8 architecture (double prec works on v8 if the source and destination registers are the same). fabss is the only instruction available
-  // on v8 to do abs operation on single/double/quad precision floats.
-
-  void fabs( FloatRegisterImpl::Width w, FloatRegister sd ) { if (VM_Version::v9_instructions_work()) emit_int32( op(arith_op) | fd(sd, w) | op3(fpop1_op3) | opf(0x08 + w) | fs2(sd, w)); else emit_int32( op(arith_op) | fd(sd, w) | op3(fpop1_op3) | opf(0x09) | fs2(sd, w)); }
+  void fabs( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x08 + w) | fs2(s, w)); }
 
   // pp 163
 
@@ -839,11 +807,6 @@
   void impdep1( int id1, int const19a ) { v9_only();  emit_int32( op(arith_op) | fcn(id1) | op3(impdep1_op3) | u_field(const19a, 18, 0)); }
   void impdep2( int id1, int const19a ) { v9_only();  emit_int32( op(arith_op) | fcn(id1) | op3(impdep2_op3) | u_field(const19a, 18, 0)); }
 
-  // pp 149 (v8)
-
-  void cpop1( int opc, int cr1, int cr2, int crd ) { v8_only();  emit_int32( op(arith_op) | fcn(crd) | op3(impdep1_op3) | u_field(cr1, 18, 14) | opf(opc) | u_field(cr2, 4, 0)); }
-  void cpop2( int opc, int cr1, int cr2, int crd ) { v8_only();  emit_int32( op(arith_op) | fcn(crd) | op3(impdep2_op3) | u_field(cr1, 18, 14) | opf(opc) | u_field(cr2, 4, 0)); }
-
   // pp 170
 
   void jmpl( Register s1, Register s2, Register d );
@@ -860,16 +823,6 @@
   inline void ldxfsr( Register s1, Register s2 );
   inline void ldxfsr( Register s1, int simm13a);
 
-  // pp 94 (v8)
-
-  inline void ldc(   Register s1, Register s2, int crd );
-  inline void ldc(   Register s1, int simm13a, int crd);
-  inline void lddc(  Register s1, Register s2, int crd );
-  inline void lddc(  Register s1, int simm13a, int crd);
-  inline void ldcsr( Register s1, Register s2, int crd );
-  inline void ldcsr( Register s1, int simm13a, int crd);
-
-
   // 173
 
   void ldfa(  FloatRegisterImpl::Width w, Register s1, Register s2, int ia, FloatRegister d ) { v9_only();  emit_int32( op(ldst_op) | fd(d, w) | alt_op3(ldf_op3 | alt_bit_op3, w) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
@@ -910,18 +863,6 @@
   void lduwa(  Register s1, int simm13a,         Register d ) {             emit_int32( op(ldst_op) | rd(d) | op3(lduw_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
   void ldxa(   Register s1, Register s2, int ia, Register d ) { v9_only();  emit_int32( op(ldst_op) | rd(d) | op3(ldx_op3  | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
   void ldxa(   Register s1, int simm13a,         Register d ) { v9_only();  emit_int32( op(ldst_op) | rd(d) | op3(ldx_op3  | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void ldda(   Register s1, Register s2, int ia, Register d ) { v9_dep();   emit_int32( op(ldst_op) | rd(d) | op3(ldd_op3  | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void ldda(   Register s1, int simm13a,         Register d ) { v9_dep();   emit_int32( op(ldst_op) | rd(d) | op3(ldd_op3  | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-
-  // pp 179
-
-  inline void ldstub(  Register s1, Register s2, Register d );
-  inline void ldstub(  Register s1, int simm13a, Register d);
-
-  // pp 180
-
-  void ldstuba( Register s1, Register s2, int ia, Register d ) { emit_int32( op(ldst_op) | rd(d) | op3(ldstub_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void ldstuba( Register s1, int simm13a,         Register d ) { emit_int32( op(ldst_op) | rd(d) | op3(ldstub_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 181
 
@@ -992,11 +933,6 @@
   void smulcc( Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(smul_op3 | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
   void smulcc( Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(smul_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
-  // pp 199
-
-  void mulscc(   Register s1, Register s2, Register d ) { v9_dep();  emit_int32( op(arith_op) | rd(d) | op3(mulscc_op3) | rs1(s1) | rs2(s2) ); }
-  void mulscc(   Register s1, int simm13a, Register d ) { v9_dep();  emit_int32( op(arith_op) | rd(d) | op3(mulscc_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-
   // pp 201
 
   void nop() { emit_int32( op(branch_op) | op2(sethi_op2) ); }
@@ -1116,17 +1052,6 @@
   void stda(  Register d, Register s1, Register s2, int ia ) {             emit_int32( op(ldst_op) | rd(d) | op3(std_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
   void stda(  Register d, Register s1, int simm13a         ) {             emit_int32( op(ldst_op) | rd(d) | op3(std_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
-  // pp 97 (v8)
-
-  inline void stc(   int crd, Register s1, Register s2 );
-  inline void stc(   int crd, Register s1, int simm13a);
-  inline void stdc(  int crd, Register s1, Register s2 );
-  inline void stdc(  int crd, Register s1, int simm13a);
-  inline void stcsr( int crd, Register s1, Register s2 );
-  inline void stcsr( int crd, Register s1, int simm13a);
-  inline void stdcq( int crd, Register s1, Register s2 );
-  inline void stdcq( int crd, Register s1, int simm13a);
-
   // pp 230
 
   void sub(    Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(sub_op3              ) | rs1(s1) | rs2(s2) ); }
@@ -1153,20 +1078,16 @@
 
   void taddcc(    Register s1, Register s2, Register d ) {            emit_int32( op(arith_op) | rd(d) | op3(taddcc_op3  ) | rs1(s1) | rs2(s2) ); }
   void taddcc(    Register s1, int simm13a, Register d ) {            emit_int32( op(arith_op) | rd(d) | op3(taddcc_op3  ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void taddcctv(  Register s1, Register s2, Register d ) { v9_dep();  emit_int32( op(arith_op) | rd(d) | op3(taddcctv_op3) | rs1(s1) | rs2(s2) ); }
-  void taddcctv(  Register s1, int simm13a, Register d ) { v9_dep();  emit_int32( op(arith_op) | rd(d) | op3(taddcctv_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 235
 
   void tsubcc(    Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(tsubcc_op3  ) | rs1(s1) | rs2(s2) ); }
   void tsubcc(    Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(tsubcc_op3  ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void tsubcctv(  Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(tsubcctv_op3) | rs1(s1) | rs2(s2) ); }
-  void tsubcctv(  Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(tsubcctv_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 237
 
-  void trap( Condition c, CC cc, Register s1, Register s2 ) { v8_no_cc(cc);  emit_int32( op(arith_op) | cond(c) | op3(trap_op3) | rs1(s1) | trapcc(cc) | rs2(s2)); }
-  void trap( Condition c, CC cc, Register s1, int trapa   ) { v8_no_cc(cc);  emit_int32( op(arith_op) | cond(c) | op3(trap_op3) | rs1(s1) | trapcc(cc) | immed(true) | u_field(trapa, 6, 0)); }
+  void trap( Condition c, CC cc, Register s1, Register s2 ) { emit_int32( op(arith_op) | cond(c) | op3(trap_op3) | rs1(s1) | trapcc(cc) | rs2(s2)); }
+  void trap( Condition c, CC cc, Register s1, int trapa   ) { emit_int32( op(arith_op) | cond(c) | op3(trap_op3) | rs1(s1) | trapcc(cc) | immed(true) | u_field(trapa, 6, 0)); }
   // simple uncond. trap
   void trap( int trapa ) { trap( always, icc, G0, trapa ); }
 
--- a/hotspot/src/cpu/sparc/vm/assembler_sparc.inline.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/assembler_sparc.inline.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -63,9 +63,6 @@
 inline void Assembler::fbp( Condition c, bool a, CC cc, Predict p, address d, relocInfo::relocType rt ) { v9_only();  cti();  emit_data( op(branch_op) | annul(a) | cond(c) | op2(fbp_op2) | branchcc(cc) | predict(p) | wdisp(intptr_t(d), intptr_t(pc()), 19), rt);  has_delay_slot(); }
 inline void Assembler::fbp( Condition c, bool a, CC cc, Predict p, Label& L ) { fbp(c, a, cc, p, target(L)); }
 
-inline void Assembler::cb( Condition c, bool a, address d, relocInfo::relocType rt ) { v8_only();  cti();  emit_data( op(branch_op) | annul(a) | cond(c) | op2(cb_op2) | wdisp(intptr_t(d), intptr_t(pc()), 22), rt);  has_delay_slot(); }
-inline void Assembler::cb( Condition c, bool a, Label& L ) { cb(c, a, target(L)); }
-
 inline void Assembler::br( Condition c, bool a, address d, relocInfo::relocType rt ) { v9_dep();  cti();   emit_data( op(branch_op) | annul(a) | cond(c) | op2(br_op2) | wdisp(intptr_t(d), intptr_t(pc()), 22), rt);  has_delay_slot(); }
 inline void Assembler::br( Condition c, bool a, Label& L ) { br(c, a, target(L)); }
 
@@ -88,18 +85,9 @@
 inline void Assembler::ldf(FloatRegisterImpl::Width w, Register s1, Register s2, FloatRegister d) { emit_int32( op(ldst_op) | fd(d, w) | alt_op3(ldf_op3, w) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldf(FloatRegisterImpl::Width w, Register s1, int simm13a, FloatRegister d, RelocationHolder const& rspec) { emit_data( op(ldst_op) | fd(d, w) | alt_op3(ldf_op3, w) | rs1(s1) | immed(true) | simm(simm13a, 13), rspec); }
 
-inline void Assembler::ldfsr(  Register s1, Register s2) { v9_dep();   emit_int32( op(ldst_op) |             op3(ldfsr_op3) | rs1(s1) | rs2(s2) ); }
-inline void Assembler::ldfsr(  Register s1, int simm13a) { v9_dep();   emit_data( op(ldst_op) |             op3(ldfsr_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 inline void Assembler::ldxfsr( Register s1, Register s2) { v9_only();  emit_int32( op(ldst_op) | rd(G1)    | op3(ldfsr_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldxfsr( Register s1, int simm13a) { v9_only();  emit_data( op(ldst_op) | rd(G1)    | op3(ldfsr_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
-inline void Assembler::ldc(   Register s1, Register s2, int crd) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(ldc_op3  ) | rs1(s1) | rs2(s2) ); }
-inline void Assembler::ldc(   Register s1, int simm13a, int crd) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(ldc_op3  ) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::lddc(  Register s1, Register s2, int crd) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(lddc_op3 ) | rs1(s1) | rs2(s2) ); }
-inline void Assembler::lddc(  Register s1, int simm13a, int crd) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(lddc_op3 ) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::ldcsr( Register s1, Register s2, int crd) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(ldcsr_op3) | rs1(s1) | rs2(s2) ); }
-inline void Assembler::ldcsr( Register s1, int simm13a, int crd) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(ldcsr_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-
 inline void Assembler::ldsb(  Register s1, Register s2, Register d) { emit_int32( op(ldst_op) | rd(d) | op3(ldsb_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldsb(  Register s1, int simm13a, Register d) { emit_data( op(ldst_op) | rd(d) | op3(ldsb_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
@@ -119,9 +107,6 @@
 inline void Assembler::ldd(   Register s1, Register s2, Register d) { v9_dep(); assert(d->is_even(), "not even"); emit_int32( op(ldst_op) | rd(d) | op3(ldd_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldd(   Register s1, int simm13a, Register d) { v9_dep(); assert(d->is_even(), "not even"); emit_data( op(ldst_op) | rd(d) | op3(ldd_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
-inline void Assembler::ldstub(  Register s1, Register s2, Register d) { emit_int32( op(ldst_op) | rd(d) | op3(ldstub_op3) | rs1(s1) | rs2(s2) ); }
-inline void Assembler::ldstub(  Register s1, int simm13a, Register d) { emit_data( op(ldst_op) | rd(d) | op3(ldstub_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-
 inline void Assembler::rett( Register s1, Register s2                         ) { cti();  emit_int32( op(arith_op) | op3(rett_op3) | rs1(s1) | rs2(s2));  has_delay_slot(); }
 inline void Assembler::rett( Register s1, int simm13a, relocInfo::relocType rt) { cti();  emit_data( op(arith_op) | op3(rett_op3) | rs1(s1) | immed(true) | simm(simm13a, 13), rt);  has_delay_slot(); }
 
@@ -132,8 +117,6 @@
 inline void Assembler::stf(    FloatRegisterImpl::Width w, FloatRegister d, Register s1, Register s2) { emit_int32( op(ldst_op) | fd(d, w) | alt_op3(stf_op3, w) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::stf(    FloatRegisterImpl::Width w, FloatRegister d, Register s1, int simm13a) { emit_data( op(ldst_op) | fd(d, w) | alt_op3(stf_op3, w) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
-inline void Assembler::stfsr(  Register s1, Register s2) { v9_dep();   emit_int32( op(ldst_op) |             op3(stfsr_op3) | rs1(s1) | rs2(s2) ); }
-inline void Assembler::stfsr(  Register s1, int simm13a) { v9_dep();   emit_data( op(ldst_op) |             op3(stfsr_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 inline void Assembler::stxfsr( Register s1, Register s2) { v9_only();  emit_int32( op(ldst_op) | rd(G1)    | op3(stfsr_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::stxfsr( Register s1, int simm13a) { v9_only();  emit_data( op(ldst_op) | rd(G1)    | op3(stfsr_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
@@ -152,17 +135,6 @@
 inline void Assembler::std(  Register d, Register s1, Register s2) { v9_dep(); assert(d->is_even(), "not even"); emit_int32( op(ldst_op) | rd(d) | op3(std_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::std(  Register d, Register s1, int simm13a) { v9_dep(); assert(d->is_even(), "not even"); emit_data( op(ldst_op) | rd(d) | op3(std_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
-// v8 p 99
-
-inline void Assembler::stc(    int crd, Register s1, Register s2) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(stc_op3 ) | rs1(s1) | rs2(s2) ); }
-inline void Assembler::stc(    int crd, Register s1, int simm13a) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(stc_op3 ) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::stdc(   int crd, Register s1, Register s2) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(stdc_op3) | rs1(s1) | rs2(s2) ); }
-inline void Assembler::stdc(   int crd, Register s1, int simm13a) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(stdc_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::stcsr(  int crd, Register s1, Register s2) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(stcsr_op3) | rs1(s1) | rs2(s2) ); }
-inline void Assembler::stcsr(  int crd, Register s1, int simm13a) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(stcsr_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::stdcq(  int crd, Register s1, Register s2) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(stdcq_op3) | rs1(s1) | rs2(s2) ); }
-inline void Assembler::stdcq(  int crd, Register s1, int simm13a) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(stdcq_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-
 // pp 231
 
 inline void Assembler::swap(    Register s1, Register s2, Register d) { v9_dep();  emit_int32( op(ldst_op) | rd(d) | op3(swap_op3) | rs1(s1) | rs2(s2) ); }
--- a/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -597,13 +597,6 @@
 
   __ sra(Rdividend, 31, Rscratch);
   __ wry(Rscratch);
-  if (!VM_Version::v9_instructions_work()) {
-    // v9 doesn't require these nops
-    __ nop();
-    __ nop();
-    __ nop();
-    __ nop();
-  }
 
   add_debug_info_for_div0_here(op->info());
 
@@ -652,10 +645,6 @@
       case lir_cond_lessEqual:     acond = (is_unordered ? Assembler::f_unorderedOrLessOrEqual   : Assembler::f_lessOrEqual);    break;
       case lir_cond_greaterEqual:  acond = (is_unordered ? Assembler::f_unorderedOrGreaterOrEqual: Assembler::f_greaterOrEqual); break;
       default :                         ShouldNotReachHere();
-    };
-
-    if (!VM_Version::v9_instructions_work()) {
-      __ nop();
     }
     __ fb( acond, false, Assembler::pn, *(op->label()));
   } else {
@@ -725,9 +714,6 @@
       Label L;
       // result must be 0 if value is NaN; test by comparing value to itself
       __ fcmp(FloatRegisterImpl::S, Assembler::fcc0, rsrc, rsrc);
-      if (!VM_Version::v9_instructions_work()) {
-        __ nop();
-      }
       __ fb(Assembler::f_unordered, true, Assembler::pn, L);
       __ delayed()->st(G0, addr); // annuled if contents of rsrc is not NaN
       __ ftoi(FloatRegisterImpl::S, rsrc, rsrc);
@@ -1909,7 +1895,7 @@
       switch (code) {
         case lir_add:  __ add  (lreg, rreg, res); break;
         case lir_sub:  __ sub  (lreg, rreg, res); break;
-        case lir_mul:  __ mult (lreg, rreg, res); break;
+        case lir_mul:  __ mulx (lreg, rreg, res); break;
         default: ShouldNotReachHere();
       }
     }
@@ -1924,7 +1910,7 @@
       switch (code) {
         case lir_add:  __ add  (lreg, simm13, res); break;
         case lir_sub:  __ sub  (lreg, simm13, res); break;
-        case lir_mul:  __ mult (lreg, simm13, res); break;
+        case lir_mul:  __ mulx (lreg, simm13, res); break;
         default: ShouldNotReachHere();
       }
     } else {
@@ -1936,7 +1922,7 @@
       switch (code) {
         case lir_add:  __ add  (lreg, (int)con, res); break;
         case lir_sub:  __ sub  (lreg, (int)con, res); break;
-        case lir_mul:  __ mult (lreg, (int)con, res); break;
+        case lir_mul:  __ mulx (lreg, (int)con, res); break;
         default: ShouldNotReachHere();
       }
     }
@@ -3234,48 +3220,26 @@
     Register base = mem_addr->base()->as_register();
     if (src->is_register() && dest->is_address()) {
       // G4 is high half, G5 is low half
-      if (VM_Version::v9_instructions_work()) {
-        // clear the top bits of G5, and scale up G4
-        __ srl (src->as_register_lo(),  0, G5);
-        __ sllx(src->as_register_hi(), 32, G4);
-        // combine the two halves into the 64 bits of G4
-        __ or3(G4, G5, G4);
-        null_check_offset = __ offset();
-        if (idx == noreg) {
-          __ stx(G4, base, disp);
-        } else {
-          __ stx(G4, base, idx);
-        }
+      // clear the top bits of G5, and scale up G4
+      __ srl (src->as_register_lo(),  0, G5);
+      __ sllx(src->as_register_hi(), 32, G4);
+      // combine the two halves into the 64 bits of G4
+      __ or3(G4, G5, G4);
+      null_check_offset = __ offset();
+      if (idx == noreg) {
+        __ stx(G4, base, disp);
       } else {
-        __ mov (src->as_register_hi(), G4);
-        __ mov (src->as_register_lo(), G5);
-        null_check_offset = __ offset();
-        if (idx == noreg) {
-          __ std(G4, base, disp);
-        } else {
-          __ std(G4, base, idx);
-        }
+        __ stx(G4, base, idx);
       }
     } else if (src->is_address() && dest->is_register()) {
       null_check_offset = __ offset();
-      if (VM_Version::v9_instructions_work()) {
-        if (idx == noreg) {
-          __ ldx(base, disp, G5);
-        } else {
-          __ ldx(base, idx, G5);
-        }
-        __ srax(G5, 32, dest->as_register_hi()); // fetch the high half into hi
-        __ mov (G5, dest->as_register_lo());     // copy low half into lo
+      if (idx == noreg) {
+        __ ldx(base, disp, G5);
       } else {
-        if (idx == noreg) {
-          __ ldd(base, disp, G4);
-        } else {
-          __ ldd(base, idx, G4);
-        }
-        // G4 is high half, G5 is low half
-        __ mov (G4, dest->as_register_hi());
-        __ mov (G5, dest->as_register_lo());
+        __ ldx(base, idx, G5);
       }
+      __ srax(G5, 32, dest->as_register_hi()); // fetch the high half into hi
+      __ mov (G5, dest->as_register_lo());     // copy low half into lo
     } else {
       Unimplemented();
     }
--- a/hotspot/src/cpu/sparc/vm/c1_MacroAssembler_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/c1_MacroAssembler_sparc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -108,7 +108,7 @@
 
   // compare object markOop with Rmark and if equal exchange Rscratch with object markOop
   assert(mark_addr.disp() == 0, "cas must take a zero displacement");
-  casx_under_lock(mark_addr.base(), Rmark, Rscratch, (address)StubRoutines::Sparc::atomic_memory_operation_lock_addr());
+  cas_ptr(mark_addr.base(), Rmark, Rscratch);
   // if compare/exchange succeeded we found an unlocked object and we now have locked it
   // hence we are done
   cmp(Rmark, Rscratch);
@@ -149,7 +149,7 @@
 
   // Check if it is still a light weight lock, this is is true if we see
   // the stack address of the basicLock in the markOop of the object
-  casx_under_lock(mark_addr.base(), Rbox, Rmark, (address)StubRoutines::Sparc::atomic_memory_operation_lock_addr());
+  cas_ptr(mark_addr.base(), Rbox, Rmark);
   cmp(Rbox, Rmark);
 
   brx(Assembler::notEqual, false, Assembler::pn, slow_case);
@@ -276,7 +276,7 @@
     sub(var_size_in_bytes, hdr_size_in_bytes, t2); // compute size of body
     initialize_body(t1, t2);
 #ifndef _LP64
-  } else if (VM_Version::v9_instructions_work() && con_size_in_bytes < threshold * 2) {
+  } else if (con_size_in_bytes < threshold * 2) {
     // on v9 we can do double word stores to fill twice as much space.
     assert(hdr_size_in_bytes % 8 == 0, "double word aligned");
     assert(con_size_in_bytes % 8 == 0, "double word aligned");
--- a/hotspot/src/cpu/sparc/vm/c2_init_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/c2_init_sparc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -30,5 +30,4 @@
 
 void Compile::pd_compiler2_init() {
   guarantee(CodeEntryAlignment >= InteriorEntryAlignment, "" );
-  guarantee( VM_Version::v9_instructions_work(), "Server compiler does not run on V8 systems" );
 }
--- a/hotspot/src/cpu/sparc/vm/disassembler_sparc.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/disassembler_sparc.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -30,8 +30,7 @@
   }
 
   static const char* pd_cpu_opts() {
-    return (VM_Version::v9_instructions_work()?
-            (VM_Version::v8_instructions_work()? "" : "v9only") : "v8only");
+    return "v9only";
   }
 
 #endif // CPU_SPARC_VM_DISASSEMBLER_SPARC_HPP
--- a/hotspot/src/cpu/sparc/vm/globals_sparc.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/globals_sparc.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -110,8 +110,5 @@
                                                                             \
   product(uintx,  ArraycopyDstPrefetchDistance, 0,                          \
           "Distance to prefetch destination array in arracopy")             \
-                                                                            \
-  develop(intx, V8AtomicOperationUnderLockSpinCount,    50,                 \
-          "Number of times to spin wait on a v8 atomic operation lock")     \
 
 #endif // CPU_SPARC_VM_GLOBALS_SPARC_HPP
--- a/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1210,8 +1210,7 @@
     st_ptr(mark_reg, lock_addr, BasicLock::displaced_header_offset_in_bytes());
     // compare and exchange object_addr, markOop | 1, stack address of basicLock
     assert(mark_addr.disp() == 0, "cas must take a zero displacement");
-    casx_under_lock(mark_addr.base(), mark_reg, temp_reg,
-      (address)StubRoutines::Sparc::atomic_memory_operation_lock_addr());
+    cas_ptr(mark_addr.base(), mark_reg, temp_reg);
 
     // if the compare and exchange succeeded we are done (we saw an unlocked object)
     cmp_and_brx_short(mark_reg, temp_reg, Assembler::equal, Assembler::pt, done);
@@ -1291,8 +1290,7 @@
     // we expect to see the stack address of the basicLock in case the
     // lock is still a light weight lock (lock_reg)
     assert(mark_addr.disp() == 0, "cas must take a zero displacement");
-    casx_under_lock(mark_addr.base(), lock_reg, displaced_header_reg,
-      (address)StubRoutines::Sparc::atomic_memory_operation_lock_addr());
+    cas_ptr(mark_addr.base(), lock_reg, displaced_header_reg);
     cmp(lock_reg, displaced_header_reg);
     brx(Assembler::equal, true, Assembler::pn, done);
     delayed()->st_ptr(G0, lockobj_addr);  // free entry
--- a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -118,7 +118,6 @@
       case bp_op2:     m = wdisp(  word_aligned_ones, 0, 19);  v = wdisp(  dest_pos, inst_pos, 19); break;
       case fb_op2:     m = wdisp(  word_aligned_ones, 0, 22);  v = wdisp(  dest_pos, inst_pos, 22); break;
       case br_op2:     m = wdisp(  word_aligned_ones, 0, 22);  v = wdisp(  dest_pos, inst_pos, 22); break;
-      case cb_op2:     m = wdisp(  word_aligned_ones, 0, 22);  v = wdisp(  dest_pos, inst_pos, 22); break;
       case bpr_op2: {
         if (is_cbcond(inst)) {
           m = wdisp10(word_aligned_ones, 0);
@@ -149,7 +148,6 @@
       case bp_op2:     r = inv_wdisp(  inst, pos, 19);  break;
       case fb_op2:     r = inv_wdisp(  inst, pos, 22);  break;
       case br_op2:     r = inv_wdisp(  inst, pos, 22);  break;
-      case cb_op2:     r = inv_wdisp(  inst, pos, 22);  break;
       case bpr_op2: {
         if (is_cbcond(inst)) {
           r = inv_wdisp10(inst, pos);
@@ -325,12 +323,6 @@
   trap(ST_RESERVED_FOR_USER_0);
 }
 
-// flush windows (except current) using flushw instruction if avail.
-void MacroAssembler::flush_windows() {
-  if (VM_Version::v9_instructions_work())  flushw();
-  else                                     flush_windows_trap();
-}
-
 // Write serialization page so VM thread can do a pseudo remote membar
 // We use the current thread pointer to calculate a thread specific
 // offset to write to within the page. This minimizes bus traffic
@@ -358,88 +350,6 @@
   Unimplemented();
 }
 
-void MacroAssembler::mult(Register s1, Register s2, Register d) {
-  if(VM_Version::v9_instructions_work()) {
-    mulx (s1, s2, d);
-  } else {
-    smul (s1, s2, d);
-  }
-}
-
-void MacroAssembler::mult(Register s1, int simm13a, Register d) {
-  if(VM_Version::v9_instructions_work()) {
-    mulx (s1, simm13a, d);
-  } else {
-    smul (s1, simm13a, d);
-  }
-}
-
-
-#ifdef ASSERT
-void MacroAssembler::read_ccr_v8_assert(Register ccr_save) {
-  const Register s1 = G3_scratch;
-  const Register s2 = G4_scratch;
-  Label get_psr_test;
-  // Get the condition codes the V8 way.
-  read_ccr_trap(s1);
-  mov(ccr_save, s2);
-  // This is a test of V8 which has icc but not xcc
-  // so mask off the xcc bits
-  and3(s2, 0xf, s2);
-  // Compare condition codes from the V8 and V9 ways.
-  subcc(s2, s1, G0);
-  br(Assembler::notEqual, true, Assembler::pt, get_psr_test);
-  delayed()->breakpoint_trap();
-  bind(get_psr_test);
-}
-
-void MacroAssembler::write_ccr_v8_assert(Register ccr_save) {
-  const Register s1 = G3_scratch;
-  const Register s2 = G4_scratch;
-  Label set_psr_test;
-  // Write out the saved condition codes the V8 way
-  write_ccr_trap(ccr_save, s1, s2);
-  // Read back the condition codes using the V9 instruction
-  rdccr(s1);
-  mov(ccr_save, s2);
-  // This is a test of V8 which has icc but not xcc
-  // so mask off the xcc bits
-  and3(s2, 0xf, s2);
-  and3(s1, 0xf, s1);
-  // Compare the V8 way with the V9 way.
-  subcc(s2, s1, G0);
-  br(Assembler::notEqual, true, Assembler::pt, set_psr_test);
-  delayed()->breakpoint_trap();
-  bind(set_psr_test);
-}
-#else
-#define read_ccr_v8_assert(x)
-#define write_ccr_v8_assert(x)
-#endif // ASSERT
-
-void MacroAssembler::read_ccr(Register ccr_save) {
-  if (VM_Version::v9_instructions_work()) {
-    rdccr(ccr_save);
-    // Test code sequence used on V8.  Do not move above rdccr.
-    read_ccr_v8_assert(ccr_save);
-  } else {
-    read_ccr_trap(ccr_save);
-  }
-}
-
-void MacroAssembler::write_ccr(Register ccr_save) {
-  if (VM_Version::v9_instructions_work()) {
-    // Test code sequence used on V8.  Do not move below wrccr.
-    write_ccr_v8_assert(ccr_save);
-    wrccr(ccr_save);
-  } else {
-    const Register temp_reg1 = G3_scratch;
-    const Register temp_reg2 = G4_scratch;
-    write_ccr_trap(ccr_save, temp_reg1, temp_reg2);
-  }
-}
-
-
 // Calls to C land
 
 #ifdef ASSERT
@@ -465,8 +375,8 @@
 #ifdef ASSERT
   AddressLiteral last_get_thread_addrlit(&last_get_thread);
   set(last_get_thread_addrlit, L3);
-  inc(L4, get_pc(L4) + 2 * BytesPerInstWord); // skip getpc() code + inc + st_ptr to point L4 at call
-  st_ptr(L4, L3, 0);
+  rdpc(L4);
+  inc(L4, 3 * BytesPerInstWord); // skip rdpc + inc + st_ptr to point L4 at call  st_ptr(L4, L3, 0);
 #endif
   call(CAST_FROM_FN_PTR(address, reinitialize_thread), relocInfo::runtime_call_type);
   delayed()->nop();
@@ -1327,7 +1237,7 @@
 
 void RegistersForDebugging::save_registers(MacroAssembler* a) {
   a->sub(FP, round_to(sizeof(RegistersForDebugging), sizeof(jdouble)) - STACK_BIAS, O0);
-  a->flush_windows();
+  a->flushw();
   int i;
   for (i = 0; i < 8; ++i) {
     a->ld_ptr(as_iRegister(i)->address_in_saved_window().after_save(), L1);  a->st_ptr( L1, O0, i_offset(i));
@@ -1338,7 +1248,7 @@
   for (i = 0;  i < 32; ++i) {
     a->stf(FloatRegisterImpl::S, as_FloatRegister(i), O0, f_offset(i));
   }
-  for (i = 0; i < (VM_Version::v9_instructions_work() ? 64 : 32); i += 2) {
+  for (i = 0; i < 64; i += 2) {
     a->stf(FloatRegisterImpl::D, as_FloatRegister(i), O0, d_offset(i));
   }
 }
@@ -1350,7 +1260,7 @@
   for (int j = 0; j < 32; ++j) {
     a->ldf(FloatRegisterImpl::S, O0, f_offset(j), as_FloatRegister(j));
   }
-  for (int k = 0; k < (VM_Version::v9_instructions_work() ? 64 : 32); k += 2) {
+  for (int k = 0; k < 64; k += 2) {
     a->ldf(FloatRegisterImpl::D, O0, d_offset(k), as_FloatRegister(k));
   }
 }
@@ -1465,8 +1375,6 @@
 // the high bits of the O-regs if they contain Long values.  Acts as a 'leaf'
 // call.
 void MacroAssembler::verify_oop_subroutine() {
-  assert( VM_Version::v9_instructions_work(), "VerifyOops not supported for V8" );
-
   // Leaf call; no frame.
   Label succeed, fail, null_or_fail;
 
@@ -1870,26 +1778,17 @@
   // And the equals case for the high part does not need testing,
   // since that triplet is reached only after finding the high halves differ.
 
-  if (VM_Version::v9_instructions_work()) {
-    mov(-1, Rresult);
-    ba(done);  delayed()-> movcc(greater, false, icc,  1, Rresult);
-  } else {
-    br(less,    true, pt, done); delayed()-> set(-1, Rresult);
-    br(greater, true, pt, done); delayed()-> set( 1, Rresult);
-  }
-
-  bind( check_low_parts );
-
-  if (VM_Version::v9_instructions_work()) {
-    mov(                               -1, Rresult);
-    movcc(equal,           false, icc,  0, Rresult);
-    movcc(greaterUnsigned, false, icc,  1, Rresult);
-  } else {
-    set(-1, Rresult);
-    br(equal,           true, pt, done); delayed()->set( 0, Rresult);
-    br(greaterUnsigned, true, pt, done); delayed()->set( 1, Rresult);
-  }
-  bind( done );
+  mov(-1, Rresult);
+  ba(done);
+  delayed()->movcc(greater, false, icc,  1, Rresult);
+
+  bind(check_low_parts);
+
+  mov(                               -1, Rresult);
+  movcc(equal,           false, icc,  0, Rresult);
+  movcc(greaterUnsigned, false, icc,  1, Rresult);
+
+  bind(done);
 }
 
 void MacroAssembler::lneg( Register Rhi, Register Rlow ) {
@@ -2117,118 +2016,23 @@
 void MacroAssembler::float_cmp( bool is_float, int unordered_result,
                                 FloatRegister Fa, FloatRegister Fb,
                                 Register Rresult) {
-
-  fcmp(is_float ? FloatRegisterImpl::S : FloatRegisterImpl::D, fcc0, Fa, Fb);
-
-  Condition lt = unordered_result == -1 ? f_unorderedOrLess    : f_less;
-  Condition eq =                          f_equal;
-  Condition gt = unordered_result ==  1 ? f_unorderedOrGreater : f_greater;
-
-  if (VM_Version::v9_instructions_work()) {
-
-    mov(-1, Rresult);
-    movcc(eq, true, fcc0, 0, Rresult);
-    movcc(gt, true, fcc0, 1, Rresult);
-
+  if (is_float) {
+    fcmp(FloatRegisterImpl::S, fcc0, Fa, Fb);
   } else {
-    Label done;
-
-    set( -1, Rresult );
-    //fb(lt, true, pn, done); delayed()->set( -1, Rresult );
-    fb( eq, true, pn, done);  delayed()->set(  0, Rresult );
-    fb( gt, true, pn, done);  delayed()->set(  1, Rresult );
-
-    bind (done);
+    fcmp(FloatRegisterImpl::D, fcc0, Fa, Fb);
   }
-}
-
-
-void MacroAssembler::fneg( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d)
-{
-  if (VM_Version::v9_instructions_work()) {
-    Assembler::fneg(w, s, d);
+
+  if (unordered_result == 1) {
+    mov(                                    -1, Rresult);
+    movcc(f_equal,              true, fcc0,  0, Rresult);
+    movcc(f_unorderedOrGreater, true, fcc0,  1, Rresult);
   } else {
-    if (w == FloatRegisterImpl::S) {
-      Assembler::fneg(w, s, d);
-    } else if (w == FloatRegisterImpl::D) {
-      // number() does a sanity check on the alignment.
-      assert(((s->encoding(FloatRegisterImpl::D) & 1) == 0) &&
-        ((d->encoding(FloatRegisterImpl::D) & 1) == 0), "float register alignment check");
-
-      Assembler::fneg(FloatRegisterImpl::S, s, d);
-      Assembler::fmov(FloatRegisterImpl::S, s->successor(), d->successor());
-    } else {
-      assert(w == FloatRegisterImpl::Q, "Invalid float register width");
-
-      // number() does a sanity check on the alignment.
-      assert(((s->encoding(FloatRegisterImpl::D) & 3) == 0) &&
-        ((d->encoding(FloatRegisterImpl::D) & 3) == 0), "float register alignment check");
-
-      Assembler::fneg(FloatRegisterImpl::S, s, d);
-      Assembler::fmov(FloatRegisterImpl::S, s->successor(), d->successor());
-      Assembler::fmov(FloatRegisterImpl::S, s->successor()->successor(), d->successor()->successor());
-      Assembler::fmov(FloatRegisterImpl::S, s->successor()->successor()->successor(), d->successor()->successor()->successor());
-    }
+    mov(                                    -1, Rresult);
+    movcc(f_equal,              true, fcc0,  0, Rresult);
+    movcc(f_greater,            true, fcc0,  1, Rresult);
   }
 }
 
-void MacroAssembler::fmov( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d)
-{
-  if (VM_Version::v9_instructions_work()) {
-    Assembler::fmov(w, s, d);
-  } else {
-    if (w == FloatRegisterImpl::S) {
-      Assembler::fmov(w, s, d);
-    } else if (w == FloatRegisterImpl::D) {
-      // number() does a sanity check on the alignment.
-      assert(((s->encoding(FloatRegisterImpl::D) & 1) == 0) &&
-        ((d->encoding(FloatRegisterImpl::D) & 1) == 0), "float register alignment check");
-
-      Assembler::fmov(FloatRegisterImpl::S, s, d);
-      Assembler::fmov(FloatRegisterImpl::S, s->successor(), d->successor());
-    } else {
-      assert(w == FloatRegisterImpl::Q, "Invalid float register width");
-
-      // number() does a sanity check on the alignment.
-      assert(((s->encoding(FloatRegisterImpl::D) & 3) == 0) &&
-        ((d->encoding(FloatRegisterImpl::D) & 3) == 0), "float register alignment check");
-
-      Assembler::fmov(FloatRegisterImpl::S, s, d);
-      Assembler::fmov(FloatRegisterImpl::S, s->successor(), d->successor());
-      Assembler::fmov(FloatRegisterImpl::S, s->successor()->successor(), d->successor()->successor());
-      Assembler::fmov(FloatRegisterImpl::S, s->successor()->successor()->successor(), d->successor()->successor()->successor());
-    }
-  }
-}
-
-void MacroAssembler::fabs( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d)
-{
-  if (VM_Version::v9_instructions_work()) {
-    Assembler::fabs(w, s, d);
-  } else {
-    if (w == FloatRegisterImpl::S) {
-      Assembler::fabs(w, s, d);
-    } else if (w == FloatRegisterImpl::D) {
-      // number() does a sanity check on the alignment.
-      assert(((s->encoding(FloatRegisterImpl::D) & 1) == 0) &&
-        ((d->encoding(FloatRegisterImpl::D) & 1) == 0), "float register alignment check");
-
-      Assembler::fabs(FloatRegisterImpl::S, s, d);
-      Assembler::fmov(FloatRegisterImpl::S, s->successor(), d->successor());
-    } else {
-      assert(w == FloatRegisterImpl::Q, "Invalid float register width");
-
-      // number() does a sanity check on the alignment.
-      assert(((s->encoding(FloatRegisterImpl::D) & 3) == 0) &&
-       ((d->encoding(FloatRegisterImpl::D) & 3) == 0), "float register alignment check");
-
-      Assembler::fabs(FloatRegisterImpl::S, s, d);
-      Assembler::fmov(FloatRegisterImpl::S, s->successor(), d->successor());
-      Assembler::fmov(FloatRegisterImpl::S, s->successor()->successor(), d->successor()->successor());
-      Assembler::fmov(FloatRegisterImpl::S, s->successor()->successor()->successor(), d->successor()->successor()->successor());
-    }
-  }
-}
 
 void MacroAssembler::save_all_globals_into_locals() {
   mov(G1,L1);
@@ -2250,135 +2054,6 @@
   mov(L7,G7);
 }
 
-// Use for 64 bit operation.
-void MacroAssembler::casx_under_lock(Register top_ptr_reg, Register top_reg, Register ptr_reg, address lock_addr, bool use_call_vm)
-{
-  // store ptr_reg as the new top value
-#ifdef _LP64
-  casx(top_ptr_reg, top_reg, ptr_reg);
-#else
-  cas_under_lock(top_ptr_reg, top_reg, ptr_reg, lock_addr, use_call_vm);
-#endif // _LP64
-}
-
-// [RGV] This routine does not handle 64 bit operations.
-//       use casx_under_lock() or casx directly!!!
-void MacroAssembler::cas_under_lock(Register top_ptr_reg, Register top_reg, Register ptr_reg, address lock_addr, bool use_call_vm)
-{
-  // store ptr_reg as the new top value
-  if (VM_Version::v9_instructions_work()) {
-    cas(top_ptr_reg, top_reg, ptr_reg);
-  } else {
-
-    // If the register is not an out nor global, it is not visible
-    // after the save.  Allocate a register for it, save its
-    // value in the register save area (the save may not flush
-    // registers to the save area).
-
-    Register top_ptr_reg_after_save;
-    Register top_reg_after_save;
-    Register ptr_reg_after_save;
-
-    if (top_ptr_reg->is_out() || top_ptr_reg->is_global()) {
-      top_ptr_reg_after_save = top_ptr_reg->after_save();
-    } else {
-      Address reg_save_addr = top_ptr_reg->address_in_saved_window();
-      top_ptr_reg_after_save = L0;
-      st(top_ptr_reg, reg_save_addr);
-    }
-
-    if (top_reg->is_out() || top_reg->is_global()) {
-      top_reg_after_save = top_reg->after_save();
-    } else {
-      Address reg_save_addr = top_reg->address_in_saved_window();
-      top_reg_after_save = L1;
-      st(top_reg, reg_save_addr);
-    }
-
-    if (ptr_reg->is_out() || ptr_reg->is_global()) {
-      ptr_reg_after_save = ptr_reg->after_save();
-    } else {
-      Address reg_save_addr = ptr_reg->address_in_saved_window();
-      ptr_reg_after_save = L2;
-      st(ptr_reg, reg_save_addr);
-    }
-
-    const Register& lock_reg = L3;
-    const Register& lock_ptr_reg = L4;
-    const Register& value_reg = L5;
-    const Register& yield_reg = L6;
-    const Register& yieldall_reg = L7;
-
-    save_frame();
-
-    if (top_ptr_reg_after_save == L0) {
-      ld(top_ptr_reg->address_in_saved_window().after_save(), top_ptr_reg_after_save);
-    }
-
-    if (top_reg_after_save == L1) {
-      ld(top_reg->address_in_saved_window().after_save(), top_reg_after_save);
-    }
-
-    if (ptr_reg_after_save == L2) {
-      ld(ptr_reg->address_in_saved_window().after_save(), ptr_reg_after_save);
-    }
-
-    Label(retry_get_lock);
-    Label(not_same);
-    Label(dont_yield);
-
-    assert(lock_addr, "lock_address should be non null for v8");
-    set((intptr_t)lock_addr, lock_ptr_reg);
-    // Initialize yield counter
-    mov(G0,yield_reg);
-    mov(G0, yieldall_reg);
-    set(StubRoutines::Sparc::locked, lock_reg);
-
-    bind(retry_get_lock);
-    cmp_and_br_short(yield_reg, V8AtomicOperationUnderLockSpinCount, Assembler::less, Assembler::pt, dont_yield);
-
-    if(use_call_vm) {
-      Untested("Need to verify global reg consistancy");
-      call_VM(noreg, CAST_FROM_FN_PTR(address, SharedRuntime::yield_all), yieldall_reg);
-    } else {
-      // Save the regs and make space for a C call
-      save(SP, -96, SP);
-      save_all_globals_into_locals();
-      call(CAST_FROM_FN_PTR(address,os::yield_all));
-      delayed()->mov(yieldall_reg, O0);
-      restore_globals_from_locals();
-      restore();
-    }
-
-    // reset the counter
-    mov(G0,yield_reg);
-    add(yieldall_reg, 1, yieldall_reg);
-
-    bind(dont_yield);
-    // try to get lock
-    Assembler::swap(lock_ptr_reg, 0, lock_reg);
-
-    // did we get the lock?
-    cmp(lock_reg, StubRoutines::Sparc::unlocked);
-    br(Assembler::notEqual, true, Assembler::pn, retry_get_lock);
-    delayed()->add(yield_reg,1,yield_reg);
-
-    // yes, got lock.  do we have the same top?
-    ld(top_ptr_reg_after_save, 0, value_reg);
-    cmp_and_br_short(value_reg, top_reg_after_save, Assembler::notEqual, Assembler::pn, not_same);
-
-    // yes, same top.
-    st(ptr_reg_after_save, top_ptr_reg_after_save, 0);
-    membar(Assembler::StoreStore);
-
-    bind(not_same);
-    mov(value_reg, ptr_reg_after_save);
-    st(lock_reg, lock_ptr_reg, 0); // unlock
-
-    restore();
-  }
-}
-
 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
                                                       Register tmp,
                                                       int offset) {
@@ -2970,7 +2645,7 @@
                   markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place,
                   mark_reg);
   or3(G2_thread, mark_reg, temp_reg);
-  casn(mark_addr.base(), mark_reg, temp_reg);
+  cas_ptr(mark_addr.base(), mark_reg, temp_reg);
   // If the biasing toward our thread failed, this means that
   // another thread succeeded in biasing it toward itself and we
   // need to revoke that bias. The revocation will occur in the
@@ -2998,7 +2673,7 @@
   load_klass(obj_reg, temp_reg);
   ld_ptr(Address(temp_reg, Klass::prototype_header_offset()), temp_reg);
   or3(G2_thread, temp_reg, temp_reg);
-  casn(mark_addr.base(), mark_reg, temp_reg);
+  cas_ptr(mark_addr.base(), mark_reg, temp_reg);
   // If the biasing toward our thread failed, this means that
   // another thread succeeded in biasing it toward itself and we
   // need to revoke that bias. The revocation will occur in the
@@ -3027,7 +2702,7 @@
   // bits in this situation. Should attempt to preserve them.
   load_klass(obj_reg, temp_reg);
   ld_ptr(Address(temp_reg, Klass::prototype_header_offset()), temp_reg);
-  casn(mark_addr.base(), mark_reg, temp_reg);
+  cas_ptr(mark_addr.base(), mark_reg, temp_reg);
   // Fall through to the normal CAS-based lock, because no matter what
   // the result of the above CAS, some thread must have succeeded in
   // removing the bias bit from the object's header.
@@ -3058,15 +2733,6 @@
 }
 
 
-// CASN -- 32-64 bit switch hitter similar to the synthetic CASN provided by
-// Solaris/SPARC's "as".  Another apt name would be cas_ptr()
-
-void MacroAssembler::casn (Register addr_reg, Register cmp_reg, Register set_reg ) {
-  casx_under_lock (addr_reg, cmp_reg, set_reg, (address)StubRoutines::Sparc::atomic_memory_operation_lock_addr());
-}
-
-
-
 // compiler_lock_object() and compiler_unlock_object() are direct transliterations
 // of i486.ad fast_lock() and fast_unlock().  See those methods for detailed comments.
 // The code could be tightened up considerably.
@@ -3129,8 +2795,7 @@
 
      // compare object markOop with Rmark and if equal exchange Rscratch with object markOop
      assert(mark_addr.disp() == 0, "cas must take a zero displacement");
-     casx_under_lock(mark_addr.base(), Rmark, Rscratch,
-        (address)StubRoutines::Sparc::atomic_memory_operation_lock_addr());
+     cas_ptr(mark_addr.base(), Rmark, Rscratch);
 
      // if compare/exchange succeeded we found an unlocked object and we now have locked it
      // hence we are done
@@ -3176,7 +2841,7 @@
       mov(Rbox,  Rscratch);
       or3(Rmark, markOopDesc::unlocked_value, Rmark);
       assert(mark_addr.disp() == 0, "cas must take a zero displacement");
-      casn(mark_addr.base(), Rmark, Rscratch);
+      cas_ptr(mark_addr.base(), Rmark, Rscratch);
       cmp(Rmark, Rscratch);
       brx(Assembler::equal, false, Assembler::pt, done);
       delayed()->sub(Rscratch, SP, Rscratch);
@@ -3207,7 +2872,7 @@
       // Invariant: if we acquire the lock then _recursions should be 0.
       add(Rmark, ObjectMonitor::owner_offset_in_bytes()-2, Rmark);
       mov(G2_thread, Rscratch);
-      casn(Rmark, G0, Rscratch);
+      cas_ptr(Rmark, G0, Rscratch);
       cmp(Rscratch, G0);
       // Intentional fall-through into done
    } else {
@@ -3240,7 +2905,7 @@
       mov(0, Rscratch);
       or3(Rmark, markOopDesc::unlocked_value, Rmark);
       assert(mark_addr.disp() == 0, "cas must take a zero displacement");
-      casn(mark_addr.base(), Rmark, Rscratch);
+      cas_ptr(mark_addr.base(), Rmark, Rscratch);
 // prefetch (mark_addr, Assembler::severalWritesAndPossiblyReads);
       cmp(Rscratch, Rmark);
       brx(Assembler::notZero, false, Assembler::pn, Recursive);
@@ -3266,7 +2931,7 @@
       // the fast-path stack-lock code from the interpreter and always passed
       // control to the "slow" operators in synchronizer.cpp.
 
-      // RScratch contains the fetched obj->mark value from the failed CASN.
+      // RScratch contains the fetched obj->mark value from the failed CAS.
 #ifdef _LP64
       sub(Rscratch, STACK_BIAS, Rscratch);
 #endif
@@ -3300,7 +2965,7 @@
       // Invariant: if we acquire the lock then _recursions should be 0.
       add(Rmark, ObjectMonitor::owner_offset_in_bytes()-2, Rmark);
       mov(G2_thread, Rscratch);
-      casn(Rmark, G0, Rscratch);
+      cas_ptr(Rmark, G0, Rscratch);
       cmp(Rscratch, G0);
       // ST box->displaced_header = NonZero.
       // Any non-zero value suffices:
@@ -3336,8 +3001,7 @@
      // Check if it is still a light weight lock, this is is true if we see
      // the stack address of the basicLock in the markOop of the object
      assert(mark_addr.disp() == 0, "cas must take a zero displacement");
-     casx_under_lock(mark_addr.base(), Rbox, Rmark,
-       (address)StubRoutines::Sparc::atomic_memory_operation_lock_addr());
+     cas_ptr(mark_addr.base(), Rbox, Rmark);
      ba(done);
      delayed()->cmp(Rbox, Rmark);
      bind(done);
@@ -3398,7 +3062,7 @@
       delayed()->andcc(G0, G0, G0);
       add(Rmark, ObjectMonitor::owner_offset_in_bytes()-2, Rmark);
       mov(G2_thread, Rscratch);
-      casn(Rmark, G0, Rscratch);
+      cas_ptr(Rmark, G0, Rscratch);
       // invert icc.zf and goto done
       br_notnull(Rscratch, false, Assembler::pt, done);
       delayed()->cmp(G0, G0);
@@ -3440,7 +3104,7 @@
    // A prototype implementation showed excellent results, although
    // the scavenger and timeout code was rather involved.
 
-   casn(mark_addr.base(), Rbox, Rscratch);
+   cas_ptr(mark_addr.base(), Rbox, Rscratch);
    cmp(Rbox, Rscratch);
    // Intentional fall through into done ...
 
@@ -3540,7 +3204,8 @@
 
   if (CMSIncrementalMode || !Universe::heap()->supports_inline_contig_alloc()) {
     // No allocation in the shared eden.
-    ba_short(slow_case);
+    ba(slow_case);
+    delayed()->nop();
   } else {
     // get eden boundaries
     // note: we need both top & top_addr!
@@ -3583,7 +3248,7 @@
     // Compare obj with the value at top_addr; if still equal, swap the value of
     // end with the value at top_addr. If not equal, read the value at top_addr
     // into end.
-    casx_under_lock(top_addr, obj, end, (address)StubRoutines::Sparc::atomic_memory_operation_lock_addr());
+    cas_ptr(top_addr, obj, end);
     // if someone beat us on the allocation, try again, otherwise continue
     cmp(obj, end);
     brx(Assembler::notEqual, false, Assembler::pn, retry);
--- a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -963,7 +963,7 @@
   inline void sub(Register s1, RegisterOrConstant s2, Register d, int offset = 0);
 
   using Assembler::swap;
-  inline void swap(Address& a, Register d, int offset = 0);
+  inline void swap(const Address& a, Register d, int offset = 0);
 
   // address pseudos: make these names unlike instruction names to avoid confusion
   inline intptr_t load_pc_address( Register reg, int bytes_to_skip );
@@ -1056,13 +1056,6 @@
 
   void breakpoint_trap();
   void breakpoint_trap(Condition c, CC cc);
-  void flush_windows_trap();
-  void clean_windows_trap();
-  void get_psr_trap();
-  void set_psr_trap();
-
-  // V8/V9 flush_windows
-  void flush_windows();
 
   // Support for serializing memory accesses between threads
   void serialize_memory(Register thread, Register tmp1, Register tmp2);
@@ -1071,14 +1064,6 @@
   void enter();
   void leave();
 
-  // V8/V9 integer multiply
-  void mult(Register s1, Register s2, Register d);
-  void mult(Register s1, int simm13a, Register d);
-
-  // V8/V9 read and write of condition codes.
-  void read_ccr(Register d);
-  void write_ccr(Register s);
-
   // Manipulation of C++ bools
   // These are idioms to flag the need for care with accessing bools but on
   // this platform we assume byte size
@@ -1162,21 +1147,6 @@
   // check_and_forward_exception to handle exceptions when it is safe
   void check_and_forward_exception(Register scratch_reg);
 
- private:
-  // For V8
-  void read_ccr_trap(Register ccr_save);
-  void write_ccr_trap(Register ccr_save1, Register scratch1, Register scratch2);
-
-#ifdef ASSERT
-  // For V8 debugging.  Uses V8 instruction sequence and checks
-  // result with V9 insturctions rdccr and wrccr.
-  // Uses Gscatch and Gscatch2
-  void read_ccr_v8_assert(Register ccr_save);
-  void write_ccr_v8_assert(Register ccr_save);
-#endif // ASSERT
-
- public:
-
   // Write to card table for - register is destroyed afterwards.
   void card_table_write(jbyte* byte_map_base, Register tmp, Register obj);
 
@@ -1314,20 +1284,9 @@
                   FloatRegister Fa, FloatRegister Fb,
                   Register Rresult);
 
-  void fneg( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d);
-  void fneg( FloatRegisterImpl::Width w, FloatRegister sd ) { Assembler::fneg(w, sd); }
-  void fmov( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d);
-  void fabs( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d);
-
   void save_all_globals_into_locals();
   void restore_globals_from_locals();
 
-  void casx_under_lock(Register top_ptr_reg, Register top_reg, Register ptr_reg,
-    address lock_addr=0, bool use_call_vm=false);
-  void cas_under_lock(Register top_ptr_reg, Register top_reg, Register ptr_reg,
-    address lock_addr=0, bool use_call_vm=false);
-  void casn (Register addr_reg, Register cmp_reg, Register set_reg) ;
-
   // These set the icc condition code to equal if the lock succeeded
   // and notEqual if it failed and requires a slow case
   void compiler_lock_object(Register Roop, Register Rmark, Register Rbox,
--- a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.inline.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.inline.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -229,10 +229,7 @@
 // Use the right branch for the platform
 
 inline void MacroAssembler::br( Condition c, bool a, Predict p, address d, relocInfo::relocType rt ) {
-  if (VM_Version::v9_instructions_work())
-    Assembler::bp(c, a, icc, p, d, rt);
-  else
-    Assembler::br(c, a, d, rt);
+  Assembler::bp(c, a, icc, p, d, rt);
 }
 
 inline void MacroAssembler::br( Condition c, bool a, Predict p, Label& L ) {
@@ -268,10 +265,7 @@
 }
 
 inline void MacroAssembler::fb( Condition c, bool a, Predict p, address d, relocInfo::relocType rt ) {
-  if (VM_Version::v9_instructions_work())
-    fbp(c, a, fcc0, p, d, rt);
-  else
-    Assembler::fb(c, a, d, rt);
+  fbp(c, a, fcc0, p, d, rt);
 }
 
 inline void MacroAssembler::fb( Condition c, bool a, Predict p, Label& L ) {
@@ -334,7 +328,7 @@
 
 // prefetch instruction
 inline void MacroAssembler::iprefetch( address d, relocInfo::relocType rt ) {
-  if (VM_Version::v9_instructions_work())
+  Assembler::bp( never, true, xcc, pt, d, rt );
     Assembler::bp( never, true, xcc, pt, d, rt );
 }
 inline void MacroAssembler::iprefetch( Label& L) { iprefetch( target(L) ); }
@@ -344,15 +338,7 @@
 // returns delta from gotten pc to addr after
 inline int MacroAssembler::get_pc( Register d ) {
   int x = offset();
-  if (VM_Version::v9_instructions_work())
-    rdpc(d);
-  else {
-    Label lbl;
-    Assembler::call(lbl, relocInfo::none);  // No relocation as this is call to pc+0x8
-    if (d == O7)  delayed()->nop();
-    else          delayed()->mov(O7, d);
-    bind(lbl);
-  }
+  rdpc(d);
   return offset() - x;
 }
 
@@ -646,41 +632,26 @@
 // returns if membar generates anything, obviously this code should mirror
 // membar below.
 inline bool MacroAssembler::membar_has_effect( Membar_mask_bits const7a ) {
-  if( !os::is_MP() ) return false;  // Not needed on single CPU
-  if( VM_Version::v9_instructions_work() ) {
-    const Membar_mask_bits effective_mask =
-        Membar_mask_bits(const7a & ~(LoadLoad | LoadStore | StoreStore));
-    return (effective_mask != 0);
-  } else {
-    return true;
-  }
+  if (!os::is_MP())
+    return false;  // Not needed on single CPU
+  const Membar_mask_bits effective_mask =
+      Membar_mask_bits(const7a & ~(LoadLoad | LoadStore | StoreStore));
+  return (effective_mask != 0);
 }
 
 inline void MacroAssembler::membar( Membar_mask_bits const7a ) {
   // Uniprocessors do not need memory barriers
-  if (!os::is_MP()) return;
+  if (!os::is_MP())
+    return;
   // Weakened for current Sparcs and TSO.  See the v9 manual, sections 8.4.3,
   // 8.4.4.3, a.31 and a.50.
-  if( VM_Version::v9_instructions_work() ) {
-    // Under TSO, setting bit 3, 2, or 0 is redundant, so the only value
-    // of the mmask subfield of const7a that does anything that isn't done
-    // implicitly is StoreLoad.
-    const Membar_mask_bits effective_mask =
-        Membar_mask_bits(const7a & ~(LoadLoad | LoadStore | StoreStore));
-    if ( effective_mask != 0 ) {
-      Assembler::membar( effective_mask );
-    }
-  } else {
-    // stbar is the closest there is on v8.  Equivalent to membar(StoreStore).  We
-    // do not issue the stbar because to my knowledge all v8 machines implement TSO,
-    // which guarantees that all stores behave as if an stbar were issued just after
-    // each one of them.  On these machines, stbar ought to be a nop.  There doesn't
-    // appear to be an equivalent of membar(StoreLoad) on v8: TSO doesn't require it,
-    // it can't be specified by stbar, nor have I come up with a way to simulate it.
-    //
-    // Addendum.  Dave says that ldstub guarantees a write buffer flush to coherent
-    // space.  Put one here to be on the safe side.
-    Assembler::ldstub(SP, 0, G0);
+  // Under TSO, setting bit 3, 2, or 0 is redundant, so the only value
+  // of the mmask subfield of const7a that does anything that isn't done
+  // implicitly is StoreLoad.
+  const Membar_mask_bits effective_mask =
+      Membar_mask_bits(const7a & ~(LoadLoad | LoadStore | StoreStore));
+  if (effective_mask != 0) {
+    Assembler::membar(effective_mask);
   }
 }
 
@@ -748,7 +719,7 @@
   if (offset != 0)       sub(d,  offset,                    d);
 }
 
-inline void MacroAssembler::swap(Address& a, Register d, int offset) {
+inline void MacroAssembler::swap(const Address& a, Register d, int offset) {
   relocate(a.rspec(offset));
   if (a.has_index()) { assert(offset == 0, ""); swap(a.base(), a.index(), d        ); }
   else               {                          swap(a.base(), a.disp() + offset, d); }
--- a/hotspot/src/cpu/sparc/vm/nativeInst_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/nativeInst_sparc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -162,7 +162,7 @@
    int i1 = ((int*)code_buffer)[1];
    int* contention_addr = (int*) n_call->addr_at(1*BytesPerInstWord);
    assert(inv_op(*contention_addr) == Assembler::arith_op ||
-          *contention_addr == nop_instruction() || !VM_Version::v9_instructions_work(),
+          *contention_addr == nop_instruction(),
           "must not interfere with original call");
    // The set_long_at calls do the ICacheInvalidate so we just need to do them in reverse order
    n_call->set_long_at(1*BytesPerInstWord, i1);
@@ -181,7 +181,7 @@
    // Make sure the first-patched instruction, which may co-exist
    // briefly with the call, will do something harmless.
    assert(inv_op(*contention_addr) == Assembler::arith_op ||
-          *contention_addr == nop_instruction() || !VM_Version::v9_instructions_work(),
+          *contention_addr == nop_instruction(),
           "must not interfere with original call");
 }
 
@@ -933,11 +933,7 @@
   int code_size = 1 * BytesPerInstWord;
   CodeBuffer cb(verified_entry, code_size + 1);
   MacroAssembler* a = new MacroAssembler(&cb);
-  if (VM_Version::v9_instructions_work()) {
-    a->ldsw(G0, 0, O7); // "ld" must agree with code in the signal handler
-  } else {
-    a->lduw(G0, 0, O7); // "ld" must agree with code in the signal handler
-  }
+  a->ldsw(G0, 0, O7); // "ld" must agree with code in the signal handler
   ICache::invalidate_range(verified_entry, code_size);
 }
 
@@ -1024,7 +1020,7 @@
    int i1 = ((int*)code_buffer)[1];
    int* contention_addr = (int*) h_jump->addr_at(1*BytesPerInstWord);
    assert(inv_op(*contention_addr) == Assembler::arith_op ||
-          *contention_addr == nop_instruction() || !VM_Version::v9_instructions_work(),
+          *contention_addr == nop_instruction(),
           "must not interfere with original call");
    // The set_long_at calls do the ICacheInvalidate so we just need to do them in reverse order
    h_jump->set_long_at(1*BytesPerInstWord, i1);
@@ -1043,6 +1039,6 @@
    // Make sure the first-patched instruction, which may co-exist
    // briefly with the call, will do something harmless.
    assert(inv_op(*contention_addr) == Assembler::arith_op ||
-          *contention_addr == nop_instruction() || !VM_Version::v9_instructions_work(),
+          *contention_addr == nop_instruction(),
           "must not interfere with original call");
 }
--- a/hotspot/src/cpu/sparc/vm/nativeInst_sparc.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/nativeInst_sparc.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -70,8 +70,7 @@
   bool is_zombie() {
     int x = long_at(0);
     return is_op3(x,
-                  VM_Version::v9_instructions_work() ?
-                    Assembler::ldsw_op3 : Assembler::lduw_op3,
+                  Assembler::ldsw_op3,
                   Assembler::ldst_op)
         && Assembler::inv_rs1(x) == G0
         && Assembler::inv_rd(x) == O7;
--- a/hotspot/src/cpu/sparc/vm/register_sparc.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/register_sparc.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -249,12 +249,10 @@
 
       case D:
         assert(c < 64  &&  (c & 1) == 0, "bad double float register");
-        assert(c < 32 || VM_Version::v9_instructions_work(), "V9 float work only on V9 platform");
         return (c & 0x1e) | ((c & 0x20) >> 5);
 
       case Q:
         assert(c < 64  &&  (c & 3) == 0, "bad quad float register");
-        assert(c < 32 || VM_Version::v9_instructions_work(), "V9 float work only on V9 platform");
         return (c & 0x1c) | ((c & 0x20) >> 5);
     }
     ShouldNotReachHere();
--- a/hotspot/src/cpu/sparc/vm/sharedRuntime_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/sharedRuntime_sparc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -2459,7 +2459,7 @@
 
   // Finally just about ready to make the JNI call
 
-  __ flush_windows();
+  __ flushw();
   if (inner_frame_created) {
     __ restore();
   } else {
--- a/hotspot/src/cpu/sparc/vm/sparc.ad	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/sparc.ad	Wed Jul 05 19:00:49 2017 +0200
@@ -2778,10 +2778,7 @@
     Register Rold = reg_to_register_object($old$$reg);
     Register Rnew = reg_to_register_object($new$$reg);
 
-    // casx_under_lock picks 1 of 3 encodings:
-    // For 32-bit pointers you get a 32-bit CAS
-    // For 64-bit pointers you get a 64-bit CASX
-    __ casn(Rmem, Rold, Rnew); // Swap(*Rmem,Rnew) if *Rmem == Rold
+    __ cas_ptr(Rmem, Rold, Rnew); // Swap(*Rmem,Rnew) if *Rmem == Rold
     __ cmp( Rold, Rnew );
   %}
 
@@ -3067,7 +3064,7 @@
     AddressLiteral last_rethrow_addrlit(&last_rethrow);
     __ sethi(last_rethrow_addrlit, L1);
     Address addr(L1, last_rethrow_addrlit.low10());
-    __ get_pc(L2);
+    __ rdpc(L2);
     __ inc(L2, 3 * BytesPerInstWord);  // skip this & 2 more insns to point at jump_to
     __ st_ptr(L2, addr);
     __ restore();
--- a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -566,7 +566,7 @@
     StubCodeMark mark(this, "StubRoutines", "flush_callers_register_windows");
     address start = __ pc();
 
-    __ flush_windows();
+    __ flushw();
     __ retl(false);
     __ delayed()->add( FP, STACK_BIAS, O0 );
     // The returned value must be a stack pointer whose register save area
@@ -575,67 +575,9 @@
     return start;
   }
 
-  // Helper functions for v8 atomic operations.
-  //
-  void get_v8_oop_lock_ptr(Register lock_ptr_reg, Register mark_oop_reg, Register scratch_reg) {
-    if (mark_oop_reg == noreg) {
-      address lock_ptr = (address)StubRoutines::Sparc::atomic_memory_operation_lock_addr();
-      __ set((intptr_t)lock_ptr, lock_ptr_reg);
-    } else {
-      assert(scratch_reg != noreg, "just checking");
-      address lock_ptr = (address)StubRoutines::Sparc::_v8_oop_lock_cache;
-      __ set((intptr_t)lock_ptr, lock_ptr_reg);
-      __ and3(mark_oop_reg, StubRoutines::Sparc::v8_oop_lock_mask_in_place, scratch_reg);
-      __ add(lock_ptr_reg, scratch_reg, lock_ptr_reg);
-    }
-  }
-
-  void generate_v8_lock_prologue(Register lock_reg, Register lock_ptr_reg, Register yield_reg, Label& retry, Label& dontyield, Register mark_oop_reg = noreg, Register scratch_reg = noreg) {
-
-    get_v8_oop_lock_ptr(lock_ptr_reg, mark_oop_reg, scratch_reg);
-    __ set(StubRoutines::Sparc::locked, lock_reg);
-    // Initialize yield counter
-    __ mov(G0,yield_reg);
-
-    __ BIND(retry);
-    __ cmp_and_br_short(yield_reg, V8AtomicOperationUnderLockSpinCount, Assembler::less, Assembler::pt, dontyield);
-
-    // This code can only be called from inside the VM, this
-    // stub is only invoked from Atomic::add().  We do not
-    // want to use call_VM, because _last_java_sp and such
-    // must already be set.
-    //
-    // Save the regs and make space for a C call
-    __ save(SP, -96, SP);
-    __ save_all_globals_into_locals();
-    BLOCK_COMMENT("call os::naked_sleep");
-    __ call(CAST_FROM_FN_PTR(address, os::naked_sleep));
-    __ delayed()->nop();
-    __ restore_globals_from_locals();
-    __ restore();
-    // reset the counter
-    __ mov(G0,yield_reg);
-
-    __ BIND(dontyield);
-
-    // try to get lock
-    __ swap(lock_ptr_reg, 0, lock_reg);
-
-    // did we get the lock?
-    __ cmp(lock_reg, StubRoutines::Sparc::unlocked);
-    __ br(Assembler::notEqual, true, Assembler::pn, retry);
-    __ delayed()->add(yield_reg,1,yield_reg);
-
-    // yes, got lock. do the operation here.
-  }
-
-  void generate_v8_lock_epilogue(Register lock_reg, Register lock_ptr_reg, Register yield_reg, Label& retry, Label& dontyield, Register mark_oop_reg = noreg, Register scratch_reg = noreg) {
-    __ st(lock_reg, lock_ptr_reg, 0); // unlock
-  }
-
   // Support for jint Atomic::xchg(jint exchange_value, volatile jint* dest).
   //
-  // Arguments :
+  // Arguments:
   //
   //      exchange_value: O0
   //      dest:           O1
@@ -656,33 +598,14 @@
       __ mov(O0, O3);       // scratch copy of exchange value
       __ ld(O1, 0, O2);     // observe the previous value
       // try to replace O2 with O3
-      __ cas_under_lock(O1, O2, O3,
-      (address)StubRoutines::Sparc::atomic_memory_operation_lock_addr(),false);
+      __ cas(O1, O2, O3);
       __ cmp_and_br_short(O2, O3, Assembler::notEqual, Assembler::pn, retry);
 
       __ retl(false);
       __ delayed()->mov(O2, O0);  // report previous value to caller
-
     } else {
-      if (VM_Version::v9_instructions_work()) {
-        __ retl(false);
-        __ delayed()->swap(O1, 0, O0);
-      } else {
-        const Register& lock_reg = O2;
-        const Register& lock_ptr_reg = O3;
-        const Register& yield_reg = O4;
-
-        Label retry;
-        Label dontyield;
-
-        generate_v8_lock_prologue(lock_reg, lock_ptr_reg, yield_reg, retry, dontyield);
-        // got the lock, do the swap
-        __ swap(O1, 0, O0);
-
-        generate_v8_lock_epilogue(lock_reg, lock_ptr_reg, yield_reg, retry, dontyield);
-        __ retl(false);
-        __ delayed()->nop();
-      }
+      __ retl(false);
+      __ delayed()->swap(O1, 0, O0);
     }
 
     return start;
@@ -691,7 +614,7 @@
 
   // Support for jint Atomic::cmpxchg(jint exchange_value, volatile jint* dest, jint compare_value)
   //
-  // Arguments :
+  // Arguments:
   //
   //      exchange_value: O0
   //      dest:           O1
@@ -701,15 +624,12 @@
   //
   //     O0: the value previously stored in dest
   //
-  // Overwrites (v8): O3,O4,O5
-  //
   address generate_atomic_cmpxchg() {
     StubCodeMark mark(this, "StubRoutines", "atomic_cmpxchg");
     address start = __ pc();
 
     // cmpxchg(dest, compare_value, exchange_value)
-    __ cas_under_lock(O1, O2, O0,
-      (address)StubRoutines::Sparc::atomic_memory_operation_lock_addr(),false);
+    __ cas(O1, O2, O0);
     __ retl(false);
     __ delayed()->nop();
 
@@ -718,7 +638,7 @@
 
   // Support for jlong Atomic::cmpxchg(jlong exchange_value, volatile jlong *dest, jlong compare_value)
   //
-  // Arguments :
+  // Arguments:
   //
   //      exchange_value: O1:O0
   //      dest:           O2
@@ -728,17 +648,12 @@
   //
   //     O1:O0: the value previously stored in dest
   //
-  // This only works on V9, on V8 we don't generate any
-  // code and just return NULL.
-  //
   // Overwrites: G1,G2,G3
   //
   address generate_atomic_cmpxchg_long() {
     StubCodeMark mark(this, "StubRoutines", "atomic_cmpxchg_long");
     address start = __ pc();
 
-    if (!VM_Version::supports_cx8())
-        return NULL;;
     __ sllx(O0, 32, O0);
     __ srl(O1, 0, O1);
     __ or3(O0,O1,O0);      // O0 holds 64-bit value from compare_value
@@ -756,7 +671,7 @@
 
   // Support for jint Atomic::add(jint add_value, volatile jint* dest).
   //
-  // Arguments :
+  // Arguments:
   //
   //      add_value: O0   (e.g., +1 or -1)
   //      dest:      O1
@@ -765,47 +680,22 @@
   //
   //     O0: the new value stored in dest
   //
-  // Overwrites (v9): O3
-  // Overwrites (v8): O3,O4,O5
+  // Overwrites: O3
   //
   address generate_atomic_add() {
     StubCodeMark mark(this, "StubRoutines", "atomic_add");
     address start = __ pc();
     __ BIND(_atomic_add_stub);
 
-    if (VM_Version::v9_instructions_work()) {
-      Label(retry);
-      __ BIND(retry);
-
-      __ lduw(O1, 0, O2);
-      __ add(O0, O2, O3);
-      __ cas(O1, O2, O3);
-      __ cmp_and_br_short(O2, O3, Assembler::notEqual, Assembler::pn, retry);
-      __ retl(false);
-      __ delayed()->add(O0, O2, O0); // note that cas made O2==O3
-    } else {
-      const Register& lock_reg = O2;
-      const Register& lock_ptr_reg = O3;
-      const Register& value_reg = O4;
-      const Register& yield_reg = O5;
-
-      Label(retry);
-      Label(dontyield);
-
-      generate_v8_lock_prologue(lock_reg, lock_ptr_reg, yield_reg, retry, dontyield);
-      // got lock, do the increment
-      __ ld(O1, 0, value_reg);
-      __ add(O0, value_reg, value_reg);
-      __ st(value_reg, O1, 0);
-
-      // %%% only for RMO and PSO
-      __ membar(Assembler::StoreStore);
-
-      generate_v8_lock_epilogue(lock_reg, lock_ptr_reg, yield_reg, retry, dontyield);
-
-      __ retl(false);
-      __ delayed()->mov(value_reg, O0);
-    }
+    Label(retry);
+    __ BIND(retry);
+
+    __ lduw(O1, 0, O2);
+    __ add(O0, O2, O3);
+    __ cas(O1, O2, O3);
+    __ cmp_and_br_short(O2, O3, Assembler::notEqual, Assembler::pn, retry);
+    __ retl(false);
+    __ delayed()->add(O0, O2, O0); // note that cas made O2==O3
 
     return start;
   }
@@ -841,7 +731,7 @@
     __ mov(G3, L3);
     __ mov(G4, L4);
     __ mov(G5, L5);
-    for (i = 0; i < (VM_Version::v9_instructions_work() ? 64 : 32); i += 2) {
+    for (i = 0; i < 64; i += 2) {
       __ stf(FloatRegisterImpl::D, as_FloatRegister(i), preserve_addr, i * wordSize);
     }
 
@@ -855,7 +745,7 @@
     __ mov(L3, G3);
     __ mov(L4, G4);
     __ mov(L5, G5);
-    for (i = 0; i < (VM_Version::v9_instructions_work() ? 64 : 32); i += 2) {
+    for (i = 0; i < 64; i += 2) {
       __ ldf(FloatRegisterImpl::D, preserve_addr, as_FloatRegister(i), i * wordSize);
     }
 
--- a/hotspot/src/cpu/sparc/vm/stubRoutines_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/stubRoutines_sparc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -52,7 +52,3 @@
 address StubRoutines::Sparc::_flush_callers_register_windows_entry = CAST_FROM_FN_PTR(address, bootstrap_flush_windows);
 
 address StubRoutines::Sparc::_partial_subtype_check = NULL;
-
-int StubRoutines::Sparc::_atomic_memory_operation_lock = StubRoutines::Sparc::unlocked;
-
-int StubRoutines::Sparc::_v8_oop_lock_cache[StubRoutines::Sparc::nof_v8_oop_lock_cache_entries];
--- a/hotspot/src/cpu/sparc/vm/stubRoutines_sparc.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/stubRoutines_sparc.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -47,46 +47,14 @@
 class Sparc {
  friend class StubGenerator;
 
- public:
-  enum { nof_instance_allocators = 10 };
-
-  // allocator lock values
-  enum {
-    unlocked = 0,
-    locked   = 1
-  };
-
-  enum {
-    v8_oop_lock_ignore_bits = 2,
-    v8_oop_lock_bits = 4,
-    nof_v8_oop_lock_cache_entries = 1 << (v8_oop_lock_bits+v8_oop_lock_ignore_bits),
-    v8_oop_lock_mask = right_n_bits(v8_oop_lock_bits),
-    v8_oop_lock_mask_in_place = v8_oop_lock_mask << v8_oop_lock_ignore_bits
-  };
-
-  static int _v8_oop_lock_cache[nof_v8_oop_lock_cache_entries];
-
  private:
   static address _test_stop_entry;
   static address _stop_subroutine_entry;
   static address _flush_callers_register_windows_entry;
 
-  static int _atomic_memory_operation_lock;
-
   static address _partial_subtype_check;
 
  public:
-  // %%% global lock for everyone who needs to use atomic_compare_and_exchange
-  // %%% or atomic_increment -- should probably use more locks for more
-  // %%% scalability-- for instance one for each eden space or group of
-
-  // address of the lock for atomic_compare_and_exchange
-  static int* atomic_memory_operation_lock_addr() { return &_atomic_memory_operation_lock; }
-
-  // accessor and mutator for _atomic_memory_operation_lock
-  static int atomic_memory_operation_lock() { return _atomic_memory_operation_lock; }
-  static void set_atomic_memory_operation_lock(int value) { _atomic_memory_operation_lock = value; }
-
   // test assembler stop routine by setting registers
   static void (*test_stop_entry()) ()                     { return CAST_TO_FN_PTR(void (*)(void), _test_stop_entry); }
 
--- a/hotspot/src/cpu/sparc/vm/templateInterpreter_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/templateInterpreter_sparc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1054,7 +1054,7 @@
   // flush the windows now. We don't care about the current (protection) frame
   // only the outer frames
 
-  __ flush_windows();
+  __ flushw();
 
   // mark windows as flushed
   Address flags(G2_thread, JavaThread::frame_anchor_offset() + JavaFrameAnchor::flags_offset());
--- a/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/templateTable_sparc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1338,14 +1338,13 @@
 
 void TemplateTable::fneg() {
   transition(ftos, ftos);
-  __ fneg(FloatRegisterImpl::S, Ftos_f);
+  __ fneg(FloatRegisterImpl::S, Ftos_f, Ftos_f);
 }
 
 
 void TemplateTable::dneg() {
   transition(dtos, dtos);
-  // v8 has fnegd if source and dest are the same
-  __ fneg(FloatRegisterImpl::D, Ftos_f);
+  __ fneg(FloatRegisterImpl::D, Ftos_f, Ftos_f);
 }
 
 
@@ -1470,19 +1469,10 @@
     __ st_long(Otos_l, __ d_tmp);
     __ ldf(FloatRegisterImpl::D, __ d_tmp, Ftos_d);
 
-    if (VM_Version::v9_instructions_work()) {
-      if (bytecode() == Bytecodes::_l2f) {
-        __ fxtof(FloatRegisterImpl::S, Ftos_d, Ftos_f);
-      } else {
-        __ fxtof(FloatRegisterImpl::D, Ftos_d, Ftos_d);
-      }
+    if (bytecode() == Bytecodes::_l2f) {
+      __ fxtof(FloatRegisterImpl::S, Ftos_d, Ftos_f);
     } else {
-      __ call_VM_leaf(
-        Lscratch,
-        bytecode() == Bytecodes::_l2f
-          ? CAST_FROM_FN_PTR(address, SharedRuntime::l2f)
-          : CAST_FROM_FN_PTR(address, SharedRuntime::l2d)
-      );
+      __ fxtof(FloatRegisterImpl::D, Ftos_d, Ftos_d);
     }
     break;
 
@@ -1490,11 +1480,6 @@
       Label isNaN;
       // result must be 0 if value is NaN; test by comparing value to itself
       __ fcmp(FloatRegisterImpl::S, Assembler::fcc0, Ftos_f, Ftos_f);
-      // According to the v8 manual, you have to have a non-fp instruction
-      // between fcmp and fb.
-      if (!VM_Version::v9_instructions_work()) {
-        __ nop();
-      }
       __ fb(Assembler::f_unordered, true, Assembler::pn, isNaN);
       __ delayed()->clr(Otos_i);                                     // NaN
       __ ftoi(FloatRegisterImpl::S, Ftos_f, F30);
@@ -1537,16 +1522,7 @@
     break;
 
     case Bytecodes::_d2f:
-    if (VM_Version::v9_instructions_work()) {
       __ ftof( FloatRegisterImpl::D, FloatRegisterImpl::S, Ftos_d, Ftos_f);
-    }
-    else {
-      // must uncache tos
-      __ push_d();
-      __ pop_i(O0);
-      __ pop_i(O1);
-      __ call_VM_leaf(Lscratch, CAST_FROM_FN_PTR(address, SharedRuntime::d2f));
-    }
     break;
 
     default: ShouldNotReachHere();
@@ -1956,17 +1932,8 @@
     __ ld( Rarray, Rscratch, Rscratch );
     // (Rscratch is already in the native byte-ordering.)
     __ cmp( Rkey, Rscratch );
-    if ( VM_Version::v9_instructions_work() ) {
-      __ movcc( Assembler::less,         false, Assembler::icc, Rh, Rj );  // j = h if (key <  array[h].fast_match())
-      __ movcc( Assembler::greaterEqual, false, Assembler::icc, Rh, Ri );  // i = h if (key >= array[h].fast_match())
-    }
-    else {
-      Label end_of_if;
-      __ br( Assembler::less, true, Assembler::pt, end_of_if );
-      __ delayed()->mov( Rh, Rj ); // if (<) Rj = Rh
-      __ mov( Rh, Ri );            // else i = h
-      __ bind(end_of_if);          // }
-    }
+    __ movcc( Assembler::less,         false, Assembler::icc, Rh, Rj );  // j = h if (key <  array[h].fast_match())
+    __ movcc( Assembler::greaterEqual, false, Assembler::icc, Rh, Ri );  // i = h if (key >= array[h].fast_match())
 
     // while (i+1 < j)
     __ bind( entry );
@@ -3418,9 +3385,7 @@
     // has been allocated.
     __ cmp_and_brx_short(RnewTopValue, RendValue, Assembler::greaterUnsigned, Assembler::pn, slow_case);
 
-    __ casx_under_lock(RtopAddr, RoldTopValue, RnewTopValue,
-      VM_Version::v9_instructions_work() ? NULL :
-      (address)StubRoutines::Sparc::atomic_memory_operation_lock_addr());
+    __ cas_ptr(RtopAddr, RoldTopValue, RnewTopValue);
 
     // if someone beat us on the allocation, try again, otherwise continue
     __ cmp_and_brx_short(RoldTopValue, RnewTopValue, Assembler::notEqual, Assembler::pn, retry);
@@ -3701,14 +3666,7 @@
 
     __ verify_oop(O4);          // verify each monitor's oop
     __ tst(O4); // is this entry unused?
-    if (VM_Version::v9_instructions_work())
-      __ movcc( Assembler::zero, false, Assembler::ptr_cc, O3, O1);
-    else {
-      Label L;
-      __ br( Assembler::zero, true, Assembler::pn, L );
-      __ delayed()->mov(O3, O1); // rememeber this one if match
-      __ bind(L);
-    }
+    __ movcc( Assembler::zero, false, Assembler::ptr_cc, O3, O1);
 
     __ cmp(O4, O0); // check if current entry is for same object
     __ brx( Assembler::equal, false, Assembler::pn, exit );
--- a/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -75,23 +75,14 @@
     FLAG_SET_DEFAULT(AllocatePrefetchStyle, 1);
   }
 
-  if (has_v9()) {
-    assert(ArraycopySrcPrefetchDistance < 4096, "invalid value");
-    if (ArraycopySrcPrefetchDistance >= 4096)
-      ArraycopySrcPrefetchDistance = 4064;
-    assert(ArraycopyDstPrefetchDistance < 4096, "invalid value");
-    if (ArraycopyDstPrefetchDistance >= 4096)
-      ArraycopyDstPrefetchDistance = 4064;
-  } else {
-    if (ArraycopySrcPrefetchDistance > 0) {
-      warning("prefetch instructions are not available on this CPU");
-      FLAG_SET_DEFAULT(ArraycopySrcPrefetchDistance, 0);
-    }
-    if (ArraycopyDstPrefetchDistance > 0) {
-      warning("prefetch instructions are not available on this CPU");
-      FLAG_SET_DEFAULT(ArraycopyDstPrefetchDistance, 0);
-    }
-  }
+  guarantee(VM_Version::has_v9(), "only SPARC v9 is supported");
+
+  assert(ArraycopySrcPrefetchDistance < 4096, "invalid value");
+  if (ArraycopySrcPrefetchDistance >= 4096)
+    ArraycopySrcPrefetchDistance = 4064;
+  assert(ArraycopyDstPrefetchDistance < 4096, "invalid value");
+  if (ArraycopyDstPrefetchDistance >= 4096)
+    ArraycopyDstPrefetchDistance = 4064;
 
   UseSSE = 0; // Only on x86 and x64
 
--- a/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -177,10 +177,6 @@
     return AllocatePrefetchDistance > 0 ? AllocatePrefetchStyle : 0;
   }
 
-  // Legacy
-  static bool v8_instructions_work() { return has_v8() && !has_v9(); }
-  static bool v9_instructions_work() { return has_v9(); }
-
   // Assembler testing
   static void allow_all();
   static void revert();
--- a/hotspot/src/cpu/x86/vm/globals_x86.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/globals_x86.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -55,7 +55,7 @@
 define_pd_global(intx, InlineFrequencyCount,     100);
 define_pd_global(intx, InlineSmallCode,          1000);
 
-define_pd_global(intx, StackYellowPages, 2);
+define_pd_global(intx, StackYellowPages, NOT_WINDOWS(2) WINDOWS_ONLY(3));
 define_pd_global(intx, StackRedPages, 1);
 #ifdef AMD64
 // Very large C++ stack frames using solaris-amd64 optimized builds
--- a/hotspot/src/cpu/x86/vm/sharedRuntime_x86_64.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/sharedRuntime_x86_64.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1429,6 +1429,8 @@
   assert(!length_arg.first()->is_Register() || length_arg.first()->as_Register() != tmp_reg,
          "possible collision");
 
+  __ block_comment("unpack_array_argument {");
+
   // Pass the length, ptr pair
   Label is_null, done;
   VMRegPair tmp;
@@ -1453,6 +1455,8 @@
   move_ptr(masm, tmp, body_arg);
   move32_64(masm, tmp, length_arg);
   __ bind(done);
+
+  __ block_comment("} unpack_array_argument");
 }
 
 
@@ -2170,27 +2174,34 @@
     }
   }
 
-  // point c_arg at the first arg that is already loaded in case we
-  // need to spill before we call out
-  int c_arg = total_c_args - total_in_args;
+  int c_arg;
 
   // Pre-load a static method's oop into r14.  Used both by locking code and
   // the normal JNI call code.
-  if (method->is_static() && !is_critical_native) {
-
-    //  load oop into a register
-    __ movoop(oop_handle_reg, JNIHandles::make_local(method->method_holder()->java_mirror()));
-
-    // Now handlize the static class mirror it's known not-null.
-    __ movptr(Address(rsp, klass_offset), oop_handle_reg);
-    map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
-
-    // Now get the handle
-    __ lea(oop_handle_reg, Address(rsp, klass_offset));
-    // store the klass handle as second argument
-    __ movptr(c_rarg1, oop_handle_reg);
-    // and protect the arg if we must spill
-    c_arg--;
+  if (!is_critical_native) {
+    // point c_arg at the first arg that is already loaded in case we
+    // need to spill before we call out
+    c_arg = total_c_args - total_in_args;
+
+    if (method->is_static()) {
+
+      //  load oop into a register
+      __ movoop(oop_handle_reg, JNIHandles::make_local(method->method_holder()->java_mirror()));
+
+      // Now handlize the static class mirror it's known not-null.
+      __ movptr(Address(rsp, klass_offset), oop_handle_reg);
+      map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
+
+      // Now get the handle
+      __ lea(oop_handle_reg, Address(rsp, klass_offset));
+      // store the klass handle as second argument
+      __ movptr(c_rarg1, oop_handle_reg);
+      // and protect the arg if we must spill
+      c_arg--;
+    }
+  } else {
+    // For JNI critical methods we need to save all registers in save_args.
+    c_arg = 0;
   }
 
   // Change state to native (we save the return address in the thread, since it might not
--- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -83,7 +83,7 @@
  private:
 
 #ifdef PRODUCT
-#define inc_counter_np(counter) (0)
+#define inc_counter_np(counter) ((void)0)
 #else
   void inc_counter_np_(int& counter) {
     __ incrementl(ExternalAddress((address)&counter));
--- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -81,7 +81,7 @@
  private:
 
 #ifdef PRODUCT
-#define inc_counter_np(counter) (0)
+#define inc_counter_np(counter) ((void)0)
 #else
   void inc_counter_np_(int& counter) {
     // This can destroy rscratch1 if counter is far from the code cache
--- a/hotspot/src/os/bsd/dtrace/jvm_dtrace.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/bsd/dtrace/jvm_dtrace.c	Wed Jul 05 19:00:49 2017 +0200
@@ -122,9 +122,7 @@
 }
 
 static int file_close(int fd) {
-    int ret;
-    RESTARTABLE(close(fd), ret);
-    return ret;
+    return close(fd);
 }
 
 static int file_read(int fd, char* buf, int len) {
--- a/hotspot/src/os/bsd/vm/attachListener_bsd.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/bsd/vm/attachListener_bsd.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -199,7 +199,7 @@
   ::unlink(initial_path);
   int res = ::bind(listener, (struct sockaddr*)&addr, sizeof(addr));
   if (res == -1) {
-    RESTARTABLE(::close(listener), res);
+    ::close(listener);
     return -1;
   }
 
@@ -217,7 +217,7 @@
     }
   }
   if (res == -1) {
-    RESTARTABLE(::close(listener), res);
+    ::close(listener);
     ::unlink(initial_path);
     return -1;
   }
@@ -345,24 +345,21 @@
     uid_t puid;
     gid_t pgid;
     if (::getpeereid(s, &puid, &pgid) != 0) {
-      int res;
-      RESTARTABLE(::close(s), res);
+      ::close(s);
       continue;
     }
     uid_t euid = geteuid();
     gid_t egid = getegid();
 
     if (puid != euid || pgid != egid) {
-      int res;
-      RESTARTABLE(::close(s), res);
+      ::close(s);
       continue;
     }
 
     // peer credential look okay so we read the request
     BsdAttachOperation* op = read_request(s);
     if (op == NULL) {
-      int res;
-      RESTARTABLE(::close(s), res);
+      ::close(s);
       continue;
     } else {
       return op;
@@ -413,7 +410,7 @@
   }
 
   // done
-  RESTARTABLE(::close(this->socket()), rc);
+  ::close(this->socket());
 
   // were we externally suspended while we were waiting?
   thread->check_and_wait_while_suspended();
--- a/hotspot/src/os/bsd/vm/os_bsd.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/bsd/vm/os_bsd.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -2074,6 +2074,13 @@
   }
 }
 
+static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
+                                    int err) {
+  warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
+          ", %d) failed; error='%s' (errno=%d)", addr, size, exec,
+          strerror(err), err);
+}
+
 // NOTE: Bsd kernel does not really reserve the pages for us.
 //       All it does is to check if there are enough free pages
 //       left at the time of mmap(). This could be a potential
@@ -2082,18 +2089,45 @@
   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
 #ifdef __OpenBSD__
   // XXX: Work-around mmap/MAP_FIXED bug temporarily on OpenBSD
-  return ::mprotect(addr, size, prot) == 0;
+  if (::mprotect(addr, size, prot) == 0) {
+    return true;
+  }
 #else
   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
                                    MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
-  return res != (uintptr_t) MAP_FAILED;
+  if (res != (uintptr_t) MAP_FAILED) {
+    return true;
+  }
 #endif
+
+  // Warn about any commit errors we see in non-product builds just
+  // in case mmap() doesn't work as described on the man page.
+  NOT_PRODUCT(warn_fail_commit_memory(addr, size, exec, errno);)
+
+  return false;
 }
 
-
 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
                        bool exec) {
-  return commit_memory(addr, size, exec);
+  // alignment_hint is ignored on this OS
+  return pd_commit_memory(addr, size, exec);
+}
+
+void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
+                                  const char* mesg) {
+  assert(mesg != NULL, "mesg must be specified");
+  if (!pd_commit_memory(addr, size, exec)) {
+    // add extra info in product mode for vm_exit_out_of_memory():
+    PRODUCT_ONLY(warn_fail_commit_memory(addr, size, exec, errno);)
+    vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
+  }
+}
+
+void os::pd_commit_memory_or_exit(char* addr, size_t size,
+                                  size_t alignment_hint, bool exec,
+                                  const char* mesg) {
+  // alignment_hint is ignored on this OS
+  pd_commit_memory_or_exit(addr, size, exec, mesg);
 }
 
 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
@@ -2148,7 +2182,7 @@
 }
 
 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
-  return os::commit_memory(addr, size);
+  return os::commit_memory(addr, size, !ExecMem);
 }
 
 // If this is a growable mapping, remove the guard pages entirely by
@@ -2320,21 +2354,20 @@
   }
 
   // The memory is committed
-  address pc = CALLER_PC;
-  MemTracker::record_virtual_memory_reserve((address)addr, bytes, pc);
-  MemTracker::record_virtual_memory_commit((address)addr, bytes, pc);
+  MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, mtNone, CALLER_PC);
 
   return addr;
 }
 
 bool os::release_memory_special(char* base, size_t bytes) {
+  MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
   // detaching the SHM segment will also delete it, see reserve_memory_special()
   int rslt = shmdt(base);
   if (rslt == 0) {
-    MemTracker::record_virtual_memory_uncommit((address)base, bytes);
-    MemTracker::record_virtual_memory_release((address)base, bytes);
+    tkr.record((address)base, bytes);
     return true;
   } else {
+    tkr.discard();
     return false;
   }
 
@@ -3512,7 +3545,7 @@
 
   if (!UseMembar) {
     address mem_serialize_page = (address) ::mmap(NULL, Bsd::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
-    guarantee( mem_serialize_page != NULL, "mmap Failed for memory serialize page");
+    guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
     os::set_memory_serialize_page( mem_serialize_page );
 
 #ifndef PRODUCT
--- a/hotspot/src/os/bsd/vm/os_bsd.inline.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/bsd/vm/os_bsd.inline.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -178,11 +178,11 @@
 }
 
 inline int os::close(int fd) {
-  RESTARTABLE_RETURN_INT(::close(fd));
+  return ::close(fd);
 }
 
 inline int os::socket_close(int fd) {
-  RESTARTABLE_RETURN_INT(::close(fd));
+  return ::close(fd);
 }
 
 inline int os::socket(int domain, int type, int protocol) {
--- a/hotspot/src/os/bsd/vm/perfMemory_bsd.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/bsd/vm/perfMemory_bsd.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -60,7 +60,7 @@
   }
 
   // commit memory
-  if (!os::commit_memory(mapAddress, size)) {
+  if (!os::commit_memory(mapAddress, size, !ExecMem)) {
     if (PrintMiscellaneous && Verbose) {
       warning("Could not commit PerfData memory\n");
     }
@@ -120,7 +120,7 @@
       addr += result;
     }
 
-    RESTARTABLE(::close(fd), result);
+    result = ::close(fd);
     if (PrintMiscellaneous && Verbose) {
       if (result == OS_ERR) {
         warning("Could not close %s: %s\n", destfile, strerror(errno));
@@ -632,7 +632,7 @@
     if (PrintMiscellaneous && Verbose) {
       warning("could not set shared memory file size: %s\n", strerror(errno));
     }
-    RESTARTABLE(::close(fd), result);
+    ::close(fd);
     return -1;
   }
 
@@ -656,7 +656,7 @@
   if (result != -1) {
     return fd;
   } else {
-    RESTARTABLE(::close(fd), result);
+    ::close(fd);
     return -1;
   }
 }
@@ -734,9 +734,7 @@
 
   mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
 
-  // attempt to close the file - restart it if it was interrupted,
-  // but ignore other failures
-  RESTARTABLE(::close(fd), result);
+  result = ::close(fd);
   assert(result != OS_ERR, "could not close file");
 
   if (mapAddress == MAP_FAILED) {
@@ -755,8 +753,7 @@
   (void)::memset((void*) mapAddress, 0, size);
 
   // it does not go through os api, the operation has to record from here
-  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC);
-  MemTracker::record_virtual_memory_type((address)mapAddress, mtInternal);
+  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, mtInternal, CURRENT_PC);
 
   return mapAddress;
 }
@@ -909,7 +906,7 @@
 
   // attempt to close the file - restart if it gets interrupted,
   // but ignore other failures
-  RESTARTABLE(::close(fd), result);
+  result = ::close(fd);
   assert(result != OS_ERR, "could not close file");
 
   if (mapAddress == MAP_FAILED) {
@@ -921,8 +918,7 @@
   }
 
   // it does not go through os api, the operation has to record from here
-  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC);
-  MemTracker::record_virtual_memory_type((address)mapAddress, mtInternal);
+  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, mtInternal, CURRENT_PC);
 
   *addr = mapAddress;
   *sizep = size;
--- a/hotspot/src/os/linux/vm/attachListener_linux.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/linux/vm/attachListener_linux.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -199,7 +199,7 @@
   ::unlink(initial_path);
   int res = ::bind(listener, (struct sockaddr*)&addr, sizeof(addr));
   if (res == -1) {
-    RESTARTABLE(::close(listener), res);
+    ::close(listener);
     return -1;
   }
 
@@ -212,7 +212,7 @@
       }
   }
   if (res == -1) {
-    RESTARTABLE(::close(listener), res);
+    ::close(listener);
     ::unlink(initial_path);
     return -1;
   }
@@ -340,24 +340,21 @@
     struct ucred cred_info;
     socklen_t optlen = sizeof(cred_info);
     if (::getsockopt(s, SOL_SOCKET, SO_PEERCRED, (void*)&cred_info, &optlen) == -1) {
-      int res;
-      RESTARTABLE(::close(s), res);
+      ::close(s);
       continue;
     }
     uid_t euid = geteuid();
     gid_t egid = getegid();
 
     if (cred_info.uid != euid || cred_info.gid != egid) {
-      int res;
-      RESTARTABLE(::close(s), res);
+      ::close(s);
       continue;
     }
 
     // peer credential look okay so we read the request
     LinuxAttachOperation* op = read_request(s);
     if (op == NULL) {
-      int res;
-      RESTARTABLE(::close(s), res);
+      ::close(s);
       continue;
     } else {
       return op;
@@ -408,7 +405,7 @@
   }
 
   // done
-  RESTARTABLE(::close(this->socket()), rc);
+  ::close(this->socket());
 
   // were we externally suspended while we were waiting?
   thread->check_and_wait_while_suspended();
--- a/hotspot/src/os/linux/vm/os_linux.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/linux/vm/os_linux.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -2612,11 +2612,49 @@
   }
 }
 
+static bool recoverable_mmap_error(int err) {
+  // See if the error is one we can let the caller handle. This
+  // list of errno values comes from JBS-6843484. I can't find a
+  // Linux man page that documents this specific set of errno
+  // values so while this list currently matches Solaris, it may
+  // change as we gain experience with this failure mode.
+  switch (err) {
+  case EBADF:
+  case EINVAL:
+  case ENOTSUP:
+    // let the caller deal with these errors
+    return true;
+
+  default:
+    // Any remaining errors on this OS can cause our reserved mapping
+    // to be lost. That can cause confusion where different data
+    // structures think they have the same memory mapped. The worst
+    // scenario is if both the VM and a library think they have the
+    // same memory mapped.
+    return false;
+  }
+}
+
+static void warn_fail_commit_memory(char* addr, size_t size, bool exec,
+                                    int err) {
+  warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
+          ", %d) failed; error='%s' (errno=%d)", addr, size, exec,
+          strerror(err), err);
+}
+
+static void warn_fail_commit_memory(char* addr, size_t size,
+                                    size_t alignment_hint, bool exec,
+                                    int err) {
+  warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
+          ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, size,
+          alignment_hint, exec, strerror(err), err);
+}
+
 // NOTE: Linux kernel does not really reserve the pages for us.
 //       All it does is to check if there are enough free pages
 //       left at the time of mmap(). This could be a potential
 //       problem.
-bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
+int os::Linux::commit_memory_impl(char* addr, size_t size, bool exec) {
   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
   uintptr_t res = (uintptr_t) ::mmap(addr, size, prot,
                                    MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0);
@@ -2624,9 +2662,32 @@
     if (UseNUMAInterleaving) {
       numa_make_global(addr, size);
     }
-    return true;
-  }
-  return false;
+    return 0;
+  }
+
+  int err = errno;  // save errno from mmap() call above
+
+  if (!recoverable_mmap_error(err)) {
+    warn_fail_commit_memory(addr, size, exec, err);
+    vm_exit_out_of_memory(size, OOM_MMAP_ERROR, "committing reserved memory.");
+  }
+
+  return err;
+}
+
+bool os::pd_commit_memory(char* addr, size_t size, bool exec) {
+  return os::Linux::commit_memory_impl(addr, size, exec) == 0;
+}
+
+void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
+                                  const char* mesg) {
+  assert(mesg != NULL, "mesg must be specified");
+  int err = os::Linux::commit_memory_impl(addr, size, exec);
+  if (err != 0) {
+    // the caller wants all commit errors to exit with the specified mesg:
+    warn_fail_commit_memory(addr, size, exec, err);
+    vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
+  }
 }
 
 // Define MAP_HUGETLB here so we can build HotSpot on old systems.
@@ -2639,8 +2700,9 @@
 #define MADV_HUGEPAGE 14
 #endif
 
-bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
-                       bool exec) {
+int os::Linux::commit_memory_impl(char* addr, size_t size,
+                                  size_t alignment_hint, bool exec) {
+  int err;
   if (UseHugeTLBFS && alignment_hint > (size_t)vm_page_size()) {
     int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
     uintptr_t res =
@@ -2651,16 +2713,46 @@
       if (UseNUMAInterleaving) {
         numa_make_global(addr, size);
       }
-      return true;
+      return 0;
+    }
+
+    err = errno;  // save errno from mmap() call above
+
+    if (!recoverable_mmap_error(err)) {
+      // However, it is not clear that this loss of our reserved mapping
+      // happens with large pages on Linux or that we cannot recover
+      // from the loss. For now, we just issue a warning and we don't
+      // call vm_exit_out_of_memory(). This issue is being tracked by
+      // JBS-8007074.
+      warn_fail_commit_memory(addr, size, alignment_hint, exec, err);
+//    vm_exit_out_of_memory(size, OOM_MMAP_ERROR,
+//                          "committing reserved memory.");
     }
     // Fall through and try to use small pages
   }
 
-  if (commit_memory(addr, size, exec)) {
+  err = os::Linux::commit_memory_impl(addr, size, exec);
+  if (err == 0) {
     realign_memory(addr, size, alignment_hint);
-    return true;
-  }
-  return false;
+  }
+  return err;
+}
+
+bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
+                          bool exec) {
+  return os::Linux::commit_memory_impl(addr, size, alignment_hint, exec) == 0;
+}
+
+void os::pd_commit_memory_or_exit(char* addr, size_t size,
+                                  size_t alignment_hint, bool exec,
+                                  const char* mesg) {
+  assert(mesg != NULL, "mesg must be specified");
+  int err = os::Linux::commit_memory_impl(addr, size, alignment_hint, exec);
+  if (err != 0) {
+    // the caller wants all commit errors to exit with the specified mesg:
+    warn_fail_commit_memory(addr, size, alignment_hint, exec, err);
+    vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
+  }
 }
 
 void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) {
@@ -2678,7 +2770,7 @@
   // small pages on top of the SHM segment. This method always works for small pages, so we
   // allow that in any case.
   if (alignment_hint <= (size_t)os::vm_page_size() || !UseSHM) {
-    commit_memory(addr, bytes, alignment_hint, false);
+    commit_memory(addr, bytes, alignment_hint, !ExecMem);
   }
 }
 
@@ -2931,7 +3023,7 @@
       ::munmap((void*)stack_extent, (uintptr_t)addr - stack_extent);
   }
 
-  return os::commit_memory(addr, size);
+  return os::commit_memory(addr, size, !ExecMem);
 }
 
 // If this is a growable mapping, remove the guard pages entirely by
@@ -3053,7 +3145,7 @@
                   MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB,
                   -1, 0);
 
-  if (p != (void *) -1) {
+  if (p != MAP_FAILED) {
     // We don't know if this really is a huge page or not.
     FILE *fp = fopen("/proc/self/maps", "r");
     if (fp) {
@@ -3271,22 +3363,21 @@
   }
 
   // The memory is committed
-  address pc = CALLER_PC;
-  MemTracker::record_virtual_memory_reserve((address)addr, bytes, pc);
-  MemTracker::record_virtual_memory_commit((address)addr, bytes, pc);
+  MemTracker::record_virtual_memory_reserve_and_commit((address)addr, bytes, mtNone, CALLER_PC);
 
   return addr;
 }
 
 bool os::release_memory_special(char* base, size_t bytes) {
+  MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
   // detaching the SHM segment will also delete it, see reserve_memory_special()
   int rslt = shmdt(base);
   if (rslt == 0) {
-    MemTracker::record_virtual_memory_uncommit((address)base, bytes);
-    MemTracker::record_virtual_memory_release((address)base, bytes);
+    tkr.record((address)base, bytes);
     return true;
   } else {
-   return false;
+    tkr.discard();
+    return false;
   }
 }
 
@@ -4393,7 +4484,7 @@
 
   if (!UseMembar) {
     address mem_serialize_page = (address) ::mmap(NULL, Linux::page_size(), PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
-    guarantee( mem_serialize_page != NULL, "mmap Failed for memory serialize page");
+    guarantee( mem_serialize_page != MAP_FAILED, "mmap Failed for memory serialize page");
     os::set_memory_serialize_page( mem_serialize_page );
 
 #ifndef PRODUCT
--- a/hotspot/src/os/linux/vm/os_linux.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/linux/vm/os_linux.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -76,6 +76,10 @@
   static julong physical_memory() { return _physical_memory; }
   static void initialize_system_info();
 
+  static int commit_memory_impl(char* addr, size_t bytes, bool exec);
+  static int commit_memory_impl(char* addr, size_t bytes,
+                                size_t alignment_hint, bool exec);
+
   static void set_glibc_version(const char *s)      { _glibc_version = s; }
   static void set_libpthread_version(const char *s) { _libpthread_version = s; }
 
--- a/hotspot/src/os/linux/vm/perfMemory_linux.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/linux/vm/perfMemory_linux.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -60,7 +60,7 @@
   }
 
   // commit memory
-  if (!os::commit_memory(mapAddress, size)) {
+  if (!os::commit_memory(mapAddress, size, !ExecMem)) {
     if (PrintMiscellaneous && Verbose) {
       warning("Could not commit PerfData memory\n");
     }
@@ -120,7 +120,7 @@
       addr += result;
     }
 
-    RESTARTABLE(::close(fd), result);
+    result = ::close(fd);
     if (PrintMiscellaneous && Verbose) {
       if (result == OS_ERR) {
         warning("Could not close %s: %s\n", destfile, strerror(errno));
@@ -632,7 +632,7 @@
     if (PrintMiscellaneous && Verbose) {
       warning("could not set shared memory file size: %s\n", strerror(errno));
     }
-    RESTARTABLE(::close(fd), result);
+    ::close(fd);
     return -1;
   }
 
@@ -656,7 +656,7 @@
   if (result != -1) {
     return fd;
   } else {
-    RESTARTABLE(::close(fd), result);
+    ::close(fd);
     return -1;
   }
 }
@@ -734,9 +734,7 @@
 
   mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
 
-  // attempt to close the file - restart it if it was interrupted,
-  // but ignore other failures
-  RESTARTABLE(::close(fd), result);
+  result = ::close(fd);
   assert(result != OS_ERR, "could not close file");
 
   if (mapAddress == MAP_FAILED) {
@@ -755,8 +753,7 @@
   (void)::memset((void*) mapAddress, 0, size);
 
   // it does not go through os api, the operation has to record from here
-  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC);
-  MemTracker::record_virtual_memory_type((address)mapAddress, mtInternal);
+  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, mtInternal, CURRENT_PC);
 
   return mapAddress;
 }
@@ -907,9 +904,7 @@
 
   mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);
 
-  // attempt to close the file - restart if it gets interrupted,
-  // but ignore other failures
-  RESTARTABLE(::close(fd), result);
+  result = ::close(fd);
   assert(result != OS_ERR, "could not close file");
 
   if (mapAddress == MAP_FAILED) {
@@ -921,8 +916,7 @@
   }
 
   // it does not go through os api, the operation has to record from here
-  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC);
-  MemTracker::record_virtual_memory_type((address)mapAddress, mtInternal);
+  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, mtInternal, CURRENT_PC);
 
   *addr = mapAddress;
   *sizep = size;
--- a/hotspot/src/os/solaris/dtrace/jvm_dtrace.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/solaris/dtrace/jvm_dtrace.c	Wed Jul 05 19:00:49 2017 +0200
@@ -122,9 +122,7 @@
 }
 
 static int file_close(int fd) {
-    int ret;
-    RESTARTABLE(close(fd), ret);
-    return ret;
+    return close(fd);
 }
 
 static int file_read(int fd, char* buf, int len) {
--- a/hotspot/src/os/solaris/vm/attachListener_solaris.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/solaris/vm/attachListener_solaris.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -392,7 +392,7 @@
     return -1;
   }
   assert(fd >= 0, "bad file descriptor");
-  RESTARTABLE(::close(fd), res);
+  ::close(fd);
 
   // attach the door descriptor to the file
   if ((res = ::fattach(dd, initial_path)) == -1) {
@@ -410,7 +410,7 @@
   // rename file so that clients can attach
   if (dd >= 0) {
     if (::rename(initial_path, door_path) == -1) {
-        RESTARTABLE(::close(dd), res);
+        ::close(dd);
         ::fdetach(initial_path);
         dd = -1;
     }
@@ -549,7 +549,7 @@
     }
 
     // close socket and we're done
-    RESTARTABLE(::close(this->socket()), rc);
+    ::close(this->socket());
 
     // were we externally suspended while we were waiting?
     thread->check_and_wait_while_suspended();
--- a/hotspot/src/os/solaris/vm/os_solaris.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/solaris/vm/os_solaris.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -2784,7 +2784,42 @@
   return page_size;
 }
 
-bool os::pd_commit_memory(char* addr, size_t bytes, bool exec) {
+static bool recoverable_mmap_error(int err) {
+  // See if the error is one we can let the caller handle. This
+  // list of errno values comes from the Solaris mmap(2) man page.
+  switch (err) {
+  case EBADF:
+  case EINVAL:
+  case ENOTSUP:
+    // let the caller deal with these errors
+    return true;
+
+  default:
+    // Any remaining errors on this OS can cause our reserved mapping
+    // to be lost. That can cause confusion where different data
+    // structures think they have the same memory mapped. The worst
+    // scenario is if both the VM and a library think they have the
+    // same memory mapped.
+    return false;
+  }
+}
+
+static void warn_fail_commit_memory(char* addr, size_t bytes, bool exec,
+                                    int err) {
+  warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
+          ", %d) failed; error='%s' (errno=%d)", addr, bytes, exec,
+          strerror(err), err);
+}
+
+static void warn_fail_commit_memory(char* addr, size_t bytes,
+                                    size_t alignment_hint, bool exec,
+                                    int err) {
+  warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
+          ", " SIZE_FORMAT ", %d) failed; error='%s' (errno=%d)", addr, bytes,
+          alignment_hint, exec, strerror(err), err);
+}
+
+int os::Solaris::commit_memory_impl(char* addr, size_t bytes, bool exec) {
   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
   size_t size = bytes;
   char *res = Solaris::mmap_chunk(addr, size, MAP_PRIVATE|MAP_FIXED, prot);
@@ -2792,14 +2827,38 @@
     if (UseNUMAInterleaving) {
       numa_make_global(addr, bytes);
     }
-    return true;
-  }
-  return false;
-}
-
-bool os::pd_commit_memory(char* addr, size_t bytes, size_t alignment_hint,
-                       bool exec) {
-  if (commit_memory(addr, bytes, exec)) {
+    return 0;
+  }
+
+  int err = errno;  // save errno from mmap() call in mmap_chunk()
+
+  if (!recoverable_mmap_error(err)) {
+    warn_fail_commit_memory(addr, bytes, exec, err);
+    vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, "committing reserved memory.");
+  }
+
+  return err;
+}
+
+bool os::pd_commit_memory(char* addr, size_t bytes, bool exec) {
+  return Solaris::commit_memory_impl(addr, bytes, exec) == 0;
+}
+
+void os::pd_commit_memory_or_exit(char* addr, size_t bytes, bool exec,
+                                  const char* mesg) {
+  assert(mesg != NULL, "mesg must be specified");
+  int err = os::Solaris::commit_memory_impl(addr, bytes, exec);
+  if (err != 0) {
+    // the caller wants all commit errors to exit with the specified mesg:
+    warn_fail_commit_memory(addr, bytes, exec, err);
+    vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, mesg);
+  }
+}
+
+int os::Solaris::commit_memory_impl(char* addr, size_t bytes,
+                                    size_t alignment_hint, bool exec) {
+  int err = Solaris::commit_memory_impl(addr, bytes, exec);
+  if (err == 0) {
     if (UseMPSS && alignment_hint > (size_t)vm_page_size()) {
       // If the large page size has been set and the VM
       // is using large pages, use the large page size
@@ -2821,9 +2880,25 @@
       // Since this is a hint, ignore any failures.
       (void)Solaris::set_mpss_range(addr, bytes, page_size);
     }
-    return true;
-  }
-  return false;
+  }
+  return err;
+}
+
+bool os::pd_commit_memory(char* addr, size_t bytes, size_t alignment_hint,
+                          bool exec) {
+  return Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec) == 0;
+}
+
+void os::pd_commit_memory_or_exit(char* addr, size_t bytes,
+                                  size_t alignment_hint, bool exec,
+                                  const char* mesg) {
+  assert(mesg != NULL, "mesg must be specified");
+  int err = os::Solaris::commit_memory_impl(addr, bytes, alignment_hint, exec);
+  if (err != 0) {
+    // the caller wants all commit errors to exit with the specified mesg:
+    warn_fail_commit_memory(addr, bytes, alignment_hint, exec, err);
+    vm_exit_out_of_memory(bytes, OOM_MMAP_ERROR, mesg);
+  }
 }
 
 // Uncommit the pages in a specified region.
@@ -2835,7 +2910,7 @@
 }
 
 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
-  return os::commit_memory(addr, size);
+  return os::commit_memory(addr, size, !ExecMem);
 }
 
 bool os::remove_stack_guard_pages(char* addr, size_t size) {
@@ -3457,22 +3532,21 @@
   }
 
   // The memory is committed
-  address pc = CALLER_PC;
-  MemTracker::record_virtual_memory_reserve((address)retAddr, size, pc);
-  MemTracker::record_virtual_memory_commit((address)retAddr, size, pc);
+  MemTracker::record_virtual_memory_reserve_and_commit((address)retAddr, size, mtNone, CURRENT_PC);
 
   return retAddr;
 }
 
 bool os::release_memory_special(char* base, size_t bytes) {
+  MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
   // detaching the SHM segment will also delete it, see reserve_memory_special()
   int rslt = shmdt(base);
   if (rslt == 0) {
-    MemTracker::record_virtual_memory_uncommit((address)base, bytes);
-    MemTracker::record_virtual_memory_release((address)base, bytes);
+    tkr.record((address)base, bytes);
     return true;
   } else {
-   return false;
+    tkr.discard();
+    return false;
   }
 }
 
@@ -6604,11 +6678,11 @@
 }
 
 int os::close(int fd) {
-  RESTARTABLE_RETURN_INT(::close(fd));
+  return ::close(fd);
 }
 
 int os::socket_close(int fd) {
-  RESTARTABLE_RETURN_INT(::close(fd));
+  return ::close(fd);
 }
 
 int os::recv(int fd, char* buf, size_t nBytes, uint flags) {
--- a/hotspot/src/os/solaris/vm/os_solaris.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/solaris/vm/os_solaris.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -168,6 +168,9 @@
   static int _dev_zero_fd;
   static int get_dev_zero_fd() { return _dev_zero_fd; }
   static void set_dev_zero_fd(int fd) { _dev_zero_fd = fd; }
+  static int commit_memory_impl(char* addr, size_t bytes, bool exec);
+  static int commit_memory_impl(char* addr, size_t bytes,
+                                size_t alignment_hint, bool exec);
   static char* mmap_chunk(char *addr, size_t size, int flags, int prot);
   static char* anon_mmap(char* requested_addr, size_t bytes, size_t alignment_hint, bool fixed);
   static bool mpss_sanity_check(bool warn, size_t * page_size);
--- a/hotspot/src/os/solaris/vm/perfMemory_solaris.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/solaris/vm/perfMemory_solaris.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
   }
 
   // commit memory
-  if (!os::commit_memory(mapAddress, size)) {
+  if (!os::commit_memory(mapAddress, size, !ExecMem)) {
     if (PrintMiscellaneous && Verbose) {
       warning("Could not commit PerfData memory\n");
     }
@@ -122,7 +122,7 @@
       addr += result;
     }
 
-    RESTARTABLE(::close(fd), result);
+    result = ::close(fd);
     if (PrintMiscellaneous && Verbose) {
       if (result == OS_ERR) {
         warning("Could not close %s: %s\n", destfile, strerror(errno));
@@ -437,7 +437,7 @@
       addr+=result;
     }
 
-    RESTARTABLE(::close(fd), result);
+    ::close(fd);
 
     // get the user name for the effective user id of the process
     char* user_name = get_user_name(psinfo.pr_euid);
@@ -669,7 +669,7 @@
     if (PrintMiscellaneous && Verbose) {
       warning("could not set shared memory file size: %s\n", strerror(errno));
     }
-    RESTARTABLE(::close(fd), result);
+    ::close(fd);
     return -1;
   }
 
@@ -749,9 +749,7 @@
 
   mapAddress = (char*)::mmap((char*)0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
 
-  // attempt to close the file - restart it if it was interrupted,
-  // but ignore other failures
-  RESTARTABLE(::close(fd), result);
+  result = ::close(fd);
   assert(result != OS_ERR, "could not close file");
 
   if (mapAddress == MAP_FAILED) {
@@ -770,8 +768,7 @@
   (void)::memset((void*) mapAddress, 0, size);
 
   // it does not go through os api, the operation has to record from here
-  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC);
-  MemTracker::record_virtual_memory_type((address)mapAddress, mtInternal);
+  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, mtInternal, CURRENT_PC);
 
   return mapAddress;
 }
@@ -922,9 +919,7 @@
 
   mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);
 
-  // attempt to close the file - restart if it gets interrupted,
-  // but ignore other failures
-  RESTARTABLE(::close(fd), result);
+  result = ::close(fd);
   assert(result != OS_ERR, "could not close file");
 
   if (mapAddress == MAP_FAILED) {
@@ -936,8 +931,7 @@
   }
 
   // it does not go through os api, the operation has to record from here
-  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC);
-  MemTracker::record_virtual_memory_type((address)mapAddress, mtInternal);
+  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, mtInternal, CURRENT_PC);
 
   *addr = mapAddress;
   *sizep = size;
--- a/hotspot/src/os/windows/vm/os_windows.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/windows/vm/os_windows.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -2524,7 +2524,7 @@
                   addr = (address)((uintptr_t)addr &
                          (~((uintptr_t)os::vm_page_size() - (uintptr_t)1)));
                   os::commit_memory((char *)addr, thread->stack_base() - addr,
-                                    false );
+                                    !ExecMem);
                   return EXCEPTION_CONTINUE_EXECUTION;
           }
           else
@@ -2875,7 +2875,7 @@
                                 PAGE_READWRITE);
   // If reservation failed, return NULL
   if (p_buf == NULL) return NULL;
-  MemTracker::record_virtual_memory_reserve((address)p_buf, size_of_reserve, CALLER_PC);
+  MemTracker::record_virtual_memory_reserve((address)p_buf, size_of_reserve, mtNone, CALLER_PC);
   os::release_memory(p_buf, bytes + chunk_size);
 
   // we still need to round up to a page boundary (in case we are using large pages)
@@ -2941,7 +2941,7 @@
         // need to create a dummy 'reserve' record to match
         // the release.
         MemTracker::record_virtual_memory_reserve((address)p_buf,
-          bytes_to_release, CALLER_PC);
+          bytes_to_release, mtNone, CALLER_PC);
         os::release_memory(p_buf, bytes_to_release);
       }
 #ifdef ASSERT
@@ -2961,9 +2961,10 @@
   // Although the memory is allocated individually, it is returned as one.
   // NMT records it as one block.
   address pc = CALLER_PC;
-  MemTracker::record_virtual_memory_reserve((address)p_buf, bytes, pc);
   if ((flags & MEM_COMMIT) != 0) {
-    MemTracker::record_virtual_memory_commit((address)p_buf, bytes, pc);
+    MemTracker::record_virtual_memory_reserve_and_commit((address)p_buf, bytes, mtNone, pc);
+  } else {
+    MemTracker::record_virtual_memory_reserve((address)p_buf, bytes, mtNone, pc);
   }
 
   // made it this far, success
@@ -3154,8 +3155,7 @@
     char * res = (char *)VirtualAlloc(NULL, bytes, flag, prot);
     if (res != NULL) {
       address pc = CALLER_PC;
-      MemTracker::record_virtual_memory_reserve((address)res, bytes, pc);
-      MemTracker::record_virtual_memory_commit((address)res, bytes, pc);
+      MemTracker::record_virtual_memory_reserve_and_commit((address)res, bytes, mtNone, pc);
     }
 
     return res;
@@ -3164,14 +3164,21 @@
 
 bool os::release_memory_special(char* base, size_t bytes) {
   assert(base != NULL, "Sanity check");
-  // Memory allocated via reserve_memory_special() is committed
-  MemTracker::record_virtual_memory_uncommit((address)base, bytes);
   return release_memory(base, bytes);
 }
 
 void os::print_statistics() {
 }
 
+static void warn_fail_commit_memory(char* addr, size_t bytes, bool exec) {
+  int err = os::get_last_error();
+  char buf[256];
+  size_t buf_len = os::lasterror(buf, sizeof(buf));
+  warning("INFO: os::commit_memory(" PTR_FORMAT ", " SIZE_FORMAT
+          ", %d) failed; error='%s' (DOS error/errno=%d)", addr, bytes,
+          exec, buf_len != 0 ? buf : "<no_error_string>", err);
+}
+
 bool os::pd_commit_memory(char* addr, size_t bytes, bool exec) {
   if (bytes == 0) {
     // Don't bother the OS with noops.
@@ -3186,11 +3193,17 @@
   // is always within a reserve covered by a single VirtualAlloc
   // in that case we can just do a single commit for the requested size
   if (!UseNUMAInterleaving) {
-    if (VirtualAlloc(addr, bytes, MEM_COMMIT, PAGE_READWRITE) == NULL) return false;
+    if (VirtualAlloc(addr, bytes, MEM_COMMIT, PAGE_READWRITE) == NULL) {
+      NOT_PRODUCT(warn_fail_commit_memory(addr, bytes, exec);)
+      return false;
+    }
     if (exec) {
       DWORD oldprot;
       // Windows doc says to use VirtualProtect to get execute permissions
-      if (!VirtualProtect(addr, bytes, PAGE_EXECUTE_READWRITE, &oldprot)) return false;
+      if (!VirtualProtect(addr, bytes, PAGE_EXECUTE_READWRITE, &oldprot)) {
+        NOT_PRODUCT(warn_fail_commit_memory(addr, bytes, exec);)
+        return false;
+      }
     }
     return true;
   } else {
@@ -3205,12 +3218,20 @@
       MEMORY_BASIC_INFORMATION alloc_info;
       VirtualQuery(next_alloc_addr, &alloc_info, sizeof(alloc_info));
       size_t bytes_to_rq = MIN2(bytes_remaining, (size_t)alloc_info.RegionSize);
-      if (VirtualAlloc(next_alloc_addr, bytes_to_rq, MEM_COMMIT, PAGE_READWRITE) == NULL)
+      if (VirtualAlloc(next_alloc_addr, bytes_to_rq, MEM_COMMIT,
+                       PAGE_READWRITE) == NULL) {
+        NOT_PRODUCT(warn_fail_commit_memory(next_alloc_addr, bytes_to_rq,
+                                            exec);)
         return false;
+      }
       if (exec) {
         DWORD oldprot;
-        if (!VirtualProtect(next_alloc_addr, bytes_to_rq, PAGE_EXECUTE_READWRITE, &oldprot))
+        if (!VirtualProtect(next_alloc_addr, bytes_to_rq,
+                            PAGE_EXECUTE_READWRITE, &oldprot)) {
+          NOT_PRODUCT(warn_fail_commit_memory(next_alloc_addr, bytes_to_rq,
+                                              exec);)
           return false;
+        }
       }
       bytes_remaining -= bytes_to_rq;
       next_alloc_addr += bytes_to_rq;
@@ -3222,7 +3243,24 @@
 
 bool os::pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
                        bool exec) {
-  return commit_memory(addr, size, exec);
+  // alignment_hint is ignored on this OS
+  return pd_commit_memory(addr, size, exec);
+}
+
+void os::pd_commit_memory_or_exit(char* addr, size_t size, bool exec,
+                                  const char* mesg) {
+  assert(mesg != NULL, "mesg must be specified");
+  if (!pd_commit_memory(addr, size, exec)) {
+    warn_fail_commit_memory(addr, size, exec);
+    vm_exit_out_of_memory(size, OOM_MMAP_ERROR, mesg);
+  }
+}
+
+void os::pd_commit_memory_or_exit(char* addr, size_t size,
+                                  size_t alignment_hint, bool exec,
+                                  const char* mesg) {
+  // alignment_hint is ignored on this OS
+  pd_commit_memory_or_exit(addr, size, exec, mesg);
 }
 
 bool os::pd_uncommit_memory(char* addr, size_t bytes) {
@@ -3240,7 +3278,7 @@
 }
 
 bool os::pd_create_stack_guard_pages(char* addr, size_t size) {
-  return os::commit_memory(addr, size);
+  return os::commit_memory(addr, size, !ExecMem);
 }
 
 bool os::remove_stack_guard_pages(char* addr, size_t size) {
@@ -3264,8 +3302,9 @@
 
   // Strange enough, but on Win32 one can change protection only for committed
   // memory, not a big deal anyway, as bytes less or equal than 64K
-  if (!is_committed && !commit_memory(addr, bytes, prot == MEM_PROT_RWX)) {
-    fatal("cannot commit protection page");
+  if (!is_committed) {
+    commit_memory_or_exit(addr, bytes, prot == MEM_PROT_RWX,
+                          "cannot commit protection page");
   }
   // One cannot use os::guard_memory() here, as on Win32 guard page
   // have different (one-shot) semantics, from MSDN on PAGE_GUARD:
--- a/hotspot/src/os/windows/vm/perfMemory_windows.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os/windows/vm/perfMemory_windows.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -58,7 +58,7 @@
   }
 
   // commit memory
-  if (!os::commit_memory(mapAddress, size)) {
+  if (!os::commit_memory(mapAddress, size, !ExecMem)) {
     if (PrintMiscellaneous && Verbose) {
       warning("Could not commit PerfData memory\n");
     }
@@ -1498,8 +1498,7 @@
   (void)memset(mapAddress, '\0', size);
 
   // it does not go through os api, the operation has to record from here
-  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC);
-  MemTracker::record_virtual_memory_type((address)mapAddress, mtInternal);
+  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, mtInternal, CURRENT_PC);
 
   return (char*) mapAddress;
 }
@@ -1681,8 +1680,7 @@
   }
 
   // it does not go through os api, the operation has to record from here
-  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, CURRENT_PC);
-  MemTracker::record_virtual_memory_type((address)mapAddress, mtInternal);
+  MemTracker::record_virtual_memory_reserve((address)mapAddress, size, mtInternal, CURRENT_PC);
 
 
   *addrp = (char*)mapAddress;
@@ -1836,9 +1834,10 @@
     return;
   }
 
+  MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
   remove_file_mapping(addr);
   // it does not go through os api, the operation has to record from here
-  MemTracker::record_virtual_memory_release((address)addr, bytes);
+  tkr.record((address)addr, bytes);
 }
 
 char* PerfMemory::backing_store_filename() {
--- a/hotspot/src/os_cpu/linux_sparc/vm/assembler_linux_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
- * 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 "asm/macroAssembler.hpp"
-#include "runtime/os.hpp"
-#include "runtime/threadLocalStorage.hpp"
-
-#include <asm-sparc/traps.h>
-
-void MacroAssembler::read_ccr_trap(Register ccr_save) {
-  // No implementation
-  breakpoint_trap();
-}
-
-void MacroAssembler::write_ccr_trap(Register ccr_save, Register scratch1, Register scratch2) {
-  // No implementation
-  breakpoint_trap();
-}
-
-void MacroAssembler::flush_windows_trap() { trap(SP_TRAP_FWIN); }
-void MacroAssembler::clean_windows_trap() { trap(SP_TRAP_CWIN); }
-
-// Use software breakpoint trap until we figure out how to do this on Linux
-void MacroAssembler::get_psr_trap()       { trap(SP_TRAP_SBPT); }
-void MacroAssembler::set_psr_trap()       { trap(SP_TRAP_SBPT); }
--- a/hotspot/src/os_cpu/linux_sparc/vm/atomic_linux_sparc.inline.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os_cpu/linux_sparc/vm/atomic_linux_sparc.inline.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -169,7 +169,6 @@
     : "memory");
   return rv;
 #else
-  assert(VM_Version::v9_instructions_work(), "cas only supported on v9");
   volatile jlong_accessor evl, cvl, rv;
   evl.long_value = exchange_value;
   cvl.long_value = compare_value;
--- a/hotspot/src/os_cpu/solaris_sparc/vm/assembler_solaris_sparc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
- * 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 "asm/macroAssembler.inline.hpp"
-#include "runtime/os.hpp"
-#include "runtime/threadLocalStorage.hpp"
-
-#include <sys/trap.h>          // For trap numbers
-#include <v9/sys/psr_compat.h> // For V8 compatibility
-
-void MacroAssembler::read_ccr_trap(Register ccr_save) {
-  // Execute a trap to get the PSR, mask and shift
-  // to get the condition codes.
-  get_psr_trap();
-  nop();
-  set(PSR_ICC, ccr_save);
-  and3(O0, ccr_save, ccr_save);
-  srl(ccr_save, PSR_ICC_SHIFT, ccr_save);
-}
-
-void MacroAssembler::write_ccr_trap(Register ccr_save, Register scratch1, Register scratch2) {
-  // Execute a trap to get the PSR, shift back
-  // the condition codes, mask the condition codes
-  // back into and PSR and trap to write back the
-  // PSR.
-  sll(ccr_save, PSR_ICC_SHIFT, scratch2);
-  get_psr_trap();
-  nop();
-  set(~PSR_ICC, scratch1);
-  and3(O0, scratch1, O0);
-  or3(O0, scratch2, O0);
-  set_psr_trap();
-  nop();
-}
-
-void MacroAssembler::flush_windows_trap() { trap(ST_FLUSH_WINDOWS); }
-void MacroAssembler::clean_windows_trap() { trap(ST_CLEAN_WINDOWS); }
-void MacroAssembler::get_psr_trap()       { trap(ST_GETPSR); }
-void MacroAssembler::set_psr_trap()       { trap(ST_SETPSR); }
--- a/hotspot/src/os_cpu/solaris_sparc/vm/atomic_solaris_sparc.inline.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/atomic_solaris_sparc.inline.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -60,21 +60,10 @@
 
 #else
 
-extern "C" void _Atomic_move_long_v8(volatile jlong* src, volatile jlong* dst);
 extern "C" void _Atomic_move_long_v9(volatile jlong* src, volatile jlong* dst);
 
 inline void Atomic_move_long(volatile jlong* src, volatile jlong* dst) {
-#ifdef COMPILER2
-  // Compiler2 does not support v8, it is used only for v9.
   _Atomic_move_long_v9(src, dst);
-#else
-  // The branch is cheaper then emulated LDD.
-  if (VM_Version::v9_instructions_work()) {
-    _Atomic_move_long_v9(src, dst);
-  } else {
-    _Atomic_move_long_v8(src, dst);
-  }
-#endif
 }
 
 inline jlong Atomic::load(volatile jlong* src) {
@@ -209,7 +198,6 @@
     : "memory");
   return rv;
 #else  //_LP64
-  assert(VM_Version::v9_instructions_work(), "cas only supported on v9");
   volatile jlong_accessor evl, cvl, rv;
   evl.long_value = exchange_value;
   cvl.long_value = compare_value;
@@ -318,7 +306,6 @@
   // Return 64 bit value in %o0
   return _Atomic_cas64((intptr_t)exchange_value, (intptr_t *)dest, (intptr_t)compare_value);
 #else  // _LP64
-  assert (VM_Version::v9_instructions_work(), "only supported on v9");
   // Return 64 bit value in %o0,%o1 by hand
   return _Atomic_casl(exchange_value, dest, compare_value);
 #endif // _LP64
--- a/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.il	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.il	Wed Jul 05 19:00:49 2017 +0200
@@ -152,23 +152,6 @@
         .nonvolatile
         .end
 
-  // Support for jlong Atomic::load and Atomic::store on v8.
-  //
-  // void _Atomic_move_long_v8(volatile jlong* src, volatile jlong* dst)
-  //
-  // Arguments:
-  //      src:  O0
-  //      dest: O1
-  //
-  // Overwrites O2 and O3
-
-        .inline _Atomic_move_long_v8,2
-        .volatile
-        ldd     [%o0], %o2
-        std     %o2, [%o1]
-        .nonvolatile
-        .end
-
   // Support for jlong Atomic::load and Atomic::store on v9.
   //
   // void _Atomic_move_long_v9(volatile jlong* src, volatile jlong* dst)
--- a/hotspot/src/share/vm/adlc/formssel.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/adlc/formssel.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -235,6 +235,9 @@
   return false;
 }
 
+bool InstructForm::is_ideal_negD() const {
+  return (_matrule && _matrule->_rChild && strcmp(_matrule->_rChild->_opType, "NegD") == 0);
+}
 
 // Return 'true' if this instruction matches an ideal 'Copy*' node
 int InstructForm::is_ideal_copy() const {
@@ -533,6 +536,12 @@
   if( data_type != Form::none )
     rematerialize = true;
 
+  // Ugly: until a better fix is implemented, disable rematerialization for
+  // negD nodes because they are proved to be problematic.
+  if (is_ideal_negD()) {
+    return false;
+  }
+
   // Constants
   if( _components.count() == 1 && _components[0]->is(Component::USE_DEF) )
     rematerialize = true;
--- a/hotspot/src/share/vm/adlc/formssel.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/adlc/formssel.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -147,6 +147,7 @@
   virtual int         is_empty_encoding() const; // _size=0 and/or _insencode empty
   virtual int         is_tls_instruction() const; // tlsLoadP rule or ideal ThreadLocal
   virtual int         is_ideal_copy() const;    // node matches ideal 'Copy*'
+  virtual bool        is_ideal_negD() const;    // node matches ideal 'NegD'
   virtual bool        is_ideal_if()   const;    // node matches ideal 'If'
   virtual bool        is_ideal_fastlock() const; // node matches 'FastLock'
   virtual bool        is_ideal_membar() const;  // node matches ideal 'MemBarXXX'
--- a/hotspot/src/share/vm/c1/c1_IR.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/c1/c1_IR.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -506,7 +506,7 @@
   _loop_map(0, 0),          // initialized later with correct size
   _compilation(c)
 {
-  TRACE_LINEAR_SCAN(2, "***** computing linear-scan block order");
+  TRACE_LINEAR_SCAN(2, tty->print_cr("***** computing linear-scan block order"));
 
   init_visited();
   count_edges(start_block, NULL);
@@ -683,7 +683,7 @@
 }
 
 void ComputeLinearScanOrder::assign_loop_depth(BlockBegin* start_block) {
-  TRACE_LINEAR_SCAN(3, "----- computing loop-depth and weight");
+  TRACE_LINEAR_SCAN(3, tty->print_cr("----- computing loop-depth and weight"));
   init_visited();
 
   assert(_work_list.is_empty(), "work list must be empty before processing");
@@ -868,7 +868,7 @@
 }
 
 void ComputeLinearScanOrder::compute_order(BlockBegin* start_block) {
-  TRACE_LINEAR_SCAN(3, "----- computing final block order");
+  TRACE_LINEAR_SCAN(3, tty->print_cr("----- computing final block order"));
 
   // the start block is always the first block in the linear scan order
   _linear_scan_order = new BlockList(_num_blocks);
--- a/hotspot/src/share/vm/c1/c1_LIR.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/c1/c1_LIR.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -201,23 +201,24 @@
 
 #ifdef ASSERT
   if (!is_pointer() && !is_illegal()) {
+    OprKind kindfield = kind_field(); // Factored out because of compiler bug, see 8002160
     switch (as_BasicType(type_field())) {
     case T_LONG:
-      assert((kind_field() == cpu_register || kind_field() == stack_value) &&
+      assert((kindfield == cpu_register || kindfield == stack_value) &&
              size_field() == double_size, "must match");
       break;
     case T_FLOAT:
       // FP return values can be also in CPU registers on ARM and PPC (softfp ABI)
-      assert((kind_field() == fpu_register || kind_field() == stack_value
-             ARM_ONLY(|| kind_field() == cpu_register)
-             PPC_ONLY(|| kind_field() == cpu_register) ) &&
+      assert((kindfield == fpu_register || kindfield == stack_value
+             ARM_ONLY(|| kindfield == cpu_register)
+             PPC_ONLY(|| kindfield == cpu_register) ) &&
              size_field() == single_size, "must match");
       break;
     case T_DOUBLE:
       // FP return values can be also in CPU registers on ARM and PPC (softfp ABI)
-      assert((kind_field() == fpu_register || kind_field() == stack_value
-             ARM_ONLY(|| kind_field() == cpu_register)
-             PPC_ONLY(|| kind_field() == cpu_register) ) &&
+      assert((kindfield == fpu_register || kindfield == stack_value
+             ARM_ONLY(|| kindfield == cpu_register)
+             PPC_ONLY(|| kindfield == cpu_register) ) &&
              size_field() == double_size, "must match");
       break;
     case T_BOOLEAN:
@@ -229,7 +230,7 @@
     case T_OBJECT:
     case T_METADATA:
     case T_ARRAY:
-      assert((kind_field() == cpu_register || kind_field() == stack_value) &&
+      assert((kindfield == cpu_register || kindfield == stack_value) &&
              size_field() == single_size, "must match");
       break;
 
--- a/hotspot/src/share/vm/ci/ciUtilities.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/ci/ciUtilities.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -96,7 +96,7 @@
     CLEAR_PENDING_EXCEPTION;                     \
     return (result);                             \
   }                                              \
-  (0
+  (void)(0
 
 #define KILL_COMPILE_ON_ANY                      \
   THREAD);                                       \
@@ -104,7 +104,7 @@
     fatal("unhandled ci exception");             \
     CLEAR_PENDING_EXCEPTION;                     \
   }                                              \
-(0
+(void)(0
 
 
 inline const char* bool_to_str(bool b) {
--- a/hotspot/src/share/vm/classfile/genericSignatures.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/classfile/genericSignatures.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -124,7 +124,7 @@
       fatal(STREAM->parse_error());      \
     }                                   \
     return NULL;                        \
-  } 0
+  } (void)0
 
 #define READ() STREAM->read(); CHECK_FOR_PARSE_ERROR()
 #define PEEK() STREAM->peek(); CHECK_FOR_PARSE_ERROR()
@@ -133,7 +133,7 @@
 #define EXPECTED(c, ch) STREAM->assert_char(c, ch); CHECK_FOR_PARSE_ERROR()
 #define EXPECT_END() STREAM->expect_end(); CHECK_FOR_PARSE_ERROR()
 
-#define CHECK_STREAM STREAM); CHECK_FOR_PARSE_ERROR(); (0
+#define CHECK_STREAM STREAM); CHECK_FOR_PARSE_ERROR(); ((void)0
 
 #ifndef PRODUCT
 void Identifier::print_on(outputStream* str) const {
--- a/hotspot/src/share/vm/classfile/javaClasses.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/classfile/javaClasses.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -2825,6 +2825,7 @@
 int java_security_AccessControlContext::_context_offset = 0;
 int java_security_AccessControlContext::_privilegedContext_offset = 0;
 int java_security_AccessControlContext::_isPrivileged_offset = 0;
+int java_security_AccessControlContext::_isAuthorized_offset = -1;
 
 void java_security_AccessControlContext::compute_offsets() {
   assert(_isPrivileged_offset == 0, "offsets should be initialized only once");
@@ -2845,8 +2846,19 @@
     fatal("Invalid layout of java.security.AccessControlContext");
   }
   _isPrivileged_offset = fd.offset();
-}
-
+
+  // The offset may not be present for bootstrapping with older JDK.
+  if (ik->find_local_field(vmSymbols::isAuthorized_name(), vmSymbols::bool_signature(), &fd)) {
+    _isAuthorized_offset = fd.offset();
+  }
+}
+
+
+bool java_security_AccessControlContext::is_authorized(Handle context) {
+  assert(context.not_null() && context->klass() == SystemDictionary::AccessControlContext_klass(), "Invalid type");
+  assert(_isAuthorized_offset != -1, "should be set");
+  return context->bool_field(_isAuthorized_offset) != 0;
+}
 
 oop java_security_AccessControlContext::create(objArrayHandle context, bool isPrivileged, Handle privileged_context, TRAPS) {
   assert(_isPrivileged_offset != 0, "offsets should have been initialized");
@@ -2858,6 +2870,10 @@
   result->obj_field_put(_context_offset, context());
   result->obj_field_put(_privilegedContext_offset, privileged_context());
   result->bool_field_put(_isPrivileged_offset, isPrivileged);
+  // whitelist AccessControlContexts created by the JVM if present
+  if (_isAuthorized_offset != -1) {
+    result->bool_field_put(_isAuthorized_offset, true);
+  }
   return result;
 }
 
@@ -2967,6 +2983,15 @@
 }
 
 
+bool java_lang_System::has_security_manager() {
+  InstanceKlass* ik = InstanceKlass::cast(SystemDictionary::System_klass());
+  address addr = ik->static_field_addr(static_security_offset);
+  if (UseCompressedOops) {
+    return oopDesc::load_decode_heap_oop((narrowOop *)addr) != NULL;
+  } else {
+    return oopDesc::load_decode_heap_oop((oop*)addr) != NULL;
+  }
+}
 
 int java_lang_Class::_klass_offset;
 int java_lang_Class::_array_klass_offset;
@@ -3030,6 +3055,7 @@
 int java_lang_System::static_in_offset;
 int java_lang_System::static_out_offset;
 int java_lang_System::static_err_offset;
+int java_lang_System::static_security_offset;
 int java_lang_StackTraceElement::declaringClass_offset;
 int java_lang_StackTraceElement::methodName_offset;
 int java_lang_StackTraceElement::fileName_offset;
@@ -3155,6 +3181,7 @@
   java_lang_System::static_in_offset  = java_lang_System::hc_static_in_offset  * x;
   java_lang_System::static_out_offset = java_lang_System::hc_static_out_offset * x;
   java_lang_System::static_err_offset = java_lang_System::hc_static_err_offset * x;
+  java_lang_System::static_security_offset = java_lang_System::hc_static_security_offset * x;
 
   // java_lang_StackTraceElement
   java_lang_StackTraceElement::declaringClass_offset = java_lang_StackTraceElement::hc_declaringClass_offset  * x + header;
@@ -3354,6 +3381,7 @@
   CHECK_STATIC_OFFSET("java/lang/System", java_lang_System,  in, "Ljava/io/InputStream;");
   CHECK_STATIC_OFFSET("java/lang/System", java_lang_System, out, "Ljava/io/PrintStream;");
   CHECK_STATIC_OFFSET("java/lang/System", java_lang_System, err, "Ljava/io/PrintStream;");
+  CHECK_STATIC_OFFSET("java/lang/System", java_lang_System, security, "Ljava/lang/SecurityManager;");
 
   // java.lang.StackTraceElement
 
--- a/hotspot/src/share/vm/classfile/javaClasses.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/classfile/javaClasses.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1167,11 +1167,14 @@
   static int _context_offset;
   static int _privilegedContext_offset;
   static int _isPrivileged_offset;
+  static int _isAuthorized_offset;
 
   static void compute_offsets();
  public:
   static oop create(objArrayHandle context, bool isPrivileged, Handle privileged_context, TRAPS);
 
+  static bool is_authorized(Handle context);
+
   // Debugging/initialization
   friend class JavaClasses;
 };
@@ -1231,18 +1234,22 @@
   enum {
    hc_static_in_offset  = 0,
    hc_static_out_offset = 1,
-   hc_static_err_offset = 2
+   hc_static_err_offset = 2,
+   hc_static_security_offset = 3
   };
 
   static int  static_in_offset;
   static int static_out_offset;
   static int static_err_offset;
+  static int static_security_offset;
 
  public:
   static int  in_offset_in_bytes();
   static int out_offset_in_bytes();
   static int err_offset_in_bytes();
 
+  static bool has_security_manager();
+
   // Debugging
   friend class JavaClasses;
 };
--- a/hotspot/src/share/vm/classfile/symbolTable.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/classfile/symbolTable.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -598,6 +598,8 @@
 
 bool StringTable::_needs_rehashing = false;
 
+volatile int StringTable::_parallel_claimed_idx = 0;
+
 // Pick hashing algorithm
 unsigned int StringTable::hash_string(const jchar* s, int len) {
   return use_alternate_hashcode() ? AltHashing::murmur3_32(seed(), s, len) :
@@ -761,8 +763,18 @@
   }
 }
 
-void StringTable::oops_do(OopClosure* f) {
-  for (int i = 0; i < the_table()->table_size(); ++i) {
+void StringTable::buckets_do(OopClosure* f, int start_idx, int end_idx) {
+  const int limit = the_table()->table_size();
+
+  assert(0 <= start_idx && start_idx <= limit,
+         err_msg("start_idx (" INT32_FORMAT ") oob?", start_idx));
+  assert(0 <= end_idx && end_idx <= limit,
+         err_msg("end_idx (" INT32_FORMAT ") oob?", end_idx));
+  assert(start_idx <= end_idx,
+         err_msg("Ordering: start_idx=" INT32_FORMAT", end_idx=" INT32_FORMAT,
+                 start_idx, end_idx));
+
+  for (int i = start_idx; i < end_idx; i += 1) {
     HashtableEntry<oop, mtSymbol>* entry = the_table()->bucket(i);
     while (entry != NULL) {
       assert(!entry->is_shared(), "CDS not used for the StringTable");
@@ -774,6 +786,27 @@
   }
 }
 
+void StringTable::oops_do(OopClosure* f) {
+  buckets_do(f, 0, the_table()->table_size());
+}
+
+void StringTable::possibly_parallel_oops_do(OopClosure* f) {
+  const int ClaimChunkSize = 32;
+  const int limit = the_table()->table_size();
+
+  for (;;) {
+    // Grab next set of buckets to scan
+    int start_idx = Atomic::add(ClaimChunkSize, &_parallel_claimed_idx) - ClaimChunkSize;
+    if (start_idx >= limit) {
+      // End of table
+      break;
+    }
+
+    int end_idx = MIN2(limit, start_idx + ClaimChunkSize);
+    buckets_do(f, start_idx, end_idx);
+  }
+}
+
 void StringTable::verify() {
   for (int i = 0; i < the_table()->table_size(); ++i) {
     HashtableEntry<oop, mtSymbol>* p = the_table()->bucket(i);
--- a/hotspot/src/share/vm/classfile/symbolTable.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/classfile/symbolTable.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -246,12 +246,19 @@
   // Set if one bucket is out of balance due to hash algorithm deficiency
   static bool _needs_rehashing;
 
+  // Claimed high water mark for parallel chunked scanning
+  static volatile int _parallel_claimed_idx;
+
   static oop intern(Handle string_or_null, jchar* chars, int length, TRAPS);
   oop basic_add(int index, Handle string_or_null, jchar* name, int len,
                 unsigned int hashValue, TRAPS);
 
   oop lookup(int index, jchar* chars, int length, unsigned int hashValue);
 
+  // Apply the give oop closure to the entries to the buckets
+  // in the range [start_idx, end_idx).
+  static void buckets_do(OopClosure* f, int start_idx, int end_idx);
+
   StringTable() : Hashtable<oop, mtSymbol>((int)StringTableSize,
                               sizeof (HashtableEntry<oop, mtSymbol>)) {}
 
@@ -277,9 +284,12 @@
     unlink_or_oops_do(cl, NULL);
   }
 
-  // Invoke "f->do_oop" on the locations of all oops in the table.
+  // Serially invoke "f->do_oop" on the locations of all oops in the table.
   static void oops_do(OopClosure* f);
 
+  // Possibly parallel version of the above
+  static void possibly_parallel_oops_do(OopClosure* f);
+
   // Hashing algorithm, used as the hash value used by the
   //     StringTable for bucket selection and comparison (stored in the
   //     HashtableEntry structures).  This is used in the String.intern() method.
@@ -315,5 +325,8 @@
   // Rehash the symbol table if it gets out of balance
   static void rehash_table();
   static bool needs_rehashing() { return _needs_rehashing; }
+
+  // Parallel chunked scanning
+  static void clear_parallel_claimed_index() { _parallel_claimed_idx = 0; }
 };
 #endif // SHARE_VM_CLASSFILE_SYMBOLTABLE_HPP
--- a/hotspot/src/share/vm/classfile/verifier.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/classfile/verifier.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -86,9 +86,9 @@
 // These macros are used similarly to CHECK macros but also check
 // the status of the verifier and return if that has an error.
 #define CHECK_VERIFY(verifier) \
-  CHECK); if ((verifier)->has_error()) return; (0
+  CHECK); if ((verifier)->has_error()) return; ((void)0
 #define CHECK_VERIFY_(verifier, result) \
-  CHECK_(result)); if ((verifier)->has_error()) return (result); (0
+  CHECK_(result)); if ((verifier)->has_error()) return (result); ((void)0
 
 class TypeOrigin VALUE_OBJ_CLASS_SPEC {
  private:
--- a/hotspot/src/share/vm/classfile/vmSymbols.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -94,6 +94,7 @@
   template(java_lang_SecurityManager,                 "java/lang/SecurityManager")                \
   template(java_security_AccessControlContext,        "java/security/AccessControlContext")       \
   template(java_security_ProtectionDomain,            "java/security/ProtectionDomain")           \
+  template(impliesCreateAccessControlContext_name,    "impliesCreateAccessControlContext")        \
   template(java_io_OutputStream,                      "java/io/OutputStream")                     \
   template(java_io_Reader,                            "java/io/Reader")                           \
   template(java_io_BufferedReader,                    "java/io/BufferedReader")                   \
@@ -346,6 +347,7 @@
   template(contextClassLoader_name,                   "contextClassLoader")                       \
   template(inheritedAccessControlContext_name,        "inheritedAccessControlContext")            \
   template(isPrivileged_name,                         "isPrivileged")                             \
+  template(isAuthorized_name,                         "isAuthorized")                             \
   template(getClassContext_name,                      "getClassContext")                          \
   template(wait_name,                                 "wait")                                     \
   template(checkPackageAccess_name,                   "checkPackageAccess")                       \
--- a/hotspot/src/share/vm/code/dependencies.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/code/dependencies.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -989,7 +989,7 @@
   assert(changes.involves_context(context_type), "irrelevant dependency");
   Klass* new_type = changes.new_type();
 
-  count_find_witness_calls();
+  (void)count_find_witness_calls();
   NOT_PRODUCT(deps_find_witness_singles++);
 
   // Current thread must be in VM (not native mode, as in CI):
--- a/hotspot/src/share/vm/code/nmethod.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/code/nmethod.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -2615,7 +2615,8 @@
                       relocation_begin()-1+ip[1]);
       for (; ip < index_end; ip++)
         tty->print_cr("  (%d ?)", ip[0]);
-      tty->print_cr("          @" INTPTR_FORMAT ": index_size=%d", ip, *ip++);
+      tty->print_cr("          @" INTPTR_FORMAT ": index_size=%d", ip, *ip);
+      ip++;
       tty->print_cr("reloc_end @" INTPTR_FORMAT ":", ip);
     }
   }
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/cardTableExtension.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/cardTableExtension.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -565,11 +565,9 @@
     if(new_start_aligned < new_end_for_commit) {
       MemRegion new_committed =
         MemRegion(new_start_aligned, new_end_for_commit);
-      if (!os::commit_memory((char*)new_committed.start(),
-                             new_committed.byte_size())) {
-        vm_exit_out_of_memory(new_committed.byte_size(), OOM_MMAP_ERROR,
-                              "card table expansion");
-      }
+      os::commit_memory_or_exit((char*)new_committed.start(),
+                                new_committed.byte_size(), !ExecMem,
+                                "card table expansion");
     }
     result = true;
   } else if (new_start_aligned > cur_committed.start()) {
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psAdaptiveSizePolicy.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psAdaptiveSizePolicy.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1250,14 +1250,13 @@
                   avg_promoted()->deviation());
     }
 
-    gclog_or_tty->print( "  avg_promoted_padded_avg: %f"
+    gclog_or_tty->print_cr( "  avg_promoted_padded_avg: %f"
                 "  avg_pretenured_padded_avg: %f"
                 "  tenuring_thresh: %d"
                 "  target_size: " SIZE_FORMAT,
                 avg_promoted()->padded_average(),
                 _avg_pretenured->padded_average(),
                 tenuring_threshold, target_size);
-    tty->cr();
   }
 
   set_survivor_size(target_size);
@@ -1279,7 +1278,7 @@
   avg_promoted()->sample(promoted + _avg_pretenured->padded_average());
 
   if (PrintAdaptiveSizePolicy) {
-    gclog_or_tty->print(
+    gclog_or_tty->print_cr(
                   "AdaptiveSizePolicy::update_averages:"
                   "  survived: "  SIZE_FORMAT
                   "  promoted: "  SIZE_FORMAT
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psVirtualspace.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psVirtualspace.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -101,7 +101,8 @@
   }
 
   char* const base_addr = committed_high_addr();
-  bool result = special() || os::commit_memory(base_addr, bytes, alignment());
+  bool result = special() ||
+         os::commit_memory(base_addr, bytes, alignment(), !ExecMem);
   if (result) {
     _committed_high_addr += bytes;
   }
@@ -154,7 +155,7 @@
   if (tmp_bytes > 0) {
     char* const commit_base = committed_high_addr();
     if (other_space->special() ||
-        os::commit_memory(commit_base, tmp_bytes, alignment())) {
+        os::commit_memory(commit_base, tmp_bytes, alignment(), !ExecMem)) {
       // Reduce the reserved region in the other space.
       other_space->set_reserved(other_space->reserved_low_addr() + tmp_bytes,
                                 other_space->reserved_high_addr(),
@@ -269,7 +270,8 @@
   }
 
   char* const base_addr = committed_low_addr() - bytes;
-  bool result = special() || os::commit_memory(base_addr, bytes, alignment());
+  bool result = special() ||
+         os::commit_memory(base_addr, bytes, alignment(), !ExecMem);
   if (result) {
     _committed_low_addr -= bytes;
   }
@@ -322,7 +324,7 @@
   if (tmp_bytes > 0) {
     char* const commit_base = committed_low_addr() - tmp_bytes;
     if (other_space->special() ||
-        os::commit_memory(commit_base, tmp_bytes, alignment())) {
+        os::commit_memory(commit_base, tmp_bytes, alignment(), !ExecMem)) {
       // Reduce the reserved region in the other space.
       other_space->set_reserved(other_space->reserved_low_addr(),
                                 other_space->reserved_high_addr() - tmp_bytes,
--- a/hotspot/src/share/vm/memory/allocation.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/memory/allocation.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -263,7 +263,7 @@
    ChunkPool(size_t size) : _size(size) { _first = NULL; _num_chunks = _num_used = 0; }
 
   // Allocate a new chunk from the pool (might expand the pool)
-  _NOINLINE_ void* allocate(size_t bytes) {
+  _NOINLINE_ void* allocate(size_t bytes, AllocFailType alloc_failmode) {
     assert(bytes == _size, "bad size");
     void* p = NULL;
     // No VM lock can be taken inside ThreadCritical lock, so os::malloc
@@ -273,9 +273,9 @@
       p = get_first();
     }
     if (p == NULL) p = os::malloc(bytes, mtChunk, CURRENT_PC);
-    if (p == NULL)
+    if (p == NULL && alloc_failmode == AllocFailStrategy::EXIT_OOM) {
       vm_exit_out_of_memory(bytes, OOM_MALLOC_ERROR, "ChunkPool::allocate");
-
+    }
     return p;
   }
 
@@ -372,7 +372,7 @@
 //--------------------------------------------------------------------------------------
 // Chunk implementation
 
-void* Chunk::operator new(size_t requested_size, size_t length) {
+void* Chunk::operator new (size_t requested_size, AllocFailType alloc_failmode, size_t length) {
   // requested_size is equal to sizeof(Chunk) but in order for the arena
   // allocations to come out aligned as expected the size must be aligned
   // to expected arena alignment.
@@ -380,13 +380,14 @@
   assert(ARENA_ALIGN(requested_size) == aligned_overhead_size(), "Bad alignment");
   size_t bytes = ARENA_ALIGN(requested_size) + length;
   switch (length) {
-   case Chunk::size:        return ChunkPool::large_pool()->allocate(bytes);
-   case Chunk::medium_size: return ChunkPool::medium_pool()->allocate(bytes);
-   case Chunk::init_size:   return ChunkPool::small_pool()->allocate(bytes);
+   case Chunk::size:        return ChunkPool::large_pool()->allocate(bytes, alloc_failmode);
+   case Chunk::medium_size: return ChunkPool::medium_pool()->allocate(bytes, alloc_failmode);
+   case Chunk::init_size:   return ChunkPool::small_pool()->allocate(bytes, alloc_failmode);
    default: {
-     void *p =  os::malloc(bytes, mtChunk, CALLER_PC);
-     if (p == NULL)
+     void* p = os::malloc(bytes, mtChunk, CALLER_PC);
+     if (p == NULL && alloc_failmode == AllocFailStrategy::EXIT_OOM) {
        vm_exit_out_of_memory(bytes, OOM_MALLOC_ERROR, "Chunk::new");
+     }
      return p;
    }
   }
@@ -440,7 +441,7 @@
 Arena::Arena(size_t init_size) {
   size_t round_size = (sizeof (char *)) - 1;
   init_size = (init_size+round_size) & ~round_size;
-  _first = _chunk = new (init_size) Chunk(init_size);
+  _first = _chunk = new (AllocFailStrategy::EXIT_OOM, init_size) Chunk(init_size);
   _hwm = _chunk->bottom();      // Save the cached hwm, max
   _max = _chunk->top();
   set_size_in_bytes(init_size);
@@ -448,7 +449,7 @@
 }
 
 Arena::Arena() {
-  _first = _chunk = new (Chunk::init_size) Chunk(Chunk::init_size);
+  _first = _chunk = new (AllocFailStrategy::EXIT_OOM, Chunk::init_size) Chunk(Chunk::init_size);
   _hwm = _chunk->bottom();      // Save the cached hwm, max
   _max = _chunk->top();
   set_size_in_bytes(Chunk::init_size);
@@ -555,12 +556,9 @@
   size_t len = MAX2(x, (size_t) Chunk::size);
 
   Chunk *k = _chunk;            // Get filled-up chunk address
-  _chunk = new (len) Chunk(len);
+  _chunk = new (alloc_failmode, len) Chunk(len);
 
   if (_chunk == NULL) {
-    if (alloc_failmode == AllocFailStrategy::EXIT_OOM) {
-      signal_out_of_memory(len * Chunk::aligned_overhead_size(), "Arena::grow");
-    }
     return NULL;
   }
   if (k) k->set_next(_chunk);   // Append new chunk to end of linked list
--- a/hotspot/src/share/vm/memory/allocation.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/memory/allocation.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -340,7 +340,7 @@
   Chunk*       _next;     // Next Chunk in list
   const size_t _len;      // Size of this Chunk
  public:
-  void* operator new(size_t size, size_t length);
+  void* operator new(size_t size, AllocFailType alloc_failmode, size_t length);
   void  operator delete(void* p);
   Chunk(size_t length);
 
@@ -403,10 +403,15 @@
 
   void signal_out_of_memory(size_t request, const char* whence) const;
 
-  void check_for_overflow(size_t request, const char* whence) const {
+  bool check_for_overflow(size_t request, const char* whence,
+      AllocFailType alloc_failmode = AllocFailStrategy::EXIT_OOM) const {
     if (UINTPTR_MAX - request < (uintptr_t)_hwm) {
+      if (alloc_failmode == AllocFailStrategy::RETURN_NULL) {
+        return false;
+      }
       signal_out_of_memory(request, whence);
     }
+    return true;
  }
 
  public:
@@ -430,7 +435,8 @@
     assert(is_power_of_2(ARENA_AMALLOC_ALIGNMENT) , "should be a power of 2");
     x = ARENA_ALIGN(x);
     debug_only(if (UseMallocOnly) return malloc(x);)
-    check_for_overflow(x, "Arena::Amalloc");
+    if (!check_for_overflow(x, "Arena::Amalloc", alloc_failmode))
+      return NULL;
     NOT_PRODUCT(inc_bytes_allocated(x);)
     if (_hwm + x > _max) {
       return grow(x, alloc_failmode);
@@ -444,7 +450,8 @@
   void *Amalloc_4(size_t x, AllocFailType alloc_failmode = AllocFailStrategy::EXIT_OOM) {
     assert( (x&(sizeof(char*)-1)) == 0, "misaligned size" );
     debug_only(if (UseMallocOnly) return malloc(x);)
-    check_for_overflow(x, "Arena::Amalloc_4");
+    if (!check_for_overflow(x, "Arena::Amalloc_4", alloc_failmode))
+      return NULL;
     NOT_PRODUCT(inc_bytes_allocated(x);)
     if (_hwm + x > _max) {
       return grow(x, alloc_failmode);
@@ -465,7 +472,8 @@
     size_t delta = (((size_t)_hwm + DALIGN_M1) & ~DALIGN_M1) - (size_t)_hwm;
     x += delta;
 #endif
-    check_for_overflow(x, "Arena::Amalloc_D");
+    if (!check_for_overflow(x, "Arena::Amalloc_D", alloc_failmode))
+      return NULL;
     NOT_PRODUCT(inc_bytes_allocated(x);)
     if (_hwm + x > _max) {
       return grow(x, alloc_failmode); // grow() returns a result aligned >= 8 bytes.
@@ -635,8 +643,15 @@
 #define NEW_RESOURCE_ARRAY_IN_THREAD(thread, type, size)\
   (type*) resource_allocate_bytes(thread, (size) * sizeof(type))
 
+#define NEW_RESOURCE_ARRAY_IN_THREAD_RETURN_NULL(thread, type, size)\
+  (type*) resource_allocate_bytes(thread, (size) * sizeof(type), AllocFailStrategy::RETURN_NULL)
+
 #define REALLOC_RESOURCE_ARRAY(type, old, old_size, new_size)\
-  (type*) resource_reallocate_bytes((char*)(old), (old_size) * sizeof(type), (new_size) * sizeof(type) )
+  (type*) resource_reallocate_bytes((char*)(old), (old_size) * sizeof(type), (new_size) * sizeof(type))
+
+#define REALLOC_RESOURCE_ARRAY_RETURN_NULL(type, old, old_size, new_size)\
+  (type*) resource_reallocate_bytes((char*)(old), (old_size) * sizeof(type),\
+                                    (new_size) * sizeof(type), AllocFailStrategy::RETURN_NULL)
 
 #define FREE_RESOURCE_ARRAY(type, old, size)\
   resource_free_bytes((char*)(old), (size) * sizeof(type))
@@ -647,28 +662,40 @@
 #define NEW_RESOURCE_OBJ(type)\
   NEW_RESOURCE_ARRAY(type, 1)
 
+#define NEW_RESOURCE_OBJ_RETURN_NULL(type)\
+  NEW_RESOURCE_ARRAY_RETURN_NULL(type, 1)
+
+#define NEW_C_HEAP_ARRAY3(type, size, memflags, pc, allocfail)\
+  (type*) AllocateHeap(size * sizeof(type), memflags, pc, allocfail)
+
+#define NEW_C_HEAP_ARRAY2(type, size, memflags, pc)\
+  (type*) (AllocateHeap((size) * sizeof(type), memflags, pc))
+
 #define NEW_C_HEAP_ARRAY(type, size, memflags)\
   (type*) (AllocateHeap((size) * sizeof(type), memflags))
 
+#define NEW_C_HEAP_ARRAY2_RETURN_NULL(type, size, memflags, pc)\
+  NEW_C_HEAP_ARRAY3(type, size, memflags, pc, AllocFailStrategy::RETURN_NULL)
+
+#define NEW_C_HEAP_ARRAY_RETURN_NULL(type, size, memflags)\
+  NEW_C_HEAP_ARRAY3(type, size, memflags, (address)0, AllocFailStrategy::RETURN_NULL)
+
 #define REALLOC_C_HEAP_ARRAY(type, old, size, memflags)\
   (type*) (ReallocateHeap((char*)old, (size) * sizeof(type), memflags))
 
+#define REALLOC_C_HEAP_ARRAY_RETURN_NULL(type, old, size, memflags)\
+   (type*) (ReallocateHeap((char*)old, (size) * sizeof(type), memflags, AllocFailStrategy::RETURN_NULL))
+
 #define FREE_C_HEAP_ARRAY(type, old, memflags) \
   FreeHeap((char*)(old), memflags)
 
-#define NEW_C_HEAP_ARRAY2(type, size, memflags, pc)\
-  (type*) (AllocateHeap((size) * sizeof(type), memflags, pc))
-
-#define REALLOC_C_HEAP_ARRAY2(type, old, size, memflags, pc)\
-  (type*) (ReallocateHeap((char*)old, (size) * sizeof(type), memflags, pc))
-
-#define NEW_C_HEAP_ARRAY3(type, size, memflags, pc, allocfail)         \
-  (type*) AllocateHeap(size * sizeof(type), memflags, pc, allocfail)
-
 // allocate type in heap without calling ctor
 #define NEW_C_HEAP_OBJ(type, memflags)\
   NEW_C_HEAP_ARRAY(type, 1, memflags)
 
+#define NEW_C_HEAP_OBJ_RETURN_NULL(type, memflags)\
+  NEW_C_HEAP_ARRAY_RETURN_NULL(type, 1, memflags)
+
 // deallocate obj of type in heap without calling dtor
 #define FREE_C_HEAP_OBJ(objname, memflags)\
   FreeHeap((char*)objname, memflags);
@@ -713,13 +740,21 @@
 // is set so that we always use malloc except for Solaris where we set the
 // limit to get mapped memory.
 template <class E, MEMFLAGS F>
-class ArrayAllocator : StackObj {
+class ArrayAllocator VALUE_OBJ_CLASS_SPEC {
   char* _addr;
   bool _use_malloc;
   size_t _size;
+  bool _free_in_destructor;
  public:
-  ArrayAllocator() : _addr(NULL), _use_malloc(false), _size(0) { }
-  ~ArrayAllocator() { free(); }
+  ArrayAllocator(bool free_in_destructor = true) :
+    _addr(NULL), _use_malloc(false), _size(0), _free_in_destructor(free_in_destructor) { }
+
+  ~ArrayAllocator() {
+    if (_free_in_destructor) {
+      free();
+    }
+  }
+
   E* allocate(size_t length);
   void free();
 };
--- a/hotspot/src/share/vm/memory/allocation.inline.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/memory/allocation.inline.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -146,10 +146,7 @@
     vm_exit_out_of_memory(_size, OOM_MMAP_ERROR, "Allocator (reserve)");
   }
 
-  bool success = os::commit_memory(_addr, _size, false /* executable */);
-  if (!success) {
-    vm_exit_out_of_memory(_size, OOM_MMAP_ERROR, "Allocator (commit)");
-  }
+  os::commit_memory_or_exit(_addr, _size, !ExecMem, "Allocator (commit)");
 
   return (E*)_addr;
 }
--- a/hotspot/src/share/vm/memory/cardTableModRefBS.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/memory/cardTableModRefBS.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -110,11 +110,8 @@
   jbyte* guard_card = &_byte_map[_guard_index];
   uintptr_t guard_page = align_size_down((uintptr_t)guard_card, _page_size);
   _guard_region = MemRegion((HeapWord*)guard_page, _page_size);
-  if (!os::commit_memory((char*)guard_page, _page_size, _page_size)) {
-    // Do better than this for Merlin
-    vm_exit_out_of_memory(_page_size, OOM_MMAP_ERROR, "card table last card");
-  }
-
+  os::commit_memory_or_exit((char*)guard_page, _page_size, _page_size,
+                            !ExecMem, "card table last card");
   *guard_card = last_card;
 
    _lowest_non_clean =
@@ -312,12 +309,9 @@
         MemRegion(cur_committed.end(), new_end_for_commit);
 
       assert(!new_committed.is_empty(), "Region should not be empty here");
-      if (!os::commit_memory((char*)new_committed.start(),
-                             new_committed.byte_size(), _page_size)) {
-        // Do better than this for Merlin
-        vm_exit_out_of_memory(new_committed.byte_size(), OOM_MMAP_ERROR,
-                "card table expansion");
-      }
+      os::commit_memory_or_exit((char*)new_committed.start(),
+                                new_committed.byte_size(), _page_size,
+                                !ExecMem, "card table expansion");
     // Use new_end_aligned (as opposed to new_end_for_commit) because
     // the cur_committed region may include the guard region.
     } else if (new_end_aligned < cur_committed.end()) {
@@ -418,7 +412,7 @@
   }
   // Touch the last card of the covered region to show that it
   // is committed (or SEGV).
-  debug_only(*byte_for(_covered[ind].last());)
+  debug_only((void) (*byte_for(_covered[ind].last()));)
   debug_only(verify_guard();)
 }
 
--- a/hotspot/src/share/vm/memory/referenceProcessorStats.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/memory/referenceProcessorStats.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/sharedHeap.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/memory/sharedHeap.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -47,7 +47,6 @@
   SH_PS_SystemDictionary_oops_do,
   SH_PS_ClassLoaderDataGraph_oops_do,
   SH_PS_jvmti_oops_do,
-  SH_PS_StringTable_oops_do,
   SH_PS_CodeCache_oops_do,
   // Leave this one last.
   SH_PS_NumElements
@@ -127,6 +126,8 @@
 {
   if (_active) {
     outer->change_strong_roots_parity();
+    // Zero the claimed high water mark in the StringTable
+    StringTable::clear_parallel_claimed_index();
   }
 }
 
@@ -154,14 +155,16 @@
   // Global (strong) JNI handles
   if (!_process_strong_tasks->is_task_claimed(SH_PS_JNIHandles_oops_do))
     JNIHandles::oops_do(roots);
+
   // All threads execute this; the individual threads are task groups.
   CLDToOopClosure roots_from_clds(roots);
   CLDToOopClosure* roots_from_clds_p = (is_scavenging ? NULL : &roots_from_clds);
-  if (ParallelGCThreads > 0) {
-    Threads::possibly_parallel_oops_do(roots, roots_from_clds_p ,code_roots);
+  if (CollectedHeap::use_parallel_gc_threads()) {
+    Threads::possibly_parallel_oops_do(roots, roots_from_clds_p, code_roots);
   } else {
     Threads::oops_do(roots, roots_from_clds_p, code_roots);
   }
+
   if (!_process_strong_tasks-> is_task_claimed(SH_PS_ObjectSynchronizer_oops_do))
     ObjectSynchronizer::oops_do(roots);
   if (!_process_strong_tasks->is_task_claimed(SH_PS_FlatProfiler_oops_do))
@@ -189,8 +192,12 @@
     }
   }
 
-  if (!_process_strong_tasks->is_task_claimed(SH_PS_StringTable_oops_do)) {
-    if (so & SO_Strings) {
+  // All threads execute the following. A specific chunk of buckets
+  // from the StringTable are the individual tasks.
+  if (so & SO_Strings) {
+    if (CollectedHeap::use_parallel_gc_threads()) {
+      StringTable::possibly_parallel_oops_do(roots);
+    } else {
       StringTable::oops_do(roots);
     }
   }
--- a/hotspot/src/share/vm/memory/universe.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/memory/universe.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -108,6 +108,7 @@
 oop Universe::_the_min_jint_string                   = NULL;
 LatestMethodOopCache* Universe::_finalizer_register_cache = NULL;
 LatestMethodOopCache* Universe::_loader_addClass_cache    = NULL;
+LatestMethodOopCache* Universe::_pd_implies_cache         = NULL;
 ActiveMethodOopsCache* Universe::_reflect_invoke_cache    = NULL;
 oop Universe::_out_of_memory_error_java_heap          = NULL;
 oop Universe::_out_of_memory_error_perm_gen           = NULL;
@@ -224,6 +225,7 @@
   _finalizer_register_cache->serialize(f);
   _loader_addClass_cache->serialize(f);
   _reflect_invoke_cache->serialize(f);
+  _pd_implies_cache->serialize(f);
 }
 
 void Universe::check_alignment(uintx size, uintx alignment, const char* name) {
@@ -529,7 +531,9 @@
   if (vt) vt->initialize_vtable(false, CHECK);
   if (ko->oop_is_instance()) {
     InstanceKlass* ik = (InstanceKlass*)ko;
-    for (KlassHandle s_h(THREAD, ik->subklass()); s_h() != NULL; s_h = (THREAD, s_h()->next_sibling())) {
+    for (KlassHandle s_h(THREAD, ik->subklass());
+         s_h() != NULL;
+         s_h = KlassHandle(THREAD, s_h()->next_sibling())) {
       reinitialize_vtable_of(s_h, CHECK);
     }
   }
@@ -645,6 +649,7 @@
   // Metaspace::initialize_shared_spaces() tries to populate them.
   Universe::_finalizer_register_cache = new LatestMethodOopCache();
   Universe::_loader_addClass_cache    = new LatestMethodOopCache();
+  Universe::_pd_implies_cache         = new LatestMethodOopCache();
   Universe::_reflect_invoke_cache     = new ActiveMethodOopsCache();
 
   if (UseSharedSpaces) {
@@ -1108,6 +1113,23 @@
   Universe::_loader_addClass_cache->init(
     SystemDictionary::ClassLoader_klass(), m, CHECK_false);
 
+  // Setup method for checking protection domain
+  InstanceKlass::cast(SystemDictionary::ProtectionDomain_klass())->link_class(CHECK_false);
+  m = InstanceKlass::cast(SystemDictionary::ProtectionDomain_klass())->
+            find_method(vmSymbols::impliesCreateAccessControlContext_name(),
+                        vmSymbols::void_boolean_signature());
+  // Allow NULL which should only happen with bootstrapping.
+  if (m != NULL) {
+    if (m->is_static()) {
+      // NoSuchMethodException doesn't actually work because it tries to run the
+      // <init> function before java_lang_Class is linked. Print error and exit.
+      tty->print_cr("ProtectionDomain.impliesCreateAccessControlContext() has the wrong linkage");
+      return false; // initialization failed
+    }
+    Universe::_pd_implies_cache->init(
+      SystemDictionary::ProtectionDomain_klass(), m, CHECK_false);;
+  }
+
   // The folowing is initializing converter functions for serialization in
   // JVM.cpp. If we clean up the StrictMath code above we may want to find
   // a better solution for this as well.
@@ -1525,6 +1547,7 @@
 
 
 Method* LatestMethodOopCache::get_Method() {
+  if (klass() == NULL) return NULL;
   InstanceKlass* ik = InstanceKlass::cast(klass());
   Method* m = ik->method_with_idnum(method_idnum());
   assert(m != NULL, "sanity check");
--- a/hotspot/src/share/vm/memory/universe.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/memory/universe.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -176,6 +176,7 @@
   static oop          _the_min_jint_string;          // A cache of "-2147483648" as a Java string
   static LatestMethodOopCache* _finalizer_register_cache; // static method for registering finalizable objects
   static LatestMethodOopCache* _loader_addClass_cache;    // method for registering loaded classes in class loader vector
+  static LatestMethodOopCache* _pd_implies_cache;         // method for checking protection domain attributes
   static ActiveMethodOopsCache* _reflect_invoke_cache;    // method for security checks
   static oop          _out_of_memory_error_java_heap; // preallocated error object (no backtrace)
   static oop          _out_of_memory_error_perm_gen;  // preallocated error object (no backtrace)
@@ -333,7 +334,10 @@
   static oop          the_min_jint_string()          { return _the_min_jint_string;          }
   static Method*      finalizer_register_method()     { return _finalizer_register_cache->get_Method(); }
   static Method*      loader_addClass_method()        { return _loader_addClass_cache->get_Method(); }
+
+  static Method*      protection_domain_implies_method() { return _pd_implies_cache->get_Method(); }
   static ActiveMethodOopsCache* reflect_invoke_cache() { return _reflect_invoke_cache; }
+
   static oop          null_ptr_exception_instance()   { return _null_ptr_exception_instance;   }
   static oop          arithmetic_exception_instance() { return _arithmetic_exception_instance; }
   static oop          virtual_machine_error_instance() { return _virtual_machine_error_instance; }
--- a/hotspot/src/share/vm/oops/generateOopMap.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/oops/generateOopMap.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -642,11 +642,21 @@
 // CellType handling methods
 //
 
+// Allocate memory and throw LinkageError if failure.
+#define ALLOC_RESOURCE_ARRAY(var, type, count) \
+  var = NEW_RESOURCE_ARRAY_RETURN_NULL(type, count);              \
+  if (var == NULL) {                                              \
+    report_error("Cannot reserve enough memory to analyze this method"); \
+    return;                                                       \
+  }
+
+
 void GenerateOopMap::init_state() {
   _state_len     = _max_locals + _max_stack + _max_monitors;
-  _state         = NEW_RESOURCE_ARRAY(CellTypeState, _state_len);
+  ALLOC_RESOURCE_ARRAY(_state, CellTypeState, _state_len);
   memset(_state, 0, _state_len * sizeof(CellTypeState));
-  _state_vec_buf = NEW_RESOURCE_ARRAY(char, MAX3(_max_locals, _max_stack, _max_monitors) + 1/*for null terminator char */);
+  int count = MAX3(_max_locals, _max_stack, _max_monitors) + 1/*for null terminator char */;
+  ALLOC_RESOURCE_ARRAY(_state_vec_buf, char, count);
 }
 
 void GenerateOopMap::make_context_uninitialized() {
@@ -905,7 +915,7 @@
   // But cumbersome since we don't know the stack heights yet.  (Nor the
   // monitor stack heights...)
 
-  _basic_blocks = NEW_RESOURCE_ARRAY(BasicBlock, _bb_count);
+  ALLOC_RESOURCE_ARRAY(_basic_blocks, BasicBlock, _bb_count);
 
   // Make a pass through the bytecodes.  Count the number of monitorenters.
   // This can be used an upper bound on the monitor stack depth in programs
@@ -976,8 +986,8 @@
     return;
   }
 
-  CellTypeState *basicBlockState =
-      NEW_RESOURCE_ARRAY(CellTypeState, bbNo * _state_len);
+  CellTypeState *basicBlockState;
+  ALLOC_RESOURCE_ARRAY(basicBlockState, CellTypeState, bbNo * _state_len);
   memset(basicBlockState, 0, bbNo * _state_len * sizeof(CellTypeState));
 
   // Make a pass over the basicblocks and assign their state vectors.
--- a/hotspot/src/share/vm/opto/c2_globals.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/opto/c2_globals.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -406,10 +406,10 @@
   develop(intx, WarmCallMaxSize, 999999,                                    \
           "size of the largest inlinable method")                           \
                                                                             \
-  product(intx, MaxNodeLimit, 65000,                                        \
+  product(intx, MaxNodeLimit, 80000,                                        \
           "Maximum number of nodes")                                        \
                                                                             \
-  product(intx, NodeLimitFudgeFactor, 1000,                                 \
+  product(intx, NodeLimitFudgeFactor, 2000,                                 \
           "Fudge Factor for certain optimizations")                         \
                                                                             \
   product(bool, UseJumpTables, true,                                        \
--- a/hotspot/src/share/vm/opto/chaitin.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/opto/chaitin.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -435,6 +435,9 @@
     // Insert un-coalesced copies.  Visit all Phis.  Where inputs to a Phi do
     // not match the Phi itself, insert a copy.
     coalesce.insert_copies(_matcher);
+    if (C->failing()) {
+      return;
+    }
   }
 
   // After aggressive coalesce, attempt a first cut at coloring.
--- a/hotspot/src/share/vm/opto/coalesce.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/opto/coalesce.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -240,6 +240,8 @@
   _unique = C->unique();
 
   for( uint i=0; i<_phc._cfg._num_blocks; i++ ) {
+    C->check_node_count(NodeLimitFudgeFactor, "out of nodes in coalesce");
+    if (C->failing()) return;
     Block *b = _phc._cfg._blocks[i];
     uint cnt = b->num_preds();  // Number of inputs to the Phi
 
--- a/hotspot/src/share/vm/opto/matcher.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/opto/matcher.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -985,6 +985,8 @@
   mstack.push(n, Visit, NULL, -1);  // set NULL as parent to indicate root
 
   while (mstack.is_nonempty()) {
+    C->check_node_count(NodeLimitFudgeFactor, "too many nodes matching instructions");
+    if (C->failing()) return NULL;
     n = mstack.node();          // Leave node on stack
     Node_State nstate = mstack.state();
     if (nstate == Visit) {
--- a/hotspot/src/share/vm/opto/memnode.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/opto/memnode.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -2930,7 +2930,9 @@
 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
   if (remove_dead_region(phase, can_reshape)) return this;
   // Don't bother trying to transform a dead node
-  if (in(0) && in(0)->is_top())  return NULL;
+  if (in(0) && in(0)->is_top()) {
+    return NULL;
+  }
 
   // Eliminate volatile MemBars for scalar replaced objects.
   if (can_reshape && req() == (Precedent+1)) {
@@ -2939,6 +2941,14 @@
     if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) {
       // Volatile field loads and stores.
       Node* my_mem = in(MemBarNode::Precedent);
+      // The MembarAquire may keep an unused LoadNode alive through the Precedent edge
+      if ((my_mem != NULL) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) {
+        assert(my_mem->unique_out() == this, "sanity");
+        phase->hash_delete(this);
+        del_req(Precedent);
+        phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later
+        my_mem = NULL;
+      }
       if (my_mem != NULL && my_mem->is_Mem()) {
         const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr();
         // Check for scalar replaced object reference.
@@ -4384,7 +4394,7 @@
   }
 }
 #else // !ASSERT
-#define verify_memory_slice(m,i,n) (0)  // PRODUCT version is no-op
+#define verify_memory_slice(m,i,n) (void)(0)  // PRODUCT version is no-op
 #endif
 
 
--- a/hotspot/src/share/vm/prims/forte.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/prims/forte.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -619,7 +619,7 @@
                             void* null_argument_3);
 #pragma weak collector_func_load
 #define collector_func_load(x0,x1,x2,x3,x4,x5,x6) \
-        ( collector_func_load ? collector_func_load(x0,x1,x2,x3,x4,x5,x6),0 : 0 )
+        ( collector_func_load ? collector_func_load(x0,x1,x2,x3,x4,x5,x6),(void)0 : (void)0 )
 #endif // __APPLE__
 #endif // !_WINDOWS
 
--- a/hotspot/src/share/vm/prims/jvm.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/prims/jvm.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1141,6 +1141,56 @@
   }
 JVM_END
 
+static bool is_authorized(Handle context, instanceKlassHandle klass, TRAPS) {
+  // If there is a security manager and protection domain, check the access
+  // in the protection domain, otherwise it is authorized.
+  if (java_lang_System::has_security_manager()) {
+
+    // For bootstrapping, if pd implies method isn't in the JDK, allow
+    // this context to revert to older behavior.
+    // In this case the isAuthorized field in AccessControlContext is also not
+    // present.
+    if (Universe::protection_domain_implies_method() == NULL) {
+      return true;
+    }
+
+    // Whitelist certain access control contexts
+    if (java_security_AccessControlContext::is_authorized(context)) {
+      return true;
+    }
+
+    oop prot = klass->protection_domain();
+    if (prot != NULL) {
+      // Call pd.implies(new SecurityPermission("createAccessControlContext"))
+      // in the new wrapper.
+      methodHandle m(THREAD, Universe::protection_domain_implies_method());
+      Handle h_prot(THREAD, prot);
+      JavaValue result(T_BOOLEAN);
+      JavaCallArguments args(h_prot);
+      JavaCalls::call(&result, m, &args, CHECK_false);
+      return (result.get_jboolean() != 0);
+    }
+  }
+  return true;
+}
+
+// Create an AccessControlContext with a protection domain with null codesource
+// and null permissions - which gives no permissions.
+oop create_dummy_access_control_context(TRAPS) {
+  InstanceKlass* pd_klass = InstanceKlass::cast(SystemDictionary::ProtectionDomain_klass());
+  // new ProtectionDomain(null,null);
+  oop null_protection_domain = pd_klass->allocate_instance(CHECK_NULL);
+  Handle null_pd(THREAD, null_protection_domain);
+
+  // new ProtectionDomain[] {pd};
+  objArrayOop context = oopFactory::new_objArray(pd_klass, 1, CHECK_NULL);
+  context->obj_at_put(0, null_pd());
+
+  // new AccessControlContext(new ProtectionDomain[] {pd})
+  objArrayHandle h_context(THREAD, context);
+  oop result = java_security_AccessControlContext::create(h_context, false, Handle(), CHECK_NULL);
+  return result;
+}
 
 JVM_ENTRY(jobject, JVM_DoPrivileged(JNIEnv *env, jclass cls, jobject action, jobject context, jboolean wrapException))
   JVMWrapper("JVM_DoPrivileged");
@@ -1149,8 +1199,29 @@
     THROW_MSG_0(vmSymbols::java_lang_NullPointerException(), "Null action");
   }
 
-  // Stack allocated list of privileged stack elements
-  PrivilegedElement pi;
+  // Compute the frame initiating the do privileged operation and setup the privileged stack
+  vframeStream vfst(thread);
+  vfst.security_get_caller_frame(1);
+
+  if (vfst.at_end()) {
+    THROW_MSG_0(vmSymbols::java_lang_InternalError(), "no caller?");
+  }
+
+  Method* method        = vfst.method();
+  instanceKlassHandle klass (THREAD, method->method_holder());
+
+  // Check that action object understands "Object run()"
+  Handle h_context;
+  if (context != NULL) {
+    h_context = Handle(THREAD, JNIHandles::resolve(context));
+    bool authorized = is_authorized(h_context, klass, CHECK_NULL);
+    if (!authorized) {
+      // Create an unprivileged access control object and call it's run function
+      // instead.
+      oop noprivs = create_dummy_access_control_context(CHECK_NULL);
+      h_context = Handle(THREAD, noprivs);
+    }
+  }
 
   // Check that action object understands "Object run()"
   Handle object (THREAD, JNIHandles::resolve(action));
@@ -1164,12 +1235,10 @@
     THROW_MSG_0(vmSymbols::java_lang_InternalError(), "No run method");
   }
 
-  // Compute the frame initiating the do privileged operation and setup the privileged stack
-  vframeStream vfst(thread);
-  vfst.security_get_caller_frame(1);
-
+  // Stack allocated list of privileged stack elements
+  PrivilegedElement pi;
   if (!vfst.at_end()) {
-    pi.initialize(&vfst, JNIHandles::resolve(context), thread->privileged_stack_top(), CHECK_NULL);
+    pi.initialize(&vfst, h_context(), thread->privileged_stack_top(), CHECK_NULL);
     thread->set_privileged_stack_top(&pi);
   }
 
@@ -3241,24 +3310,10 @@
 JVM_END
 
 
-// Utility object for collecting method holders walking down the stack
-class KlassLink: public ResourceObj {
- public:
-  KlassHandle klass;
-  KlassLink*  next;
-
-  KlassLink(KlassHandle k) { klass = k; next = NULL; }
-};
-
-
 JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
   JVMWrapper("JVM_GetClassContext");
   ResourceMark rm(THREAD);
   JvmtiVMObjectAllocEventCollector oam;
-  // Collect linked list of (handles to) method holders
-  KlassLink* first = NULL;
-  KlassLink* last  = NULL;
-  int depth = 0;
   vframeStream vfst(thread);
 
   if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {
@@ -3272,32 +3327,23 @@
   }
 
   // Collect method holders
+  GrowableArray<KlassHandle>* klass_array = new GrowableArray<KlassHandle>();
   for (; !vfst.at_end(); vfst.security_next()) {
     Method* m = vfst.method();
     // Native frames are not returned
     if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {
       Klass* holder = m->method_holder();
       assert(holder->is_klass(), "just checking");
-      depth++;
-      KlassLink* l = new KlassLink(KlassHandle(thread, holder));
-      if (first == NULL) {
-        first = last = l;
-      } else {
-        last->next = l;
-        last = l;
-      }
+      klass_array->append(holder);
     }
   }
 
   // Create result array of type [Ljava/lang/Class;
-  objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), depth, CHECK_NULL);
+  objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), klass_array->length(), CHECK_NULL);
   // Fill in mirrors corresponding to method holders
-  int index = 0;
-  while (first != NULL) {
-    result->obj_at_put(index++, first->klass()->java_mirror());
-    first = first->next;
+  for (int i = 0; i < klass_array->length(); i++) {
+    result->obj_at_put(i, klass_array->at(i)->java_mirror());
   }
-  assert(index == depth, "just checking");
 
   return (jobjectArray) JNIHandles::make_local(env, result);
 JVM_END
--- a/hotspot/src/share/vm/prims/jvmti.xml	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/prims/jvmti.xml	Wed Jul 05 19:00:49 2017 +0200
@@ -1897,7 +1897,7 @@
 	  </description>
 	</param>
 	<param id="monitor_info_ptr">
-	  <allocbuf outcount="owned_monitor_depth_count_ptr">
+	  <allocbuf outcount="monitor_info_count_ptr">
             <struct>jvmtiMonitorStackDepthInfo</struct>
           </allocbuf>
 	  <description>
--- a/hotspot/src/share/vm/prims/whitebox.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/prims/whitebox.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -159,7 +159,7 @@
 
 
 WB_ENTRY(void, WB_NMTCommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
-  os::commit_memory((char *)(uintptr_t)addr, size);
+  os::commit_memory((char *)(uintptr_t)addr, size, !ExecMem);
   MemTracker::record_virtual_memory_type((address)(uintptr_t)addr, mtTest);
 WB_END
 
--- a/hotspot/src/share/vm/runtime/arguments.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/runtime/arguments.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1566,6 +1566,15 @@
   return result;
 }
 
+void Arguments::set_heap_base_min_address() {
+  if (FLAG_IS_DEFAULT(HeapBaseMinAddress) && UseG1GC && HeapBaseMinAddress < 1*G) {
+    // By default HeapBaseMinAddress is 2G on all platforms except Solaris x86.
+    // G1 currently needs a lot of C-heap, so on Solaris we have to give G1
+    // some extra space for the C-heap compared to other collectors.
+    FLAG_SET_ERGO(uintx, HeapBaseMinAddress, 1*G);
+  }
+}
+
 void Arguments::set_heap_size() {
   if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
     // Deprecated flag
@@ -1885,21 +1894,6 @@
   // Note: Needs platform-dependent factoring.
   bool status = true;
 
-#if ( (defined(COMPILER2) && defined(SPARC)))
-  // NOTE: The call to VM_Version_init depends on the fact that VM_Version_init
-  // on sparc doesn't require generation of a stub as is the case on, e.g.,
-  // x86.  Normally, VM_Version_init must be called from init_globals in
-  // init.cpp, which is called by the initial java thread *after* arguments
-  // have been parsed.  VM_Version_init gets called twice on sparc.
-  extern void VM_Version_init();
-  VM_Version_init();
-  if (!VM_Version::has_v9()) {
-    jio_fprintf(defaultStream::error_stream(),
-                "V8 Machine detected, Server requires V9\n");
-    status = false;
-  }
-#endif /* COMPILER2 && SPARC */
-
   // Allow both -XX:-UseStackBanging and -XX:-UseBoundThreads in non-product
   // builds so the cost of stack banging can be measured.
 #if (defined(PRODUCT) && defined(SOLARIS))
@@ -3525,6 +3519,8 @@
     }
   }
 
+  set_heap_base_min_address();
+
   // Set heap size based on available physical memory
   set_heap_size();
 
--- a/hotspot/src/share/vm/runtime/arguments.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/runtime/arguments.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -315,6 +315,8 @@
   // limits the given memory size by the maximum amount of memory this process is
   // currently allowed to allocate or reserve.
   static julong limit_by_allocatable_memory(julong size);
+  // Setup HeapBaseMinAddress
+  static void set_heap_base_min_address();
   // Setup heap size
   static void set_heap_size();
   // Based on automatic selection criteria, should the
--- a/hotspot/src/share/vm/runtime/os.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/runtime/os.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -647,10 +647,13 @@
 #ifndef ASSERT
   NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
   NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
+  MemTracker::Tracker tkr = MemTracker::get_realloc_tracker();
   void* ptr = ::realloc(memblock, size);
   if (ptr != NULL) {
-    MemTracker::record_realloc((address)memblock, (address)ptr, size, memflags,
+    tkr.record((address)memblock, (address)ptr, size, memflags,
      caller == 0 ? CALLER_PC : caller);
+  } else {
+    tkr.discard();
   }
   return ptr;
 #else
@@ -1456,7 +1459,7 @@
 char* os::reserve_memory(size_t bytes, char* addr, size_t alignment_hint) {
   char* result = pd_reserve_memory(bytes, addr, alignment_hint);
   if (result != NULL) {
-    MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
+    MemTracker::record_virtual_memory_reserve((address)result, bytes, mtNone, CALLER_PC);
   }
 
   return result;
@@ -1466,7 +1469,7 @@
    MEMFLAGS flags) {
   char* result = pd_reserve_memory(bytes, addr, alignment_hint);
   if (result != NULL) {
-    MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
+    MemTracker::record_virtual_memory_reserve((address)result, bytes, mtNone, CALLER_PC);
     MemTracker::record_virtual_memory_type((address)result, flags);
   }
 
@@ -1476,7 +1479,7 @@
 char* os::attempt_reserve_memory_at(size_t bytes, char* addr) {
   char* result = pd_attempt_reserve_memory_at(bytes, addr);
   if (result != NULL) {
-    MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
+    MemTracker::record_virtual_memory_reserve((address)result, bytes, mtNone, CALLER_PC);
   }
   return result;
 }
@@ -1503,18 +1506,36 @@
   return res;
 }
 
+void os::commit_memory_or_exit(char* addr, size_t bytes, bool executable,
+                               const char* mesg) {
+  pd_commit_memory_or_exit(addr, bytes, executable, mesg);
+  MemTracker::record_virtual_memory_commit((address)addr, bytes, CALLER_PC);
+}
+
+void os::commit_memory_or_exit(char* addr, size_t size, size_t alignment_hint,
+                               bool executable, const char* mesg) {
+  os::pd_commit_memory_or_exit(addr, size, alignment_hint, executable, mesg);
+  MemTracker::record_virtual_memory_commit((address)addr, size, CALLER_PC);
+}
+
 bool os::uncommit_memory(char* addr, size_t bytes) {
+  MemTracker::Tracker tkr = MemTracker::get_virtual_memory_uncommit_tracker();
   bool res = pd_uncommit_memory(addr, bytes);
   if (res) {
-    MemTracker::record_virtual_memory_uncommit((address)addr, bytes);
+    tkr.record((address)addr, bytes);
+  } else {
+    tkr.discard();
   }
   return res;
 }
 
 bool os::release_memory(char* addr, size_t bytes) {
+  MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
   bool res = pd_release_memory(addr, bytes);
   if (res) {
-    MemTracker::record_virtual_memory_release((address)addr, bytes);
+    tkr.record((address)addr, bytes);
+  } else {
+    tkr.discard();
   }
   return res;
 }
@@ -1525,8 +1546,7 @@
                            bool allow_exec) {
   char* result = pd_map_memory(fd, file_name, file_offset, addr, bytes, read_only, allow_exec);
   if (result != NULL) {
-    MemTracker::record_virtual_memory_reserve((address)result, bytes, CALLER_PC);
-    MemTracker::record_virtual_memory_commit((address)result, bytes, CALLER_PC);
+    MemTracker::record_virtual_memory_reserve_and_commit((address)result, bytes, mtNone, CALLER_PC);
   }
   return result;
 }
@@ -1539,10 +1559,12 @@
 }
 
 bool os::unmap_memory(char *addr, size_t bytes) {
+  MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
   bool result = pd_unmap_memory(addr, bytes);
   if (result) {
-    MemTracker::record_virtual_memory_uncommit((address)addr, bytes);
-    MemTracker::record_virtual_memory_release((address)addr, bytes);
+    tkr.record((address)addr, bytes);
+  } else {
+    tkr.discard();
   }
   return result;
 }
--- a/hotspot/src/share/vm/runtime/os.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/runtime/os.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -78,6 +78,10 @@
   CriticalPriority = 11      // Critical thread priority
 };
 
+// Executable parameter flag for os::commit_memory() and
+// os::commit_memory_or_exit().
+const bool ExecMem = true;
+
 // Typedef for structured exception handling support
 typedef void (*java_call_t)(JavaValue* value, methodHandle* method, JavaCallArguments* args, Thread* thread);
 
@@ -104,9 +108,16 @@
   static char*  pd_attempt_reserve_memory_at(size_t bytes, char* addr);
   static void   pd_split_reserved_memory(char *base, size_t size,
                                       size_t split, bool realloc);
-  static bool   pd_commit_memory(char* addr, size_t bytes, bool executable = false);
+  static bool   pd_commit_memory(char* addr, size_t bytes, bool executable);
   static bool   pd_commit_memory(char* addr, size_t size, size_t alignment_hint,
-                              bool executable = false);
+                                 bool executable);
+  // Same as pd_commit_memory() that either succeeds or calls
+  // vm_exit_out_of_memory() with the specified mesg.
+  static void   pd_commit_memory_or_exit(char* addr, size_t bytes,
+                                         bool executable, const char* mesg);
+  static void   pd_commit_memory_or_exit(char* addr, size_t size,
+                                         size_t alignment_hint,
+                                         bool executable, const char* mesg);
   static bool   pd_uncommit_memory(char* addr, size_t bytes);
   static bool   pd_release_memory(char* addr, size_t bytes);
 
@@ -261,9 +272,16 @@
   static char*  attempt_reserve_memory_at(size_t bytes, char* addr);
   static void   split_reserved_memory(char *base, size_t size,
                                       size_t split, bool realloc);
-  static bool   commit_memory(char* addr, size_t bytes, bool executable = false);
+  static bool   commit_memory(char* addr, size_t bytes, bool executable);
   static bool   commit_memory(char* addr, size_t size, size_t alignment_hint,
-                              bool executable = false);
+                              bool executable);
+  // Same as commit_memory() that either succeeds or calls
+  // vm_exit_out_of_memory() with the specified mesg.
+  static void   commit_memory_or_exit(char* addr, size_t bytes,
+                                      bool executable, const char* mesg);
+  static void   commit_memory_or_exit(char* addr, size_t size,
+                                      size_t alignment_hint,
+                                      bool executable, const char* mesg);
   static bool   uncommit_memory(char* addr, size_t bytes);
   static bool   release_memory(char* addr, size_t bytes);
 
--- a/hotspot/src/share/vm/runtime/sharedRuntime.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/runtime/sharedRuntime.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -2731,7 +2731,7 @@
   // ResourceObject, so do not put any ResourceMarks in here.
   char *s = sig->as_C_string();
   int len = (int)strlen(s);
-  *s++; len--;                  // Skip opening paren
+  s++; len--;                   // Skip opening paren
   char *t = s+len;
   while( *(--t) != ')' ) ;      // Find close paren
 
--- a/hotspot/src/share/vm/runtime/virtualspace.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/runtime/virtualspace.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -533,11 +533,13 @@
            lower_high() + lower_needs <= lower_high_boundary(),
            "must not expand beyond region");
     if (!os::commit_memory(lower_high(), lower_needs, _executable)) {
-      debug_only(warning("os::commit_memory failed"));
+      debug_only(warning("INFO: os::commit_memory(" PTR_FORMAT
+                         ", lower_needs=" SIZE_FORMAT ", %d) failed",
+                         lower_high(), lower_needs, _executable);)
       return false;
     } else {
       _lower_high += lower_needs;
-     }
+    }
   }
   if (middle_needs > 0) {
     assert(lower_high_boundary() <= middle_high() &&
@@ -545,7 +547,10 @@
            "must not expand beyond region");
     if (!os::commit_memory(middle_high(), middle_needs, middle_alignment(),
                            _executable)) {
-      debug_only(warning("os::commit_memory failed"));
+      debug_only(warning("INFO: os::commit_memory(" PTR_FORMAT
+                         ", middle_needs=" SIZE_FORMAT ", " SIZE_FORMAT
+                         ", %d) failed", middle_high(), middle_needs,
+                         middle_alignment(), _executable);)
       return false;
     }
     _middle_high += middle_needs;
@@ -555,7 +560,9 @@
            upper_high() + upper_needs <= upper_high_boundary(),
            "must not expand beyond region");
     if (!os::commit_memory(upper_high(), upper_needs, _executable)) {
-      debug_only(warning("os::commit_memory failed"));
+      debug_only(warning("INFO: os::commit_memory(" PTR_FORMAT
+                         ", upper_needs=" SIZE_FORMAT ", %d) failed",
+                         upper_high(), upper_needs, _executable);)
       return false;
     } else {
       _upper_high += upper_needs;
--- a/hotspot/src/share/vm/services/diagnosticArgument.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/services/diagnosticArgument.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -247,7 +247,7 @@
   } else {
     _value._time = 0;
     _value._nanotime = 0;
-    strcmp(_value._unit, "ns");
+    strcpy(_value._unit, "ns");
   }
 }
 
--- a/hotspot/src/share/vm/services/memBaseline.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/services/memBaseline.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -130,7 +130,7 @@
       if (malloc_ptr->is_arena_record()) {
         // see if arena memory record present
         MemPointerRecord* next_malloc_ptr = (MemPointerRecordEx*)malloc_itr.peek_next();
-        if (next_malloc_ptr->is_arena_memory_record()) {
+        if (next_malloc_ptr != NULL && next_malloc_ptr->is_arena_memory_record()) {
           assert(next_malloc_ptr->is_memory_record_of_arena(malloc_ptr),
              "Arena records do not match");
           size = next_malloc_ptr->size();
--- a/hotspot/src/share/vm/services/memPtr.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/services/memPtr.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -457,9 +457,8 @@
  public:
   SeqMemPointerRecord(): _seq(0){ }
 
-  SeqMemPointerRecord(address addr, MEMFLAGS flags, size_t size)
-    : MemPointerRecord(addr, flags, size) {
-    _seq = SequenceGenerator::next();
+  SeqMemPointerRecord(address addr, MEMFLAGS flags, size_t size, jint seq)
+    : MemPointerRecord(addr, flags, size), _seq(seq)  {
   }
 
   SeqMemPointerRecord(const SeqMemPointerRecord& copy_from)
@@ -488,8 +487,8 @@
   SeqMemPointerRecordEx(): _seq(0) { }
 
   SeqMemPointerRecordEx(address addr, MEMFLAGS flags, size_t size,
-    address pc): MemPointerRecordEx(addr, flags, size, pc) {
-    _seq = SequenceGenerator::next();
+    jint seq, address pc):
+    MemPointerRecordEx(addr, flags, size, pc), _seq(seq)  {
   }
 
   SeqMemPointerRecordEx(const SeqMemPointerRecordEx& copy_from)
--- a/hotspot/src/share/vm/services/memRecorder.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/services/memRecorder.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,10 +69,11 @@
 
   if (_pointer_records != NULL) {
     // recode itself
+    address pc = CURRENT_PC;
     record((address)this, (MemPointerRecord::malloc_tag()|mtNMT|otNMTRecorder),
-        sizeof(MemRecorder), CALLER_PC);
+        sizeof(MemRecorder), SequenceGenerator::next(), pc);
     record((address)_pointer_records, (MemPointerRecord::malloc_tag()|mtNMT|otNMTRecorder),
-        _pointer_records->instance_size(),CURRENT_PC);
+        _pointer_records->instance_size(), SequenceGenerator::next(), pc);
   }
 }
 
@@ -116,7 +117,8 @@
   }
 }
 
-bool MemRecorder::record(address p, MEMFLAGS flags, size_t size, address pc) {
+bool MemRecorder::record(address p, MEMFLAGS flags, size_t size, jint seq, address pc) {
+  assert(seq > 0, "No sequence number");
 #ifdef ASSERT
   if (MemPointerRecord::is_virtual_memory_record(flags)) {
     assert((flags & MemPointerRecord::tag_masks) != 0, "bad virtual memory record");
@@ -133,11 +135,11 @@
 #endif
 
   if (MemTracker::track_callsite()) {
-    SeqMemPointerRecordEx ap(p, flags, size, pc);
+    SeqMemPointerRecordEx ap(p, flags, size, seq, pc);
     debug_only(check_dup_seq(ap.seq());)
     return _pointer_records->append(&ap);
   } else {
-    SeqMemPointerRecord ap(p, flags, size);
+    SeqMemPointerRecord ap(p, flags, size, seq);
     debug_only(check_dup_seq(ap.seq());)
     return _pointer_records->append(&ap);
   }
--- a/hotspot/src/share/vm/services/memRecorder.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/services/memRecorder.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -220,7 +220,7 @@
   ~MemRecorder();
 
   // record a memory operation
-  bool record(address addr, MEMFLAGS flags, size_t size, address caller_pc = 0);
+  bool record(address addr, MEMFLAGS flags, size_t size, jint seq, address caller_pc = 0);
 
   // linked list support
   inline void set_next(MemRecorder* rec) {
--- a/hotspot/src/share/vm/services/memReporter.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/services/memReporter.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -190,17 +190,18 @@
   while (cur_malloc_callsite != NULL || prev_malloc_callsite != NULL) {
     if (prev_malloc_callsite == NULL ||
         cur_malloc_callsite->addr() < prev_malloc_callsite->addr()) {
+      // this is a new callsite
       _outputer.diff_malloc_callsite(cur_malloc_callsite->addr(),
         amount_in_current_scale(cur_malloc_callsite->amount()),
         cur_malloc_callsite->count(),
         diff_in_current_scale(cur_malloc_callsite->amount(), 0),
         diff(cur_malloc_callsite->count(), 0));
       cur_malloc_callsite = (MallocCallsitePointer*)cur_malloc_itr.next();
-    } else if (prev_malloc_callsite == NULL ||
+    } else if (cur_malloc_callsite == NULL ||
                cur_malloc_callsite->addr() > prev_malloc_callsite->addr()) {
-      _outputer.diff_malloc_callsite(cur_malloc_callsite->addr(),
-        amount_in_current_scale(prev_malloc_callsite->amount()),
-        prev_malloc_callsite->count(),
+      // this callsite is already gone
+      _outputer.diff_malloc_callsite(prev_malloc_callsite->addr(),
+        amount_in_current_scale(0), 0,
         diff_in_current_scale(0, prev_malloc_callsite->amount()),
         diff(0, prev_malloc_callsite->count()));
       prev_malloc_callsite = (MallocCallsitePointer*)prev_malloc_itr.next();
@@ -222,6 +223,7 @@
   VMCallsitePointer*          prev_vm_callsite = (VMCallsitePointer*)prev_vm_itr.current();
   while (cur_vm_callsite != NULL || prev_vm_callsite != NULL) {
     if (prev_vm_callsite == NULL || cur_vm_callsite->addr() < prev_vm_callsite->addr()) {
+      // this is a new callsite
       _outputer.diff_virtual_memory_callsite(cur_vm_callsite->addr(),
         amount_in_current_scale(cur_vm_callsite->reserved_amount()),
         amount_in_current_scale(cur_vm_callsite->committed_amount()),
@@ -229,9 +231,10 @@
         diff_in_current_scale(cur_vm_callsite->committed_amount(), 0));
       cur_vm_callsite = (VMCallsitePointer*)cur_vm_itr.next();
     } else if (cur_vm_callsite == NULL || cur_vm_callsite->addr() > prev_vm_callsite->addr()) {
+      // this callsite is already gone
       _outputer.diff_virtual_memory_callsite(prev_vm_callsite->addr(),
-        amount_in_current_scale(prev_vm_callsite->reserved_amount()),
-        amount_in_current_scale(prev_vm_callsite->committed_amount()),
+        amount_in_current_scale(0),
+        amount_in_current_scale(0),
         diff_in_current_scale(0, prev_vm_callsite->reserved_amount()),
         diff_in_current_scale(0, prev_vm_callsite->committed_amount()));
       prev_vm_callsite = (VMCallsitePointer*)prev_vm_itr.next();
--- a/hotspot/src/share/vm/services/memTracker.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/services/memTracker.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -69,6 +69,7 @@
 volatile jint                   MemTracker::_pooled_recorder_count = 0;
 volatile unsigned long          MemTracker::_processing_generation = 0;
 volatile bool                   MemTracker::_worker_thread_idle = false;
+volatile jint                   MemTracker::_pending_op_count = 0;
 volatile bool                   MemTracker::_slowdown_calling_thread = false;
 debug_only(intx                 MemTracker::_main_thread_tid = 0;)
 NOT_PRODUCT(volatile jint       MemTracker::_pending_recorder_count = 0;)
@@ -337,92 +338,14 @@
   Atomic::inc(&_pooled_recorder_count);
 }
 
-/*
- * This is the most important method in whole nmt implementation.
- *
- * Create a memory record.
- * 1. When nmt is in single-threaded bootstrapping mode, no lock is needed as VM
- *    still in single thread mode.
- * 2. For all threads other than JavaThread, ThreadCritical is needed
- *    to write to recorders to global recorder.
- * 3. For JavaThreads that are not longer visible by safepoint, also
- *    need to take ThreadCritical and records are written to global
- *    recorders, since these threads are NOT walked by Threads.do_thread().
- * 4. JavaThreads that are running in native state, have to transition
- *    to VM state before writing to per-thread recorders.
- * 5. JavaThreads that are running in VM state do not need any lock and
- *    records are written to per-thread recorders.
- * 6. For a thread has yet to attach VM 'Thread', they need to take
- *    ThreadCritical to write to global recorder.
- *
- *    Important note:
- *    NO LOCK should be taken inside ThreadCritical lock !!!
- */
-void MemTracker::create_memory_record(address addr, MEMFLAGS flags,
-    size_t size, address pc, Thread* thread) {
-  assert(addr != NULL, "Sanity check");
-  if (!shutdown_in_progress()) {
-    // single thread, we just write records direct to global recorder,'
-    // with any lock
-    if (_state == NMT_bootstrapping_single_thread) {
-      assert(_main_thread_tid == os::current_thread_id(), "wrong thread");
-      thread = NULL;
-    } else {
-      if (thread == NULL) {
-          // don't use Thread::current(), since it is possible that
-          // the calling thread has yet to attach to VM 'Thread',
-          // which will result assertion failure
-          thread = ThreadLocalStorage::thread();
-      }
-    }
-
-    if (thread != NULL) {
-      // slow down all calling threads except NMT worker thread, so it
-      // can catch up.
-      if (_slowdown_calling_thread && thread != _worker_thread) {
-        os::yield_all();
-      }
-
-      if (thread->is_Java_thread() && ((JavaThread*)thread)->is_safepoint_visible()) {
-        JavaThread*      java_thread = (JavaThread*)thread;
-        JavaThreadState  state = java_thread->thread_state();
-        if (SafepointSynchronize::safepoint_safe(java_thread, state)) {
-          // JavaThreads that are safepoint safe, can run through safepoint,
-          // so ThreadCritical is needed to ensure no threads at safepoint create
-          // new records while the records are being gathered and the sequence number is changing
-          ThreadCritical tc;
-          create_record_in_recorder(addr, flags, size, pc, java_thread);
-        } else {
-          create_record_in_recorder(addr, flags, size, pc, java_thread);
-        }
-      } else {
-        // other threads, such as worker and watcher threads, etc. need to
-        // take ThreadCritical to write to global recorder
-        ThreadCritical tc;
-        create_record_in_recorder(addr, flags, size, pc, NULL);
-      }
-    } else {
-      if (_state == NMT_bootstrapping_single_thread) {
-        // single thread, no lock needed
-        create_record_in_recorder(addr, flags, size, pc, NULL);
-      } else {
-        // for thread has yet to attach VM 'Thread', we can not use VM mutex.
-        // use native thread critical instead
-        ThreadCritical tc;
-        create_record_in_recorder(addr, flags, size, pc, NULL);
-      }
-    }
-  }
-}
-
 // write a record to proper recorder. No lock can be taken from this method
 // down.
-void MemTracker::create_record_in_recorder(address addr, MEMFLAGS flags,
-    size_t size, address pc, JavaThread* thread) {
+void MemTracker::write_tracking_record(address addr, MEMFLAGS flags,
+    size_t size, jint seq, address pc, JavaThread* thread) {
 
     MemRecorder* rc = get_thread_recorder(thread);
     if (rc != NULL) {
-      rc->record(addr, flags, size, pc);
+      rc->record(addr, flags, size, seq, pc);
     }
 }
 
@@ -487,39 +410,43 @@
         return;
       }
     }
-    _sync_point_skip_count = 0;
     {
       // This method is running at safepoint, with ThreadCritical lock,
       // it should guarantee that NMT is fully sync-ed.
       ThreadCritical tc;
 
-      SequenceGenerator::reset();
+      // We can NOT execute NMT sync-point if there are pending tracking ops.
+      if (_pending_op_count == 0) {
+        SequenceGenerator::reset();
+        _sync_point_skip_count = 0;
 
-      // walk all JavaThreads to collect recorders
-      SyncThreadRecorderClosure stc;
-      Threads::threads_do(&stc);
+        // walk all JavaThreads to collect recorders
+        SyncThreadRecorderClosure stc;
+        Threads::threads_do(&stc);
+
+        _thread_count = stc.get_thread_count();
+        MemRecorder* pending_recorders = get_pending_recorders();
 
-      _thread_count = stc.get_thread_count();
-      MemRecorder* pending_recorders = get_pending_recorders();
+        if (_global_recorder != NULL) {
+          _global_recorder->set_next(pending_recorders);
+          pending_recorders = _global_recorder;
+          _global_recorder = NULL;
+        }
 
-      if (_global_recorder != NULL) {
-        _global_recorder->set_next(pending_recorders);
-        pending_recorders = _global_recorder;
-        _global_recorder = NULL;
+        // see if NMT has too many outstanding recorder instances, it usually
+        // means that worker thread is lagging behind in processing them.
+        if (!AutoShutdownNMT) {
+          _slowdown_calling_thread = (MemRecorder::_instance_count > MAX_RECORDER_THREAD_RATIO * _thread_count);
+        }
+
+        // check _worker_thread with lock to avoid racing condition
+        if (_worker_thread != NULL) {
+          _worker_thread->at_sync_point(pending_recorders, InstanceKlass::number_of_instance_classes());
+        }
+        assert(SequenceGenerator::peek() == 1, "Should not have memory activities during sync-point");
+      } else {
+        _sync_point_skip_count ++;
       }
-
-      // see if NMT has too many outstanding recorder instances, it usually
-      // means that worker thread is lagging behind in processing them.
-      if (!AutoShutdownNMT) {
-        _slowdown_calling_thread = (MemRecorder::_instance_count > MAX_RECORDER_THREAD_RATIO * _thread_count);
-      }
-
-      // check _worker_thread with lock to avoid racing condition
-      if (_worker_thread != NULL) {
-        _worker_thread->at_sync_point(pending_recorders, InstanceKlass::number_of_instance_classes());
-      }
-
-      assert(SequenceGenerator::peek() == 1, "Should not have memory activities during sync-point");
     }
   }
 
@@ -708,3 +635,243 @@
 }
 #endif
 
+
+// Tracker Implementation
+
+/*
+ * Create a tracker.
+ * This is a fairly complicated constructor, as it has to make two important decisions:
+ *   1) Does it need to take ThreadCritical lock to write tracking record
+ *   2) Does it need to pre-reserve a sequence number for the tracking record
+ *
+ * The rules to determine if ThreadCritical is needed:
+ *   1. When nmt is in single-threaded bootstrapping mode, no lock is needed as VM
+ *      still in single thread mode.
+ *   2. For all threads other than JavaThread, ThreadCritical is needed
+ *      to write to recorders to global recorder.
+ *   3. For JavaThreads that are no longer visible by safepoint, also
+ *      need to take ThreadCritical and records are written to global
+ *      recorders, since these threads are NOT walked by Threads.do_thread().
+ *   4. JavaThreads that are running in safepoint-safe states do not stop
+ *      for safepoints, ThreadCritical lock should be taken to write
+ *      memory records.
+ *   5. JavaThreads that are running in VM state do not need any lock and
+ *      records are written to per-thread recorders.
+ *   6. For a thread has yet to attach VM 'Thread', they need to take
+ *      ThreadCritical to write to global recorder.
+ *
+ *  The memory operations that need pre-reserve sequence numbers:
+ *    The memory operations that "release" memory blocks and the
+ *    operations can fail, need to pre-reserve sequence number. They
+ *    are realloc, uncommit and release.
+ *
+ *  The reason for pre-reserve sequence number, is to prevent race condition:
+ *    Thread 1                      Thread 2
+ *    <release>
+ *                                  <allocate>
+ *                                  <write allocate record>
+ *   <write release record>
+ *   if Thread 2 happens to obtain the memory address Thread 1 just released,
+ *   then NMT can mistakenly report the memory is free.
+ *
+ *  Noticeably, free() does not need pre-reserve sequence number, because the call
+ *  does not fail, so we can alway write "release" record before the memory is actaully
+ *  freed.
+ *
+ *  For realloc, uncommit and release, following coding pattern should be used:
+ *
+ *     MemTracker::Tracker tkr = MemTracker::get_realloc_tracker();
+ *     ptr = ::realloc(...);
+ *     if (ptr == NULL) {
+ *       tkr.record(...)
+ *     } else {
+ *       tkr.discard();
+ *     }
+ *
+ *     MemTracker::Tracker tkr = MemTracker::get_virtual_memory_uncommit_tracker();
+ *     if (uncommit(...)) {
+ *       tkr.record(...);
+ *     } else {
+ *       tkr.discard();
+ *     }
+ *
+ *     MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
+ *     if (release(...)) {
+ *       tkr.record(...);
+ *     } else {
+ *       tkr.discard();
+ *     }
+ *
+ * Since pre-reserved sequence number is only good for the generation that it is acquired,
+ * when there is pending Tracker that reserved sequence number, NMT sync-point has
+ * to be skipped to prevent from advancing generation. This is done by inc and dec
+ * MemTracker::_pending_op_count, when MemTracker::_pending_op_count > 0, NMT sync-point is skipped.
+ * Not all pre-reservation of sequence number will increment pending op count. For JavaThreads
+ * that honor safepoints, safepoint can not occur during the memory operations, so the
+ * pre-reserved sequence number won't cross the generation boundry.
+ */
+MemTracker::Tracker::Tracker(MemoryOperation op, Thread* thr) {
+  _op = NoOp;
+  _seq = 0;
+  if (MemTracker::is_on()) {
+    _java_thread = NULL;
+    _op = op;
+
+    // figure out if ThreadCritical lock is needed to write this operation
+    // to MemTracker
+    if (MemTracker::is_single_threaded_bootstrap()) {
+      thr = NULL;
+    } else if (thr == NULL) {
+      // don't use Thread::current(), since it is possible that
+      // the calling thread has yet to attach to VM 'Thread',
+      // which will result assertion failure
+      thr = ThreadLocalStorage::thread();
+    }
+
+    if (thr != NULL) {
+      // Check NMT load
+      MemTracker::check_NMT_load(thr);
+
+      if (thr->is_Java_thread() && ((JavaThread*)thr)->is_safepoint_visible()) {
+        _java_thread = (JavaThread*)thr;
+        JavaThreadState  state = _java_thread->thread_state();
+        // JavaThreads that are safepoint safe, can run through safepoint,
+        // so ThreadCritical is needed to ensure no threads at safepoint create
+        // new records while the records are being gathered and the sequence number is changing
+        _need_thread_critical_lock =
+          SafepointSynchronize::safepoint_safe(_java_thread, state);
+      } else {
+        _need_thread_critical_lock = true;
+      }
+    } else {
+       _need_thread_critical_lock
+         = !MemTracker::is_single_threaded_bootstrap();
+    }
+
+    // see if we need to pre-reserve sequence number for this operation
+    if (_op == Realloc || _op == Uncommit || _op == Release) {
+      if (_need_thread_critical_lock) {
+        ThreadCritical tc;
+        MemTracker::inc_pending_op_count();
+        _seq = SequenceGenerator::next();
+      } else {
+        // for the threads that honor safepoints, no safepoint can occur
+        // during the lifespan of tracker, so we don't need to increase
+        // pending op count.
+        _seq = SequenceGenerator::next();
+      }
+    }
+  }
+}
+
+void MemTracker::Tracker::discard() {
+  if (MemTracker::is_on() && _seq != 0) {
+    if (_need_thread_critical_lock) {
+      ThreadCritical tc;
+      MemTracker::dec_pending_op_count();
+    }
+    _seq = 0;
+  }
+}
+
+
+void MemTracker::Tracker::record(address old_addr, address new_addr, size_t size,
+  MEMFLAGS flags, address pc) {
+  assert(old_addr != NULL && new_addr != NULL, "Sanity check");
+  assert(_op == Realloc || _op == NoOp, "Wrong call");
+  if (MemTracker::is_on() && NMT_CAN_TRACK(flags) && _op != NoOp) {
+    assert(_seq > 0, "Need pre-reserve sequence number");
+    if (_need_thread_critical_lock) {
+      ThreadCritical tc;
+      // free old address, use pre-reserved sequence number
+      MemTracker::write_tracking_record(old_addr, MemPointerRecord::free_tag(),
+        0, _seq, pc, _java_thread);
+      MemTracker::write_tracking_record(new_addr, flags | MemPointerRecord::malloc_tag(),
+        size, SequenceGenerator::next(), pc, _java_thread);
+      // decrement MemTracker pending_op_count
+      MemTracker::dec_pending_op_count();
+    } else {
+      // free old address, use pre-reserved sequence number
+      MemTracker::write_tracking_record(old_addr, MemPointerRecord::free_tag(),
+        0, _seq, pc, _java_thread);
+      MemTracker::write_tracking_record(new_addr, flags | MemPointerRecord::malloc_tag(),
+        size, SequenceGenerator::next(), pc, _java_thread);
+    }
+    _seq = 0;
+  }
+}
+
+void MemTracker::Tracker::record(address addr, size_t size, MEMFLAGS flags, address pc) {
+  // OOM already?
+  if (addr == NULL) return;
+
+  if (MemTracker::is_on() && NMT_CAN_TRACK(flags) && _op != NoOp) {
+    bool pre_reserved_seq = (_seq != 0);
+    address  pc = CALLER_CALLER_PC;
+    MEMFLAGS orig_flags = flags;
+
+    // or the tagging flags
+    switch(_op) {
+      case Malloc:
+        flags |= MemPointerRecord::malloc_tag();
+        break;
+      case Free:
+        flags = MemPointerRecord::free_tag();
+        break;
+      case Realloc:
+        fatal("Use the other Tracker::record()");
+        break;
+      case Reserve:
+      case ReserveAndCommit:
+        flags |= MemPointerRecord::virtual_memory_reserve_tag();
+        break;
+      case Commit:
+        flags = MemPointerRecord::virtual_memory_commit_tag();
+        break;
+      case Type:
+        flags |= MemPointerRecord::virtual_memory_type_tag();
+        break;
+      case Uncommit:
+        assert(pre_reserved_seq, "Need pre-reserve sequence number");
+        flags = MemPointerRecord::virtual_memory_uncommit_tag();
+        break;
+      case Release:
+        assert(pre_reserved_seq, "Need pre-reserve sequence number");
+        flags = MemPointerRecord::virtual_memory_release_tag();
+        break;
+      case ArenaSize:
+        // a bit of hack here, add a small postive offset to arena
+        // address for its size record, so the size record is sorted
+        // right after arena record.
+        flags = MemPointerRecord::arena_size_tag();
+        addr += sizeof(void*);
+        break;
+      case StackRelease:
+        flags = MemPointerRecord::virtual_memory_release_tag();
+        break;
+      default:
+        ShouldNotReachHere();
+    }
+
+    // write memory tracking record
+    if (_need_thread_critical_lock) {
+      ThreadCritical tc;
+      if (_seq == 0) _seq = SequenceGenerator::next();
+      MemTracker::write_tracking_record(addr, flags, size, _seq, pc, _java_thread);
+      if (_op == ReserveAndCommit) {
+        MemTracker::write_tracking_record(addr, orig_flags | MemPointerRecord::virtual_memory_commit_tag(),
+          size, SequenceGenerator::next(), pc, _java_thread);
+      }
+      if (pre_reserved_seq) MemTracker::dec_pending_op_count();
+    } else {
+      if (_seq == 0) _seq = SequenceGenerator::next();
+      MemTracker::write_tracking_record(addr, flags, size, _seq, pc, _java_thread);
+      if (_op == ReserveAndCommit) {
+        MemTracker::write_tracking_record(addr, orig_flags | MemPointerRecord::virtual_memory_commit_tag(),
+          size, SequenceGenerator::next(), pc, _java_thread);
+      }
+    }
+    _seq = 0;
+  }
+}
+
--- a/hotspot/src/share/vm/services/memTracker.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/services/memTracker.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,18 @@
       NMT_sequence_overflow  // overflow the sequence number
    };
 
+  class Tracker {
+   public:
+    void discard() { }
+
+    void record(address addr, size_t size = 0, MEMFLAGS flags = mtNone, address pc = NULL) { }
+    void record(address old_addr, address new_addr, size_t size,
+      MEMFLAGS flags, address pc = NULL) { }
+  };
+
+  private:
+   static Tracker  _tkr;
+
 
   public:
    static inline void init_tracking_options(const char* option_line) { }
@@ -68,19 +80,18 @@
    static inline void record_malloc(address addr, size_t size, MEMFLAGS flags,
         address pc = 0, Thread* thread = NULL) { }
    static inline void record_free(address addr, MEMFLAGS flags, Thread* thread = NULL) { }
-   static inline void record_realloc(address old_addr, address new_addr, size_t size,
-        MEMFLAGS flags, address pc = 0, Thread* thread = NULL) { }
    static inline void record_arena_size(address addr, size_t size) { }
    static inline void record_virtual_memory_reserve(address addr, size_t size,
-        address pc = 0, Thread* thread = NULL) { }
+        MEMFLAGS flags, address pc = 0, Thread* thread = NULL) { }
+   static inline void record_virtual_memory_reserve_and_commit(address addr, size_t size,
+        MEMFLAGS flags, address pc = 0, Thread* thread = NULL) { }
    static inline void record_virtual_memory_commit(address addr, size_t size,
         address pc = 0, Thread* thread = NULL) { }
-   static inline void record_virtual_memory_uncommit(address addr, size_t size,
-        Thread* thread = NULL) { }
-   static inline void record_virtual_memory_release(address addr, size_t size,
-        Thread* thread = NULL) { }
    static inline void record_virtual_memory_type(address base, MEMFLAGS flags,
         Thread* thread = NULL) { }
+   static inline Tracker get_realloc_tracker() { return _tkr; }
+   static inline Tracker get_virtual_memory_uncommit_tracker() { return _tkr; }
+   static inline Tracker get_virtual_memory_release_tracker()  { return _tkr; }
    static inline bool baseline() { return false; }
    static inline bool has_baseline() { return false; }
 
@@ -165,6 +176,45 @@
   };
 
  public:
+  class Tracker : public StackObj {
+    friend class MemTracker;
+   public:
+    enum MemoryOperation {
+      NoOp,                   // no op
+      Malloc,                 // malloc
+      Realloc,                // realloc
+      Free,                   // free
+      Reserve,                // virtual memory reserve
+      Commit,                 // virtual memory commit
+      ReserveAndCommit,       // virtual memory reserve and commit
+      StackAlloc = ReserveAndCommit, // allocate thread stack
+      Type,                   // assign virtual memory type
+      Uncommit,               // virtual memory uncommit
+      Release,                // virtual memory release
+      ArenaSize,              // set arena size
+      StackRelease            // release thread stack
+    };
+
+
+   protected:
+    Tracker(MemoryOperation op, Thread* thr = NULL);
+
+   public:
+    void discard();
+
+    void record(address addr, size_t size = 0, MEMFLAGS flags = mtNone, address pc = NULL);
+    void record(address old_addr, address new_addr, size_t size,
+      MEMFLAGS flags, address pc = NULL);
+
+   private:
+    bool            _need_thread_critical_lock;
+    JavaThread*     _java_thread;
+    MemoryOperation _op;          // memory operation
+    jint            _seq;         // reserved sequence number
+  };
+
+
+ public:
   // native memory tracking level
   enum NMTLevel {
     NMT_off,              // native memory tracking is off
@@ -276,109 +326,74 @@
   // record a 'malloc' call
   static inline void record_malloc(address addr, size_t size, MEMFLAGS flags,
                             address pc = 0, Thread* thread = NULL) {
-    if (is_on() && NMT_CAN_TRACK(flags)) {
-      assert(size > 0, "Sanity check");
-      create_memory_record(addr, (flags|MemPointerRecord::malloc_tag()), size, pc, thread);
-    }
+    Tracker tkr(Tracker::Malloc, thread);
+    tkr.record(addr, size, flags, pc);
   }
   // record a 'free' call
   static inline void record_free(address addr, MEMFLAGS flags, Thread* thread = NULL) {
-    if (is_on() && NMT_CAN_TRACK(flags)) {
-      create_memory_record(addr, MemPointerRecord::free_tag(), 0, 0, thread);
-    }
-  }
-  // record a 'realloc' call
-  static inline void record_realloc(address old_addr, address new_addr, size_t size,
-       MEMFLAGS flags, address pc = 0, Thread* thread = NULL) {
-    if (is_on() && NMT_CAN_TRACK(flags)) {
-      assert(size > 0, "Sanity check");
-      record_free(old_addr, flags, thread);
-      record_malloc(new_addr, size, flags, pc, thread);
-    }
+    Tracker tkr(Tracker::Free, thread);
+    tkr.record(addr, 0, flags, DEBUG_CALLER_PC);
   }
 
-  // record arena memory size
   static inline void record_arena_size(address addr, size_t size) {
-    // we add a positive offset to arena address, so we can have arena memory record
-    // sorted after arena record
-    if (is_on() && !UseMallocOnly) {
-      assert(addr != NULL, "Sanity check");
-      create_memory_record((addr + sizeof(void*)), MemPointerRecord::arena_size_tag(), size,
-        DEBUG_CALLER_PC, NULL);
-    }
+    Tracker tkr(Tracker::ArenaSize);
+    tkr.record(addr, size);
   }
 
   // record a virtual memory 'reserve' call
   static inline void record_virtual_memory_reserve(address addr, size_t size,
-                            address pc = 0, Thread* thread = NULL) {
-    if (is_on()) {
-      assert(size > 0, "Sanity check");
-      create_memory_record(addr, MemPointerRecord::virtual_memory_reserve_tag(),
-                           size, pc, thread);
-    }
+                     MEMFLAGS flags, address pc = 0, Thread* thread = NULL) {
+    assert(size > 0, "Sanity check");
+    Tracker tkr(Tracker::Reserve, thread);
+    tkr.record(addr, size, flags, pc);
   }
 
   static inline void record_thread_stack(address addr, size_t size, Thread* thr,
                            address pc = 0) {
-    if (is_on()) {
-      assert(size > 0 && thr != NULL, "Sanity check");
-      create_memory_record(addr, MemPointerRecord::virtual_memory_reserve_tag() | mtThreadStack,
-                          size, pc, thr);
-      create_memory_record(addr, MemPointerRecord::virtual_memory_commit_tag() | mtThreadStack,
-                          size, pc, thr);
-    }
+    Tracker tkr(Tracker::StackAlloc, thr);
+    tkr.record(addr, size, mtThreadStack, pc);
   }
 
   static inline void release_thread_stack(address addr, size_t size, Thread* thr) {
-    if (is_on()) {
-      assert(size > 0 && thr != NULL, "Sanity check");
-      assert(!thr->is_Java_thread(), "too early");
-      create_memory_record(addr, MemPointerRecord::virtual_memory_uncommit_tag() | mtThreadStack,
-                          size, DEBUG_CALLER_PC, thr);
-      create_memory_record(addr, MemPointerRecord::virtual_memory_release_tag() | mtThreadStack,
-                          size, DEBUG_CALLER_PC, thr);
-    }
+    Tracker tkr(Tracker::StackRelease, thr);
+    tkr.record(addr, size, mtThreadStack, DEBUG_CALLER_PC);
   }
 
   // record a virtual memory 'commit' call
   static inline void record_virtual_memory_commit(address addr, size_t size,
                             address pc, Thread* thread = NULL) {
-    if (is_on()) {
-      assert(size > 0, "Sanity check");
-      create_memory_record(addr, MemPointerRecord::virtual_memory_commit_tag(),
-                           size, pc, thread);
-    }
+    Tracker tkr(Tracker::Commit, thread);
+    tkr.record(addr, size, mtNone, pc);
   }
 
-  // record a virtual memory 'uncommit' call
-  static inline void record_virtual_memory_uncommit(address addr, size_t size,
-                            Thread* thread = NULL) {
-    if (is_on()) {
-      assert(size > 0, "Sanity check");
-      create_memory_record(addr, MemPointerRecord::virtual_memory_uncommit_tag(),
-                           size, DEBUG_CALLER_PC, thread);
-    }
+  static inline void record_virtual_memory_reserve_and_commit(address addr, size_t size,
+    MEMFLAGS flags, address pc, Thread* thread = NULL) {
+    Tracker tkr(Tracker::ReserveAndCommit, thread);
+    tkr.record(addr, size, flags, pc);
   }
 
-  // record a virtual memory 'release' call
-  static inline void record_virtual_memory_release(address addr, size_t size,
-                            Thread* thread = NULL) {
-    if (is_on()) {
-      assert(size > 0, "Sanity check");
-      create_memory_record(addr, MemPointerRecord::virtual_memory_release_tag(),
-                           size, DEBUG_CALLER_PC, thread);
-    }
-  }
 
   // record memory type on virtual memory base address
   static inline void record_virtual_memory_type(address base, MEMFLAGS flags,
                             Thread* thread = NULL) {
-    if (is_on()) {
-      assert(base > 0, "wrong base address");
-      assert((flags & (~mt_masks)) == 0, "memory type only");
-      create_memory_record(base, (flags | MemPointerRecord::virtual_memory_type_tag()),
-                           0, DEBUG_CALLER_PC, thread);
-    }
+    Tracker tkr(Tracker::Type);
+    tkr.record(base, 0, flags);
+  }
+
+  // Get memory trackers for memory operations that can result race conditions.
+  // The memory tracker has to be obtained before realloc, virtual memory uncommit
+  // and virtual memory release, and call tracker.record() method if operation
+  // succeeded, or tracker.discard() to abort the tracking.
+  static inline Tracker get_realloc_tracker() {
+    return Tracker(Tracker::Realloc);
+  }
+
+  static inline Tracker get_virtual_memory_uncommit_tracker() {
+    return Tracker(Tracker::Uncommit);
+  }
+
+  static inline Tracker get_virtual_memory_release_tracker() {
+    return Tracker(Tracker::Release);
   }
 
 
@@ -444,6 +459,31 @@
   static MemRecorder* get_pending_recorders();
   static void delete_all_pending_recorders();
 
+  // write a memory tracking record in recorder
+  static void write_tracking_record(address addr, MEMFLAGS type,
+    size_t size, jint seq, address pc, JavaThread* thread);
+
+  static bool is_single_threaded_bootstrap() {
+    return _state == NMT_bootstrapping_single_thread;
+  }
+
+  static void check_NMT_load(Thread* thr) {
+    assert(thr != NULL, "Sanity check");
+    if (_slowdown_calling_thread && thr != _worker_thread) {
+      os::yield_all();
+    }
+  }
+
+  static void inc_pending_op_count() {
+    Atomic::inc(&_pending_op_count);
+  }
+
+  static void dec_pending_op_count() {
+    Atomic::dec(&_pending_op_count);
+    assert(_pending_op_count >= 0, "Sanity check");
+  }
+
+
  private:
   // retrieve a pooled memory record or create new one if there is not
   // one available
@@ -522,6 +562,12 @@
   // if NMT should slow down calling thread to allow
   // worker thread to catch up
   static volatile bool             _slowdown_calling_thread;
+
+  // pending memory op count.
+  // Certain memory ops need to pre-reserve sequence number
+  // before memory operation can happen to avoid race condition.
+  // See MemTracker::Tracker for detail
+  static volatile jint             _pending_op_count;
 };
 
 #endif // !INCLUDE_NMT
--- a/hotspot/src/share/vm/services/threadService.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/services/threadService.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -327,27 +327,30 @@
     while (waitingToLockMonitor != NULL || waitingToLockBlocker != NULL) {
       cycle->add_thread(currentThread);
       if (waitingToLockMonitor != NULL) {
-        currentThread = Threads::owning_thread_from_monitor_owner(
-                          (address)waitingToLockMonitor->owner(),
-                          false /* no locking needed */);
-        if (currentThread == NULL) {
-          // This function is called at a safepoint so the JavaThread
-          // that owns waitingToLockMonitor should be findable, but
-          // if it is not findable, then the previous currentThread is
-          // blocked permanently. We record this as a deadlock.
-          num_deadlocks++;
+        address currentOwner = (address)waitingToLockMonitor->owner();
+        if (currentOwner != NULL) {
+          currentThread = Threads::owning_thread_from_monitor_owner(
+                            currentOwner,
+                            false /* no locking needed */);
+          if (currentThread == NULL) {
+            // This function is called at a safepoint so the JavaThread
+            // that owns waitingToLockMonitor should be findable, but
+            // if it is not findable, then the previous currentThread is
+            // blocked permanently. We record this as a deadlock.
+            num_deadlocks++;
 
-          cycle->set_deadlock(true);
+            cycle->set_deadlock(true);
 
-          // add this cycle to the deadlocks list
-          if (deadlocks == NULL) {
-            deadlocks = cycle;
-          } else {
-            last->set_next(cycle);
+            // add this cycle to the deadlocks list
+            if (deadlocks == NULL) {
+              deadlocks = cycle;
+            } else {
+              last->set_next(cycle);
+            }
+            last = cycle;
+            cycle = new DeadlockCycle();
+            break;
           }
-          last = cycle;
-          cycle = new DeadlockCycle();
-          break;
         }
       } else {
         if (concurrent_locks) {
--- a/hotspot/src/share/vm/utilities/bitMap.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/utilities/bitMap.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -41,7 +41,7 @@
 
 
 BitMap::BitMap(bm_word_t* map, idx_t size_in_bits) :
-  _map(map), _size(size_in_bits)
+  _map(map), _size(size_in_bits), _map_allocator(false)
 {
   assert(sizeof(bm_word_t) == BytesPerWord, "Implementation assumption.");
   assert(size_in_bits >= 0, "just checking");
@@ -49,7 +49,7 @@
 
 
 BitMap::BitMap(idx_t size_in_bits, bool in_resource_area) :
-  _map(NULL), _size(0)
+  _map(NULL), _size(0), _map_allocator(false)
 {
   assert(sizeof(bm_word_t) == BytesPerWord, "Implementation assumption.");
   resize(size_in_bits, in_resource_area);
@@ -65,8 +65,10 @@
   if (in_resource_area) {
     _map = NEW_RESOURCE_ARRAY(bm_word_t, new_size_in_words);
   } else {
-    if (old_map != NULL) FREE_C_HEAP_ARRAY(bm_word_t, _map, mtInternal);
-    _map = NEW_C_HEAP_ARRAY(bm_word_t, new_size_in_words, mtInternal);
+    if (old_map != NULL) {
+      _map_allocator.free();
+    }
+    _map = _map_allocator.allocate(new_size_in_words);
   }
   Copy::disjoint_words((HeapWord*)old_map, (HeapWord*) _map,
                        MIN2(old_size_in_words, new_size_in_words));
--- a/hotspot/src/share/vm/utilities/bitMap.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/utilities/bitMap.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -48,6 +48,7 @@
   } RangeSizeHint;
 
  private:
+  ArrayAllocator<bm_word_t, mtInternal> _map_allocator;
   bm_word_t* _map;     // First word in bitmap
   idx_t      _size;    // Size of bitmap (in bits)
 
@@ -113,7 +114,7 @@
  public:
 
   // Constructs a bitmap with no map, and size 0.
-  BitMap() : _map(NULL), _size(0) {}
+  BitMap() : _map(NULL), _size(0), _map_allocator(false) {}
 
   // Constructs a bitmap with the given map and size.
   BitMap(bm_word_t* map, idx_t size_in_bits);
--- a/hotspot/src/share/vm/utilities/exceptions.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/utilities/exceptions.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -194,15 +194,15 @@
 #define HAS_PENDING_EXCEPTION                    (((ThreadShadow*)THREAD)->has_pending_exception())
 #define CLEAR_PENDING_EXCEPTION                  (((ThreadShadow*)THREAD)->clear_pending_exception())
 
-#define CHECK                                    THREAD); if (HAS_PENDING_EXCEPTION) return       ; (0
-#define CHECK_(result)                           THREAD); if (HAS_PENDING_EXCEPTION) return result; (0
+#define CHECK                                    THREAD); if (HAS_PENDING_EXCEPTION) return       ; (void)(0
+#define CHECK_(result)                           THREAD); if (HAS_PENDING_EXCEPTION) return result; (void)(0
 #define CHECK_0                                  CHECK_(0)
 #define CHECK_NH                                 CHECK_(Handle())
 #define CHECK_NULL                               CHECK_(NULL)
 #define CHECK_false                              CHECK_(false)
 
-#define CHECK_AND_CLEAR                         THREAD); if (HAS_PENDING_EXCEPTION) { CLEAR_PENDING_EXCEPTION; return;        } (0
-#define CHECK_AND_CLEAR_(result)                THREAD); if (HAS_PENDING_EXCEPTION) { CLEAR_PENDING_EXCEPTION; return result; } (0
+#define CHECK_AND_CLEAR                         THREAD); if (HAS_PENDING_EXCEPTION) { CLEAR_PENDING_EXCEPTION; return;        } (void)(0
+#define CHECK_AND_CLEAR_(result)                THREAD); if (HAS_PENDING_EXCEPTION) { CLEAR_PENDING_EXCEPTION; return result; } (void)(0
 #define CHECK_AND_CLEAR_0                       CHECK_AND_CLEAR_(0)
 #define CHECK_AND_CLEAR_NH                      CHECK_AND_CLEAR_(Handle())
 #define CHECK_AND_CLEAR_NULL                    CHECK_AND_CLEAR_(NULL)
@@ -282,7 +282,7 @@
     CLEAR_PENDING_EXCEPTION;               \
     ex->print();                           \
     ShouldNotReachHere();                  \
-  } (0
+  } (void)(0
 
 // ExceptionMark is a stack-allocated helper class for local exception handling.
 // It is used with the EXCEPTION_MARK macro.
--- a/hotspot/src/share/vm/utilities/taskqueue.hpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/src/share/vm/utilities/taskqueue.hpp	Wed Jul 05 19:00:49 2017 +0200
@@ -340,8 +340,12 @@
   if (dirty_n_elems == N - 1) {
     // Actually means 0, so do the push.
     uint localBot = _bottom;
-    // g++ complains if the volatile result of the assignment is unused.
-    const_cast<E&>(_elems[localBot] = t);
+    // g++ complains if the volatile result of the assignment is
+    // unused, so we cast the volatile away.  We cannot cast directly
+    // to void, because gcc treats that as not using the result of the
+    // assignment.  However, casting to E& means that we trigger an
+    // unused-value warning.  So, we cast the E& to void.
+    (void)const_cast<E&>(_elems[localBot] = t);
     OrderAccess::release_store(&_bottom, increment_index(localBot));
     TASKQUEUE_STATS_ONLY(stats.record_push());
     return true;
@@ -397,7 +401,12 @@
     return false;
   }
 
-  const_cast<E&>(t = _elems[oldAge.top()]);
+  // g++ complains if the volatile result of the assignment is
+  // unused, so we cast the volatile away.  We cannot cast directly
+  // to void, because gcc treats that as not using the result of the
+  // assignment.  However, casting to E& means that we trigger an
+  // unused-value warning.  So, we cast the E& to void.
+  (void) const_cast<E&>(t = _elems[oldAge.top()]);
   Age newAge(oldAge);
   newAge.increment();
   Age resAge = _age.cmpxchg(newAge, oldAge);
@@ -640,8 +649,12 @@
   uint dirty_n_elems = dirty_size(localBot, top);
   assert(dirty_n_elems < N, "n_elems out of range.");
   if (dirty_n_elems < max_elems()) {
-    // g++ complains if the volatile result of the assignment is unused.
-    const_cast<E&>(_elems[localBot] = t);
+    // g++ complains if the volatile result of the assignment is
+    // unused, so we cast the volatile away.  We cannot cast directly
+    // to void, because gcc treats that as not using the result of the
+    // assignment.  However, casting to E& means that we trigger an
+    // unused-value warning.  So, we cast the E& to void.
+    (void) const_cast<E&>(_elems[localBot] = t);
     OrderAccess::release_store(&_bottom, increment_index(localBot));
     TASKQUEUE_STATS_ONLY(stats.record_push());
     return true;
@@ -665,7 +678,12 @@
   // This is necessary to prevent any read below from being reordered
   // before the store just above.
   OrderAccess::fence();
-  const_cast<E&>(t = _elems[localBot]);
+  // g++ complains if the volatile result of the assignment is
+  // unused, so we cast the volatile away.  We cannot cast directly
+  // to void, because gcc treats that as not using the result of the
+  // assignment.  However, casting to E& means that we trigger an
+  // unused-value warning.  So, we cast the E& to void.
+  (void) const_cast<E&>(t = _elems[localBot]);
   // This is a second read of "age"; the "size()" above is the first.
   // If there's still at least one element in the queue, based on the
   // "_bottom" and "age" we've read, then there can be no interference with
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/CommandLine/CompilerConfigFileWarning.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 7167142
+ * @summary Warn if unused .hotspot_compiler file is present
+ * @library /testlibrary
+ */
+
+import java.io.PrintWriter;
+import com.oracle.java.testlibrary.*;
+
+public class CompilerConfigFileWarning {
+    public static void main(String[] args) throws Exception {
+        String vmVersion = System.getProperty("java.vm.version");
+        if (vmVersion.toLowerCase().contains("debug") || vmVersion.toLowerCase().contains("jvmg")) {
+            System.out.println("Skip on debug builds since we'll always read the file there");
+            return;
+        }
+
+        PrintWriter pw = new PrintWriter(".hotspot_compiler");
+        pw.println("aa");
+        pw.close();
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-version");
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldContain("warning: .hotspot_compiler file is present but has been ignored.  Run with -XX:CompileCommandFile=.hotspot_compiler to load the file.");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/CommandLine/ConfigFileWarning.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 7167142
+ * @summary Warn if unused .hotspot_rc file is present
+ * @library /testlibrary
+ */
+
+import java.io.PrintWriter;
+import com.oracle.java.testlibrary.*;
+
+public class ConfigFileWarning {
+    public static void main(String[] args) throws Exception {
+        String vmVersion = System.getProperty("java.vm.version");
+        if (vmVersion.toLowerCase().contains("debug") || vmVersion.toLowerCase().contains("jvmg")) {
+            System.out.println("Skip on debug builds since we'll always read the file there");
+            return;
+        }
+
+        PrintWriter pw = new PrintWriter(".hotspotrc");
+        pw.println("aa");
+        pw.close();
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-version");
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldContain("warning: .hotspotrc file is present but has been ignored.  Run with -XX:Flags=.hotspotrc to load the file.");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/SharedArchiveFile/CdsDifferentObjectAlignment.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 CdsDifferentObjectAlignment
+ * @summary Testing CDS (class data sharing) using varying object alignment.
+ *          Using different object alignment for each dump/load pair.
+ *          This is a negative test; using  object alignment for loading that
+ *          is different from object alignment for creating a CDS file
+ *          should fail when loading.
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class CdsDifferentObjectAlignment {
+    public static void main(String[] args) throws Exception {
+        String nativeWordSize = System.getProperty("sun.arch.data.model");
+        if (!Platform.is64bit()) {
+            System.out.println("ObjectAlignmentInBytes for CDS is only " +
+                "supported on 64bit platforms; this plaform is " +
+                nativeWordSize);
+            System.out.println("Skipping the test");
+        } else {
+            createAndLoadSharedArchive(16, 64);
+            createAndLoadSharedArchive(64, 32);
+        }
+    }
+
+
+    // Parameters are object alignment expressed in bytes
+    private static void
+    createAndLoadSharedArchive(int createAlignment, int loadAlignment)
+    throws Exception {
+        String createAlignmentArgument = "-XX:ObjectAlignmentInBytes=" +
+            createAlignment;
+        String loadAlignmentArgument = "-XX:ObjectAlignmentInBytes=" +
+            loadAlignment;
+
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+            "-XX:+UnlockDiagnosticVMOptions",
+            "-XX:SharedArchiveFile=./sample.jsa",
+            "-Xshare:dump",
+            createAlignmentArgument);
+
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldContain("Loading classes to share");
+        output.shouldHaveExitValue(0);
+
+        pb = ProcessTools.createJavaProcessBuilder(
+            "-XX:+UnlockDiagnosticVMOptions",
+            "-XX:SharedArchiveFile=./sample.jsa",
+            "-Xshare:on",
+            loadAlignmentArgument,
+            "-version");
+
+        output = new OutputAnalyzer(pb.start());
+        String expectedErrorMsg =
+            String.format(
+            "The shared archive file's ObjectAlignmentInBytes of %d " +
+            "does not equal the current ObjectAlignmentInBytes of %d",
+            createAlignment,
+            loadAlignment);
+
+        output.shouldContain(expectedErrorMsg);
+        output.shouldHaveExitValue(1);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/SharedArchiveFile/CdsSameObjectAlignment.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 CdsSameObjectAlignment
+ * @summary Testing CDS (class data sharing) using varying object alignment.
+ *          Using same object alignment for each dump/load pair
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class CdsSameObjectAlignment {
+    public static void main(String[] args) throws Exception {
+        String nativeWordSize = System.getProperty("sun.arch.data.model");
+        if (!Platform.is64bit()) {
+            System.out.println("ObjectAlignmentInBytes for CDS is only " +
+                "supported on 64bit platforms; this plaform is " +
+                nativeWordSize);
+            System.out.println("Skipping the test");
+        } else {
+            dumpAndLoadSharedArchive(8);
+            dumpAndLoadSharedArchive(16);
+            dumpAndLoadSharedArchive(32);
+            dumpAndLoadSharedArchive(64);
+        }
+    }
+
+    private static void
+    dumpAndLoadSharedArchive(int objectAlignmentInBytes) throws Exception {
+        String objectAlignmentArg = "-XX:ObjectAlignmentInBytes="
+            + objectAlignmentInBytes;
+        System.out.println("dumpAndLoadSharedArchive(): objectAlignmentInBytes = "
+            + objectAlignmentInBytes);
+
+        // create shared archive
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+            "-XX:+UnlockDiagnosticVMOptions",
+            "-XX:SharedArchiveFile=./sample.jsa",
+            "-Xshare:dump",
+            objectAlignmentArg);
+
+        OutputAnalyzer output = new OutputAnalyzer(pb.start());
+        output.shouldContain("Loading classes to share");
+        output.shouldHaveExitValue(0);
+
+
+        // run using the shared archive
+        pb = ProcessTools.createJavaProcessBuilder(
+            "-XX:+UnlockDiagnosticVMOptions",
+            "-XX:SharedArchiveFile=./sample.jsa",
+            "-Xshare:on",
+            objectAlignmentArg,
+            "-version");
+
+        output = new OutputAnalyzer(pb.start());
+
+        try {
+            output.shouldContain("sharing");
+            output.shouldHaveExitValue(0);
+        } catch (RuntimeException e) {
+            // CDS uses absolute addresses for performance.
+            // It will try to reserve memory at a specific address;
+            // there is a chance such reservation will fail
+            // If it does, it is NOT considered a failure of the feature,
+            // rather a possible expected outcome, though not likely
+            output.shouldContain(
+                "Unable to reserve shared space at required address");
+            output.shouldHaveExitValue(1);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/serviceability/threads/TestFalseDeadLock.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadMXBean;
+import java.util.Random;
+
+/*
+ * @test
+ * @bug 8016304
+ * @summary Make sure no deadlock is reported for this program which has no deadlocks.
+ * @run main/othervm TestFalseDeadLock
+ */
+
+/*
+ * This test will not provoke the bug every time it is run since the bug is intermittent.
+ * The test has a fixed running time of 5 seconds.
+ */
+
+public class TestFalseDeadLock {
+    private static ThreadMXBean bean;
+    private static volatile boolean running = true;
+    private static volatile boolean found = false;
+
+    public static void main(String[] args) throws Exception {
+        bean = ManagementFactory.getThreadMXBean();
+        Thread[] threads = new Thread[500];
+        for (int i = 0; i < threads.length; i++) {
+            Test t = new Test();
+            threads[i] = new Thread(t);
+            threads[i].start();
+        }
+        try {
+            Thread.sleep(5000);
+        } catch (InterruptedException ex) {
+        }
+        running = false;
+        for (Thread t : threads) {
+            t.join();
+        }
+        if (found) {
+            throw new Exception("Deadlock reported, but there is no deadlock.");
+        }
+    }
+
+    public static class Test implements Runnable {
+        public void run() {
+            Random r = new Random();
+            while (running) {
+                try {
+                    synchronized (this) {
+                        wait(r.nextInt(1000) + 1);
+                    }
+                } catch (InterruptedException ex) {
+                }
+                recurse(2000);
+            }
+            if (bean.findDeadlockedThreads() != null) {
+                System.out.println("FOUND!");
+                found = true;
+            }
+        }
+
+        private void recurse(int i) {
+            if (!running) {
+                // It is important for the test to call println here
+                // since there are locks inside that path.
+                System.out.println("Hullo");
+            }
+            else if (i > 0) {
+                recurse(i - 1);
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/testlibrary/com/oracle/java/testlibrary/Platform.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.oracle.java.testlibrary;
+
+public class Platform {
+  private static final String osName = System.getProperty("os.name");
+  private static final String dataModel = System.getProperty("sun.arch.data.model");
+  private static final String vmVersion = System.getProperty("java.vm.version");
+
+  public static boolean is64bit() {
+    return dataModel.equals("64");
+  }
+
+  public static boolean isSolaris() {
+    return osName.toLowerCase().startsWith("sunos");
+  }
+
+  public static boolean isWindows() {
+    return osName.toLowerCase().startsWith("win");
+  }
+
+  public static boolean isOSX() {
+    return osName.toLowerCase().startsWith("mac");
+  }
+
+  public static boolean isLinux() {
+    return osName.toLowerCase().startsWith("linux");
+  }
+
+  public static String getOsName() {
+    return osName;
+  }
+
+  public static boolean isDebugBuild() {
+    return vmVersion.toLowerCase().contains("debug");
+  }
+
+  public static String getVMVersion() {
+    return vmVersion;
+  }
+}
--- a/hotspot/test/testlibrary/com/oracle/java/testlibrary/ProcessTools.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/hotspot/test/testlibrary/com/oracle/java/testlibrary/ProcessTools.java	Wed Jul 05 19:00:49 2017 +0200
@@ -112,10 +112,8 @@
    * @return String[] with platform specific arguments, empty if there are none
    */
   public static String[] getPlatformSpecificVMArgs() {
-    String osName = System.getProperty("os.name");
-    String dataModel = System.getProperty("sun.arch.data.model");
 
-    if (osName.equals("SunOS") && dataModel.equals("64")) {
+    if (Platform.is64bit() && Platform.isSolaris()) {
       return new String[] { "-d64" };
     }
 
--- a/jdk/.hgtags	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/.hgtags	Wed Jul 05 19:00:49 2017 +0200
@@ -216,3 +216,4 @@
 a2a2a91075ad85becbe10a39d7fd04ef9bea8df5 jdk8-b92
 691d6c6cd332d98b0f0221445a73906776f31f72 jdk8-b93
 51479fa56b7c4363c6d87c2e8b898d8185cf4b22 jdk8-b94
+42aa9f1828852bb8b77e98ec695211493ae0759d jdk8-b95
--- a/jdk/make/java/nio/mapfile-bsd	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/make/java/nio/mapfile-bsd	Wed Jul 05 19:00:49 2017 +0200
@@ -109,6 +109,7 @@
 		Java_sun_nio_ch_Net_getInterface6;
 		Java_sun_nio_ch_Net_shutdown;
 		Java_sun_nio_ch_Net_poll;
+                Java_sun_nio_ch_Net_isExclusiveBindAvailable;
                 Java_sun_nio_ch_PollArrayWrapper_interrupt;
                 Java_sun_nio_ch_PollArrayWrapper_poll0;
                 Java_sun_nio_ch_ServerSocketChannelImpl_accept0;
--- a/jdk/make/java/nio/mapfile-linux	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/make/java/nio/mapfile-linux	Wed Jul 05 19:00:49 2017 +0200
@@ -117,6 +117,7 @@
 		Java_sun_nio_ch_Net_getInterface6;
 		Java_sun_nio_ch_Net_shutdown;
 		Java_sun_nio_ch_Net_poll;
+                Java_sun_nio_ch_Net_isExclusiveBindAvailable;
                 Java_sun_nio_ch_PollArrayWrapper_interrupt;
                 Java_sun_nio_ch_PollArrayWrapper_poll0;
                 Java_sun_nio_ch_ServerSocketChannelImpl_accept0;
--- a/jdk/make/java/nio/mapfile-solaris	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/make/java/nio/mapfile-solaris	Wed Jul 05 19:00:49 2017 +0200
@@ -105,6 +105,7 @@
 		Java_sun_nio_ch_Net_getInterface6;
 		Java_sun_nio_ch_Net_shutdown;
 		Java_sun_nio_ch_Net_poll;
+                Java_sun_nio_ch_Net_isExclusiveBindAvailable;
                 Java_sun_nio_ch_PollArrayWrapper_interrupt;
                 Java_sun_nio_ch_PollArrayWrapper_poll0;
                 Java_sun_nio_ch_ServerSocketChannelImpl_accept0;
--- a/jdk/make/java/zip/mapfile-vers	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/make/java/zip/mapfile-vers	Wed Jul 05 19:00:49 2017 +0200
@@ -65,6 +65,7 @@
 		Java_java_util_zip_ZipFile_initIDs;
 		Java_java_util_zip_ZipFile_open;
 		Java_java_util_zip_ZipFile_read;
+		Java_java_util_zip_ZipFile_startsWithLOC;
 
 		ZIP_Close;
 		ZIP_CRC32;
--- a/jdk/make/java/zip/reorder-i586	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/make/java/zip/reorder-i586	Wed Jul 05 19:00:49 2017 +0200
@@ -19,6 +19,7 @@
 text: .text%Java_java_util_zip_ZipFile_initIDs;
 text: .text%Java_java_util_zip_ZipFile_open;
 text: .text%Java_java_util_zip_ZipFile_getTotal;
+text: .text%Java_java_util_zip_ZipFile_startsWithLOC;
 text: .text%Java_java_util_zip_ZipFile_getEntry;
 text: .text%Java_java_util_zip_ZipFile_freeEntry;
 text: .text%Java_java_util_zip_ZipFile_getEntryTime;
--- a/jdk/make/java/zip/reorder-sparc	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/make/java/zip/reorder-sparc	Wed Jul 05 19:00:49 2017 +0200
@@ -18,6 +18,7 @@
 text: .text%Java_java_util_zip_ZipFile_initIDs;
 text: .text%Java_java_util_zip_ZipFile_open;
 text: .text%Java_java_util_zip_ZipFile_getTotal;
+text: .text%Java_java_util_zip_ZipFile_startsWithLOC;
 text: .text%Java_java_util_zip_ZipFile_getEntry;
 text: .text%Java_java_util_zip_ZipFile_freeEntry;
 text: .text%Java_java_util_zip_ZipFile_getEntryTime;
--- a/jdk/make/java/zip/reorder-sparcv9	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/make/java/zip/reorder-sparcv9	Wed Jul 05 19:00:49 2017 +0200
@@ -18,6 +18,7 @@
 text: .text%Java_java_util_zip_ZipFile_initIDs;
 text: .text%Java_java_util_zip_ZipFile_open;
 text: .text%Java_java_util_zip_ZipFile_getTotal;
+text: .text%Java_java_util_zip_ZipFile_startsWithLOC;
 text: .text%Java_java_util_zip_ZipFile_getEntry;
 text: .text%Java_java_util_zip_ZipFile_freeEntry;
 text: .text%Java_java_util_zip_ZipFile_getEntryTime;
--- a/jdk/make/netbeans/common/shared.xml	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/make/netbeans/common/shared.xml	Wed Jul 05 19:00:49 2017 +0200
@@ -77,7 +77,7 @@
         <echo level="verbose">System configuration claims architecture is ${platform}-${arch}</echo>
         <property name="build.dir" location="${root}/build/${platform}-${arch}"/>
         <property name="bin.dir" location="${build.dir}/bin"/>
-        <property name="make.dir" location="${root}/make"/>
+        <property name="make.dir" location="${root}/make"/> <!-- this is old build make files! -->
         <property name="gensrc.dir" location="${build.dir}/gensrc"/>
         <property name="classes.dir" location="${build.dir}/classes"/>
         <property name="jtreg.dir" location="${build.dir}/jtreg/${ant.project.name}"/>
@@ -126,7 +126,7 @@
             <attribute name="classesdir" default="${classes.dir}"/>
             <sequential>
                 <mkdir dir="@{classesdir}"/>
-                <javac srcdir="@{srcdir}" includes="@{includes}" excludes="@{excludes}" sourcepath="" 
+                <javac srcdir="@{srcdir}" includes="@{includes}" excludes="@{excludes}" sourcepath=""
                     destdir="@{classesdir}" fork="true" executable="${bootstrap.javac}"
                     debug="${javac.debug}" debuglevel="${javac.debuglevel}">
                     <!-- Mandatory for compiling partial JDK sources against a snapshot; should NEVER be used for any other purpose: -->
@@ -146,7 +146,7 @@
         <!-- Empty placeholder for easier customization. -->
         <!-- You can override this target in the ../build.xml file. -->
     </target>
-    
+
     <target name="build" depends="-init,-pre-compile,-build-ant,-build-make,-post-compile" description="Build sources."/>
     <target name="-do-build-ant">
         <depend srcdir="${share.src.dir}:${platform.src.dir}:${root}/src/closed/share/classes:${gensrc.dir}" destdir="${classes.dir}" cache="${build.dir}/depcache" includes="${includes}" excludes="${excludes}"/>
@@ -312,7 +312,7 @@
             <param name="jtreg.vm.options" value="-Xdebug -Xrunjdwp:transport=dt_socket,address=${jpda.address}"/>
         </antcall>
     </target>
-    
+
     <target name="debug" depends="-init" if="netbeans.home">
         <!-- No package decls -> "source root" is immediately containing dir -->
         <dirname file="${root}/test/${jtreg.tests}" property="test.dir"/>
--- a/jdk/make/netbeans/j2se/build.xml	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/make/netbeans/j2se/build.xml	Wed Jul 05 19:00:49 2017 +0200
@@ -37,11 +37,11 @@
     <import file="../common/shared.xml"/>
 
     <target name="-build-make" depends="-make.init" if="use.make">
-        <make-run target="all" dir="${make.dir}"/>
+        <make-run target="jdk" dir="${root}/.."/>
     </target>
 
     <target name="-clean-make" depends="-make.init" if="use.make">
-        <make-run target="clean" dir="${make.dir}"/>
+        <make-run target="clean-jdk" dir="${root}/.."/>
     </target>
 
 </project>
--- a/jdk/make/sun/awt/Makefile	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/make/sun/awt/Makefile	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -38,6 +38,10 @@
 
 OTHER_CFLAGS += -D__MEDIALIB_OLD_NAMES -D__USE_J2D_NAMES
 
+ifneq  ($(PLATFORM), windows)
+CLASSES_INIT += $(TEMPDIR)/.gen_icons
+endif
+
 #
 # Files
 #
@@ -208,6 +212,79 @@
 endif
 build: fontconfigs
 
+ifneq ($(PLATFORM), windows)
+
+GEN_DIR=$(GENSRCDIR)/sun/awt/
+
+ifdef OPENJDK
+    ICONS_PATH_PREFIX=$(PLATFORM_SRC)
+else
+    ICONS_PATH_PREFIX=$(CLOSED_SRC)/solaris
+endif
+
+ICONS = \
+    $(ICONS_PATH_PREFIX)/classes/sun/awt/X11/java-icon16.png \
+    $(ICONS_PATH_PREFIX)/classes/sun/awt/X11/java-icon24.png \
+    $(ICONS_PATH_PREFIX)/classes/sun/awt/X11/java-icon32.png \
+    $(ICONS_PATH_PREFIX)/classes/sun/awt/X11/java-icon48.png
+
+ICONPATH=$(SHARE_SRC)/classes/sun/awt/resources
+
+ICONS += \
+   $(ICONPATH)/security-icon-bw16.png \
+   $(ICONPATH)/security-icon-interim16.png \
+   $(ICONPATH)/security-icon-yellow16.png \
+   $(ICONPATH)/security-icon-bw24.png \
+   $(ICONPATH)/security-icon-interim24.png \
+   $(ICONPATH)/security-icon-yellow24.png \
+   $(ICONPATH)/security-icon-bw32.png \
+   $(ICONPATH)/security-icon-interim32.png \
+   $(ICONPATH)/security-icon-yellow32.png \
+   $(ICONPATH)/security-icon-bw48.png \
+   $(ICONPATH)/security-icon-interim48.png \
+   $(ICONPATH)/security-icon-yellow48.png
+
+TEMPDIR_CLASSES = $(TEMPDIR)/classes
+   
+generated.clean:
+	$(RM) -r $(GEN_DIR)/*.java
+	$(RM) -r $(TEMPDIR)/.gen_icons   
+
+$(TEMPDIR_CLASSES)/sun/awt/ToBin.class: ToBin.java
+	@$(prep-target)
+	$(BOOT_JAVAC_CMD) -d $(TEMPDIR_CLASSES) $<
+
+$(TEMPDIR)/.gen_icons: $(TEMPDIR_CLASSES)/sun/awt/ToBin.class $(ICONS)
+	$(prep-target)
+	for i in $(ICONS); do \
+            filename=`basename $$i`; \
+	    name=`$(ECHO) $$filename | $(TR) '\-.' '__'`;  \
+            classname=$(GEN_DIR)/AWTIcon32_$$name.java; \
+	    $(RM) $$classname; \
+	    $(ECHO) "package sun.awt;" >> $$classname ; \
+	    $(ECHO) "public class AWTIcon32_$$name {" >> $$classname; \
+	    $(ECHO) "public final static int[] $$name = { " >> $$classname;  \
+	    $(CAT) $$i | \
+	      $(BOOT_JAVA_CMD) -cp $(TEMPDIR_CLASSES)  \
+		-Djava.awt.headless=true \
+		sun.awt.ToBin >> $$classname; \
+	    $(ECHO) "}; }" >> $$classname;  \
+            classname=$(GEN_DIR)/AWTIcon64_$$name.java; \
+	    $(RM) $$classname; \
+	    $(ECHO) "package sun.awt;" >> $$classname ; \
+	    $(ECHO) "public class AWTIcon64_$$name {" >> $$classname; \
+	    $(ECHO) "public final static long[] $$name = { " >> $$classname;  \
+	    $(CAT) $$i | \
+	      $(BOOT_JAVA_CMD) -cp $(TEMPDIR_CLASSES)  \
+		-Djava.awt.headless=true \
+		sun.awt.ToBin >> $$classname; \
+	    $(ECHO) "}; }" >> $$classname;  \
+	done
+	$(TOUCH) $@
+
+clean clobber:: generated.clean    
+endif
+
 
 ifeq ($(PLATFORM), windows)
 # vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv WINDOWS
@@ -570,5 +647,5 @@
 		  java.lang.Integer \
 		  java.lang.ThreadGroup
 
-.PHONY: dgalibs dgalib.clean fontconfigs fontconfigs.clean
+.PHONY: dgalibs dgalib.clean fontconfigs fontconfigs.clean generated.clean
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/sun/awt/ToBin.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.awt;
+
+import java.io.*;
+import java.awt.image.*;
+import javax.imageio.*;
+import java.awt.*;
+
+public class ToBin {
+    public static void main(String[] args) throws Exception {
+        BufferedImage im = ImageIO.read(System.in);
+        BufferedImage bi = null;
+        int iconWidth = im.getWidth(null);
+        int iconHeight = im.getHeight(null);
+        if (im != null && iconHeight != 0 &&  iconWidth != 0) {
+            bi = new BufferedImage(iconWidth, iconHeight, BufferedImage.TYPE_INT_ARGB);
+            Graphics g = bi.getGraphics();
+            try {
+                g.drawImage(im, 0, 0, iconWidth, iconHeight, null);
+            } finally {
+                g.dispose();
+            }
+        }
+        DataBuffer srcBuf = bi.getData().getDataBuffer();
+        int[] buf = ((DataBufferInt)srcBuf).getData();
+        System.out.print(iconWidth + ",");
+        System.out.println(iconHeight + ",");
+        for (int i = 0; i < buf.length; i++) {
+            System.out.print("0x" + Integer.toHexString(buf[i]) + ", ");
+            if (i % 10 == 0) {
+                System.out.println();
+            }
+        }
+    }
+}
--- a/jdk/make/sun/lwawt/FILES_export_macosx.gmk	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/make/sun/lwawt/FILES_export_macosx.gmk	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -109,6 +109,7 @@
         sun/lwawt/LWToolkit.java \
         sun/lwawt/LWWindowPeer.java \
         sun/lwawt/PlatformWindow.java \
+        sun/lwawt/SecurityWarningWindow.java \
         sun/lwawt/SelectionClearListener.java \
         sun/lwawt/macosx/CPrinterDevice.java \
         sun/lwawt/macosx/CPrinterDialog.java \
@@ -143,6 +144,7 @@
         sun/lwawt/macosx/CMouseInfoPeer.java \
         sun/lwawt/macosx/CPlatformView.java \
         sun/lwawt/macosx/CPlatformWindow.java \
+        sun/lwawt/macosx/CWarningWindow.java \
         sun/lwawt/macosx/CPlatformComponent.java \
         sun/lwawt/macosx/CEmbeddedFrame.java \
         sun/lwawt/macosx/CPlatformEmbeddedFrame.java \
--- a/jdk/make/sun/xawt/Makefile	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/make/sun/xawt/Makefile	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -32,7 +32,7 @@
 
 GEN_DIR=$(GENSRCDIR)/sun/awt/X11
 
-CLASSES_INIT += $(TEMPDIR)/.gen.wrappers $(TEMPDIR)/.gen_icons touch.wrappers
+CLASSES_INIT += $(TEMPDIR)/.gen.wrappers touch.wrappers
 
 .PHONY: generated.clean
 
@@ -317,70 +317,7 @@
 	$(RM) -r $(WRAPPER_GENERATOR_TEMPDIR)
 	$(RM) -r $(WRAPPER_GENERATOR_DIR)
 	$(RM) -r $(GEN_DIR)/*.java
-	$(RM) -r $(TEMPDIR)/.gen_icons
 
-ifdef OPENJDK
-    ICONS_PATH_PREFIX=$(PLATFORM_SRC)
-else
-    ICONS_PATH_PREFIX=$(CLOSED_SRC)/solaris
-endif
-
-ICONS = \
-    $(ICONS_PATH_PREFIX)/classes/sun/awt/X11/java-icon16.png \
-    $(ICONS_PATH_PREFIX)/classes/sun/awt/X11/java-icon24.png \
-    $(ICONS_PATH_PREFIX)/classes/sun/awt/X11/java-icon32.png \
-    $(ICONS_PATH_PREFIX)/classes/sun/awt/X11/java-icon48.png
-
-
-ICONPATH=$(PLATFORM_SRC)/classes/sun/awt/X11
-
-ICONS += \
-   $(ICONPATH)/security-icon-bw16.png \
-   $(ICONPATH)/security-icon-interim16.png \
-   $(ICONPATH)/security-icon-yellow16.png \
-   $(ICONPATH)/security-icon-bw24.png \
-   $(ICONPATH)/security-icon-interim24.png \
-   $(ICONPATH)/security-icon-yellow24.png \
-   $(ICONPATH)/security-icon-bw32.png \
-   $(ICONPATH)/security-icon-interim32.png \
-   $(ICONPATH)/security-icon-yellow32.png \
-   $(ICONPATH)/security-icon-bw48.png \
-   $(ICONPATH)/security-icon-interim48.png \
-   $(ICONPATH)/security-icon-yellow48.png
-
-TEMPDIR_CLASSES = $(TEMPDIR)/classes
-
-$(TEMPDIR_CLASSES)/sun/awt/X11/ToBin.class: ToBin.java
-	@$(prep-target)
-	$(BOOT_JAVAC_CMD) -d $(TEMPDIR_CLASSES) $<
-
-$(TEMPDIR)/.gen_icons: $(TEMPDIR_CLASSES)/sun/awt/X11/ToBin.class $(ICONS)
-	$(prep-target)
-	for i in $(ICONS); do \
-            filename=`basename $$i`; \
-	    name=`$(ECHO) $$filename | $(TR) '\-.' '__'`;  \
-            classname=$(GEN_DIR)/XAWTIcon32_$$name.java; \
-	    $(RM) $$classname; \
-	    $(ECHO) "package sun.awt.X11;" >> $$classname ; \
-	    $(ECHO) "public class XAWTIcon32_$$name {" >> $$classname; \
-	    $(ECHO) "public static int[] $$name = { " >> $$classname;  \
-	    $(CAT) $$i | \
-	      $(BOOT_JAVA_CMD) -cp $(TEMPDIR_CLASSES)  \
-		-Djava.awt.headless=true \
-		sun.awt.X11.ToBin >> $$classname; \
-	    $(ECHO) "}; }" >> $$classname;  \
-            classname=$(GEN_DIR)/XAWTIcon64_$$name.java; \
-	    $(RM) $$classname; \
-	    $(ECHO) "package sun.awt.X11;" >> $$classname ; \
-	    $(ECHO) "public class XAWTIcon64_$$name {" >> $$classname; \
-	    $(ECHO) "public static long[] $$name = { " >> $$classname;  \
-	    $(CAT) $$i | \
-	      $(BOOT_JAVA_CMD) -cp $(TEMPDIR_CLASSES)  \
-		-Djava.awt.headless=true \
-		sun.awt.X11.ToBin >> $$classname; \
-	    $(ECHO) "}; }" >> $$classname;  \
-	done
-	$(TOUCH) $@
 
 clean clobber:: generated.clean
 
--- a/jdk/make/sun/xawt/ToBin.java	Mon Jun 24 14:26:58 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.awt.X11;
-
-import java.io.*;
-import java.awt.image.*;
-import javax.imageio.*;
-import java.awt.*;
-
-public class ToBin {
-    public static void main(String[] args) throws Exception {
-        BufferedImage im = ImageIO.read(System.in);
-        BufferedImage bi = null;
-        int iconWidth = im.getWidth(null);
-        int iconHeight = im.getHeight(null);
-        if (im != null && iconHeight != 0 &&  iconWidth != 0) {
-            bi = new BufferedImage(iconWidth, iconHeight, BufferedImage.TYPE_INT_ARGB);
-            Graphics g = bi.getGraphics();
-            try {
-                g.drawImage(im, 0, 0, iconWidth, iconHeight, null);
-            } finally {
-                g.dispose();
-            }
-        }
-        DataBuffer srcBuf = bi.getData().getDataBuffer();
-        int[] buf = ((DataBufferInt)srcBuf).getData();
-        System.out.print(iconWidth + ",");
-        System.out.println(iconHeight + ",");
-        for (int i = 0; i < buf.length; i++) {
-            System.out.print("0x" + Integer.toHexString(buf[i]) + ", ");
-            if (i % 10 == 0) {
-                System.out.println();
-            }
-        }
-    }
-}
--- a/jdk/makefiles/CopyFiles.gmk	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/makefiles/CopyFiles.gmk	Wed Jul 05 19:00:49 2017 +0200
@@ -538,21 +538,4 @@
 
 ##########################################################################################
 
-ifndef OPENJDK
-ifeq ($(ENABLE_JFR), true)
-
-JFR_CONFIGURATION_DIR_SRC := $(JDK_TOPDIR)/src/closed/share/classes/oracle/jrockit/jfr/settings/
-JFR_CONFIGURATION_DIR_DST := $(LIBDIR)/jfr/
-
-JFR_SRC_FILES = $(wildcard $(JFR_CONFIGURATION_DIR_SRC)/*.jfc)
-JFR_TARGET_FILES = $(subst $(JFR_CONFIGURATION_DIR_SRC),$(JFR_CONFIGURATION_DIR_DST),$(JFR_SRC_FILES))
-
-$(JFR_CONFIGURATION_DIR_DST)/%.jfc : $(JFR_CONFIGURATION_DIR_SRC)/%.jfc
-	$(call install-file)
-
-COPY_FILES += $(JFR_TARGET_FILES)
-
-endif
-endif
-
-##########################################################################################
+-include $(CUSTOM_MAKE_DIR)/CopyFiles.gmk
--- a/jdk/makefiles/GenerateJavaSources.gmk	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/makefiles/GenerateJavaSources.gmk	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -67,7 +67,7 @@
 
 ifneq ($(OPENJDK_TARGET_OS),windows)
 include GensrcIcons.gmk
-GENSRC += $(GENSRC_X11_ICONS)
+GENSRC += $(GENSRC_AWT_ICONS)
 
 ifeq ($(OPENJDK_TARGET_OS),macosx)
 GENSRC += $(GENSRC_OSX_ICONS)
--- a/jdk/makefiles/GensrcIcons.gmk	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/makefiles/GensrcIcons.gmk	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -23,10 +23,10 @@
 # questions.
 #
 
-GENSRC_X11_ICONS :=
-GENSRC_X11_ICONS_SRC :=
-GENSRC_X11_ICONS_TMP := $(JDK_OUTPUTDIR)/gensrc
-GENSRC_X11_ICONS_DST := $(GENSRC_X11_ICONS_TMP)/sun/awt/X11
+GENSRC_AWT_ICONS :=
+GENSRC_AWT_ICONS_SRC :=
+GENSRC_AWT_ICONS_TMP := $(JDK_OUTPUTDIR)/gensrc
+GENSRC_AWT_ICONS_DST := $(GENSRC_AWT_ICONS_TMP)/sun/awt/
 
 ifdef OPENJDK
   X11_ICONS_PATH_PREFIX := $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)
@@ -34,76 +34,76 @@
   X11_ICONS_PATH_PREFIX := $(JDK_TOPDIR)/src/closed/solaris
 endif
 
-GENSRC_X11_ICONS_SRC += \
+GENSRC_AWT_ICONS_SRC += \
     $(X11_ICONS_PATH_PREFIX)/classes/sun/awt/X11/java-icon16.png \
     $(X11_ICONS_PATH_PREFIX)/classes/sun/awt/X11/java-icon24.png \
     $(X11_ICONS_PATH_PREFIX)/classes/sun/awt/X11/java-icon32.png \
     $(X11_ICONS_PATH_PREFIX)/classes/sun/awt/X11/java-icon48.png
 
 
-X11_ICONPATH := $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/classes/sun/awt/X11
+AWT_ICONPATH := $(JDK_TOPDIR)/src/share/classes/sun/awt/resources
 
-GENSRC_X11_ICONS_SRC += \
-   $(X11_ICONPATH)/security-icon-bw16.png \
-   $(X11_ICONPATH)/security-icon-interim16.png \
-   $(X11_ICONPATH)/security-icon-yellow16.png \
-   $(X11_ICONPATH)/security-icon-bw24.png \
-   $(X11_ICONPATH)/security-icon-interim24.png \
-   $(X11_ICONPATH)/security-icon-yellow24.png \
-   $(X11_ICONPATH)/security-icon-bw32.png \
-   $(X11_ICONPATH)/security-icon-interim32.png \
-   $(X11_ICONPATH)/security-icon-yellow32.png \
-   $(X11_ICONPATH)/security-icon-bw48.png \
-   $(X11_ICONPATH)/security-icon-interim48.png \
-   $(X11_ICONPATH)/security-icon-yellow48.png
+GENSRC_AWT_ICONS_SRC += \
+   $(AWT_ICONPATH)/security-icon-bw16.png \
+   $(AWT_ICONPATH)/security-icon-interim16.png \
+   $(AWT_ICONPATH)/security-icon-yellow16.png \
+   $(AWT_ICONPATH)/security-icon-bw24.png \
+   $(AWT_ICONPATH)/security-icon-interim24.png \
+   $(AWT_ICONPATH)/security-icon-yellow24.png \
+   $(AWT_ICONPATH)/security-icon-bw32.png \
+   $(AWT_ICONPATH)/security-icon-interim32.png \
+   $(AWT_ICONPATH)/security-icon-yellow32.png \
+   $(AWT_ICONPATH)/security-icon-bw48.png \
+   $(AWT_ICONPATH)/security-icon-interim48.png \
+   $(AWT_ICONPATH)/security-icon-yellow48.png
 
-GENSRC_X11_ICONS_FILES := $(notdir $(GENSRC_X11_ICONS_SRC))
+GENSRC_AWT_ICONS_FILES := $(notdir $(GENSRC_AWT_ICONS_SRC))
 
-GENSRC_X11_ICONS_SHORT_NAME = $(subst .,_,$(subst -,_,$(1)))
-GENSRC_X11_ICONS_DST_NAME = XAWTIcon$(2)_$(subst .,_,$(subst -,_,$(1)))
+GENSRC_AWT_ICONS_SHORT_NAME = $(subst .,_,$(subst -,_,$(1)))
+GENSRC_AWT_ICONS_DST_NAME = AWTIcon$(2)_$(subst .,_,$(subst -,_,$(1)))
 
 ###
 
-$(GENSRC_X11_ICONS_TMP)/_the.icons.dir :
+$(GENSRC_AWT_ICONS_TMP)/_the.icons.dir :
 	$(ECHO) Generating icon classes
-	$(MKDIR) -p $(GENSRC_X11_ICONS_DST)
+	$(MKDIR) -p $(GENSRC_AWT_ICONS_DST)
 	$(TOUCH) $@
 
 ###
 
-define SetupGensrcX11Icon
+define SetupGensrcAWTIcon
         # param 1 is for src-file
         # param 2 is for src-dir
-	$1_SHORTNAME := $(call GENSRC_X11_ICONS_SHORT_NAME,$1)
-	$1_NAME32 := $(call GENSRC_X11_ICONS_DST_NAME,$1,32)
-	$1_TARGET32 := $(GENSRC_X11_ICONS_DST)/$$($1_NAME32).java
-	$1_NAME64 := $(call GENSRC_X11_ICONS_DST_NAME,$1,64)
-	$1_TARGET64 := $(GENSRC_X11_ICONS_DST)/$$($1_NAME64).java
+	$1_SHORTNAME := $(call GENSRC_AWT_ICONS_SHORT_NAME,$1)
+	$1_NAME32 := $(call GENSRC_AWT_ICONS_DST_NAME,$1,32)
+	$1_TARGET32 := $(GENSRC_AWT_ICONS_DST)/$$($1_NAME32).java
+	$1_NAME64 := $(call GENSRC_AWT_ICONS_DST_NAME,$1,64)
+	$1_TARGET64 := $(GENSRC_AWT_ICONS_DST)/$$($1_NAME64).java
 
-$$($1_TARGET32) : $2/$1 $(GENSRC_X11_ICONS_TMP)/_the.icons.dir
+$$($1_TARGET32) : $2/$1 $(GENSRC_AWT_ICONS_TMP)/_the.icons.dir
 	$(RM) $$@ $$@.tmp
-	$(ECHO) "package sun.awt.X11;" > $$@.tmp
+	$(ECHO) "package sun.awt;" > $$@.tmp
 	$(ECHO) "public class $$($1_NAME32) {" >> $$@.tmp
 	$(ECHO) "public static int[] $$($1_SHORTNAME) = { " >> $$@.tmp
-	$(CAT) $$< | $(TOOL_X11_TOBIN) >> $$@.tmp
+	$(CAT) $$< | $(TOOL_AWT_TOBIN) >> $$@.tmp
 	$(ECHO) "}; }" >> $$@.tmp
 	$(MV) $$@.tmp $$@
 
-GENSRC_X11_ICONS += $$($1_TARGET32)
+GENSRC_AWT_ICONS += $$($1_TARGET32)
 
-$$($1_TARGET64) : $2/$1 $(GENSRC_X11_ICONS_TMP)/_the.icons.dir
+$$($1_TARGET64) : $2/$1 $(GENSRC_AWT_ICONS_TMP)/_the.icons.dir
 	$(RM) $$@ $$@.tmp
-	$(ECHO) "package sun.awt.X11;" > $$@.tmp
+	$(ECHO) "package sun.awt;" > $$@.tmp
 	$(ECHO) "public class $$($1_NAME64) {" >> $$@.tmp
 	$(ECHO) "public static long[] $$($1_SHORTNAME) = { " >> $$@.tmp
-	$(CAT) $$< | $(TOOL_X11_TOBIN) >> $$@.tmp
+	$(CAT) $$< | $(TOOL_AWT_TOBIN) >> $$@.tmp
 	$(ECHO) "}; }" >> $$@.tmp
 	$(MV) $$@.tmp $$@
 
-GENSRC_X11_ICONS += $$($1_TARGET64)
+GENSRC_AWT_ICONS += $$($1_TARGET64)
 endef
 
-$(foreach I,$(GENSRC_X11_ICONS_SRC), $(eval $(call SetupGensrcX11Icon,$(notdir $(I)),$(dir $(I)))))
+$(foreach I,$(GENSRC_AWT_ICONS_SRC), $(eval $(call SetupGensrcAWTIcon,$(notdir $(I)),$(dir $(I)))))
 
 ###
 
--- a/jdk/makefiles/Tools.gmk	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/makefiles/Tools.gmk	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
 # 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,7 +29,7 @@
     $(JDK_TOPDIR)/makefiles/sun))
 
 TOOLS_SRC:=$(JDK_TOPDIR)/make/tools/src \
-           $(JDK_TOPDIR)/makefiles/sun/awt/X11 \
+           $(JDK_TOPDIR)/makefiles/sun/awt/ \
            $(JDK_TOPDIR)/makefiles/sun/osxapp \
            $(JDK_TOPDIR)/make/tools/swing-beans
 
@@ -134,8 +134,8 @@
 TOOL_WRAPPERGENERATOR=$(JAVA) -cp $(JDK_OUTPUTDIR)/btclasses \
 	WrapperGenerator
 
-TOOL_X11_TOBIN=$(JAVA) -Djava.awt.headless=true -cp $(JDK_OUTPUTDIR)/btclasses \
-	sun.awt.X11.ToBin
+TOOL_AWT_TOBIN=$(JAVA) -Djava.awt.headless=true -cp $(JDK_OUTPUTDIR)/btclasses \
+	sun.awt.ToBin
 
 TOOL_OSX_TOBIN=$(JAVA) -Djava.awt.headless=true -cp $(JDK_OUTPUTDIR)/btclasses \
 	sun.osxapp.ToBin
--- a/jdk/makefiles/mapfiles/libnio/mapfile-linux	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/makefiles/mapfiles/libnio/mapfile-linux	Wed Jul 05 19:00:49 2017 +0200
@@ -117,6 +117,7 @@
 		Java_sun_nio_ch_Net_getInterface6;
 		Java_sun_nio_ch_Net_shutdown;
 		Java_sun_nio_ch_Net_poll;
+                Java_sun_nio_ch_Net_isExclusiveBindAvailable;
                 Java_sun_nio_ch_PollArrayWrapper_interrupt;
                 Java_sun_nio_ch_PollArrayWrapper_poll0;
                 Java_sun_nio_ch_ServerSocketChannelImpl_accept0;
--- a/jdk/makefiles/mapfiles/libnio/mapfile-macosx	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/makefiles/mapfiles/libnio/mapfile-macosx	Wed Jul 05 19:00:49 2017 +0200
@@ -109,6 +109,7 @@
 		Java_sun_nio_ch_Net_getInterface6;
 		Java_sun_nio_ch_Net_shutdown;
 		Java_sun_nio_ch_Net_poll;
+                Java_sun_nio_ch_Net_isExclusiveBindAvailable;
                 Java_sun_nio_ch_PollArrayWrapper_interrupt;
                 Java_sun_nio_ch_PollArrayWrapper_poll0;
                 Java_sun_nio_ch_ServerSocketChannelImpl_accept0;
--- a/jdk/makefiles/mapfiles/libnio/mapfile-solaris	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/makefiles/mapfiles/libnio/mapfile-solaris	Wed Jul 05 19:00:49 2017 +0200
@@ -105,6 +105,7 @@
 		Java_sun_nio_ch_Net_getInterface6;
 		Java_sun_nio_ch_Net_shutdown;
 		Java_sun_nio_ch_Net_poll;
+                Java_sun_nio_ch_Net_isExclusiveBindAvailable;
                 Java_sun_nio_ch_PollArrayWrapper_interrupt;
                 Java_sun_nio_ch_PollArrayWrapper_poll0;
                 Java_sun_nio_ch_ServerSocketChannelImpl_accept0;
--- a/jdk/makefiles/mapfiles/libzip/mapfile-vers	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/makefiles/mapfiles/libzip/mapfile-vers	Wed Jul 05 19:00:49 2017 +0200
@@ -65,6 +65,7 @@
 		Java_java_util_zip_ZipFile_initIDs;
 		Java_java_util_zip_ZipFile_open;
 		Java_java_util_zip_ZipFile_read;
+		Java_java_util_zip_ZipFile_startsWithLOC;
 
 		ZIP_Close;
 		ZIP_CRC32;
--- a/jdk/makefiles/mapfiles/libzip/reorder-sparc	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/makefiles/mapfiles/libzip/reorder-sparc	Wed Jul 05 19:00:49 2017 +0200
@@ -18,6 +18,7 @@
 text: .text%Java_java_util_zip_ZipFile_initIDs;
 text: .text%Java_java_util_zip_ZipFile_open;
 text: .text%Java_java_util_zip_ZipFile_getTotal;
+text: .text%Java_java_util_zip_ZipFile_startsWithLOC;
 text: .text%Java_java_util_zip_ZipFile_getEntry;
 text: .text%Java_java_util_zip_ZipFile_freeEntry;
 text: .text%Java_java_util_zip_ZipFile_getEntryTime;
--- a/jdk/makefiles/mapfiles/libzip/reorder-sparcv9	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/makefiles/mapfiles/libzip/reorder-sparcv9	Wed Jul 05 19:00:49 2017 +0200
@@ -18,6 +18,7 @@
 text: .text%Java_java_util_zip_ZipFile_initIDs;
 text: .text%Java_java_util_zip_ZipFile_open;
 text: .text%Java_java_util_zip_ZipFile_getTotal;
+text: .text%Java_java_util_zip_ZipFile_startsWithLOC;
 text: .text%Java_java_util_zip_ZipFile_getEntry;
 text: .text%Java_java_util_zip_ZipFile_freeEntry;
 text: .text%Java_java_util_zip_ZipFile_getEntryTime;
--- a/jdk/makefiles/mapfiles/libzip/reorder-x86	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/makefiles/mapfiles/libzip/reorder-x86	Wed Jul 05 19:00:49 2017 +0200
@@ -19,6 +19,7 @@
 text: .text%Java_java_util_zip_ZipFile_initIDs;
 text: .text%Java_java_util_zip_ZipFile_open;
 text: .text%Java_java_util_zip_ZipFile_getTotal;
+text: .text%Java_java_util_zip_ZipFile_startsWithLOC;
 text: .text%Java_java_util_zip_ZipFile_getEntry;
 text: .text%Java_java_util_zip_ZipFile_freeEntry;
 text: .text%Java_java_util_zip_ZipFile_getEntryTime;
--- a/jdk/makefiles/scripts/genExceptions.sh	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/makefiles/scripts/genExceptions.sh	Wed Jul 05 19:00:49 2017 +0200
@@ -70,7 +70,7 @@
     private $ARG_TYPE $ARG_ID;
 
     /**
-     * Constructs an instance of this class. </p>
+     * Constructs an instance of this class.
      *
      * @param  $ARG_ID
      *         The $ARG_PHRASE
@@ -81,7 +81,7 @@
     }
 
     /**
-     * Retrieves the $ARG_PHRASE. </p>
+     * Retrieves the $ARG_PHRASE.
      *
      * @return  The $ARG_PHRASE
      */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/makefiles/sun/awt/ToBin.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2005, 2013 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.awt;
+
+import java.io.*;
+import java.awt.image.*;
+import javax.imageio.*;
+import java.awt.*;
+
+public class ToBin {
+    public static void main(String[] args) throws Exception {
+        BufferedImage im = ImageIO.read(System.in);
+        BufferedImage bi = null;
+        int iconWidth = im.getWidth(null);
+        int iconHeight = im.getHeight(null);
+        if (im != null && iconHeight != 0 &&  iconWidth != 0) {
+            bi = new BufferedImage(iconWidth, iconHeight, BufferedImage.TYPE_INT_ARGB);
+            Graphics g = bi.getGraphics();
+            try {
+                g.drawImage(im, 0, 0, iconWidth, iconHeight, null);
+            } finally {
+                g.dispose();
+            }
+        }
+        DataBuffer srcBuf = bi.getData().getDataBuffer();
+        int[] buf = ((DataBufferInt)srcBuf).getData();
+        System.out.print(iconWidth + ",");
+        System.out.println(iconHeight + ",");
+        for (int i = 0; i < buf.length; i++) {
+            System.out.print("0x" + Integer.toHexString(buf[i]) + ", ");
+            if (i % 10 == 0) {
+                System.out.println();
+            }
+        }
+    }
+}
--- a/jdk/makefiles/sun/awt/X11/ToBin.java	Mon Jun 24 14:26:58 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.awt.X11;
-
-import java.io.*;
-import java.awt.image.*;
-import javax.imageio.*;
-import java.awt.*;
-
-public class ToBin {
-    public static void main(String[] args) throws Exception {
-        BufferedImage im = ImageIO.read(System.in);
-        BufferedImage bi = null;
-        int iconWidth = im.getWidth(null);
-        int iconHeight = im.getHeight(null);
-        if (im != null && iconHeight != 0 &&  iconWidth != 0) {
-            bi = new BufferedImage(iconWidth, iconHeight, BufferedImage.TYPE_INT_ARGB);
-            Graphics g = bi.getGraphics();
-            try {
-                g.drawImage(im, 0, 0, iconWidth, iconHeight, null);
-            } finally {
-                g.dispose();
-            }
-        }
-        DataBuffer srcBuf = bi.getData().getDataBuffer();
-        int[] buf = ((DataBufferInt)srcBuf).getData();
-        System.out.print(iconWidth + ",");
-        System.out.println(iconHeight + ",");
-        for (int i = 0; i < buf.length; i++) {
-            System.out.print("0x" + Integer.toHexString(buf[i]) + ", ");
-            if (i % 10 == 0) {
-                System.out.println();
-            }
-        }
-    }
-}
--- a/jdk/src/macosx/classes/com/apple/laf/resources/aqua_pt_BR.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/com/apple/laf/resources/aqua_pt_BR.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -154,7 +154,7 @@
 ############ Abstract Document Strings ############
 AbstractDocument.styleChange.textAndMnemonic=altera\u00E7\u00E3o de estilo
 AbstractDocument.addition.textAndMnemonic=adi\u00E7\u00E3o
-AbstractDocument.deletion.textAndMnemonic=dele\u00E7\u00E3o
+AbstractDocument.deletion.textAndMnemonic=exclus\u00E3o
 AbstractDocument.undo.textAndMnemonic=Desfazer
 AbstractDocument.redo.textAndMnemonic=Refazer
 
--- a/jdk/src/macosx/classes/sun/java2d/opengl/CGLLayer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/java2d/opengl/CGLLayer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -73,8 +73,7 @@
     }
 
     public int getTransparency() {
-        return peer.isTranslucent() ? Transparency.TRANSLUCENT :
-               Transparency.OPAQUE;
+        return isOpaque() ? Transparency.OPAQUE : Transparency.TRANSLUCENT;
     }
 
     public Object getDestination() {
@@ -82,14 +81,14 @@
     }
 
     public SurfaceData replaceSurfaceData() {
-        if (peer.getBounds().isEmpty()) {
+        if (getBounds().isEmpty()) {
             surfaceData = NullSurfaceData.theInstance;
             return surfaceData;
         }
 
         // the layer redirects all painting to the buffer's graphics
         // and blits the buffer to the layer surface (in drawInCGLContext callback)
-        CGraphicsConfig gc = (CGraphicsConfig)peer.getGraphicsConfiguration();
+        CGraphicsConfig gc = (CGraphicsConfig)getGraphicsConfiguration();
         surfaceData = gc.createSurfaceData(this);
         setScale(gc.getDevice().getScaleFactor());
         // the layer holds a reference to the buffer, which in
--- a/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -899,7 +899,7 @@
                                 boolean focusedWindowChangeAllowed, long time,
                                 CausedFocusEvent.Cause cause)
     {
-        if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
             focusLog.finest("lightweightChild=" + lightweightChild + ", temporary=" + temporary +
                             ", focusedWindowChangeAllowed=" + focusedWindowChangeAllowed +
                             ", time= " + time + ", cause=" + cause);
@@ -940,7 +940,7 @@
                         LWWindowPeer.getOwnerFrameDialog(parentPeer) : parentPeer;
 
                     if (decoratedPeer == null || !decoratedPeer.getPlatformWindow().isActive()) {
-                        if (focusLog.isLoggable(PlatformLogger.FINE)) {
+                        if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
                             focusLog.fine("request rejected, focusedWindowChangeAllowed==false, " +
                                           "decoratedPeer is inactive: " + decoratedPeer);
                         }
@@ -953,7 +953,7 @@
                 // If parent window can be made focused and has been made focused (synchronously)
                 // then we can proceed with children, otherwise we retreat
                 if (!res || !parentWindow.isFocused()) {
-                    if (focusLog.isLoggable(PlatformLogger.FINE)) {
+                    if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
                         focusLog.fine("request rejected, res= " + res + ", parentWindow.isFocused()=" +
                                       parentWindow.isFocused());
                     }
--- a/jdk/src/macosx/classes/sun/lwawt/LWKeyboardFocusManagerPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/LWKeyboardFocusManagerPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -44,9 +44,26 @@
 
     @Override
     public void setCurrentFocusedWindow(Window win) {
+        LWWindowPeer from, to;
+
         synchronized (this) {
+            if (focusedWindow == win) {
+                return;
+            }
+
+            from = (LWWindowPeer)LWToolkit.targetToPeer(focusedWindow);
+            to = (LWWindowPeer)LWToolkit.targetToPeer(win);
+
             focusedWindow = win;
         }
+
+        if (from != null) {
+            from.updateSecurityWarningVisibility();
+        }
+
+        if (to != null) {
+            to.updateSecurityWarningVisibility();
+        }
     }
 
     @Override
--- a/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java	Wed Jul 05 19:00:49 2017 +0200
@@ -513,6 +513,8 @@
         return clipboard;
     }
 
+    protected abstract SecurityWarningWindow createSecurityWarning(Window ownerWindow, LWWindowPeer ownerPeer);
+
     // ---- DELEGATES ---- //
 
     public abstract Clipboard createPlatformClipboard();
--- a/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -41,7 +41,7 @@
 
 public class LWWindowPeer
     extends LWContainerPeer<Window, JComponent>
-    implements FramePeer, DialogPeer, FullScreenCapable, DisplayChangedListener
+    implements FramePeer, DialogPeer, FullScreenCapable, DisplayChangedListener, PlatformEventNotifier
 {
     public static enum PeerType {
         SIMPLEWINDOW,
@@ -112,6 +112,8 @@
 
     private final PeerType peerType;
 
+    private final SecurityWarningWindow warningWindow;
+
     /**
      * Current modal blocker or null.
      *
@@ -158,11 +160,26 @@
         }
 
         platformWindow.initialize(target, this, ownerDelegate);
+
+        // Init warning window(for applets)
+        SecurityWarningWindow warn = null;
+        if (((Window)target).getWarningString() != null) {
+            // accessSystemTray permission allows to display TrayIcon, TrayIcon tooltip
+            // and TrayIcon balloon windows without a warning window.
+            if (!AWTAccessor.getWindowAccessor().isTrayIconWindow((Window)target)) {
+                LWToolkit toolkit = (LWToolkit)Toolkit.getDefaultToolkit();
+                warn = toolkit.createSecurityWarning(target, this);
+            }
+        }
+
+        warningWindow = warn;
     }
 
     @Override
     void initializeImpl() {
         super.initializeImpl();
+
+
         if (getTarget() instanceof Frame) {
             setTitle(((Frame) getTarget()).getTitle());
             setState(((Frame) getTarget()).getExtendedState());
@@ -217,12 +234,20 @@
         if (isGrabbing()) {
             ungrab();
         }
+        if (warningWindow != null) {
+            warningWindow.dispose();
+        }
+
         platformWindow.dispose();
         super.disposeImpl();
     }
 
     @Override
     protected void setVisibleImpl(final boolean visible) {
+        if (!visible && warningWindow != null) {
+            warningWindow.setVisible(false, false);
+        }
+
         super.setVisibleImpl(visible);
         // TODO: update graphicsConfig, see 4868278
         platformWindow.setVisible(visible);
@@ -453,7 +478,15 @@
 
     @Override
     public void repositionSecurityWarning() {
-        throw new RuntimeException("not implemented");
+        if (warningWindow != null) {
+            AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor();
+            Window target = getTarget();
+            int x = compAccessor.getX(target);
+            int y = compAccessor.getY(target);
+            int width = compAccessor.getWidth(target);
+            int height = compAccessor.getHeight(target);
+            warningWindow.reposition(x, y, width, height);
+        }
     }
 
     // ---- FRAME PEER METHODS ---- //
@@ -513,6 +546,7 @@
 
     // ---- PEER NOTIFICATIONS ---- //
 
+    @Override
     public void notifyIconify(boolean iconify) {
         //The toplevel target is Frame and states are applicable to it.
         //Otherwise, the target is Window and it don't have state property.
@@ -537,6 +571,7 @@
         }
     }
 
+    @Override
     public void notifyZoom(boolean isZoomed) {
         int newWindowState = isZoomed ? Frame.MAXIMIZED_BOTH : Frame.NORMAL;
         postWindowStateChangedEvent(newWindowState);
@@ -546,7 +581,8 @@
      * Called by the {@code PlatformWindow} when any part of the window should
      * be repainted.
      */
-    public final void notifyExpose(final Rectangle r) {
+    @Override
+    public void notifyExpose(final Rectangle r) {
         repaintPeer(r);
     }
 
@@ -556,7 +592,8 @@
      * LWComponentPeer as the only components which could be resized by user are
      * top-level windows.
      */
-    public final void notifyReshape(int x, int y, int w, int h) {
+    @Override
+    public void notifyReshape(int x, int y, int w, int h) {
         final boolean moved;
         final boolean resized;
         final boolean invalid = updateInsets(platformWindow.getInsets());
@@ -590,6 +627,8 @@
             handleResize(w, h, true);
             repaintPeer();
         }
+
+        repositionSecurityWarning();
     }
 
     private void clearBackground(final int w, final int h) {
@@ -617,16 +656,19 @@
         }
     }
 
+    @Override
     public void notifyUpdateCursor() {
         getLWToolkit().getCursorManager().updateCursorLater(this);
     }
 
+    @Override
     public void notifyActivation(boolean activation, LWWindowPeer opposite) {
         Window oppositeWindow = (opposite == null)? null : opposite.getTarget();
         changeFocusedWindow(activation, oppositeWindow);
     }
 
     // MouseDown in non-client area
+    @Override
     public void notifyNCMouseDown() {
         // Ungrab except for a click on a Dialog with the grabbing owner
         if (grabbingWindow != null &&
@@ -643,10 +685,11 @@
      * coordinates are relative to non-client window are, i.e. the top-left
      * point of the client area is (insets.top, insets.left).
      */
-    public void dispatchMouseEvent(int id, long when, int button,
-                                   int x, int y, int screenX, int screenY,
-                                   int modifiers, int clickCount, boolean popupTrigger,
-                                   byte[] bdata)
+    @Override
+    public void notifyMouseEvent(int id, long when, int button,
+                                 int x, int y, int screenX, int screenY,
+                                 int modifiers, int clickCount, boolean popupTrigger,
+                                 byte[] bdata)
     {
         // TODO: fill "bdata" member of AWTEvent
         Rectangle r = getBounds();
@@ -659,11 +702,9 @@
                 if (lastMouseEventPeer.isEnabled()) {
                     Point lp = lastMouseEventPeer.windowToLocal(x, y,
                             this);
-                    postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
-                            MouseEvent.MOUSE_EXITED, when,
-                            modifiers, lp.x, lp.y, screenX,
-                            screenY, clickCount, popupTrigger,
-                            button));
+                    Component target = lastMouseEventPeer.getTarget();
+                    postMouseExitedEvent(target, when, modifiers, lp,
+                            screenX, screenY, clickCount, popupTrigger, button);
                 }
 
                 // Sometimes we may get MOUSE_EXITED after lastCommonMouseEventPeer is switched
@@ -679,11 +720,9 @@
             if (targetPeer != null) {
                 if (targetPeer.isEnabled()) {
                     Point lp = targetPeer.windowToLocal(x, y, this);
-                        postEvent(new MouseEvent(targetPeer.getTarget(),
-                            MouseEvent.MOUSE_ENTERED, when,
-                            modifiers, lp.x, lp.y, screenX,
-                            screenY, clickCount, popupTrigger,
-                            button));
+                    Component target = targetPeer.getTarget();
+                    postMouseEnteredEvent(target, when, modifiers, lp,
+                            screenX, screenY, clickCount, popupTrigger, button);
                 }
                 lastCommonMouseEventPeer = targetPeer;
                 lastMouseEventPeer = targetPeer;
@@ -810,11 +849,9 @@
         // Generate Mouse Exit for components
         if (lastMouseEventPeer != null && lastMouseEventPeer.isEnabled()) {
             Point oldp = lastMouseEventPeer.windowToLocal(x, y, this);
-            postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
-                    MouseEvent.MOUSE_EXITED,
-                    when, modifiers,
-                    oldp.x, oldp.y, screenX, screenY,
-                    clickCount, popupTrigger, button));
+            Component target = lastMouseEventPeer.getTarget();
+            postMouseExitedEvent(target, when, modifiers, oldp, screenX, screenY,
+                    clickCount, popupTrigger, button);
         }
         lastCommonMouseEventPeer = targetPeer;
         lastMouseEventPeer = targetPeer;
@@ -822,18 +859,42 @@
         // Generate Mouse Enter for components
         if (targetPeer != null && targetPeer.isEnabled()) {
             Point newp = targetPeer.windowToLocal(x, y, this);
-            postEvent(new MouseEvent(targetPeer.getTarget(),
-                    MouseEvent.MOUSE_ENTERED,
-                    when, modifiers,
-                    newp.x, newp.y, screenX, screenY,
-                    clickCount, popupTrigger, button));
+            Component target = targetPeer.getTarget();
+            postMouseEnteredEvent(target, when, modifiers, newp, screenX, screenY, clickCount, popupTrigger, button);
         }
     }
 
-    public void dispatchMouseWheelEvent(long when, int x, int y, int modifiers,
-                                        int scrollType, int scrollAmount,
-                                        int wheelRotation, double preciseWheelRotation,
-                                        byte[] bdata)
+    private void postMouseEnteredEvent(Component target, long when, int modifiers,
+                                       Point loc, int xAbs, int yAbs,
+                                       int clickCount, boolean popupTrigger, int button) {
+
+        updateSecurityWarningVisibility();
+
+        postEvent(new MouseEvent(target,
+                MouseEvent.MOUSE_ENTERED,
+                when, modifiers,
+                loc.x, loc.y, xAbs, yAbs,
+                clickCount, popupTrigger, button));
+    }
+
+    private void postMouseExitedEvent(Component target, long when, int modifiers,
+                                      Point loc, int xAbs, int yAbs,
+                                      int clickCount, boolean popupTrigger, int button) {
+
+        updateSecurityWarningVisibility();
+
+        postEvent(new MouseEvent(target,
+                MouseEvent.MOUSE_EXITED,
+                when, modifiers,
+                loc.x, loc.y, xAbs, yAbs,
+                clickCount, popupTrigger, button));
+    }
+
+    @Override
+    public void notifyMouseWheelEvent(long when, int x, int y, int modifiers,
+                                      int scrollType, int scrollAmount,
+                                      int wheelRotation, double preciseWheelRotation,
+                                      byte[] bdata)
     {
         // TODO: could we just use the last mouse event target here?
         Rectangle r = getBounds();
@@ -859,8 +920,9 @@
     /*
      * Called by the delegate when a key is pressed.
      */
-    public void dispatchKeyEvent(int id, long when, int modifiers,
-                                 int keyCode, char keyChar, int keyLocation)
+    @Override
+    public void notifyKeyEvent(int id, long when, int modifiers,
+                               int keyCode, char keyChar, int keyLocation)
     {
         LWKeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
         Component focusOwner = kfmPeer.getCurrentFocusOwner();
@@ -874,7 +936,6 @@
         postEvent(new KeyEvent(focusOwner, id, when, modifiers, keyCode, keyChar, keyLocation));
     }
 
-
     // ---- UTILITY METHODS ---- //
 
     private void activateDisplayListener() {
@@ -894,11 +955,14 @@
             AWTAccessor.getFrameAccessor().setExtendedState(
                     (Frame)getTarget(), newWindowState);
         }
+
         WindowEvent stateChangedEvent = new WindowEvent(getTarget(),
                 WindowEvent.WINDOW_STATE_CHANGED,
                 windowState, newWindowState);
         postEvent(stateChangedEvent);
         windowState = newWindowState;
+
+        updateSecurityWarningVisibility();
     }
 
     private static int getGraphicsConfigScreen(GraphicsConfiguration gc) {
@@ -1059,7 +1123,7 @@
      * In case of a simple window, triggers appropriate java focus change.
      */
     public boolean requestWindowFocus(CausedFocusEvent.Cause cause) {
-        if (focusLog.isLoggable(PlatformLogger.FINE)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
             focusLog.fine("requesting native focus to " + this);
         }
 
@@ -1085,7 +1149,7 @@
             // If owner is not natively active, request native
             // activation on it w/o sending events up to java.
             if (owner != null && !owner.platformWindow.isActive()) {
-                if (focusLog.isLoggable(PlatformLogger.FINE)) {
+                if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
                     focusLog.fine("requesting native focus to the owner " + owner);
                 }
                 LWWindowPeer currentActivePeer = (currentActive != null ?
@@ -1093,7 +1157,7 @@
 
                 // Ensure the opposite is natively active and suppress sending events.
                 if (currentActivePeer != null && currentActivePeer.platformWindow.isActive()) {
-                    if (focusLog.isLoggable(PlatformLogger.FINE)) {
+                    if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
                         focusLog.fine("the opposite is " + currentActivePeer);
                     }
                     currentActivePeer.skipNextFocusChange = true;
@@ -1150,7 +1214,7 @@
      * Changes focused window on java level.
      */
     protected void changeFocusedWindow(boolean becomesFocused, Window opposite) {
-        if (focusLog.isLoggable(PlatformLogger.FINE)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
             focusLog.fine((becomesFocused?"gaining":"loosing") + " focus window: " + this);
         }
         if (skipNextFocusChange) {
@@ -1165,7 +1229,7 @@
         if (becomesFocused) {
             synchronized (getPeerTreeLock()) {
                 if (blocker != null) {
-                    if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+                    if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                         focusLog.finest("the window is blocked by " + blocker);
                     }
                     return;
@@ -1179,7 +1243,7 @@
         if (!becomesFocused &&
             (isGrabbing() || getOwnerFrameDialog(grabbingWindow) == this))
         {
-            if (focusLog.isLoggable(PlatformLogger.FINE)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
                 focusLog.fine("ungrabbing on " + grabbingWindow);
             }
             // ungrab a simple window if its owner looses activation.
@@ -1222,10 +1286,12 @@
 
     public void enterFullScreenMode() {
         platformWindow.enterFullScreenMode();
+        updateSecurityWarningVisibility();
     }
 
     public void exitFullScreenMode() {
         platformWindow.exitFullScreenMode();
+        updateSecurityWarningVisibility();
     }
 
     public long getLayerPtr() {
@@ -1260,6 +1326,33 @@
         return peerType;
     }
 
+    public void updateSecurityWarningVisibility() {
+        if (warningWindow == null) {
+            return;
+        }
+
+        if (!isVisible()) {
+            return; // The warning window should already be hidden.
+        }
+
+        boolean show = false;
+
+        if (!platformWindow.isFullScreenMode()) {
+            if (isVisible()) {
+                if (LWKeyboardFocusManagerPeer.getInstance().getCurrentFocusedWindow() ==
+                        getTarget()) {
+                    show = true;
+                }
+
+                if (platformWindow.isUnderMouse() || warningWindow.isUnderMouse()) {
+                    show = true;
+                }
+            }
+        }
+
+        warningWindow.setVisible(show, true);
+    }
+
     @Override
     public String toString() {
         return super.toString() + " [target is " + getTarget() + "]";
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/macosx/classes/sun/lwawt/PlatformEventNotifier.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.lwawt;
+
+import java.awt.Rectangle;
+
+public interface PlatformEventNotifier {
+    void notifyIconify(boolean iconify);
+
+    void notifyZoom(boolean isZoomed);
+
+    void notifyExpose(Rectangle r);
+
+    void notifyReshape(int x, int y, int w, int h);
+
+    void notifyUpdateCursor();
+
+    void notifyActivation(boolean activation, LWWindowPeer opposite);
+
+    // MouseDown in non-client area
+    void notifyNCMouseDown();
+
+    /*
+     * Called by the delegate to dispatch the event to Java. Event
+     * coordinates are relative to non-client window are, i.e. the top-left
+     * point of the client area is (insets.top, insets.left).
+     */
+    void notifyMouseEvent(int id, long when, int button,
+                          int x, int y, int screenX, int screenY,
+                          int modifiers, int clickCount, boolean popupTrigger,
+                          byte[] bdata);
+
+    void notifyMouseWheelEvent(long when, int x, int y, int modifiers,
+                               int scrollType, int scrollAmount,
+                               int wheelRotation, double preciseWheelRotation,
+                               byte[] bdata);
+    /*
+     * Called by the delegate when a key is pressed.
+     */
+    void notifyKeyEvent(int id, long when, int modifiers,
+                        int keyCode, char keyChar, int keyLocation);
+}
--- a/jdk/src/macosx/classes/sun/lwawt/PlatformWindow.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/PlatformWindow.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -146,6 +146,8 @@
 
     public void exitFullScreenMode();
 
+    public boolean isFullScreenMode();
+
     public void setWindowState(int windowState);
 
     public long getLayerPtr();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/macosx/classes/sun/lwawt/SecurityWarningWindow.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.lwawt;
+
+public interface SecurityWarningWindow extends PlatformWindow {
+    /**
+     * @param x,y,w,h coordinates of the untrusted window
+     */
+    public void reposition(int x, int y, int w, int h);
+
+    public void setVisible(boolean visible, boolean doSchedule);
+}
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java	Wed Jul 05 19:00:49 2017 +0200
@@ -38,7 +38,8 @@
 public class CEmbeddedFrame extends EmbeddedFrame {
 
     private CPlatformResponder responder;
-    private boolean focused = true;
+    private static final Object classLock = new Object();
+    private static volatile CEmbeddedFrame focusedWindow;
     private boolean parentWindowActive = true;
 
     public CEmbeddedFrame() {
@@ -104,9 +105,16 @@
         responder.handleInputEvent(text);
     }
 
+    // handleFocusEvent is called when the applet becames focused/unfocused.
+    // This method can be called from different threads.
     public void handleFocusEvent(boolean focused) {
-        this.focused = focused;
-        if (focused) {
+        synchronized (classLock) {
+            // In some cases an applet may not receive the focus lost event
+            // from the parent window (see 8012330)
+            focusedWindow = (focused) ? this
+                    : ((focusedWindow == this) ? null : focusedWindow);
+        }
+        if (focusedWindow == this) {
             // see bug 8010925
             // we can't put this to handleWindowFocusEvent because
             // it won't be invoced if focuse is moved to a html element
@@ -119,11 +127,14 @@
         }
     }
 
+    // handleWindowFocusEvent is called for all applets, when the browser
+    // becames active/inactive. This event should be filtered out for
+    // non-focused applet. This method can be called from different threads.
     public void handleWindowFocusEvent(boolean parentWindowActive) {
         this.parentWindowActive = parentWindowActive;
         // ignore focus "lost" native request as it may mistakenly
         // deactivate active window (see 8001161)
-        if (focused && parentWindowActive) {
+        if (focusedWindow == this && parentWindowActive) {
             responder.handleWindowFocusEvent(parentWindowActive, null);
         }
     }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformEmbeddedFrame.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformEmbeddedFrame.java	Wed Jul 05 19:00:49 2017 +0200
@@ -186,6 +186,11 @@
     public void exitFullScreenMode() {}
 
     @Override
+    public boolean isFullScreenMode() {
+        return false;
+    }
+
+    @Override
     public void setWindowState(int windowState) {}
 
     @Override
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 
 import sun.awt.SunToolkit;
 import sun.lwawt.LWWindowPeer;
+import sun.lwawt.PlatformEventNotifier;
 import sun.lwawt.macosx.event.NSEvent;
 import java.awt.Toolkit;
 import java.awt.event.MouseEvent;
@@ -39,12 +40,13 @@
  */
 final class CPlatformResponder {
 
-    private final LWWindowPeer peer;
+    private final PlatformEventNotifier eventNotifier;
     private final boolean isNpapiCallback;
     private int lastKeyPressCode = KeyEvent.VK_UNDEFINED;
 
-    CPlatformResponder(final LWWindowPeer peer, final boolean isNpapiCallback) {
-        this.peer = peer;
+    CPlatformResponder(final PlatformEventNotifier eventNotifier,
+                       final boolean isNpapiCallback) {
+        this.eventNotifier = eventNotifier;
         this.isNpapiCallback = isNpapiCallback;
     }
 
@@ -78,9 +80,9 @@
                                                         modifierFlags);
         boolean jpopupTrigger = NSEvent.isPopupTrigger(jmodifiers);
 
-        peer.dispatchMouseEvent(jeventType, System.currentTimeMillis(), jbuttonNumber,
-                                x, y, absoluteX, absoluteY, jmodifiers, jclickCount,
-                                jpopupTrigger, null);
+        eventNotifier.notifyMouseEvent(jeventType, System.currentTimeMillis(), jbuttonNumber,
+                x, y, absoluteX, absoluteY, jmodifiers, jclickCount,
+                jpopupTrigger, null);
     }
 
     /**
@@ -116,8 +118,8 @@
             wheelRotation = signum;
         }
         // invert the wheelRotation for the peer
-        peer.dispatchMouseWheelEvent(when, x, y, modifiers, scrollType,
-                                     scrollAmount, -wheelRotation, -delta, null);
+        eventNotifier.notifyMouseWheelEvent(when, x, y, modifiers, scrollType,
+                scrollAmount, -wheelRotation, -delta, null);
     }
 
     /**
@@ -187,8 +189,8 @@
         if (jeventType == KeyEvent.KEY_PRESSED) {
             lastKeyPressCode = jkeyCode;
         }
-        peer.dispatchKeyEvent(jeventType, when, jmodifiers,
-                              jkeyCode, javaChar, jkeyLocation);
+        eventNotifier.notifyKeyEvent(jeventType, when, jmodifiers,
+                jkeyCode, javaChar, jkeyLocation);
 
         // Current browser may be sending input events, so don't
         // post the KEY_TYPED here.
@@ -206,12 +208,12 @@
             if (needsKeyReleased && (jkeyCode == KeyEvent.VK_ENTER || jkeyCode == KeyEvent.VK_SPACE)) {
                 return;
             }
-            peer.dispatchKeyEvent(KeyEvent.KEY_TYPED, when, jmodifiers,
-                                  KeyEvent.VK_UNDEFINED, javaChar,
-                                  KeyEvent.KEY_LOCATION_UNKNOWN);
+            eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED, when, jmodifiers,
+                    KeyEvent.VK_UNDEFINED, javaChar,
+                    KeyEvent.KEY_LOCATION_UNKNOWN);
             //If events come from Firefox, released events should also be generated.
             if (needsKeyReleased) {
-                peer.dispatchKeyEvent(KeyEvent.KEY_RELEASED, when, jmodifiers,
+                eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED, when, jmodifiers,
                         jkeyCode, javaChar,
                         KeyEvent.KEY_LOCATION_UNKNOWN);
             }
@@ -224,13 +226,13 @@
             char c = 0;
             while (index < length) {
                 c = text.charAt(index);
-                peer.dispatchKeyEvent(KeyEvent.KEY_TYPED,
+                eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED,
                         System.currentTimeMillis(),
                         0, KeyEvent.VK_UNDEFINED, c,
                         KeyEvent.KEY_LOCATION_UNKNOWN);
                 index++;
             }
-            peer.dispatchKeyEvent(KeyEvent.KEY_RELEASED,
+            eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED,
                     System.currentTimeMillis(),
                     0, lastKeyPressCode, c,
                     KeyEvent.KEY_LOCATION_UNKNOWN);
@@ -238,6 +240,6 @@
     }
 
     void handleWindowFocusEvent(boolean gained, LWWindowPeer opposite) {
-        peer.notifyActivation(gained, opposite);
+        eventNotifier.notifyActivation(gained, opposite);
     }
 }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -57,11 +57,15 @@
         initializeBase(peer, responder);
 
         if (!LWCToolkit.getSunAwtDisableCALayers()) {
-            this.windowLayer = new CGLLayer(peer);
+            this.windowLayer = createCGLayer();
         }
         setPtr(nativeCreateView(0, 0, 0, 0, getWindowLayerPtr()));
     }
 
+    public CGLLayer createCGLayer() {
+        return new CGLLayer(peer);
+    }
+
     protected void initializeBase(LWWindowPeer peer, CPlatformResponder responder) {
         this.peer = peer;
         this.responder = responder;
@@ -69,7 +73,7 @@
 
     public long getAWTView() {
         return ptr;
-        }
+    }
 
     public boolean isOpaque() {
         return !peer.isTranslucent();
@@ -100,6 +104,10 @@
         CWrapper.NSView.exitFullScreenMode(ptr);
     }
 
+    public void setToolTip(String msg) {
+        CWrapper.NSView.setToolTip(ptr, msg);
+    }
+
     // ----------------------------------------------------------------------
     // PAINTING METHODS
     // ----------------------------------------------------------------------
@@ -108,7 +116,7 @@
             surfaceData = windowLayer.replaceSurfaceData();
         } else {
             if (surfaceData == null) {
-                CGraphicsConfig graphicsConfig = (CGraphicsConfig)peer.getGraphicsConfiguration();
+                CGraphicsConfig graphicsConfig = (CGraphicsConfig)getGraphicsConfiguration();
                 surfaceData = graphicsConfig.createSurfaceData(this);
             } else {
                 validateSurface();
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Wed Jul 05 19:00:49 2017 +0200
@@ -204,9 +204,9 @@
 
     private Window target;
     private LWWindowPeer peer;
-    private CPlatformView contentView;
-    private CPlatformWindow owner;
-    private boolean visible = false; // visibility status from native perspective
+    protected CPlatformView contentView;
+    protected CPlatformWindow owner;
+    protected boolean visible = false; // visibility status from native perspective
     private boolean undecorated; // initialized in getInitialStyleBits()
     private Rectangle normalBounds = null; // not-null only for undecorated maximized windows
     private CPlatformResponder responder;
@@ -226,19 +226,13 @@
 
         final int styleBits = getInitialStyleBits();
 
-        // TODO: handle these misc properties
-        final long parentNSWindowPtr = (owner != null ? owner.getNSWindowPtr() : 0);
-        String warningString = target.getWarningString();
-
-        responder = new CPlatformResponder(peer, false);
+        responder = createPlatformResponder();
+        contentView = createContentView();
         contentView.initialize(peer, responder);
 
         final long nativeWindowPtr = nativeCreateNSWindow(contentView.getAWTView(), styleBits, 0, 0, 0, 0);
         setPtr(nativeWindowPtr);
 
-        // TODO: implement on top of JObjC bridged class
-    //    NSWindow window = JObjC.getInstance().AppKit().NSWindow().getInstance(nativeWindowPtr, JObjCRuntime.getInstance());
-
         if (target instanceof javax.swing.RootPaneContainer) {
             final javax.swing.JRootPane rootpane = ((javax.swing.RootPaneContainer)target).getRootPane();
             if (rootpane != null) rootpane.addPropertyChangeListener("ancestor", new PropertyChangeListener() {
@@ -261,7 +255,15 @@
         this.contentView = view;
     }
 
-    private int getInitialStyleBits() {
+    protected CPlatformResponder createPlatformResponder() {
+        return new CPlatformResponder(peer, false);
+    }
+
+    protected CPlatformView createContentView() {
+        return new CPlatformView();
+    }
+
+    protected int getInitialStyleBits() {
         // defaults style bits
         int styleBits = DECORATED | HAS_SHADOW | CLOSEABLE | MINIMIZABLE | ZOOMABLE | RESIZABLE;
 
@@ -467,7 +469,7 @@
     }
 
     private void maximize() {
-        if (isMaximized()) {
+        if (peer == null || isMaximized()) {
             return;
         }
         if (!undecorated) {
@@ -502,7 +504,7 @@
         }
     }
 
-    private boolean isVisible() {
+    public boolean isVisible() {
         return this.visible;
     }
 
@@ -534,7 +536,7 @@
         updateFocusabilityForAutoRequestFocus(false);
 
         // Actually show or hide the window
-        LWWindowPeer blocker = peer.getBlocker();
+        LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
         if (blocker == null || !visible) {
             // If it ain't blocked, or is being hidden, go regular way
             if (visible) {
@@ -633,7 +635,7 @@
     public long getNSWindowPtr() {
         final long nsWindowPtr = ptr;
         if (nsWindowPtr == 0L) {
-            if(logger.isLoggable(PlatformLogger.FINE)) {
+            if(logger.isLoggable(PlatformLogger.Level.FINE)) {
                 logger.fine("NSWindow already disposed?", new Exception("Pointer to native NSWindow is invalid."));
             }
         }
@@ -726,7 +728,8 @@
     @Override
     public void setOpaque(boolean isOpaque) {
         CWrapper.NSWindow.setOpaque(getNSWindowPtr(), isOpaque);
-        if (!isOpaque && !peer.isTextured()) {
+        boolean isTextured = (peer == null)? false : peer.isTextured();
+        if (!isOpaque && !isTextured) {
             long clearColor = CWrapper.NSColor.clearColor();
             CWrapper.NSWindow.setBackgroundColor(getNSWindowPtr(), clearColor);
         }
@@ -766,8 +769,13 @@
     }
 
     @Override
+    public boolean isFullScreenMode() {
+        return isFullScreenMode;
+    }
+
+    @Override
     public void setWindowState(int windowState) {
-        if (!peer.isVisible()) {
+        if (peer == null || !peer.isVisible()) {
             // setVisible() applies the state
             return;
         }
@@ -804,8 +812,6 @@
                 throw new RuntimeException("Unknown window state: " + windowState);
         }
 
-        nativeSynthesizeMouseEnteredExitedEvents();
-
         // NOTE: the SWP.windowState field gets updated to the newWindowState
         //       value when the native notification comes to us
     }
@@ -914,7 +920,7 @@
         responder.handleWindowFocusEvent(gained, oppositePeer);
     }
 
-    private void deliverMoveResizeEvent(int x, int y, int width, int height,
+    protected void deliverMoveResizeEvent(int x, int y, int width, int height,
                                         boolean byUser) {
         // when the content view enters the full-screen mode, the native
         // move/resize notifications contain a bounds smaller than
@@ -927,9 +933,13 @@
         final Rectangle oldB = nativeBounds;
         nativeBounds = new Rectangle(x, y, width, height);
         final GraphicsConfiguration oldGC = peer.getGraphicsConfiguration();
-        peer.notifyReshape(x, y, width, height);
+
         final GraphicsConfiguration newGC = peer.getGraphicsConfiguration();
         // System-dependent appearance optimization.
+        if (peer != null) {
+            peer.notifyReshape(x, y, width, height);
+        }
+
         if ((byUser && !oldB.getSize().equals(nativeBounds.getSize()))
             || isFullScreenAnimationOn || !Objects.equals(newGC, oldGC)) {
             flushBuffers();
@@ -937,21 +947,29 @@
     }
 
     private void deliverWindowClosingEvent() {
-        if (peer.getBlocker() == null)  {
-            peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
+        if (peer != null) {
+            if (peer.getBlocker() == null)  {
+                peer.postEvent(new WindowEvent(target, WindowEvent.WINDOW_CLOSING));
+            }
         }
     }
 
     private void deliverIconify(final boolean iconify) {
-        peer.notifyIconify(iconify);
+        if (peer != null) {
+            peer.notifyIconify(iconify);
+        }
     }
 
     private void deliverZoom(final boolean isZoomed) {
-        peer.notifyZoom(isZoomed);
+        if (peer != null) {
+            peer.notifyZoom(isZoomed);
+        }
     }
 
     private void deliverNCMouseDown() {
-        peer.notifyNCMouseDown();
+        if (peer != null) {
+            peer.notifyNCMouseDown();
+        }
     }
 
     /*
@@ -959,6 +977,10 @@
      * may become natively focusable window.
      */
     private boolean isNativelyFocusableWindow() {
+        if (peer == null) {
+            return false;
+        }
+
         return !peer.isSimpleWindow() && target.getFocusableWindowState();
     }
 
@@ -973,7 +995,7 @@
     }
 
     private boolean checkBlocking() {
-        LWWindowPeer blocker = peer.getBlocker();
+        LWWindowPeer blocker = (peer == null)? null : peer.getBlocker();
         if (blocker == null) {
             return false;
         }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CTrayIcon.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CTrayIcon.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
 
 package sun.lwawt.macosx;
 
+import sun.awt.AWTAccessor;
 import sun.awt.SunToolkit;
 import sun.lwawt.macosx.event.NSEvent;
 
@@ -339,6 +340,9 @@
 
         dialog.addWindowListener(handler);
 
+        // suppress security warning for untrusted windows
+        AWTAccessor.getWindowAccessor().setTrayIconWindow(dialog, true);
+
         dialog.pack();
 
         return dialog;
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CViewPlatformEmbeddedFrame.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CViewPlatformEmbeddedFrame.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -201,6 +201,11 @@
     }
 
     @Override
+    public boolean isFullScreenMode() {
+        return false;
+    }
+
+    @Override
     public void setWindowState(int windowState) {
     }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,444 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.lwawt.macosx;
+
+import sun.awt.AWTAccessor;
+import sun.awt.IconInfo;
+import sun.awt.SunToolkit;
+import sun.java2d.SunGraphics2D;
+import sun.java2d.SurfaceData;
+import sun.java2d.opengl.CGLLayer;
+import sun.lwawt.LWWindowPeer;
+import sun.lwawt.PlatformEventNotifier;
+import sun.lwawt.SecurityWarningWindow;
+
+import java.awt.*;
+import java.awt.event.MouseEvent;
+import java.awt.geom.Point2D;
+import java.lang.ref.WeakReference;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+
+public final class CWarningWindow extends CPlatformWindow
+        implements SecurityWarningWindow, PlatformEventNotifier {
+
+    private static class Lock {};
+    private final Lock lock = new Lock();
+
+    private final static int SHOWING_DELAY = 300;
+    private final static int HIDING_DELAY = 2000;
+
+    private Rectangle bounds = new Rectangle();
+    private final WeakReference<LWWindowPeer> ownerPeer;
+    private final Window ownerWindow;
+
+    /**
+     * Animation stage.
+     */
+    private volatile int currentIcon = 0;
+
+    /* -1 - uninitialized.
+     * 0 - 16x16
+     * 1 - 24x24
+     * 2 - 32x32
+     * 3 - 48x48
+     */
+    private int currentSize = -1;
+    private static IconInfo[][] icons;
+    private static IconInfo getSecurityIconInfo(int size, int num) {
+        synchronized (CWarningWindow.class) {
+            if (icons == null) {
+                icons = new IconInfo[4][3];
+                icons[0][0] = new IconInfo(sun.awt.AWTIcon32_security_icon_bw16_png.security_icon_bw16_png);
+                icons[0][1] = new IconInfo(sun.awt.AWTIcon32_security_icon_interim16_png.security_icon_interim16_png);
+                icons[0][2] = new IconInfo(sun.awt.AWTIcon32_security_icon_yellow16_png.security_icon_yellow16_png);
+                icons[1][0] = new IconInfo(sun.awt.AWTIcon32_security_icon_bw24_png.security_icon_bw24_png);
+                icons[1][1] = new IconInfo(sun.awt.AWTIcon32_security_icon_interim24_png.security_icon_interim24_png);
+                icons[1][2] = new IconInfo(sun.awt.AWTIcon32_security_icon_yellow24_png.security_icon_yellow24_png);
+                icons[2][0] = new IconInfo(sun.awt.AWTIcon32_security_icon_bw32_png.security_icon_bw32_png);
+                icons[2][1] = new IconInfo(sun.awt.AWTIcon32_security_icon_interim32_png.security_icon_interim32_png);
+                icons[2][2] = new IconInfo(sun.awt.AWTIcon32_security_icon_yellow32_png.security_icon_yellow32_png);
+                icons[3][0] = new IconInfo(sun.awt.AWTIcon32_security_icon_bw48_png.security_icon_bw48_png);
+                icons[3][1] = new IconInfo(sun.awt.AWTIcon32_security_icon_interim48_png.security_icon_interim48_png);
+                icons[3][2] = new IconInfo(sun.awt.AWTIcon32_security_icon_yellow48_png.security_icon_yellow48_png);
+            }
+        }
+        final int sizeIndex = size % icons.length;
+        return icons[sizeIndex][num % icons[sizeIndex].length];
+    }
+
+    public CWarningWindow(final Window _ownerWindow, final LWWindowPeer _ownerPeer) {
+        super();
+
+        this.ownerPeer = new WeakReference<LWWindowPeer>(_ownerPeer);
+        this.ownerWindow = _ownerWindow;
+
+        initialize(null, null, _ownerPeer.getPlatformWindow());
+
+        setOpaque(false);
+
+        String warningString = ownerWindow.getWarningString();
+        if (warningString != null) {
+            contentView.setToolTip(ownerWindow.getWarningString());
+        }
+
+        updateIconSize();
+    }
+
+    /**
+     * @param x,y,w,h coordinates of the untrusted window
+     */
+    public void reposition(int x, int y, int w, int h) {
+        final Point2D point = AWTAccessor.getWindowAccessor().
+                calculateSecurityWarningPosition(ownerWindow, x, y, w, h);
+        setBounds((int)point.getX(), (int)point.getY(), getWidth(), getHeight());
+    }
+
+    public void setVisible(boolean visible, boolean doSchedule) {
+        synchronized (scheduler) {
+            if (showingTaskHandle != null) {
+                showingTaskHandle.cancel(false);
+                showingTaskHandle = null;
+            }
+
+            if (hidingTaskHandle != null) {
+                hidingTaskHandle.cancel(false);
+                hidingTaskHandle = null;
+            }
+
+            if (visible) {
+                if (isVisible()) {
+                    currentIcon = 0;
+                } else {
+                    currentIcon = 2;
+                }
+
+                showingTaskHandle = scheduler.schedule(showingTask, 50,
+                        TimeUnit.MILLISECONDS);
+
+            } else {
+                if (!isVisible()) {
+                    return;
+                }
+
+                if (doSchedule) {
+                    hidingTaskHandle = scheduler.schedule(hidingTask, HIDING_DELAY,
+                            TimeUnit.MILLISECONDS);
+                } else {
+                    hidingTaskHandle = scheduler.schedule(hidingTask, 50,
+                            TimeUnit.MILLISECONDS);
+                }
+            }
+        }
+    }
+
+    @Override
+    public void notifyIconify(boolean iconify) {
+    }
+
+    @Override
+    public void notifyZoom(boolean isZoomed) {
+    }
+
+    @Override
+    public void notifyExpose(final Rectangle r) {
+        repaint();
+    }
+
+    @Override
+    public void notifyReshape(int x, int y, int w, int h) {
+    }
+
+    @Override
+    public void notifyUpdateCursor() {
+    }
+
+    @Override
+    public void notifyActivation(boolean activation, LWWindowPeer opposite) {
+    }
+
+    @Override
+    public void notifyNCMouseDown() {
+    }
+
+    @Override
+    public void notifyMouseEvent(int id, long when, int button, int x, int y,
+                                 int screenX, int screenY, int modifiers,
+                                 int clickCount, boolean popupTrigger,
+                                 byte[] bdata) {
+        LWWindowPeer peer = ownerPeer.get();
+        if (id == MouseEvent.MOUSE_EXITED) {
+            if (peer != null) {
+                peer.updateSecurityWarningVisibility();
+            }
+        } else if(id == MouseEvent.MOUSE_ENTERED) {
+            if (peer != null) {
+                peer.updateSecurityWarningVisibility();
+            }
+        }
+    }
+
+    public Rectangle getBounds() {
+        synchronized (lock) {
+            return bounds.getBounds();
+        }
+    }
+
+    @Override
+    public boolean isVisible() {
+        synchronized (lock) {
+            return visible;
+        }
+    }
+
+    @Override
+    public void setVisible(boolean visible) {
+        synchronized (lock) {
+            final long nsWindowPtr = getNSWindowPtr();
+
+            // Process parent-child relationship when hiding
+            if (!visible) {
+                // Unparent myself
+                if (owner != null && owner.isVisible()) {
+                    CWrapper.NSWindow.removeChildWindow(
+                            owner.getNSWindowPtr(), nsWindowPtr);
+                }
+            }
+
+            // Actually show or hide the window
+            if (visible) {
+                CWrapper.NSWindow.orderFront(nsWindowPtr);
+            } else {
+                CWrapper.NSWindow.orderOut(nsWindowPtr);
+            }
+
+            this.visible = visible;
+
+            // Manage parent-child relationship when showing
+            if (visible) {
+                // Add myself as a child
+                if (owner != null && owner.isVisible()) {
+                    CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(),
+                            nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
+
+                    // do not allow security warning to be obscured by other windows
+                    if (ownerWindow.isAlwaysOnTop()) {
+                        CWrapper.NSWindow.setLevel(nsWindowPtr,
+                                CWrapper.NSWindow.NSFloatingWindowLevel);
+                    }
+                }
+            }
+        }
+    }
+
+    @Override
+    public void notifyMouseWheelEvent(long when, int x, int y, int modifiers,
+                                      int scrollType, int scrollAmount,
+                                      int wheelRotation, double preciseWheelRotation,
+                                      byte[] bdata) {
+    }
+
+    @Override
+    public void notifyKeyEvent(int id, long when, int modifiers, int keyCode,
+                               char keyChar, int keyLocation) {
+    }
+
+    protected int getInitialStyleBits() {
+        int styleBits = 0;
+        CPlatformWindow.SET(styleBits, CPlatformWindow.UTILITY, true);
+        return styleBits;
+    }
+
+    protected void deliverMoveResizeEvent(int x, int y, int width, int height,
+                                          boolean byUser) {
+
+        boolean isResize;
+        synchronized (lock) {
+            isResize = (bounds.width != width || bounds.height != height);
+            bounds = new Rectangle(x, y, width, height);
+        }
+
+        if (isResize) {
+            replaceSurface();
+        }
+
+        super.deliverMoveResizeEvent(x, y, width, height, byUser);
+    }
+
+    protected CPlatformResponder createPlatformResponder() {
+        return new CPlatformResponder(this, false);
+    }
+
+    protected CPlatformView createContentView() {
+        return new CPlatformView() {
+            public GraphicsConfiguration getGraphicsConfiguration() {
+                LWWindowPeer peer = ownerPeer.get();
+                return peer.getGraphicsConfiguration();
+            }
+
+            public Rectangle getBounds() {
+                return CWarningWindow.this.getBounds();
+            }
+
+            public CGLLayer createCGLayer() {
+                return new CGLLayer(null) {
+                    public Rectangle getBounds() {
+                        return CWarningWindow.this.getBounds();
+                    }
+
+                    public GraphicsConfiguration getGraphicsConfiguration() {
+                        LWWindowPeer peer = ownerPeer.get();
+                        return peer.getGraphicsConfiguration();
+                    }
+
+                    public boolean isOpaque() {
+                        return false;
+                    }
+                };
+            }
+        };
+    }
+
+    private void updateIconSize() {
+        int newSize = -1;
+
+        if (ownerWindow != null) {
+            Insets insets = ownerWindow.getInsets();
+            int max = Math.max(insets.top, Math.max(insets.bottom,
+                    Math.max(insets.left, insets.right)));
+            if (max < 24) {
+                newSize = 0;
+            } else if (max < 32) {
+                newSize = 1;
+            } else if (max < 48) {
+                newSize = 2;
+            } else {
+                newSize = 3;
+            }
+        }
+        // Make sure we have a valid size
+        if (newSize == -1) {
+            newSize = 0;
+        }
+
+        synchronized (lock) {
+            if (newSize != currentSize) {
+                currentSize = newSize;
+                IconInfo ico = getSecurityIconInfo(currentSize, 0);
+                AWTAccessor.getWindowAccessor().setSecurityWarningSize(
+                    ownerWindow, ico.getWidth(), ico.getHeight());
+            }
+        }
+    }
+
+    private final Graphics getGraphics() {
+        SurfaceData sd = contentView.getSurfaceData();
+        if (ownerWindow == null || sd == null) {
+            return null;
+        }
+
+        return transformGraphics(new SunGraphics2D(sd, SystemColor.windowText,
+                SystemColor.window, ownerWindow.getFont()));
+    }
+
+
+    private void repaint() {
+        final Graphics g = getGraphics();
+        if (g != null) {
+            try {
+                ((Graphics2D) g).setComposite(AlphaComposite.Src);
+                g.drawImage(getSecurityIconInfo().getImage(), 0, 0, null);
+            } finally {
+                g.dispose();
+            }
+        }
+    }
+
+    private void replaceSurface() {
+        SurfaceData oldData = contentView.getSurfaceData();
+
+        replaceSurfaceData();
+
+        if (oldData != null && oldData != contentView.getSurfaceData()) {
+            oldData.flush();
+        }
+    }
+
+    private int getWidth() {
+        return getSecurityIconInfo().getWidth();
+    }
+
+    private int getHeight() {
+        return getSecurityIconInfo().getHeight();
+    }
+
+    private IconInfo getSecurityIconInfo() {
+        return getSecurityIconInfo(currentSize, currentIcon);
+    }
+
+    private final Runnable hidingTask = new Runnable() {
+        public void run() {
+            synchronized (lock) {
+                setVisible(false);
+            }
+
+            synchronized (scheduler) {
+                hidingTaskHandle = null;
+            }
+        }
+    };
+
+    private final Runnable showingTask = new Runnable() {
+        public void run() {
+            synchronized (lock) {
+                if (!isVisible()) {
+                    setVisible(true);
+                }
+
+                repaint();
+            }
+
+            synchronized (scheduler) {
+                if (currentIcon > 0) {
+                    currentIcon--;
+                    showingTaskHandle = scheduler.schedule(showingTask, SHOWING_DELAY,
+                            TimeUnit.MILLISECONDS);
+                } else {
+                    showingTaskHandle = null;
+                }
+            }
+        }
+    };
+
+    private final ScheduledExecutorService scheduler =
+            Executors.newSingleThreadScheduledExecutor();
+
+    private ScheduledFuture hidingTaskHandle;
+    private ScheduledFuture showingTaskHandle;
+}
+
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CWrapper.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,6 +87,8 @@
         public static native void exitFullScreenMode(long view);
 
         public static native void setHidden(long view, boolean hidden);
+
+        public static native void setToolTip(long view, String msg);
     }
 
     public static final class NSObject {
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java	Wed Jul 05 19:00:49 2017 +0200
@@ -179,6 +179,11 @@
     }
 
     @Override
+    protected SecurityWarningWindow createSecurityWarning(Window ownerWindow, LWWindowPeer ownerPeer) {
+        return new CWarningWindow(ownerWindow, ownerPeer);
+    }
+
+    @Override
     protected PlatformComponent createPlatformComponent() {
         return new CPlatformComponent();
     }
--- a/jdk/src/macosx/native/com/apple/laf/AquaFileView.m	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/native/com/apple/laf/AquaFileView.m	Wed Jul 05 19:00:49 2017 +0200
@@ -187,13 +187,13 @@
 JNF_COCOA_ENTER(env);
 
     UInt8 pathCString[MAXPATHLEN + 1];
-    size_t pathSize = sizeof(pathCString);
+    size_t maxPathLen = sizeof(pathCString) - 1;
 
     jbyte *byteArray = (*env)->GetByteArrayElements(env, pathToAlias, NULL);
     jsize length = (*env)->GetArrayLength(env, pathToAlias);
 
-    if (length > pathSize) {
-        length = pathSize;
+    if (length > maxPathLen) {
+        length = maxPathLen;
     }
     strncpy((char *)pathCString, (char *)byteArray, length);
     // make sure it's null terminated
--- a/jdk/src/macosx/native/sun/awt/AWTWindow.m	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/native/sun/awt/AWTWindow.m	Wed Jul 05 19:00:49 2017 +0200
@@ -447,6 +447,8 @@
         // TODO: create generic AWT assert
     }
 
+    [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
+
     NSRect frame = ConvertNSScreenRect(env, [self.nsWindow frame]);
 
     static JNF_MEMBER_CACHE(jm_deliverMoveResizeEvent, jc_CPlatformWindow, "deliverMoveResizeEvent", "(IIIIZ)V");
@@ -630,6 +632,7 @@
         [self _notifyFullScreenOp:com_apple_eawt_FullScreenHandler_FULLSCREEN_DID_ENTER withEnv:env];
         (*env)->DeleteLocalRef(env, platformWindow);
     }
+    [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
 }
 
 - (void)windowWillExitFullScreen:(NSNotification *)notification {
@@ -652,6 +655,7 @@
         [self _notifyFullScreenOp:com_apple_eawt_FullScreenHandler_FULLSCREEN_DID_EXIT withEnv:env];
         (*env)->DeleteLocalRef(env, platformWindow);
     }
+    [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
 }
 
 - (void)sendEvent:(NSEvent *)event {
@@ -891,8 +895,6 @@
         // ensure we repaint the whole window after the resize operation
         // (this will also re-enable screen updates, which were disabled above)
         // TODO: send PaintEvent
-
-        [AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
     }];
 
 JNF_COCOA_EXIT(env);
--- a/jdk/src/macosx/native/sun/awt/CRobot.m	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/native/sun/awt/CRobot.m	Wed Jul 05 19:00:49 2017 +0200
@@ -29,6 +29,7 @@
 #import "LWCToolkit.h"
 #import "sun_lwawt_macosx_CRobot.h"
 #import "java_awt_event_InputEvent.h"
+#import "sizecalc.h"
 
 
 // Starting number for event numbers generated by Robot.
@@ -115,7 +116,7 @@
         gsLastClickTime = 0;
         gsEventNumber = ROBOT_EVENT_NUMBER_START;
 
-        gsButtonEventNumber = (int*)malloc(sizeof(int) * gNumberOfButtons);
+        gsButtonEventNumber = (int*)SAFE_SIZE_ARRAY_ALLOC(malloc, sizeof(int), gNumberOfButtons);
         if (gsButtonEventNumber == NULL) {
             JNU_ThrowOutOfMemoryError(env, NULL);
             return;
--- a/jdk/src/macosx/native/sun/awt/CWrapper.m	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/native/sun/awt/CWrapper.m	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -669,6 +669,27 @@
     JNF_COCOA_EXIT(env);
 }
 
+/*
+ * Class:     sun_lwawt_macosx_CWrapper$NSView
+ * Method:    setToolTip
+ * Signature: (JLjava/lang/String;)V
+ */
+JNIEXPORT void JNICALL
+Java_sun_lwawt_macosx_CWrapper_00024NSView_setToolTip
+(JNIEnv *env, jclass cls, jlong viewPtr, jstring msg)
+{
+
+JNF_COCOA_ENTER(env);
+
+    NSView *view = (NSView *)jlong_to_ptr(viewPtr);
+    NSString* s = JNFJavaToNSString(env, msg); 
+    [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
+        [view setToolTip: s];
+    }];
+
+JNF_COCOA_EXIT(env);
+}
+
 
 /*
  * Class:     sun_lwawt_macosx_CWrapper$NSScreen
@@ -735,7 +756,7 @@
 {
     __block jlong screenPtr = 0L;
 
-JNF_COCOA_ENTER(env);
+JNF_COCOA_ENTER(env); 
 
     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
         NSArray *screens = [NSScreen screens];
--- a/jdk/src/macosx/native/sun/awt/LWCToolkit.m	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/native/sun/awt/LWCToolkit.m	Wed Jul 05 19:00:49 2017 +0200
@@ -37,6 +37,8 @@
 
 #import "sun_lwawt_macosx_LWCToolkit.h"
 
+#import "sizecalc.h"
+
 int gNumberOfButtons;
 jint* gButtonDownMasks;
 
@@ -202,7 +204,7 @@
     jintArray obj = (jintArray)(*env)->CallStaticObjectMethod(env, inputEventClazz, getButtonDownMasksID);
     jint * tmp = (*env)->GetIntArrayElements(env, obj, JNI_FALSE);
 
-    gButtonDownMasks = (jint*)malloc(sizeof(jint) * gNumberOfButtons);
+    gButtonDownMasks = (jint*)SAFE_SIZE_ARRAY_ALLOC(malloc, sizeof(jint), gNumberOfButtons);
     if (gButtonDownMasks == NULL) {
         gNumberOfButtons = 0;
         JNU_ThrowOutOfMemoryError(env, NULL);
--- a/jdk/src/macosx/native/sun/awt/splashscreen/splashscreen_sys.m	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/macosx/native/sun/awt/splashscreen/splashscreen_sys.m	Wed Jul 05 19:00:49 2017 +0200
@@ -44,6 +44,7 @@
 #include <unistd.h>
 #include <dlfcn.h>
 
+#include <sizecalc.h>
 
 static NSScreen* SplashNSScreen()
 {
@@ -99,9 +100,12 @@
         goto done;
     }
     inSize = strlen(in);
+    buf = SAFE_SIZE_ARRAY_ALLOC(malloc, inSize, 2);
+    if (!buf) {
+        return NULL;
+    }
     bufSize = inSize*2; // need 2 bytes per char for UCS-2, this is
                         // 2 bytes per source byte max
-    buf = malloc(bufSize);
     out = buf; outSize = bufSize;
     /* linux iconv wants char** source and solaris wants const char**...
        cast to void* */
--- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ja.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ja.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle expand=\u30C8\u30B0\u30EB\u5C55\u958B
+toggle expand=\u5C55\u958B\u306E\u30C8\u30B0\u30EB
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ko.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_ko.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle \uD655\uC7A5=\uD1A0\uAE00 \uD655\uC7A5
+toggle expand=\uD1A0\uAE00 \uD655\uC7A5
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_pt_BR.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_pt_BR.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle expandir=alternar expans\u00E3o
+toggle expand=alternar expans\u00E3o
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_sv.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/accessibility/internal/resources/accessibility_sv.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -102,7 +102,7 @@
 #
 # accessible actions
 #
-toggle ut\u00F6ka=v\u00E4xla ut\u00F6ka
+toggle expand=v\u00E4xla ut\u00F6ka
 
 # new relations, roles and states for J2SE 1.5.0
 
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/resources/gtk_de.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/resources/gtk_de.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -41,7 +41,7 @@
 FileChooser.openDialogTitle.textAndMnemonic=\u00D6ffnen
 FileChooser.pathLabel.textAndMnemonic=Aus&wahl:
 FileChooser.filterLabel.textAndMnemonic=Filter:
-FileChooser.foldersLabel.textAndMnemonic=&Ordner
+FileChooser.foldersLabel.textAndMnemonic=Or&dner
 FileChooser.filesLabel.textAndMnemonic=&Dateien
 
 FileChooser.cancelButtonToolTip.textAndMnemonic=Dialogfeld f\u00FCr Dateiauswahl schlie\u00DFen.
--- a/jdk/src/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1973,8 +1973,7 @@
          * does not add it to the list that is consulted by
          * ClassLoaderRepository.loadClass.
          */
-        final ModifiableClassLoaderRepository clr =
-                instantiator.getClassLoaderRepository();
+        final ModifiableClassLoaderRepository clr = getInstantiatorCLR();
         if (clr == null) {
             final RuntimeException wrapped =
                     new IllegalArgumentException(
@@ -2000,8 +1999,7 @@
          * Removes the  MBean from the default loader repository.
          */
         if (loader != server.getClass().getClassLoader()) {
-            final ModifiableClassLoaderRepository clr =
-                    instantiator.getClassLoaderRepository();
+            final ModifiableClassLoaderRepository clr = getInstantiatorCLR();
             if (clr != null) {
                 clr.removeClassLoader(logicalName);
             }
@@ -2060,5 +2058,12 @@
         return ResourceContext.NONE;
     }
 
-
+    private ModifiableClassLoaderRepository getInstantiatorCLR() {
+        return AccessController.doPrivileged(new PrivilegedAction<ModifiableClassLoaderRepository>() {
+            @Override
+            public ModifiableClassLoaderRepository run() {
+                return instantiator != null ? instantiator.getClassLoaderRepository() : null;
+            }
+        });
+    }
 }
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/ClassLoaderRepositorySupport.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/ClassLoaderRepositorySupport.java	Wed Jul 05 19:00:49 2017 +0200
@@ -27,12 +27,14 @@
 
 
 import static com.sun.jmx.defaults.JmxProperties.MBEANSERVER_LOGGER;
+import java.security.Permission;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Hashtable;
 import java.util.List;
 import java.util.Map;
 import java.util.logging.Level;
+import javax.management.MBeanPermission;
 
 import javax.management.ObjectName;
 import javax.management.loading.PrivateClassLoader;
@@ -300,7 +302,19 @@
     }
 
     public final ClassLoader getClassLoader(ObjectName name) {
-        return loadersWithNames.get(name);
+        ClassLoader instance = loadersWithNames.get(name);
+        if (instance != null) {
+            SecurityManager sm = System.getSecurityManager();
+            if (sm != null) {
+                Permission perm =
+                        new MBeanPermission(instance.getClass().getName(),
+                        null,
+                        name,
+                        "getClassLoader");
+                sm.checkPermission(perm);
+            }
+        }
+        return instance;
     }
 
 }
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/ConvertingMethod.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/ConvertingMethod.java	Wed Jul 05 19:00:49 2017 +0200
@@ -33,6 +33,7 @@
 import javax.management.MBeanException;
 import javax.management.openmbean.OpenDataException;
 import javax.management.openmbean.OpenType;
+import sun.reflect.misc.MethodUtil;
 
 final class ConvertingMethod {
     static ConvertingMethod from(Method m) {
@@ -189,7 +190,7 @@
                 "from open values: " + e;
             throw new MBeanException(e, msg);
         }
-        final Object javaReturn = method.invoke(obj, javaParams);
+        final Object javaReturn = MethodUtil.invoke(method, obj, javaParams);
         try {
             return returnMapping.toOpenValue(javaReturn);
         } catch (OpenDataException e) {
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java	Wed Jul 05 19:00:49 2017 +0200
@@ -74,6 +74,8 @@
 import javax.management.openmbean.TabularData;
 import javax.management.openmbean.TabularDataSupport;
 import javax.management.openmbean.TabularType;
+import sun.reflect.misc.MethodUtil;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  *   <p>A converter between Java types and the limited set of classes
@@ -299,6 +301,7 @@
 
     private static <T extends Enum<T>> MXBeanMapping
             makeEnumMapping(Class<?> enumClass, Class<T> fake) {
+        ReflectUtil.checkPackageAccess(enumClass);
         return new EnumMapping<T>(Util.<Class<T>>cast(enumClass));
     }
 
@@ -423,6 +426,7 @@
             (c.getName().equals("com.sun.management.GcInfo") &&
                 c.getClassLoader() == null);
 
+        ReflectUtil.checkPackageAccess(c);
         final List<Method> methods =
                 MBeanAnalyzer.eliminateCovariantMethods(Arrays.asList(c.getMethods()));
         final SortedMap<String,Method> getterMap = newSortedMap();
@@ -828,7 +832,7 @@
             Object[] values = new Object[getters.length];
             for (int i = 0; i < getters.length; i++) {
                 try {
-                    Object got = getters[i].invoke(value, (Object[]) null);
+                    Object got = MethodUtil.invoke(getters[i], value, (Object[]) null);
                     values[i] = getterMappings[i].toOpenValue(got);
                 } catch (Exception e) {
                     throw openDataException("Error calling getter for " +
@@ -1011,7 +1015,7 @@
                                        MXBeanMapping[] converters)
                 throws InvalidObjectException {
             try {
-                return fromMethod.invoke(null, cd);
+                return MethodUtil.invoke(fromMethod, null, new Object[] {cd});
             } catch (Exception e) {
                 final String msg = "Failed to invoke from(CompositeData)";
                 throw invalidObjectException(msg, e);
@@ -1107,13 +1111,15 @@
                 throws InvalidObjectException {
             Object o;
             try {
-                o = getTargetClass().newInstance();
+                final Class<?> targetClass = getTargetClass();
+                ReflectUtil.checkPackageAccess(targetClass);
+                o = targetClass.newInstance();
                 for (int i = 0; i < itemNames.length; i++) {
                     if (cd.containsKey(itemNames[i])) {
                         Object openItem = cd.get(itemNames[i]);
                         Object javaItem =
                             converters[i].fromOpenValue(openItem);
-                        setters[i].invoke(o, javaItem);
+                        MethodUtil.invoke(setters[i], o, new Object[] {javaItem});
                     }
                 }
             } catch (Exception e) {
@@ -1363,6 +1369,7 @@
             }
 
             try {
+                ReflectUtil.checkPackageAccess(max.constructor.getDeclaringClass());
                 return max.constructor.newInstance(params);
             } catch (Exception e) {
                 final String msg =
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java	Wed Jul 05 19:00:49 2017 +0200
@@ -228,6 +228,11 @@
         MXBeanIntrospector.getInstance().getAnalyzer(interfaceClass);
     }
 
+    public static void testComplianceMBeanInterface(Class<?> interfaceClass)
+            throws NotCompliantMBeanException{
+        StandardMBeanIntrospector.getInstance().getAnalyzer(interfaceClass);
+    }
+
     /**
      * Basic method for testing if a given class is a JMX compliant
      * Standard MBean.  This method is only called by the legacy code
@@ -248,6 +253,7 @@
             throws NotCompliantMBeanException {
         if (mbeanInterface == null)
             mbeanInterface = getStandardMBeanInterface(baseClass);
+        ReflectUtil.checkPackageAccess(mbeanInterface);
         MBeanIntrospector<?> introspector = StandardMBeanIntrospector.getInstance();
         return getClassMBeanInfo(introspector, baseClass, mbeanInterface);
     }
@@ -372,13 +378,19 @@
         for (Annotation a : annots) {
             Class<? extends Annotation> c = a.annotationType();
             Method[] elements = c.getMethods();
+            boolean packageAccess = false;
             for (Method element : elements) {
                 DescriptorKey key = element.getAnnotation(DescriptorKey.class);
                 if (key != null) {
                     String name = key.value();
                     Object value;
                     try {
-                        value = element.invoke(a);
+                        // Avoid checking access more than once per annotation
+                        if (!packageAccess) {
+                            ReflectUtil.checkPackageAccess(c);
+                            packageAccess = true;
+                        }
+                        value = MethodUtil.invoke(element, a, null);
                     } catch (RuntimeException e) {
                         // we don't expect this - except for possibly
                         // security exceptions?
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/JmxMBeanServer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/JmxMBeanServer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -32,6 +32,7 @@
 import java.io.ObjectInputStream;
 import java.security.AccessController;
 import java.security.Permission;
+import java.security.PrivilegedAction;
 import java.security.PrivilegedExceptionAction;
 import java.util.List;
 import java.util.Set;
@@ -227,8 +228,16 @@
                 clr = new ClassLoaderRepositorySupport();
             instantiator = new MBeanInstantiator(clr);
         }
+
+        final MBeanInstantiator fInstantiator = instantiator;
         this.secureClr = new
-          SecureClassLoaderRepository(instantiator.getClassLoaderRepository());
+            SecureClassLoaderRepository(AccessController.doPrivileged(new PrivilegedAction<ClassLoaderRepository>() {
+                @Override
+                public ClassLoaderRepository run() {
+                    return fInstantiator.getClassLoaderRepository();
+                }
+            })
+        );
         if (delegate == null)
             delegate = new MBeanServerDelegateImpl();
         if (outer == null)
@@ -1242,8 +1251,14 @@
            class loader.  The ClassLoaderRepository knows how
            to handle that case.  */
         ClassLoader myLoader = outerShell.getClass().getClassLoader();
-        final ModifiableClassLoaderRepository loaders =
-            instantiator.getClassLoaderRepository();
+        final ModifiableClassLoaderRepository loaders = AccessController.doPrivileged(new PrivilegedAction<ModifiableClassLoaderRepository>() {
+
+            @Override
+            public ModifiableClassLoaderRepository run() {
+                return instantiator.getClassLoaderRepository();
+            }
+        });
+
         if (loaders != null) {
             loaders.addClassLoader(myLoader);
 
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanInstantiator.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanInstantiator.java	Wed Jul 05 19:00:49 2017 +0200
@@ -33,7 +33,12 @@
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Modifier;
+import java.security.AccessControlContext;
+import java.security.AccessController;
 import java.security.Permission;
+import java.security.Permissions;
+import java.security.PrivilegedAction;
+import java.security.ProtectionDomain;
 import java.util.Map;
 import java.util.logging.Level;
 
@@ -127,9 +132,8 @@
 
         // Retrieve the class loader from the repository
         ClassLoader loader = null;
-        synchronized(this) {
-            if (clr!=null)
-                loader = clr.getClassLoader(aLoader);
+        synchronized (this) {
+            loader = getClassLoader(aLoader);
         }
         if (loader == null) {
             throw new InstanceNotFoundException("The loader named " +
@@ -429,8 +433,7 @@
             try {
                 ClassLoader instance = null;
 
-                if (clr!=null)
-                    instance = clr.getClassLoader(loaderName);
+                instance = getClassLoader(loaderName);
                 if (instance == null)
                     throw new ClassNotFoundException(className);
                 theClass = Class.forName(className, false, instance);
@@ -622,6 +625,7 @@
      * Return the Default Loader Repository used by this instantiator object.
      **/
     public ModifiableClassLoaderRepository getClassLoaderRepository() {
+        checkMBeanPermission((String)null, null, null, "getClassLoaderRepository");
         return clr;
     }
 
@@ -733,9 +737,19 @@
                                              String member,
                                              ObjectName objectName,
                                              String actions) {
+        if (clazz != null) {
+            checkMBeanPermission(clazz.getName(), member, objectName, actions);
+        }
+    }
+
+    private static void checkMBeanPermission(String classname,
+                                             String member,
+                                             ObjectName objectName,
+                                             String actions)
+        throws SecurityException {
         SecurityManager sm = System.getSecurityManager();
-        if (clazz != null && sm != null) {
-            Permission perm = new MBeanPermission(clazz.getName(),
+        if (sm != null) {
+            Permission perm = new MBeanPermission(classname,
                                                   member,
                                                   objectName,
                                                   actions);
@@ -751,4 +765,22 @@
             throw new IllegalAccessException("Class is not public and can't be instantiated");
         }
     }
+
+    private ClassLoader getClassLoader(final ObjectName name) {
+        if(clr == null){
+            return null;
+        }
+        // Restrict to getClassLoader permission only
+        Permissions permissions = new Permissions();
+        permissions.add(new MBeanPermission("*", null, name, "getClassLoader"));
+        ProtectionDomain protectionDomain = new ProtectionDomain(null, permissions);
+        ProtectionDomain[] domains = {protectionDomain};
+        AccessControlContext ctx = new AccessControlContext(domains);
+        ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
+            public ClassLoader run() {
+                return clr.getClassLoader(name);
+            }
+        }, ctx);
+        return loader;
+    }
 }
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java	Wed Jul 05 19:00:49 2017 +0200
@@ -51,6 +51,7 @@
 import javax.management.NotCompliantMBeanException;
 import javax.management.NotificationBroadcaster;
 import javax.management.ReflectionException;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * An introspector for MBeans of a certain type.  There is one instance
@@ -175,7 +176,8 @@
     /**
      * Get the methods to be analyzed to build the MBean interface.
      */
-    List<Method> getMethods(final Class<?> mbeanType) {
+    final List<Method> getMethods(final Class<?> mbeanType) {
+        ReflectUtil.checkPackageAccess(mbeanType);
         return Arrays.asList(mbeanType.getMethods());
     }
 
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/ObjectInputStreamWithLoader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/ObjectInputStreamWithLoader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -30,7 +30,7 @@
 import java.io.InputStream;
 import java.io.ObjectInputStream;
 import java.io.ObjectStreamClass;
-import java.io.StreamCorruptedException;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * This class deserializes an object in the context of a specific class loader.
@@ -61,6 +61,7 @@
             return super.resolveClass(aClass);
         } else {
             String name = aClass.getName();
+            ReflectUtil.checkPackageAccess(name);
             // Query the class loader ...
             return Class.forName(name, false, loader);
         }
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/StandardMBeanIntrospector.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/StandardMBeanIntrospector.java	Wed Jul 05 19:00:49 2017 +0200
@@ -38,6 +38,7 @@
 import javax.management.NotCompliantMBeanException;
 import javax.management.NotificationBroadcaster;
 import javax.management.NotificationBroadcasterSupport;
+import sun.reflect.misc.MethodUtil;
 
 /**
  * @since 1.6
@@ -108,7 +109,7 @@
     Object invokeM2(Method m, Object target, Object[] args, Object cookie)
             throws InvocationTargetException, IllegalAccessException,
                    MBeanException {
-        return m.invoke(target, args);
+        return MethodUtil.invoke(m, target, args);
     }
 
     @Override
--- a/jdk/src/share/classes/com/sun/jmx/remote/internal/ArrayNotificationBuffer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/remote/internal/ArrayNotificationBuffer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -397,6 +397,20 @@
 
                 if (nextSeq < nextSequenceNumber()) {
                     candidate = notificationAt(nextSeq);
+                    // Skip security check if NotificationBufferFilter is not overloaded
+                    if (!(filter instanceof ServerNotifForwarder.NotifForwarderBufferFilter)) {
+                        try {
+                            ServerNotifForwarder.checkMBeanPermission(this.mBeanServer,
+                                                      candidate.getObjectName(),"addNotificationListener");
+                        } catch (InstanceNotFoundException | SecurityException e) {
+                            if (logger.debugOn()) {
+                                logger.debug("fetchNotifications", "candidate: " + candidate + " skipped. exception " + e);
+                            }
+                            ++nextSeq;
+                            continue;
+                        }
+                    }
+
                     if (logger.debugOn()) {
                         logger.debug("fetchNotifications", "candidate: " +
                                      candidate);
--- a/jdk/src/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -226,8 +226,9 @@
      * why we add the found notifications to a supplied List rather than
      * just returning a boolean.
      */
-    private final NotificationBufferFilter bufferFilter =
-            new NotificationBufferFilter() {
+    private final NotifForwarderBufferFilter bufferFilter = new NotifForwarderBufferFilter();
+
+    final class NotifForwarderBufferFilter implements NotificationBufferFilter {
         public void apply(List<TargetedNotification> targetedNotifs,
                           ObjectName source, Notification notif) {
             // We proceed in two stages here, to avoid holding the listenerMap
@@ -366,9 +367,16 @@
      * Explicitly check the MBeanPermission for
      * the current access control context.
      */
-    public void checkMBeanPermission(
+    public final void checkMBeanPermission(
             final ObjectName name, final String actions)
             throws InstanceNotFoundException, SecurityException {
+        checkMBeanPermission(mbeanServer,name,actions);
+    }
+
+    static void checkMBeanPermission(
+            final MBeanServer mbs, final ObjectName name, final String actions)
+            throws InstanceNotFoundException, SecurityException {
+
         SecurityManager sm = System.getSecurityManager();
         if (sm != null) {
             AccessControlContext acc = AccessController.getContext();
@@ -378,7 +386,7 @@
                     new PrivilegedExceptionAction<ObjectInstance>() {
                         public ObjectInstance run()
                         throws InstanceNotFoundException {
-                            return mbeanServer.getObjectInstance(name);
+                            return mbs.getObjectInstance(name);
                         }
                 });
             } catch (PrivilegedActionException e) {
--- a/jdk/src/share/classes/com/sun/jmx/remote/util/OrderClassLoaders.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jmx/remote/util/OrderClassLoaders.java	Wed Jul 05 19:00:49 2017 +0200
@@ -25,6 +25,8 @@
 
 package com.sun.jmx.remote.util;
 
+import sun.reflect.misc.ReflectUtil;
+
 public class OrderClassLoaders extends ClassLoader {
     public OrderClassLoaders(ClassLoader cl1, ClassLoader cl2) {
         super(cl1);
@@ -32,9 +34,10 @@
         this.cl2 = cl2;
     }
 
-    protected Class<?> findClass(String name) throws ClassNotFoundException {
+    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
+        ReflectUtil.checkPackageAccess(name);
         try {
-            return super.findClass(name);
+            return super.loadClass(name, resolve);
         } catch (ClassNotFoundException cne) {
             if (cl2 != null) {
                 return cl2.loadClass(name);
--- a/jdk/src/share/classes/com/sun/jndi/toolkit/dir/SearchFilter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/jndi/toolkit/dir/SearchFilter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -396,7 +396,7 @@
 
             // do we need to begin with the first token?
             if(proto.charAt(0) != WILDCARD_TOKEN &&
-                    !value.toString().toLowerCase(Locale.ENGLISH).startsWith(
+                    !value.toLowerCase(Locale.ENGLISH).startsWith(
                         subStrs.nextToken().toLowerCase(Locale.ENGLISH))) {
                 if(debug) {
                     System.out.println("faild initial test");
--- a/jdk/src/share/classes/com/sun/media/sound/AbstractDataLine.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AbstractDataLine.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,15 +25,12 @@
 
 package com.sun.media.sound;
 
-import java.util.Vector;
-
 import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.Control;
 import javax.sound.sampled.DataLine;
 import javax.sound.sampled.LineEvent;
 import javax.sound.sampled.LineUnavailableException;
-import javax.sound.sampled.Mixer;
 
 
 /**
@@ -46,13 +43,13 @@
     // DEFAULTS
 
     // default format
-    protected /*final*/ AudioFormat defaultFormat;
+    private final AudioFormat defaultFormat;
 
     // default buffer size in bytes
-    protected /*final*/ int defaultBufferSize;
+    private final int defaultBufferSize;
 
     // the lock for synchronization
-    protected Object lock = new Object();
+    protected final Object lock = new Object();
 
     // STATE
 
@@ -103,7 +100,7 @@
 
     // DATA LINE METHODS
 
-    public void open(AudioFormat format, int bufferSize) throws LineUnavailableException {
+    public final void open(AudioFormat format, int bufferSize) throws LineUnavailableException {
         //$$fb 2001-10-09: Bug #4517739: avoiding deadlock by synchronizing to mixer !
         synchronized (mixer) {
             if (Printer.trace) Printer.trace("> AbstractDataLine.open(format, bufferSize) (class: "+getClass().getName());
@@ -152,7 +149,7 @@
     }
 
 
-    public void open(AudioFormat format) throws LineUnavailableException {
+    public final void open(AudioFormat format) throws LineUnavailableException {
         open(format, AudioSystem.NOT_SPECIFIED);
     }
 
@@ -181,7 +178,7 @@
     }
 
 
-    public void start() {
+    public final void start() {
         //$$fb 2001-10-09: Bug #4517739: avoiding deadlock by synchronizing to mixer !
         synchronized(mixer) {
             if (Printer.trace) Printer.trace("> "+getClass().getName()+".start() - AbstractDataLine");
@@ -205,7 +202,7 @@
     }
 
 
-    public void stop() {
+    public final void stop() {
 
         //$$fb 2001-10-09: Bug #4517739: avoiding deadlock by synchronizing to mixer !
         synchronized(mixer) {
@@ -249,16 +246,16 @@
     // in MixerSourceLine and MixerClip, and I want to touch as little
     // code as possible to change isStarted() back to isRunning().
 
-    public boolean isRunning() {
+    public final boolean isRunning() {
         return started;
     }
 
-    public boolean isActive() {
+    public final boolean isActive() {
         return active;
     }
 
 
-    public long getMicrosecondPosition() {
+    public final long getMicrosecondPosition() {
 
         long microseconds = getLongFramePosition();
         if (microseconds != AudioSystem.NOT_SPECIFIED) {
@@ -268,26 +265,26 @@
     }
 
 
-    public AudioFormat getFormat() {
+    public final AudioFormat getFormat() {
         return format;
     }
 
 
-    public int getBufferSize() {
+    public final int getBufferSize() {
         return bufferSize;
     }
 
     /**
      * This implementation does NOT change the buffer size
      */
-    public int setBufferSize(int newSize) {
+    public final int setBufferSize(int newSize) {
         return getBufferSize();
     }
 
     /**
      * This implementation returns AudioSystem.NOT_SPECIFIED.
      */
-    public float getLevel() {
+    public final float getLevel() {
         return (float)AudioSystem.NOT_SPECIFIED;
     }
 
@@ -304,7 +301,7 @@
     // it to isStartedRunning().  This is part of backing out the
     // change denied in RFE 4297981.
 
-    protected boolean isStartedRunning() {
+    final boolean isStartedRunning() {
         return running;
     }
 
@@ -312,7 +309,7 @@
      * This method sets the active state and generates
      * events if it changes.
      */
-    protected void setActive(boolean active) {
+    final void setActive(boolean active) {
 
         if (Printer.trace) Printer.trace("> AbstractDataLine: setActive(" + active + ")");
 
@@ -351,7 +348,7 @@
      * This method sets the started state and generates
      * events if it changes.
      */
-    protected void setStarted(boolean started) {
+    final void setStarted(boolean started) {
 
         if (Printer.trace) Printer.trace("> AbstractDataLine: setStarted(" + started + ")");
 
@@ -388,7 +385,7 @@
      * This method generates a STOP event and sets the started state to false.
      * It is here for historic reasons when an EOM event existed.
      */
-    protected void setEOM() {
+    final void setEOM() {
 
         if (Printer.trace) Printer.trace("> AbstractDataLine: setEOM()");
         //$$fb 2002-04-21: sometimes, 2 STOP events are generated.
@@ -408,7 +405,7 @@
      * line is open, this should return quietly because the values
      * requested will match the current ones.
      */
-    public void open() throws LineUnavailableException {
+    public final void open() throws LineUnavailableException {
 
         if (Printer.trace) Printer.trace("> "+getClass().getName()+".open() - AbstractDataLine");
 
@@ -422,7 +419,7 @@
      * This should also stop the line.  The closed line should not be running or active.
      * After we close the line, we reset the format and buffer size to the defaults.
      */
-    public void close() {
+    public final void close() {
         //$$fb 2001-10-09: Bug #4517739: avoiding deadlock by synchronizing to mixer !
         synchronized (mixer) {
             if (Printer.trace) Printer.trace("> "+getClass().getName()+".close() - in AbstractDataLine.");
--- a/jdk/src/share/classes/com/sun/media/sound/AbstractLine.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AbstractLine.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,11 +25,12 @@
 
 package com.sun.media.sound;
 
+import java.util.Map;
 import java.util.Vector;
+import java.util.WeakHashMap;
 
 import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.Control;
-import javax.sound.sampled.Mixer;
 import javax.sound.sampled.Line;
 import javax.sound.sampled.LineEvent;
 import javax.sound.sampled.LineListener;
@@ -43,28 +44,17 @@
  */
 abstract class AbstractLine implements Line {
 
-    protected Line.Info info;
+    protected final Line.Info info;
     protected Control[] controls;
-    protected AbstractMixer mixer;
+    AbstractMixer mixer;
     private boolean open     = false;
-    private Vector listeners = new Vector();
+    private final Vector listeners = new Vector();
 
     /**
-     * Global event thread
+     * Contains event dispatcher per thread group.
      */
-    private static final EventDispatcher eventDispatcher;
-
-    static {
-        // create and start the global event thread
-
-        // $$kk: 12.21.98:
-        // 1) probably don't want a single global event queue
-        // 2) need a way to stop this thread when the engine is done
-
-        eventDispatcher = new EventDispatcher();
-        eventDispatcher.start();
-    }
-
+    private static final Map<ThreadGroup, EventDispatcher> dispatchers =
+            new WeakHashMap<>();
 
     /**
      * Constructs a new AbstractLine.
@@ -85,18 +75,17 @@
 
     // LINE METHODS
 
-    public Line.Info getLineInfo() {
+    public final Line.Info getLineInfo() {
         return info;
     }
 
 
-    public boolean isOpen() {
+    public final boolean isOpen() {
         return open;
     }
 
 
-    public void addLineListener(LineListener listener) {
-
+    public final void addLineListener(LineListener listener) {
         synchronized(listeners) {
             if ( ! (listeners.contains(listener)) ) {
                 listeners.addElement(listener);
@@ -109,7 +98,7 @@
      * Removes an audio listener.
      * @param listener listener to remove
      */
-    public void removeLineListener(LineListener listener) {
+    public final void removeLineListener(LineListener listener) {
         listeners.removeElement(listener);
     }
 
@@ -120,8 +109,7 @@
      * array of length 0.
      * @return control set
      */
-    public Control[] getControls() {
-
+    public final Control[] getControls() {
         Control[] returnedArray = new Control[controls.length];
 
         for (int i = 0; i < controls.length; i++) {
@@ -132,8 +120,7 @@
     }
 
 
-    public boolean isControlSupported(Control.Type controlType) {
-
+    public final boolean isControlSupported(Control.Type controlType) {
         // protect against a NullPointerException
         if (controlType == null) {
             return false;
@@ -149,8 +136,7 @@
     }
 
 
-    public Control getControl(Control.Type controlType) {
-
+    public final Control getControl(Control.Type controlType) {
         // protect against a NullPointerException
         if (controlType != null) {
 
@@ -172,7 +158,7 @@
      * This method sets the open state and generates
      * events if it changes.
      */
-    protected void setOpen(boolean open) {
+    final void setOpen(boolean open) {
 
         if (Printer.trace) Printer.trace("> "+getClass().getName()+" (AbstractLine): setOpen(" + open + ")  this.open: " + this.open);
 
@@ -200,8 +186,8 @@
     /**
      * Send line events.
      */
-    protected void sendEvents(LineEvent event) {
-        eventDispatcher.sendAudioEvents(event, listeners);
+    final void sendEvents(LineEvent event) {
+        getEventDispatcher().sendAudioEvents(event, listeners);
     }
 
 
@@ -227,12 +213,23 @@
     // $$kk: 06.03.99: returns the mixer used in construction.
     // this is a hold-over from when there was a public method like
     // this on line and should be fixed!!
-    protected AbstractMixer getMixer() {
+    final AbstractMixer getMixer() {
         return mixer;
     }
 
-    protected EventDispatcher getEventDispatcher() {
-        return eventDispatcher;
+    final EventDispatcher getEventDispatcher() {
+        // create and start the global event thread
+        //TODO  need a way to stop this thread when the engine is done
+        final ThreadGroup tg = Thread.currentThread().getThreadGroup();
+        synchronized (dispatchers) {
+            EventDispatcher eventDispatcher = dispatchers.get(tg);
+            if (eventDispatcher == null) {
+                eventDispatcher = new EventDispatcher();
+                dispatchers.put(tg, eventDispatcher);
+                eventDispatcher.start();
+            }
+            return eventDispatcher;
+        }
     }
 
     // ABSTRACT METHODS
--- a/jdk/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AbstractMidiDevice.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -60,12 +60,12 @@
 
     // DEVICE ATTRIBUTES
 
-    private MidiDevice.Info info;
+    private final MidiDevice.Info info;
 
 
     // DEVICE STATE
 
-    protected /*private*/ boolean open          = false;
+    private boolean open          = false;
     private int openRefCount;
 
     /** List of Receivers and Transmitters that opened the device implicitely.
@@ -102,7 +102,7 @@
 
     // MIDI DEVICE METHODS
 
-    public MidiDevice.Info getDeviceInfo() {
+    public final MidiDevice.Info getDeviceInfo() {
         return info;
     }
 
@@ -111,7 +111,7 @@
      * opened the the device implicitly from closing it. The only way to close the device after
      * this call is a call to close().
      */
-    public void open() throws MidiUnavailableException {
+    public final void open() throws MidiUnavailableException {
         if (Printer.trace) Printer.trace("> AbstractMidiDevice: open()");
         synchronized(this) {
             openRefCount = -1;
@@ -159,7 +159,7 @@
     }
 
 
-    public void close() {
+    public final void close() {
         if (Printer.trace) Printer.trace("> AbstractMidiDevice: close()");
         synchronized (this) {
             doClose();
@@ -181,7 +181,7 @@
      * @param object The object that might have been opening the device implicitely (for now,
      * this may be a Transmitter or receiver).
      */
-    public void closeInternal(Object object) {
+    public final void closeInternal(Object object) {
         if (Printer.trace) Printer.trace("> AbstractMidiDevice: closeInternal()");
         synchronized(this) {
             if (getOpenKeepingObjects().remove(object)) {
@@ -197,7 +197,7 @@
     }
 
 
-    public void doClose() {
+    public final void doClose() {
         if (Printer.trace) Printer.trace("> AbstractMidiDevice: doClose()");
         synchronized(this) {
             if (isOpen()) {
@@ -209,7 +209,7 @@
     }
 
 
-    public boolean isOpen() {
+    public final boolean isOpen() {
         return open;
     }
 
@@ -329,7 +329,7 @@
 
     // HELPER METHODS
 
-    long getId() {
+    final long getId() {
         return id;
     }
 
@@ -339,7 +339,8 @@
     /** Retrieve a Receiver and open the device implicitly.
         This method is called by MidiSystem.getReceiver().
      */
-    public Receiver getReceiverReferenceCounting() throws MidiUnavailableException {
+    public final Receiver getReceiverReferenceCounting()
+            throws MidiUnavailableException {
         /* Keep this order of commands! If getReceiver() throws an exception,
            openInternal() should not be called!
         */
@@ -355,7 +356,8 @@
     /** Retrieve a Transmitter and open the device implicitly.
         This method is called by MidiSystem.getTransmitter().
      */
-    public Transmitter getTransmitterReferenceCounting() throws MidiUnavailableException {
+    public final Transmitter getTransmitterReferenceCounting()
+            throws MidiUnavailableException {
         /* Keep this order of commands! If getTransmitter() throws an exception,
            openInternal() should not be called!
         */
@@ -422,7 +424,7 @@
 
     /** Return the internal list of Transmitters, possibly creating it first.
      */
-    protected TransmitterList getTransmitterList() {
+    final TransmitterList getTransmitterList() {
         synchronized (traRecLock) {
             if (transmitterList == null) {
                 transmitterList = new TransmitterList();
@@ -462,7 +464,7 @@
     /**
      * close this device if discarded by the garbage collector
      */
-    protected void finalize() {
+    protected final void finalize() {
         close();
     }
 
@@ -534,7 +536,7 @@
      * Also, it has some optimizations regarding sending to the Receivers,
      * for known Receivers, and managing itself in the TransmitterList.
      */
-    protected class BasicTransmitter implements MidiDeviceTransmitter {
+    class BasicTransmitter implements MidiDeviceTransmitter {
 
         private Receiver receiver = null;
         TransmitterList tlist = null;
@@ -546,7 +548,7 @@
             this.tlist = tlist;
         }
 
-        public void setReceiver(Receiver receiver) {
+        public final void setReceiver(Receiver receiver) {
             if (tlist != null && this.receiver != receiver) {
                 if (Printer.debug) Printer.debug("Transmitter "+toString()+": set receiver "+receiver);
                 tlist.receiverChanged(this, this.receiver, receiver);
@@ -554,7 +556,7 @@
             }
         }
 
-        public Receiver getReceiver() {
+        public final Receiver getReceiver() {
             return receiver;
         }
 
@@ -564,7 +566,7 @@
          * Therefore, subclasses that override this method must call
          * 'super.close()'.
          */
-        public void close() {
+        public final void close() {
             AbstractMidiDevice.this.closeInternal(this);
             if (tlist != null) {
                 tlist.receiverChanged(this, this.receiver, null);
@@ -573,7 +575,7 @@
             }
         }
 
-        public MidiDevice getMidiDevice() {
+        public final MidiDevice getMidiDevice() {
             return AbstractMidiDevice.this;
         }
 
@@ -583,9 +585,9 @@
     /**
      * a class to manage a list of transmitters
      */
-    class TransmitterList {
+    final class TransmitterList {
 
-        private ArrayList<Transmitter> transmitters = new ArrayList<Transmitter>();
+        private final ArrayList<Transmitter> transmitters = new ArrayList<Transmitter>();
         private MidiOutDevice.MidiOutReceiver midiOutReceiver;
 
         // how many transmitters must be present for optimized
--- a/jdk/src/share/classes/com/sun/media/sound/AbstractMidiDeviceProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AbstractMidiDeviceProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,7 +36,7 @@
  */
 public abstract class AbstractMidiDeviceProvider extends MidiDeviceProvider {
 
-    private static boolean enabled;
+    private static final boolean enabled;
 
     /**
      * Create objects representing all MIDI output devices on the system.
@@ -52,7 +52,7 @@
     }
 
 
-    synchronized void readDeviceInfos() {
+    final synchronized void readDeviceInfos() {
         Info[] infos = getInfoCache();
         MidiDevice[] devices = getDeviceCache();
         if (!enabled) {
@@ -118,7 +118,7 @@
     }
 
 
-    public MidiDevice.Info[] getDeviceInfo() {
+    public final MidiDevice.Info[] getDeviceInfo() {
         readDeviceInfos();
         Info[] infos = getInfoCache();
         MidiDevice.Info[] localArray = new MidiDevice.Info[infos.length];
@@ -127,7 +127,7 @@
     }
 
 
-    public MidiDevice getDevice(MidiDevice.Info info) {
+    public final MidiDevice getDevice(MidiDevice.Info info) {
         if (info instanceof Info) {
             readDeviceInfos();
             MidiDevice[] devices = getDeviceCache();
@@ -164,7 +164,7 @@
             this.index = index;
         }
 
-        boolean equalStrings(Info info) {
+        final boolean equalStrings(Info info) {
             return      (info != null
                          && getName().equals(info.getName())
                          && getVendor().equals(info.getVendor())
@@ -172,11 +172,11 @@
                          && getVersion().equals(info.getVersion()));
         }
 
-        int getIndex() {
+        final int getIndex() {
             return index;
         }
 
-        void setIndex(int index) {
+        final void setIndex(int index) {
             this.index = index;
         }
 
--- a/jdk/src/share/classes/com/sun/media/sound/AbstractMixer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AbstractMixer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,14 +27,9 @@
 
 import java.util.Vector;
 
-import javax.sound.sampled.AudioFormat;
-import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.Control;
-import javax.sound.sampled.DataLine;
 import javax.sound.sampled.Mixer;
 import javax.sound.sampled.Line;
-import javax.sound.sampled.LineEvent;
-import javax.sound.sampled.LineListener;
 import javax.sound.sampled.LineUnavailableException;
 
 /**
@@ -95,13 +90,13 @@
     /**
      * Source lines (ports) currently open
      */
-    protected Vector sourceLines = new Vector();
+    private final Vector sourceLines = new Vector();
 
 
     /**
      * Target lines currently open.
      */
-    protected Vector targetLines = new Vector();
+    private final Vector targetLines = new Vector();
 
 
     /**
@@ -133,19 +128,19 @@
     // MIXER METHODS
 
 
-    public Mixer.Info getMixerInfo() {
+    public final Mixer.Info getMixerInfo() {
         return mixerInfo;
     }
 
 
-    public Line.Info[] getSourceLineInfo() {
+    public final Line.Info[] getSourceLineInfo() {
         Line.Info[] localArray = new Line.Info[sourceLineInfo.length];
         System.arraycopy(sourceLineInfo, 0, localArray, 0, sourceLineInfo.length);
         return localArray;
     }
 
 
-    public Line.Info[] getTargetLineInfo() {
+    public final Line.Info[] getTargetLineInfo() {
 
         Line.Info[] localArray = new Line.Info[targetLineInfo.length];
         System.arraycopy(targetLineInfo, 0, localArray, 0, targetLineInfo.length);
@@ -153,7 +148,7 @@
     }
 
 
-    public Line.Info[] getSourceLineInfo(Line.Info info) {
+    public final Line.Info[] getSourceLineInfo(Line.Info info) {
 
         int i;
         Vector vec = new Vector();
@@ -174,7 +169,7 @@
     }
 
 
-    public Line.Info[] getTargetLineInfo(Line.Info info) {
+    public final Line.Info[] getTargetLineInfo(Line.Info info) {
 
         int i;
         Vector vec = new Vector();
@@ -195,7 +190,7 @@
     }
 
 
-    public boolean isLineSupported(Line.Info info) {
+    public final boolean isLineSupported(Line.Info info) {
 
         int i;
 
@@ -227,7 +222,7 @@
     protected abstract void implClose();
 
 
-    public Line[] getSourceLines() {
+    public final Line[] getSourceLines() {
 
         Line[] localLines;
 
@@ -244,7 +239,7 @@
     }
 
 
-    public Line[] getTargetLines() {
+    public final Line[] getTargetLines() {
 
         Line[] localLines;
 
@@ -264,7 +259,7 @@
     /**
      * Default implementation always throws an exception.
      */
-    public void synchronize(Line[] lines, boolean maintainSync) {
+    public final void synchronize(Line[] lines, boolean maintainSync) {
         throw new IllegalArgumentException("Synchronization not supported by this mixer.");
     }
 
@@ -272,7 +267,7 @@
     /**
      * Default implementation always throws an exception.
      */
-    public void unsynchronize(Line[] lines) {
+    public final void unsynchronize(Line[] lines) {
         throw new IllegalArgumentException("Synchronization not supported by this mixer.");
     }
 
@@ -280,7 +275,8 @@
     /**
      * Default implementation always returns false.
      */
-    public boolean isSynchronizationSupported(Line[] lines, boolean maintainSync) {
+    public final boolean isSynchronizationSupported(Line[] lines,
+                                                    boolean maintainSync) {
         return false;
     }
 
@@ -290,14 +286,14 @@
     /**
      * This implementation tries to open the mixer with its current format and buffer size settings.
      */
-    public synchronized void open() throws LineUnavailableException {
+    public final synchronized void open() throws LineUnavailableException {
         open(true);
     }
 
     /**
      * This implementation tries to open the mixer with its current format and buffer size settings.
      */
-    protected synchronized void open(boolean manual) throws LineUnavailableException {
+    final synchronized void open(boolean manual) throws LineUnavailableException {
         if (Printer.trace) Printer.trace(">> AbstractMixer: open()");
         if (!isOpen()) {
             implOpen();
@@ -322,7 +318,7 @@
      * The mixer may be opened at a format different than the line's
      * format if it is a DataLine.
      */
-    protected synchronized void open(Line line) throws LineUnavailableException {
+    final synchronized void open(Line line) throws LineUnavailableException {
 
         if (Printer.trace) Printer.trace(">> AbstractMixer: open(line = " + line + ")");
 
@@ -367,7 +363,7 @@
      * open target lines, if it exists in either.
      * If the list is now empty, closes the mixer.
      */
-    protected synchronized void close(Line line) {
+    final synchronized void close(Line line) {
 
         if (Printer.trace) Printer.trace(">> AbstractMixer: close(" + line + ")");
 
@@ -396,7 +392,7 @@
     /**
      * Close all lines and then close this mixer.
      */
-    public synchronized void close() {
+    public final synchronized void close() {
         if (Printer.trace) Printer.trace(">> AbstractMixer: close()");
         if (isOpen()) {
             // close all source lines
@@ -423,7 +419,7 @@
     /**
      * Starts the mixer.
      */
-    protected synchronized void start(Line line) {
+    final synchronized void start(Line line) {
 
         if (Printer.trace) Printer.trace(">> AbstractMixer: start(" + line + ")");
 
@@ -447,7 +443,7 @@
     /**
      * Stops the mixer if this was the last running line.
      */
-    protected synchronized void stop(Line line) {
+    final synchronized void stop(Line line) {
 
         if (Printer.trace) Printer.trace(">> AbstractMixer: stop(" + line + ")");
 
@@ -501,7 +497,7 @@
      * Right now this just checks whether it's supported, but should
      * check whether it actually belongs to this mixer....
      */
-    boolean isSourceLine(Line.Info info) {
+    final boolean isSourceLine(Line.Info info) {
 
         for (int i = 0; i < sourceLineInfo.length; i++) {
             if (info.matches(sourceLineInfo[i])) {
@@ -518,7 +514,7 @@
      * Right now this just checks whether it's supported, but should
      * check whether it actually belongs to this mixer....
      */
-    boolean isTargetLine(Line.Info info) {
+    final boolean isTargetLine(Line.Info info) {
 
         for (int i = 0; i < targetLineInfo.length; i++) {
             if (info.matches(targetLineInfo[i])) {
@@ -535,7 +531,7 @@
      * matches the one specified, or null if no matching Line.Info
      * object is found.
      */
-    Line.Info getLineInfo(Line.Info info) {
+    final Line.Info getLineInfo(Line.Info info) {
         if (info == null) {
             return null;
         }
--- a/jdk/src/share/classes/com/sun/media/sound/AiffFileFormat.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AiffFileFormat.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,7 +35,7 @@
  * @author Jan Borgersen
  */
 
-class AiffFileFormat extends AudioFileFormat {
+final class AiffFileFormat extends AudioFileFormat {
 
     static final int AIFF_MAGIC         = 1179603533;
 
@@ -62,13 +62,13 @@
     //$$fb 2001-07-13: added management of header size in this class
 
     /** header size in bytes */
-    private int headerSize=AIFF_HEADERSIZE;
+    private final int headerSize=AIFF_HEADERSIZE;
 
     /** comm chunk size in bytes, inclusive magic and length field */
-    private int commChunkSize=26;
+    private final int commChunkSize=26;
 
     /** FVER chunk size in bytes, inclusive magic and length field */
-    private int fverChunkSize=0;
+    private final int fverChunkSize=0;
 
     AiffFileFormat( AudioFileFormat aff ) {
         this( aff.getType(), aff.getByteLength(), aff.getFormat(), aff.getFrameLength() );
--- a/jdk/src/share/classes/com/sun/media/sound/AiffFileReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AiffFileReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,28 +25,17 @@
 
 package com.sun.media.sound;
 
-import java.util.Vector;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
 import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.IOException;
-import java.io.EOFException;
 import java.net.URL;
-import java.net.MalformedURLException;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.DataInputStream;
-import java.io.FileInputStream;
-import java.io.DataOutputStream;
-import java.io.FileOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.SequenceInputStream;
 
 import javax.sound.sampled.AudioFileFormat;
+import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.AudioInputStream;
-import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.UnsupportedAudioFileException;
 
@@ -58,19 +47,10 @@
  * @author Jan Borgersen
  * @author Florian Bomers
  */
-public class AiffFileReader extends SunFileReader  {
+public final class AiffFileReader extends SunFileReader {
 
     private static final int MAX_READ_LENGTH = 8;
 
-
-    /**
-     * AIFF parser type
-     */
-    public static final AudioFileFormat.Type types[] = {
-        AudioFileFormat.Type.AIFF
-    };
-
-
     /**
      * Constructs a new AiffParser object.
      */
--- a/jdk/src/share/classes/com/sun/media/sound/AiffFileWriter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AiffFileWriter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -50,21 +50,13 @@
  *
  * @author Jan Borgersen
  */
-public class AiffFileWriter extends SunFileWriter {
-
-    /**
-     * AIFF type
-     */
-    private static final AudioFileFormat.Type aiffTypes[] = {
-        AudioFileFormat.Type.AIFF
-    };
-
+public final class AiffFileWriter extends SunFileWriter {
 
     /**
      * Constructs a new AiffFileWriter object.
      */
     public AiffFileWriter() {
-        super(aiffTypes);
+        super(new AudioFileFormat.Type[]{AudioFileFormat.Type.AIFF});
     }
 
 
--- a/jdk/src/share/classes/com/sun/media/sound/AlawCodec.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AlawCodec.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,14 +25,12 @@
 
 package com.sun.media.sound;
 
-import java.io.InputStream;
 import java.io.IOException;
-
 import java.util.Vector;
 
 import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioInputStream;
 import javax.sound.sampled.AudioSystem;
-import javax.sound.sampled.AudioInputStream;
 
 
 /**
@@ -40,12 +38,12 @@
  *
  * @author Kara Kytle
  */
-public class AlawCodec extends SunCodec {
+public final class AlawCodec extends SunCodec {
 
     /* Tables used for A-law decoding */
 
-    final static byte ALAW_TABH[] = new byte[256];
-    final static byte ALAW_TABL[] = new byte[256];
+    private static final byte[] ALAW_TABH = new byte[256];
+    private static final byte[] ALAW_TABL = new byte[256];
 
     private static final AudioFormat.Encoding[] alawEncodings = { AudioFormat.Encoding.ALAW, AudioFormat.Encoding.PCM_SIGNED };
 
@@ -256,7 +254,7 @@
     }
 
 
-    class AlawCodecStream extends AudioInputStream {
+    final class AlawCodecStream extends AudioInputStream {
 
         // tempBuffer required only for encoding (when encode is true)
         private static final int tempBufferSize = 64;
--- a/jdk/src/share/classes/com/sun/media/sound/AuFileFormat.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AuFileFormat.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,7 +36,7 @@
  * @author Jan Borgersen
  */
 
-class AuFileFormat extends AudioFileFormat {
+final class AuFileFormat extends AudioFileFormat {
 
     // magic numbers
     static final int AU_SUN_MAGIC =     0x2e736e64;
@@ -60,7 +60,7 @@
 
     static final int AU_HEADERSIZE       = 24;
 
-    int auType;
+    private int auType;
 
     AuFileFormat( AudioFileFormat aff ) {
 
--- a/jdk/src/share/classes/com/sun/media/sound/AuFileReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AuFileReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,28 +25,17 @@
 
 package com.sun.media.sound;
 
-import java.util.Vector;
+import java.io.BufferedInputStream;
+import java.io.DataInputStream;
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
 import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.IOException;
-import java.io.EOFException;
 import java.net.URL;
-import java.net.MalformedURLException;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.DataInputStream;
-import java.io.FileInputStream;
-import java.io.DataOutputStream;
-import java.io.FileOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.SequenceInputStream;
 
 import javax.sound.sampled.AudioFileFormat;
+import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.AudioInputStream;
-import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.UnsupportedAudioFileException;
 
@@ -58,16 +47,7 @@
  * @author Jan Borgersen
  * @author Florian Bomers
  */
-public class AuFileReader extends SunFileReader {
-
-    /**
-     * AU reader type
-     */
-
-    public static final AudioFileFormat.Type types[] = {
-        AudioFileFormat.Type.AU
-    };
-
+public final class AuFileReader extends SunFileReader {
 
     /**
      * Constructs a new AuFileReader object.
--- a/jdk/src/share/classes/com/sun/media/sound/AuFileWriter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AuFileWriter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,28 +49,18 @@
  *
  * @author Jan Borgersen
  */
-public class AuFileWriter extends SunFileWriter {
+public final class AuFileWriter extends SunFileWriter {
 
     //$$fb value for length field if length is not known
     public final static int UNKNOWN_SIZE=-1;
 
     /**
-     * AU type
-     */
-    private static final AudioFileFormat.Type auTypes[] = {
-        AudioFileFormat.Type.AU
-    };
-
-
-    /**
      * Constructs a new AuFileWriter object.
      */
     public AuFileWriter() {
-        super(auTypes);
+        super(new AudioFileFormat.Type[]{AudioFileFormat.Type.AU});
     }
 
-
-
     public AudioFileFormat.Type[] getAudioFileTypes(AudioInputStream stream) {
 
         AudioFileFormat.Type[] filetypes = new AudioFileFormat.Type[types.length];
--- a/jdk/src/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,7 +43,7 @@
  *
  * @author Karl Helgason
  */
-public class AudioFileSoundbankReader extends SoundbankReader {
+public final class AudioFileSoundbankReader extends SoundbankReader {
 
     public Soundbank getSoundbank(URL url)
             throws InvalidMidiDataException, IOException {
--- a/jdk/src/share/classes/com/sun/media/sound/AudioFloatConverter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AudioFloatConverter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,7 +51,7 @@
 
     private static class AudioFloatLSBFilter extends AudioFloatConverter {
 
-        private AudioFloatConverter converter;
+        private final AudioFloatConverter converter;
 
         final private int offset;
 
@@ -61,8 +61,7 @@
 
         private byte[] mask_buffer;
 
-        public AudioFloatLSBFilter(AudioFloatConverter converter,
-                AudioFormat format) {
+        AudioFloatLSBFilter(AudioFloatConverter converter, AudioFormat format) {
             int bits = format.getSampleSizeInBits();
             boolean bigEndian = format.isBigEndian();
             this.converter = converter;
@@ -740,7 +739,7 @@
 
         final int xbytes;
 
-        public AudioFloatConversion32xSL(int xbytes) {
+        AudioFloatConversion32xSL(int xbytes) {
             this.xbytes = xbytes;
         }
 
@@ -781,7 +780,7 @@
 
         final int xbytes;
 
-        public AudioFloatConversion32xSB(int xbytes) {
+        AudioFloatConversion32xSB(int xbytes) {
             this.xbytes = xbytes;
         }
 
@@ -823,7 +822,7 @@
 
         final int xbytes;
 
-        public AudioFloatConversion32xUL(int xbytes) {
+        AudioFloatConversion32xUL(int xbytes) {
             this.xbytes = xbytes;
         }
 
@@ -866,7 +865,7 @@
 
         final int xbytes;
 
-        public AudioFloatConversion32xUB(int xbytes) {
+        AudioFloatConversion32xUB(int xbytes) {
             this.xbytes = xbytes;
         }
 
@@ -1008,49 +1007,51 @@
 
     private AudioFormat format;
 
-    public AudioFormat getFormat() {
+    public final AudioFormat getFormat() {
         return format;
     }
 
     public abstract float[] toFloatArray(byte[] in_buff, int in_offset,
             float[] out_buff, int out_offset, int out_len);
 
-    public float[] toFloatArray(byte[] in_buff, float[] out_buff,
+    public final float[] toFloatArray(byte[] in_buff, float[] out_buff,
             int out_offset, int out_len) {
         return toFloatArray(in_buff, 0, out_buff, out_offset, out_len);
     }
 
-    public float[] toFloatArray(byte[] in_buff, int in_offset,
+    public final float[] toFloatArray(byte[] in_buff, int in_offset,
             float[] out_buff, int out_len) {
         return toFloatArray(in_buff, in_offset, out_buff, 0, out_len);
     }
 
-    public float[] toFloatArray(byte[] in_buff, float[] out_buff, int out_len) {
+    public final float[] toFloatArray(byte[] in_buff, float[] out_buff,
+                                      int out_len) {
         return toFloatArray(in_buff, 0, out_buff, 0, out_len);
     }
 
-    public float[] toFloatArray(byte[] in_buff, float[] out_buff) {
+    public final float[] toFloatArray(byte[] in_buff, float[] out_buff) {
         return toFloatArray(in_buff, 0, out_buff, 0, out_buff.length);
     }
 
     public abstract byte[] toByteArray(float[] in_buff, int in_offset,
             int in_len, byte[] out_buff, int out_offset);
 
-    public byte[] toByteArray(float[] in_buff, int in_len, byte[] out_buff,
-            int out_offset) {
+    public final byte[] toByteArray(float[] in_buff, int in_len,
+                                    byte[] out_buff, int out_offset) {
         return toByteArray(in_buff, 0, in_len, out_buff, out_offset);
     }
 
-    public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
-            byte[] out_buff) {
+    public final byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
+                                    byte[] out_buff) {
         return toByteArray(in_buff, in_offset, in_len, out_buff, 0);
     }
 
-    public byte[] toByteArray(float[] in_buff, int in_len, byte[] out_buff) {
+    public final byte[] toByteArray(float[] in_buff, int in_len,
+                                    byte[] out_buff) {
         return toByteArray(in_buff, 0, in_len, out_buff, 0);
     }
 
-    public byte[] toByteArray(float[] in_buff, byte[] out_buff) {
+    public final byte[] toByteArray(float[] in_buff, byte[] out_buff) {
         return toByteArray(in_buff, 0, in_buff.length, out_buff, 0);
     }
 }
--- a/jdk/src/share/classes/com/sun/media/sound/AudioFloatFormatConverter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AudioFloatFormatConverter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,19 +42,19 @@
  *
  * @author Karl Helgason
  */
-public class AudioFloatFormatConverter extends FormatConversionProvider {
+public final class AudioFloatFormatConverter extends FormatConversionProvider {
 
     private static class AudioFloatFormatConverterInputStream extends
             InputStream {
-        private AudioFloatConverter converter;
+        private final AudioFloatConverter converter;
 
-        private AudioFloatInputStream stream;
+        private final AudioFloatInputStream stream;
 
         private float[] readfloatbuffer;
 
-        private int fsize = 0;
+        private final int fsize;
 
-        public AudioFloatFormatConverterInputStream(AudioFormat targetFormat,
+        AudioFloatFormatConverterInputStream(AudioFormat targetFormat,
                 AudioFloatInputStream stream) {
             this.stream = stream;
             converter = AudioFloatConverter.getConverter(targetFormat);
@@ -116,17 +116,17 @@
     private static class AudioFloatInputStreamChannelMixer extends
             AudioFloatInputStream {
 
-        private int targetChannels;
+        private final int targetChannels;
 
-        private int sourceChannels;
+        private final int sourceChannels;
 
-        private AudioFloatInputStream ais;
+        private final AudioFloatInputStream ais;
 
-        private AudioFormat targetFormat;
+        private final AudioFormat targetFormat;
 
         private float[] conversion_buffer;
 
-        public AudioFloatInputStreamChannelMixer(AudioFloatInputStream ais,
+        AudioFloatInputStreamChannelMixer(AudioFloatInputStream ais,
                 int targetChannels) {
             this.sourceChannels = ais.getFormat().getChannels();
             this.targetChannels = targetChannels;
@@ -226,37 +226,37 @@
     private static class AudioFloatInputStreamResampler extends
             AudioFloatInputStream {
 
-        private AudioFloatInputStream ais;
+        private final AudioFloatInputStream ais;
 
-        private AudioFormat targetFormat;
+        private final AudioFormat targetFormat;
 
         private float[] skipbuffer;
 
         private SoftAbstractResampler resampler;
 
-        private float[] pitch = new float[1];
+        private final float[] pitch = new float[1];
 
-        private float[] ibuffer2;
+        private final float[] ibuffer2;
 
-        private float[][] ibuffer;
+        private final float[][] ibuffer;
 
         private float ibuffer_index = 0;
 
         private int ibuffer_len = 0;
 
-        private int nrofchannels = 0;
+        private final int nrofchannels;
 
         private float[][] cbuffer;
 
-        private int buffer_len = 512;
+        private final int buffer_len = 512;
 
-        private int pad;
+        private final int pad;
 
-        private int pad2;
+        private final int pad2;
 
-        private float[] ix = new float[1];
+        private final float[] ix = new float[1];
 
-        private int[] ox = new int[1];
+        private final int[] ox = new int[1];
 
         private float[][] mark_ibuffer = null;
 
@@ -264,7 +264,7 @@
 
         private int mark_ibuffer_len = 0;
 
-        public AudioFloatInputStreamResampler(AudioFloatInputStream ais,
+        AudioFloatInputStreamResampler(AudioFloatInputStream ais,
                 AudioFormat format) {
             this.ais = ais;
             AudioFormat sourceFormat = ais.getFormat();
@@ -468,8 +468,9 @@
 
     }
 
-    private Encoding[] formats = { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED,
-            Encoding.PCM_FLOAT };
+    private final Encoding[] formats = {Encoding.PCM_SIGNED,
+                                        Encoding.PCM_UNSIGNED,
+                                        Encoding.PCM_FLOAT};
 
     public AudioInputStream getAudioInputStream(Encoding targetEncoding,
             AudioInputStream sourceStream) {
--- a/jdk/src/share/classes/com/sun/media/sound/AudioFloatInputStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AudioFloatInputStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -48,14 +48,14 @@
 
         private int pos = 0;
         private int markpos = 0;
-        private AudioFloatConverter converter;
-        private AudioFormat format;
-        private byte[] buffer;
-        private int buffer_offset;
-        private int buffer_len;
-        private int framesize_pc;
+        private final AudioFloatConverter converter;
+        private final AudioFormat format;
+        private final byte[] buffer;
+        private final int buffer_offset;
+        private final int buffer_len;
+        private final int framesize_pc;
 
-        public BytaArrayAudioFloatInputStream(AudioFloatConverter converter,
+        BytaArrayAudioFloatInputStream(AudioFloatConverter converter,
                 byte[] buffer, int offset, int len) {
             this.converter = converter;
             this.format = converter.getFormat();
@@ -125,12 +125,12 @@
     private static class DirectAudioFloatInputStream
             extends AudioFloatInputStream {
 
-        private AudioInputStream stream;
+        private final AudioInputStream stream;
         private AudioFloatConverter converter;
-        private int framesize_pc; // framesize / channels
+        private final int framesize_pc; // framesize / channels
         private byte[] buffer;
 
-        public DirectAudioFloatInputStream(AudioInputStream stream) {
+        DirectAudioFloatInputStream(AudioInputStream stream) {
             converter = AudioFloatConverter.getConverter(stream.getFormat());
             if (converter == null) {
                 AudioFormat format = stream.getFormat();
@@ -255,11 +255,11 @@
 
     public abstract int read(float[] b, int off, int len) throws IOException;
 
-    public int read(float[] b) throws IOException {
+    public final int read(float[] b) throws IOException {
         return read(b, 0, b.length);
     }
 
-    public float read() throws IOException {
+    public final float read() throws IOException {
         float[] b = new float[1];
         int ret = read(b, 0, 1);
         if (ret == -1 || ret == 0)
--- a/jdk/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/AudioSynthesizerPropertyInfo.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +29,7 @@
  *
  * @author Karl Helgason
  */
-public class AudioSynthesizerPropertyInfo {
+public final class AudioSynthesizerPropertyInfo {
 
     /**
      * Constructs a <code>AudioSynthesizerPropertyInfo</code> object with a given
--- a/jdk/src/share/classes/com/sun/media/sound/DLSInfo.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/DLSInfo.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,7 +30,7 @@
  *
  * @author Karl Helgason
  */
-public class DLSInfo {
+public final class DLSInfo {
 
     /**
      * (INAM) Title or subject.
--- a/jdk/src/share/classes/com/sun/media/sound/DLSInstrument.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/DLSInstrument.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -40,15 +40,15 @@
  *
  * @author Karl Helgason
  */
-public class DLSInstrument extends ModelInstrument {
+public final class DLSInstrument extends ModelInstrument {
 
-    protected int preset = 0;
-    protected int bank = 0;
-    protected boolean druminstrument = false;
-    protected byte[] guid = null;
-    protected DLSInfo info = new DLSInfo();
-    protected List<DLSRegion> regions = new ArrayList<DLSRegion>();
-    protected List<DLSModulator> modulators = new ArrayList<DLSModulator>();
+    int preset = 0;
+    int bank = 0;
+    boolean druminstrument = false;
+    byte[] guid = null;
+    DLSInfo info = new DLSInfo();
+    List<DLSRegion> regions = new ArrayList<DLSRegion>();
+    List<DLSModulator> modulators = new ArrayList<DLSModulator>();
 
     public DLSInstrument() {
         super(null, null, null, null);
--- a/jdk/src/share/classes/com/sun/media/sound/DLSModulator.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/DLSModulator.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,7 +33,7 @@
  *
  * @author Karl Helgason
  */
-public class DLSModulator {
+public final class DLSModulator {
 
     // DLS1 Destinations
     public static final int CONN_DST_NONE = 0x000; // 0
@@ -102,12 +102,12 @@
     public static final int DST_FORMAT_CENT = 1;
     public static final int DST_FORMAT_TIMECENT = 2;
     public static final int DST_FORMAT_PERCENT = 3;
-    protected int source;
-    protected int control;
-    protected int destination;
-    protected int transform;
-    protected int scale;
-    protected int version = 1;
+    int source;
+    int control;
+    int destination;
+    int transform;
+    int scale;
+    int version = 1;
 
     public int getControl() {
         return control;
--- a/jdk/src/share/classes/com/sun/media/sound/DLSRegion.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/DLSRegion.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,21 +36,21 @@
  *
  * @author Karl Helgason
  */
-public class DLSRegion {
+public final class DLSRegion {
 
     public final static int OPTION_SELFNONEXCLUSIVE = 0x0001;
-    protected List<DLSModulator> modulators = new ArrayList<DLSModulator>();
-    protected int keyfrom;
-    protected int keyto;
-    protected int velfrom;
-    protected int velto;
-    protected int options;
-    protected int exclusiveClass;
-    protected int fusoptions;
-    protected int phasegroup;
-    protected long channel;
-    protected DLSSample sample = null;
-    protected DLSSampleOptions sampleoptions;
+    List<DLSModulator> modulators = new ArrayList<DLSModulator>();
+    int keyfrom;
+    int keyto;
+    int velfrom;
+    int velto;
+    int options;
+    int exclusiveClass;
+    int fusoptions;
+    int phasegroup;
+    long channel;
+    DLSSample sample = null;
+    DLSSampleOptions sampleoptions;
 
     public List<DLSModulator> getModulators() {
         return modulators;
--- a/jdk/src/share/classes/com/sun/media/sound/DLSSample.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/DLSSample.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -40,13 +40,13 @@
  *
  * @author Karl Helgason
  */
-public class DLSSample extends SoundbankResource {
+public final class DLSSample extends SoundbankResource {
 
-    protected byte[] guid = null;
-    protected DLSInfo info = new DLSInfo();
-    protected DLSSampleOptions sampleoptions;
-    protected ModelByteBuffer data;
-    protected AudioFormat format;
+    byte[] guid = null;
+    DLSInfo info = new DLSInfo();
+    DLSSampleOptions sampleoptions;
+    ModelByteBuffer data;
+    AudioFormat format;
 
     public DLSSample(Soundbank soundBank) {
         super(soundBank, null, AudioInputStream.class);
--- a/jdk/src/share/classes/com/sun/media/sound/DLSSampleLoop.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/DLSSampleLoop.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,13 +29,13 @@
  *
  * @author Karl Helgason
  */
-public class DLSSampleLoop {
+public final class DLSSampleLoop {
 
     public final static int LOOP_TYPE_FORWARD = 0;
     public final static int LOOP_TYPE_RELEASE = 1;
-    protected long type;
-    protected long start;
-    protected long length;
+    long type;
+    long start;
+    long length;
 
     public long getLength() {
         return length;
--- a/jdk/src/share/classes/com/sun/media/sound/DLSSampleOptions.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/DLSSampleOptions.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,13 +34,13 @@
  *
  * @author Karl Helgason
  */
-public class DLSSampleOptions {
+public final class DLSSampleOptions {
 
-    protected int unitynote;
-    protected short finetune;
-    protected int attenuation;
-    protected long options;
-    protected List<DLSSampleLoop> loops = new ArrayList<DLSSampleLoop>();
+    int unitynote;
+    short finetune;
+    int attenuation;
+    long options;
+    List<DLSSampleLoop> loops = new ArrayList<DLSSampleLoop>();
 
     public int getAttenuation() {
         return attenuation;
--- a/jdk/src/share/classes/com/sun/media/sound/DLSSoundbank.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/DLSSoundbank.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,7 +51,7 @@
  *
  * @author Karl Helgason
  */
-public class DLSSoundbank implements Soundbank {
+public final class DLSSoundbank implements Soundbank {
 
     static private class DLSID {
         long i1;
@@ -69,7 +69,7 @@
         private DLSID() {
         }
 
-        public DLSID(long i1, int s1, int s2, int x1, int x2, int x3, int x4,
+        DLSID(long i1, int s1, int s2, int x1, int x2, int x3, int x4,
                 int x5, int x6, int x7, int x8) {
             this.i1 = i1;
             this.s1 = s1;
@@ -174,10 +174,10 @@
     private long major = -1;
     private long minor = -1;
 
-    private DLSInfo info = new DLSInfo();
+    private final DLSInfo info = new DLSInfo();
 
-    private List<DLSInstrument> instruments = new ArrayList<DLSInstrument>();
-    private List<DLSSample> samples = new ArrayList<DLSSample>();
+    private final List<DLSInstrument> instruments = new ArrayList<DLSInstrument>();
+    private final List<DLSSample> samples = new ArrayList<DLSSample>();
 
     private boolean largeFormat = false;
     private File sampleFile;
--- a/jdk/src/share/classes/com/sun/media/sound/DLSSoundbankReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/DLSSoundbankReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -39,7 +39,7 @@
  *
  * @author Karl Helgason
  */
-public class DLSSoundbankReader extends SoundbankReader {
+public final class DLSSoundbankReader extends SoundbankReader {
 
     public Soundbank getSoundbank(URL url)
             throws InvalidMidiDataException, IOException {
--- a/jdk/src/share/classes/com/sun/media/sound/DataPusher.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/DataPusher.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,13 +37,13 @@
  * @author Florian Bomers
  */
 
-public class DataPusher implements Runnable {
+public final class DataPusher implements Runnable {
 
     private static final int AUTO_CLOSE_TIME = 5000;
     private static final boolean DEBUG = false;
 
-    private SourceDataLine source = null;
-    private AudioFormat format = null;
+    private final SourceDataLine source;
+    private final AudioFormat format;
 
     // stream as source data
     private AudioInputStream ais = null;
--- a/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/DirectAudioDevice.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,7 +42,7 @@
  *
  * @author Florian Bomers
  */
-class DirectAudioDevice extends AbstractMixer {
+final class DirectAudioDevice extends AbstractMixer {
 
     // CONSTANTS
     private static final int CLIP_BUFFER_TIME = 1000; // in milliseconds
@@ -335,8 +335,8 @@
      * but isFormatSupported() also returns true
      * for formats with wrong endianness.
      */
-    private static class DirectDLI extends DataLine.Info {
-        AudioFormat[] hardwareFormats;
+    private static final class DirectDLI extends DataLine.Info {
+        final AudioFormat[] hardwareFormats;
 
         private DirectDLI(Class clazz, AudioFormat[] formatArray,
                           AudioFormat[] hardwareFormatArray,
@@ -370,12 +370,12 @@
      * Private inner class as base class for direct lines
      */
     private static class DirectDL extends AbstractDataLine implements EventDispatcher.LineMonitor {
-        protected int mixerIndex;
-        protected int deviceID;
+        protected final int mixerIndex;
+        protected final int deviceID;
         protected long id;
         protected int waitTime;
         protected volatile boolean flushing = false;
-        protected boolean isSource;         // true for SourceDataLine, false for TargetDataLine
+        protected final boolean isSource;         // true for SourceDataLine, false for TargetDataLine
         protected volatile long bytePosition;
         protected volatile boolean doIO = false;     // true in between start() and stop() calls
         protected volatile boolean stoppedWritten = false; // true if a write occured in stopped state
@@ -387,10 +387,10 @@
         protected int softwareConversionSize = 0;
         protected AudioFormat hardwareFormat;
 
-        private Gain gainControl = new Gain();
-        private Mute muteControl = new Mute();
-        private Balance balanceControl = new Balance();
-        private Pan panControl = new Pan();
+        private final Gain gainControl = new Gain();
+        private final Mute muteControl = new Mute();
+        private final Balance balanceControl = new Balance();
+        private final Pan panControl = new Pan();
         private float leftGain, rightGain;
         protected volatile boolean noService = false; // do not run the nService method
 
@@ -829,7 +829,7 @@
 
         /////////////////// CONTROLS /////////////////////////////
 
-        protected class Gain extends FloatControl {
+        protected final class Gain extends FloatControl {
 
             private float linearGain = 1.0f;
 
@@ -862,7 +862,7 @@
         } // class Gain
 
 
-        private class Mute extends BooleanControl {
+        private final class Mute extends BooleanControl {
 
             private Mute() {
                 super(BooleanControl.Type.MUTE, false, "True", "False");
@@ -874,7 +874,7 @@
             }
         }  // class Mute
 
-        private class Balance extends FloatControl {
+        private final class Balance extends FloatControl {
 
             private Balance() {
                 super(FloatControl.Type.BALANCE, -1.0f, 1.0f, (1.0f / 128.0f), -1, 0.0f,
@@ -893,7 +893,7 @@
 
         } // class Balance
 
-        private class Pan extends FloatControl {
+        private final class Pan extends FloatControl {
 
             private Pan() {
                 super(FloatControl.Type.PAN, -1.0f, 1.0f, (1.0f / 128.0f), -1, 0.0f,
@@ -918,7 +918,8 @@
     /**
      * Private inner class representing a SourceDataLine
      */
-    private static class DirectSDL extends DirectDL implements SourceDataLine {
+    private static final class DirectSDL extends DirectDL
+            implements SourceDataLine {
 
         // CONSTRUCTOR
         private DirectSDL(DataLine.Info info,
@@ -934,7 +935,8 @@
     /**
      * Private inner class representing a TargetDataLine
      */
-    private static class DirectTDL extends DirectDL implements TargetDataLine {
+    private static final class DirectTDL extends DirectDL
+            implements TargetDataLine {
 
         // CONSTRUCTOR
         private DirectTDL(DataLine.Info info,
@@ -1012,7 +1014,9 @@
      * Private inner class representing a Clip
      * This clip is realized in software only
      */
-    private static class DirectClip extends DirectDL implements Clip,  Runnable, AutoClosingClip {
+    private static final class DirectClip extends DirectDL
+            implements Clip, Runnable, AutoClosingClip {
+
         private Thread thread;
         private byte[] audioData = null;
         private int frameSize;         // size of one frame in bytes
@@ -1045,7 +1049,7 @@
 
             byte[] newData = new byte[bufferSize];
             System.arraycopy(data, offset, newData, 0, bufferSize);
-            open(format, data, bufferSize / format.getFrameSize());
+            open(format, newData, bufferSize / format.getFrameSize());
         }
 
         // this method does not copy the data array
@@ -1443,7 +1447,7 @@
      * which allows retrieval of the internal array
      */
     private static class DirectBAOS extends ByteArrayOutputStream {
-        public DirectBAOS() {
+        DirectBAOS() {
             super();
         }
 
--- a/jdk/src/share/classes/com/sun/media/sound/DirectAudioDeviceProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/DirectAudioDeviceProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,6 @@
 
 package com.sun.media.sound;
 
-import java.util.Vector;
-
 import javax.sound.sampled.Mixer;
 import javax.sound.sampled.spi.MixerProvider;
 
@@ -36,7 +34,7 @@
  *
  * @author Florian Bomers
  */
-public class DirectAudioDeviceProvider extends MixerProvider {
+public final class DirectAudioDeviceProvider extends MixerProvider {
 
     // STATIC VARIABLES
 
@@ -66,16 +64,17 @@
      * Required public no-arg constructor.
      */
     public DirectAudioDeviceProvider() {
-        //if (Printer.trace) Printer.trace("DirectAudioDeviceProvider: constructor");
-        if (Platform.isDirectAudioEnabled()) {
-            init();
-        } else {
-            infos = new DirectAudioDeviceInfo[0];
-            devices = new DirectAudioDevice[0];
+        synchronized (DirectAudioDeviceProvider.class) {
+            if (Platform.isDirectAudioEnabled()) {
+                init();
+            } else {
+                infos = new DirectAudioDeviceInfo[0];
+                devices = new DirectAudioDevice[0];
+            }
         }
     }
 
-    private synchronized static void init() {
+    private static void init() {
         // get the number of input devices
         int numDevices = nGetNumDevices();
 
@@ -94,36 +93,39 @@
     }
 
     public Mixer.Info[] getMixerInfo() {
-        Mixer.Info[] localArray = new Mixer.Info[infos.length];
-        System.arraycopy(infos, 0, localArray, 0, infos.length);
-        return localArray;
+        synchronized (DirectAudioDeviceProvider.class) {
+            Mixer.Info[] localArray = new Mixer.Info[infos.length];
+            System.arraycopy(infos, 0, localArray, 0, infos.length);
+            return localArray;
+        }
     }
 
 
     public Mixer getMixer(Mixer.Info info) {
-        // if the default device is asked, we provide the mixer
-        // with SourceDataLine's
-        if (info == null) {
+        synchronized (DirectAudioDeviceProvider.class) {
+            // if the default device is asked, we provide the mixer
+            // with SourceDataLine's
+            if (info == null) {
+                for (int i = 0; i < infos.length; i++) {
+                    Mixer mixer = getDevice(infos[i]);
+                    if (mixer.getSourceLineInfo().length > 0) {
+                        return mixer;
+                    }
+                }
+            }
+            // otherwise get the first mixer that matches
+            // the requested info object
             for (int i = 0; i < infos.length; i++) {
-                Mixer mixer = getDevice(infos[i]);
-                if (mixer.getSourceLineInfo().length > 0) {
-                    return mixer;
+                if (infos[i].equals(info)) {
+                    return getDevice(infos[i]);
                 }
             }
         }
-        // otherwise get the first mixer that matches
-        // the requested info object
-        for (int i = 0; i < infos.length; i++) {
-            if (infos[i].equals(info)) {
-                return getDevice(infos[i]);
-            }
-        }
-
         throw new IllegalArgumentException("Mixer " + info.toString() + " not supported by this provider.");
     }
 
 
-    private Mixer getDevice(DirectAudioDeviceInfo info) {
+    private static Mixer getDevice(DirectAudioDeviceInfo info) {
         int index = info.getIndex();
         if (devices[index] == null) {
             devices[index] = new DirectAudioDevice(info);
@@ -139,12 +141,12 @@
      * making native references to a particular device.
      * This constructor is called from native.
      */
-    static class DirectAudioDeviceInfo extends Mixer.Info {
-        private int index;
-        private int maxSimulLines;
+    static final class DirectAudioDeviceInfo extends Mixer.Info {
+        private final int index;
+        private final int maxSimulLines;
 
         // For ALSA, the deviceID contains the encoded card index, device index, and sub-device-index
-        private int deviceID;
+        private final int deviceID;
 
         private DirectAudioDeviceInfo(int index, int deviceID, int maxSimulLines,
                                       String name, String vendor,
--- a/jdk/src/share/classes/com/sun/media/sound/EmergencySoundbank.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/EmergencySoundbank.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,7 +35,7 @@
  *
  * @author Karl Helgason
  */
-public class EmergencySoundbank {
+public final class EmergencySoundbank {
 
     private final static String[] general_midi_instruments = {
         "Acoustic Grand Piano",
--- a/jdk/src/share/classes/com/sun/media/sound/EventDispatcher.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/EventDispatcher.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,20 +25,16 @@
 
 package com.sun.media.sound;
 
-import java.util.EventObject;
 import java.util.ArrayList;
 import java.util.List;
 
-import javax.sound.sampled.Clip;
-import javax.sound.sampled.Line;
+import javax.sound.midi.ControllerEventListener;
+import javax.sound.midi.MetaEventListener;
+import javax.sound.midi.MetaMessage;
+import javax.sound.midi.ShortMessage;
 import javax.sound.sampled.LineEvent;
 import javax.sound.sampled.LineListener;
 
-import javax.sound.midi.MetaMessage;
-import javax.sound.midi.ShortMessage;
-import javax.sound.midi.MetaEventListener;
-import javax.sound.midi.ControllerEventListener;
-
 
 
 /**
@@ -49,7 +45,7 @@
  * @author Kara Kytle
  * @author Florian Bomers
  */
-class EventDispatcher implements Runnable {
+final class EventDispatcher implements Runnable {
 
     /**
      * time of inactivity until the auto closing clips
@@ -61,7 +57,7 @@
     /**
      * List of events
      */
-    private ArrayList eventQueue = new ArrayList();
+    private final ArrayList eventQueue = new ArrayList();
 
 
     /**
@@ -73,12 +69,12 @@
     /*
      * support for auto-closing Clips
      */
-    private ArrayList<ClipInfo> autoClosingClips = new ArrayList<ClipInfo>();
+    private final ArrayList<ClipInfo> autoClosingClips = new ArrayList<ClipInfo>();
 
     /*
      * support for monitoring data lines
      */
-    private ArrayList<LineMonitor> lineMonitors = new ArrayList<LineMonitor>();
+    private final ArrayList<LineMonitor> lineMonitors = new ArrayList<LineMonitor>();
 
     /**
      * Approximate interval between calls to LineMonitor.checkLine
@@ -105,7 +101,7 @@
      * Invoked when there is at least one event in the queue.
      * Implement this as a callback to process one event.
      */
-    protected void processEvent(EventInfo eventInfo) {
+    void processEvent(EventInfo eventInfo) {
         int count = eventInfo.getListenerCount();
 
         // process an LineEvent
@@ -166,7 +162,7 @@
      * exclusive access over the code where an event is removed from the
      *queue.
      */
-    protected void dispatchEvents() {
+    void dispatchEvents() {
 
         EventInfo eventInfo = null;
 
@@ -388,8 +384,8 @@
      */
     private class EventInfo {
 
-        private Object event;
-        private Object[] listeners;
+        private final Object event;
+        private final Object[] listeners;
 
         /**
          * Create a new instance of this event Info class
@@ -421,8 +417,8 @@
      */
     private class ClipInfo {
 
-        private AutoClosingClip clip;
-        private long expiration;
+        private final AutoClosingClip clip;
+        private final long expiration;
 
         /**
          * Create a new instance of this clip Info class
--- a/jdk/src/share/classes/com/sun/media/sound/FFT.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/FFT.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,11 +31,11 @@
  */
 public final class FFT {
 
-    private double[] w;
-    private int fftFrameSize;
-    private int sign;
-    private int[] bitm_array;
-    private int fftFrameSize2;
+    private final double[] w;
+    private final int fftFrameSize;
+    private final int sign;
+    private final int[] bitm_array;
+    private final int fftFrameSize2;
 
     // Sign = -1 is FFT, 1 is IFFT (inverse FFT)
     // Data = Interlaced double array to be transformed.
--- a/jdk/src/share/classes/com/sun/media/sound/FastShortMessage.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/FastShortMessage.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,13 +35,13 @@
 final class FastShortMessage extends ShortMessage {
     private int packedMsg;
 
-    public FastShortMessage(int packedMsg) throws InvalidMidiDataException {
+    FastShortMessage(int packedMsg) throws InvalidMidiDataException {
         this.packedMsg = packedMsg;
         getDataLength(packedMsg & 0xFF); // to check for validity
     }
 
     /** Creates a FastShortMessage from this ShortMessage */
-    public FastShortMessage(ShortMessage msg) {
+    FastShortMessage(ShortMessage msg) {
         this.packedMsg = msg.getStatus()
             | (msg.getData1() << 8)
             | (msg.getData2() << 16);
--- a/jdk/src/share/classes/com/sun/media/sound/JARSoundbankReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/JARSoundbankReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,14 +36,16 @@
 import javax.sound.midi.Soundbank;
 import javax.sound.midi.spi.SoundbankReader;
 
+import sun.reflect.misc.ReflectUtil;
+
 /**
- * JarSoundbankReader is used to read sounbank object from jar files.
+ * JarSoundbankReader is used to read soundbank object from jar files.
  *
  * @author Karl Helgason
  */
-public class JARSoundbankReader extends SoundbankReader {
+public final class JARSoundbankReader extends SoundbankReader {
 
-    public boolean isZIP(URL url) {
+    private static boolean isZIP(URL url) {
         boolean ok = false;
         try {
             InputStream stream = url.openStream();
@@ -81,14 +83,14 @@
             while (line != null) {
                 if (!line.startsWith("#")) {
                     try {
-                        Class c = Class.forName(line.trim(), true, ucl);
-                        Object o = c.newInstance();
-                        if (o instanceof Soundbank) {
+                        Class<?> c = Class.forName(line.trim(), false, ucl);
+                        if (Soundbank.class.isAssignableFrom(c)) {
+                            Object o = ReflectUtil.newInstance(c);
                             soundbanks.add((Soundbank) o);
                         }
-                    } catch (ClassNotFoundException  e) {
-                    } catch (InstantiationException  e) {
-                    } catch (IllegalAccessException  e) {
+                    } catch (ClassNotFoundException ignored) {
+                    } catch (InstantiationException ignored) {
+                    } catch (IllegalAccessException ignored) {
                     }
                 }
                 line = r.readLine();
--- a/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/JDK13Services.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,16 +31,6 @@
 import java.util.Map;
 import java.util.Properties;
 
-import javax.sound.sampled.spi.AudioFileReader;
-import javax.sound.sampled.spi.AudioFileWriter;
-import javax.sound.sampled.spi.FormatConversionProvider;
-import javax.sound.sampled.spi.MixerProvider;
-
-import javax.sound.midi.spi.MidiFileReader;
-import javax.sound.midi.spi.MidiFileWriter;
-import javax.sound.midi.spi.SoundbankReader;
-import javax.sound.midi.spi.MidiDeviceProvider;
-
 import javax.sound.midi.Receiver;
 import javax.sound.midi.Sequencer;
 import javax.sound.midi.Synthesizer;
@@ -62,7 +52,7 @@
  *
  * @author Matthias Pfisterer
  */
-public class JDK13Services {
+public final class JDK13Services {
 
     /** The default for the length of the period to hold the cache.
         This value is given in milliseconds. It is equivalent to
@@ -80,7 +70,7 @@
         Class objects of the provider type (MixerProvider, MidiDeviceProvider
         ...) are used as keys. The values are instances of ProviderCache.
     */
-    private static Map providersCacheMap = new HashMap();
+    private static final Map providersCacheMap = new HashMap();
 
 
     /** The length of the period to hold the cache.
--- a/jdk/src/share/classes/com/sun/media/sound/JSSecurityManager.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/JSSecurityManager.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -47,7 +47,7 @@
  *
  * @author Matthias Pfisterer
  */
-class JSSecurityManager {
+final class JSSecurityManager {
 
     /** Prevent instantiation.
      */
@@ -73,30 +73,6 @@
         }
     }
 
-
-    static void loadLibrary(final String libName) {
-        try {
-            if (hasSecurityManager()) {
-                if(Printer.debug) Printer.debug("using security manager to load library");
-                PrivilegedAction<Void> action = new PrivilegedAction<Void>() {
-                        public Void run() {
-                            System.loadLibrary(libName);
-                            return null;
-                        }
-                    };
-                AccessController.doPrivileged(action);
-            } else {
-                if(Printer.debug) Printer.debug("not using security manager to load library");
-                System.loadLibrary(libName);
-            }
-            if (Printer.debug) Printer.debug("loaded library " + libName);
-        } catch (UnsatisfiedLinkError e2) {
-            if (Printer.err)Printer.err("UnsatisfiedLinkError loading native library " + libName);
-            throw(e2);
-        }
-    }
-
-
     static String getProperty(final String propertyName) {
         String propertyValue;
         if (hasSecurityManager()) {
@@ -189,83 +165,13 @@
         if(Printer.trace)Printer.trace("<< JSSecurityManager: loadPropertiesImpl() completed");
     }
 
-
-    private static ThreadGroup getTopmostThreadGroup() {
-        ThreadGroup topmostThreadGroup;
-        if(hasSecurityManager()) {
-            try {
-                // invoke the privileged action using 1.2 security
-                PrivilegedAction<ThreadGroup> action = new PrivilegedAction<ThreadGroup>() {
-                        public ThreadGroup run() {
-                            try {
-                                return getTopmostThreadGroupImpl();
-                            } catch (Throwable t) {
-                                return null;
-                            }
-                        }
-                    };
-                topmostThreadGroup = AccessController.doPrivileged(action);
-                if(Printer.debug)Printer.debug("Got topmost thread group with JDK 1.2 security");
-            } catch (Exception e) {
-                if(Printer.debug)Printer.debug("Exception getting topmost thread group with JDK 1.2 security");
-                // try without using JDK 1.2 security
-                topmostThreadGroup = getTopmostThreadGroupImpl();
-            }
-        } else {
-            // not JDK 1.2 security, assume we already have permission
-            topmostThreadGroup = getTopmostThreadGroupImpl();
-        }
-        return topmostThreadGroup;
-    }
-
-
-    private static ThreadGroup getTopmostThreadGroupImpl() {
-        if(Printer.trace)Printer.trace(">> JSSecurityManager: getTopmostThreadGroupImpl()");
-        ThreadGroup g = Thread.currentThread().getThreadGroup();
-        while ((g.getParent() != null) && (g.getParent().getParent() != null)) {
-            g = g.getParent();
-        }
-        if(Printer.trace)Printer.trace("<< JSSecurityManager: getTopmostThreadGroupImpl() completed");
-        return g;
-    }
-
-
-    /** Create a Thread in the topmost ThreadGroup.
+    /** Create a Thread in the current ThreadGroup.
      */
     static Thread createThread(final Runnable runnable,
                                final String threadName,
                                final boolean isDaemon, final int priority,
                                final boolean doStart) {
-        Thread thread = null;
-        if(hasSecurityManager()) {
-            PrivilegedAction<Thread> action = new PrivilegedAction<Thread>() {
-                    public Thread run() {
-                        try {
-                            return createThreadImpl(runnable, threadName,
-                                                    isDaemon, priority,
-                                                    doStart);
-                        } catch (Throwable t) {
-                            return null;
-                        }
-                    }
-                };
-            thread = AccessController.doPrivileged(action);
-            if(Printer.debug) Printer.debug("created thread with JDK 1.2 security");
-        } else {
-            if(Printer.debug)Printer.debug("not using JDK 1.2 security");
-            thread = createThreadImpl(runnable, threadName, isDaemon, priority,
-                                      doStart);
-        }
-        return thread;
-    }
-
-
-    private static Thread createThreadImpl(Runnable runnable,
-                                           String threadName,
-                                           boolean isDaemon, int priority,
-                                           boolean doStart) {
-        ThreadGroup threadGroup = getTopmostThreadGroupImpl();
-        Thread thread = new Thread(threadGroup, runnable);
+        Thread thread = new Thread(runnable);
         if (threadName != null) {
             thread.setName(threadName);
         }
@@ -279,7 +185,6 @@
         return thread;
     }
 
-
     static <T> List<T> getProviders(final Class<T> providerClass) {
         List<T> p = new ArrayList<>();
         // ServiceLoader creates "lazy" iterator instance, so it doesn't,
--- a/jdk/src/share/classes/com/sun/media/sound/JavaSoundAudioClip.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/JavaSoundAudioClip.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,25 +28,19 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.applet.AudioClip;
-import java.lang.InterruptedException;
 
 import javax.sound.sampled.AudioSystem;
-import javax.sound.sampled.Mixer;
 import javax.sound.sampled.Clip;
-import javax.sound.sampled.Control;
 import javax.sound.sampled.AudioInputStream;
 import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.DataLine;
 import javax.sound.sampled.SourceDataLine;
 import javax.sound.sampled.LineEvent;
 import javax.sound.sampled.LineListener;
-import javax.sound.sampled.LineUnavailableException;
 import javax.sound.sampled.UnsupportedAudioFileException;
 
-
 import javax.sound.midi.MidiSystem;
 import javax.sound.midi.MidiFileFormat;
 import javax.sound.midi.MetaMessage;
@@ -63,7 +57,7 @@
  * @author Florian Bomers
  */
 
-public class JavaSoundAudioClip implements AudioClip, MetaEventListener, LineListener {
+public final class JavaSoundAudioClip implements AudioClip, MetaEventListener, LineListener {
 
     private static final boolean DEBUG = false;
     private static final int BUFFER_SIZE = 16384; // number of bytes written each time to the source data line
@@ -476,7 +470,7 @@
      * which allows retrieval of the internal array
      */
     private static class DirectBAOS extends ByteArrayOutputStream {
-        public DirectBAOS() {
+        DirectBAOS() {
             super();
         }
 
--- a/jdk/src/share/classes/com/sun/media/sound/MidiDeviceReceiverEnvelope.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/MidiDeviceReceiverEnvelope.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,7 +33,7 @@
  *
  * @author Alex Menkov
  */
-public class MidiDeviceReceiverEnvelope implements MidiDeviceReceiver {
+public final class MidiDeviceReceiverEnvelope implements MidiDeviceReceiver {
 
     private final MidiDevice device;
     private final Receiver receiver;
--- a/jdk/src/share/classes/com/sun/media/sound/MidiDeviceTransmitterEnvelope.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/MidiDeviceTransmitterEnvelope.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,7 +33,7 @@
  *
  * @author Alex Menkov
  */
-public class MidiDeviceTransmitterEnvelope implements MidiDeviceTransmitter {
+public final class MidiDeviceTransmitterEnvelope implements MidiDeviceTransmitter {
 
     private final MidiDevice device;
     private final Transmitter transmitter;
--- a/jdk/src/share/classes/com/sun/media/sound/MidiInDevice.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/MidiInDevice.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,9 +25,6 @@
 
 package com.sun.media.sound;
 
-import java.util.ArrayList;
-import java.util.List;
-
 import javax.sound.midi.*;
 
 
@@ -39,7 +36,7 @@
  * @author Kara Kytle
  * @author Florian Bomers
  */
-class MidiInDevice extends AbstractMidiDevice implements Runnable {
+final class MidiInDevice extends AbstractMidiDevice implements Runnable {
 
     private Thread midiInThread = null;
 
@@ -127,7 +124,7 @@
       * An own class to distinguish the class name from
       * the transmitter of other devices
       */
-    private class MidiInTransmitter extends BasicTransmitter {
+    private final class MidiInTransmitter extends BasicTransmitter {
         private MidiInTransmitter() {
             super();
         }
--- a/jdk/src/share/classes/com/sun/media/sound/MidiInDeviceProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/MidiInDeviceProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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.media.sound;
 
 import javax.sound.midi.MidiDevice;
-import javax.sound.midi.spi.MidiDeviceProvider;
 
 
 /**
@@ -35,15 +34,15 @@
  * @author Kara Kytle
  * @author Florian Bomers
  */
-public class MidiInDeviceProvider extends AbstractMidiDeviceProvider {
+public final class MidiInDeviceProvider extends AbstractMidiDeviceProvider {
 
     /** Cache of info objects for all MIDI output devices on the system. */
-    static Info[] infos = null;
+    private static Info[] infos = null;
 
     /** Cache of open MIDI input devices on the system. */
-    static MidiDevice[] devices = null;
+    private static MidiDevice[] devices = null;
 
-    private static boolean enabled;
+    private static final boolean enabled;
 
     // STATIC
 
@@ -106,8 +105,8 @@
      * previous instance may still exist and be open / in use / etc.,
      * the new instance will not reflect that state...
      */
-    static class MidiInDeviceInfo extends AbstractMidiDeviceProvider.Info {
-        private Class providerClass;
+    static final class MidiInDeviceInfo extends AbstractMidiDeviceProvider.Info {
+        private final Class providerClass;
 
         private MidiInDeviceInfo(int index, Class providerClass) {
             super(nGetName(index), nGetVendor(index), nGetDescription(index), nGetVersion(index), index);
--- a/jdk/src/share/classes/com/sun/media/sound/MidiOutDevice.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/MidiOutDevice.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,7 +36,7 @@
  * @author Kara Kytle
  * @author Florian Bomers
  */
-class MidiOutDevice extends AbstractMidiDevice {
+final class MidiOutDevice extends AbstractMidiDevice {
 
     // CONSTRUCTOR
 
@@ -101,7 +101,7 @@
 
     // INNER CLASSES
 
-    class MidiOutReceiver extends AbstractReceiver {
+    final class MidiOutReceiver extends AbstractReceiver {
 
         void implSend(final MidiMessage message, final long timeStamp) {
             final int length = message.getLength();
--- a/jdk/src/share/classes/com/sun/media/sound/MidiOutDeviceProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/MidiOutDeviceProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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.media.sound;
 
 import javax.sound.midi.MidiDevice;
-import javax.sound.midi.spi.MidiDeviceProvider;
 
 
 /**
@@ -35,15 +34,15 @@
  * @author Kara Kytle
  * @author Florian Bomers
  */
-public class MidiOutDeviceProvider extends AbstractMidiDeviceProvider {
+public final class MidiOutDeviceProvider extends AbstractMidiDeviceProvider {
 
     /** Cache of info objects for all MIDI output devices on the system. */
-    static Info[] infos = null;
+    private static Info[] infos = null;
 
     /** Cache of open MIDI output devices on the system. */
-    static MidiDevice[] devices = null;
+    private static MidiDevice[] devices = null;
 
-    private static boolean enabled;
+    private final static boolean enabled;
 
     // STATIC
 
@@ -104,8 +103,8 @@
      * previous instance may still exist and be open / in use / etc.,
      * the new instance will not reflect that state...
      */
-    static class MidiOutDeviceInfo extends AbstractMidiDeviceProvider.Info {
-        private Class providerClass;
+    static final class MidiOutDeviceInfo extends AbstractMidiDeviceProvider.Info {
+        private final Class providerClass;
 
         private MidiOutDeviceInfo(int index, Class providerClass) {
             super(nGetName(index), nGetVendor(index), nGetDescription(index), nGetVersion(index), index);
--- a/jdk/src/share/classes/com/sun/media/sound/MidiUtils.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/MidiUtils.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,12 +36,17 @@
  *
  * @author Florian Bomers
  */
-public class MidiUtils {
+public final class MidiUtils {
 
     public final static int DEFAULT_TEMPO_MPQ = 500000; // 120bpm
     public final static int META_END_OF_TRACK_TYPE = 0x2F;
     public final static int META_TEMPO_TYPE = 0x51;
 
+    /**
+     * Suppresses default constructor, ensuring non-instantiability.
+     */
+    private MidiUtils() {
+    }
 
     /** return true if the passed message is Meta End Of Track */
     public static boolean isMetaEndOfTrack(MidiMessage midiMsg) {
@@ -262,7 +267,7 @@
     }
 
 
-    public static class TempoCache {
+    public static final class TempoCache {
         long[] ticks;
         int[] tempos; // in MPQ
         // index in ticks/tempos at the snapshot
--- a/jdk/src/share/classes/com/sun/media/sound/ModelByteBuffer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelByteBuffer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,7 +38,7 @@
  *
  * @author Karl Helgason
  */
-public class ModelByteBuffer {
+public final class ModelByteBuffer {
 
     private ModelByteBuffer root = this;
     private File file;
@@ -49,12 +49,12 @@
 
     private class RandomFileInputStream extends InputStream {
 
-        private RandomAccessFile raf;
+        private final RandomAccessFile raf;
         private long left;
         private long mark = 0;
         private long markleft = 0;
 
-        public RandomFileInputStream() throws IOException {
+        RandomFileInputStream() throws IOException {
             raf = new RandomAccessFile(root.file, "r");
             raf.seek(root.fileoffset + arrayOffset());
             left = capacity();
--- a/jdk/src/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,18 +36,18 @@
  *
  * @author Karl Helgason
  */
-public class ModelByteBufferWavetable implements ModelWavetable {
+public final class ModelByteBufferWavetable implements ModelWavetable {
 
     private class Buffer8PlusInputStream extends InputStream {
 
-        private boolean bigendian;
-        private int framesize_pc;
+        private final boolean bigendian;
+        private final int framesize_pc;
         int pos = 0;
         int pos2 = 0;
         int markpos = 0;
         int markpos2 = 0;
 
-        public Buffer8PlusInputStream() {
+        Buffer8PlusInputStream() {
             framesize_pc = format.getFrameSize() / format.getChannels();
             bigendian = format.isBigEndian();
         }
@@ -127,7 +127,7 @@
 
     private float loopStart = -1;
     private float loopLength = -1;
-    private ModelByteBuffer buffer;
+    private final ModelByteBuffer buffer;
     private ModelByteBuffer buffer8 = null;
     private AudioFormat format = null;
     private float pitchcorrection = 0;
--- a/jdk/src/share/classes/com/sun/media/sound/ModelConnectionBlock.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelConnectionBlock.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,7 +34,7 @@
  *
  * @author Karl Helgason
  */
-public class ModelConnectionBlock {
+public final class ModelConnectionBlock {
 
     //
     //   source1 * source2 * scale -> destination
--- a/jdk/src/share/classes/com/sun/media/sound/ModelDestination.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelDestination.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,7 +30,7 @@
  *
  * @author Karl Helgason
  */
-public class ModelDestination {
+public final class ModelDestination {
 
     public static final ModelIdentifier DESTINATION_NONE = null;
     public static final ModelIdentifier DESTINATION_KEYNUMBER
--- a/jdk/src/share/classes/com/sun/media/sound/ModelIdentifier.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelIdentifier.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,7 +30,7 @@
  *
  * @author Karl Helgason
  */
-public class ModelIdentifier {
+public final class ModelIdentifier {
 
     /*
      *  Object    Variable
--- a/jdk/src/share/classes/com/sun/media/sound/ModelInstrument.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelInstrument.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +69,7 @@
     }
 
     // Get General MIDI 2 Alias patch for this instrument.
-    public Patch getPatchAlias() {
+    public final Patch getPatchAlias() {
         Patch patch = getPatch();
         int program = patch.getProgram();
         int bank = patch.getBank();
@@ -87,7 +87,7 @@
     // Return name of all the keys.
     // This information is generated from ModelPerformer.getName()
     // returned from getPerformers().
-    public String[] getKeys() {
+    public final String[] getKeys() {
         String[] keys = new String[128];
         for (ModelPerformer performer : getPerformers()) {
             for (int k = performer.getKeyFrom(); k <= performer.getKeyTo(); k++) {
@@ -104,7 +104,7 @@
 
     // Return what channels this instrument will probably response
     // on General MIDI synthesizer.
-    public boolean[] getChannels() {
+    public final boolean[] getChannels() {
         boolean percussion = false;
         if (getPatch() instanceof ModelPatch)
             percussion = ((ModelPatch)getPatch()).isPercussion();
--- a/jdk/src/share/classes/com/sun/media/sound/ModelInstrumentComparator.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelInstrumentComparator.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,7 +34,7 @@
  *
  * @author Karl Helgason
  */
-public class ModelInstrumentComparator implements Comparator<Instrument> {
+public final class ModelInstrumentComparator implements Comparator<Instrument> {
 
     public int compare(Instrument arg0, Instrument arg1) {
         Patch p0 = arg0.getPatch();
--- a/jdk/src/share/classes/com/sun/media/sound/ModelMappedInstrument.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelMappedInstrument.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,9 +33,9 @@
  *
  * @author Karl Helgason
  */
-public class ModelMappedInstrument extends ModelInstrument {
+public final class ModelMappedInstrument extends ModelInstrument {
 
-    private ModelInstrument ins;
+    private final ModelInstrument ins;
 
     public ModelMappedInstrument(ModelInstrument ins, Patch patch) {
         super(ins.getSoundbank(), patch, ins.getName(), ins.getDataClass());
--- a/jdk/src/share/classes/com/sun/media/sound/ModelPatch.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelPatch.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,7 +33,7 @@
  *
  * @author Karl Helgason
  */
-public class ModelPatch extends Patch {
+public final class ModelPatch extends Patch {
 
     private boolean percussion = false;
 
--- a/jdk/src/share/classes/com/sun/media/sound/ModelPerformer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelPerformer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,9 +33,9 @@
  *
  * @author Karl Helgason
  */
-public class ModelPerformer {
+public final class ModelPerformer {
 
-    private List<ModelOscillator> oscillators = new ArrayList<ModelOscillator>();
+    private final List<ModelOscillator> oscillators = new ArrayList<ModelOscillator>();
     private List<ModelConnectionBlock> connectionBlocks
             = new ArrayList<ModelConnectionBlock>();
     private int keyFrom = 0;
--- a/jdk/src/share/classes/com/sun/media/sound/ModelSource.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelSource.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,7 +30,7 @@
  *
  * @author Karl Helgason
  */
-public class ModelSource {
+public final class ModelSource {
 
     public static final ModelIdentifier SOURCE_NONE = null;
     public static final ModelIdentifier SOURCE_NOTEON_KEYNUMBER =
--- a/jdk/src/share/classes/com/sun/media/sound/ModelStandardDirector.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelStandardDirector.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,7 +30,7 @@
  *
  * @author Karl Helgason
  */
-public class ModelStandardDirector implements ModelDirector {
+public final class ModelStandardDirector implements ModelDirector {
 
     ModelPerformer[] performers;
     ModelDirectedPlayer player;
--- a/jdk/src/share/classes/com/sun/media/sound/ModelStandardIndexedDirector.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelStandardIndexedDirector.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,7 +30,7 @@
  *
  * @author Karl Helgason
  */
-public class ModelStandardIndexedDirector implements ModelDirector {
+public final class ModelStandardIndexedDirector implements ModelDirector {
 
     ModelPerformer[] performers;
     ModelDirectedPlayer player;
--- a/jdk/src/share/classes/com/sun/media/sound/ModelStandardTransform.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/ModelStandardTransform.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,7 +36,7 @@
  *
  * @author Karl Helgason
  */
-public class ModelStandardTransform implements ModelTransform {
+public final class ModelStandardTransform implements ModelTransform {
 
     public static final boolean DIRECTION_MIN2MAX = false;
     public static final boolean DIRECTION_MAX2MIN = true;
--- a/jdk/src/share/classes/com/sun/media/sound/PCMtoPCMCodec.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/PCMtoPCMCodec.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,14 +25,12 @@
 
 package com.sun.media.sound;
 
-import java.io.InputStream;
 import java.io.IOException;
-
 import java.util.Vector;
 
 import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioInputStream;
 import javax.sound.sampled.AudioSystem;
-import javax.sound.sampled.AudioInputStream;
 
 
 /**
@@ -40,7 +38,7 @@
  *
  * @author Jan Borgersen
  */
-public class PCMtoPCMCodec extends SunCodec {
+public final class PCMtoPCMCodec extends SunCodec {
 
 
     private static final AudioFormat.Encoding[] inputEncodings = {
@@ -356,7 +354,7 @@
         private final int PCM_UNSIGNED_BE2SIGNED_LE             = 7;
         private final int PCM_SIGNED_BE2UNSIGNED_LE             = 8;
 
-        private int sampleSizeInBytes = 0;
+        private final int sampleSizeInBytes;
         private int conversionType = 0;
 
 
--- a/jdk/src/share/classes/com/sun/media/sound/Platform.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/Platform.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,8 @@
 
 package com.sun.media.sound;
 
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.StringTokenizer;
 
 
@@ -35,7 +37,7 @@
  * @author Kara Kytle
  * @author Florian Bomers
  */
-class Platform {
+final class Platform {
 
 
     // STATIC FINAL CHARACTERISTICS
@@ -157,7 +159,13 @@
 
         try {
             // load the main library
-            JSSecurityManager.loadLibrary(libNameMain);
+            AccessController.doPrivileged(new PrivilegedAction<Void>() {
+                @Override
+                public Void run() {
+                    System.loadLibrary(libNameMain);
+                    return null;
+                }
+            });
             // just for the heck of it...
             loadedLibs |= LIB_MAIN;
         } catch (SecurityException e) {
@@ -171,9 +179,16 @@
         // the string is the libraries, separated by white space
         StringTokenizer st = new StringTokenizer(extraLibs);
         while (st.hasMoreTokens()) {
-            String lib = st.nextToken();
+            final String lib = st.nextToken();
             try {
-                JSSecurityManager.loadLibrary(lib);
+                AccessController.doPrivileged(new PrivilegedAction<Void>() {
+                    @Override
+                    public Void run() {
+                        System.loadLibrary(lib);
+                        return null;
+                    }
+                });
+
                 if (lib.equals(libNameALSA)) {
                     loadedLibs |= LIB_ALSA;
                     if (Printer.debug) Printer.debug("Loaded ALSA lib successfully.");
--- a/jdk/src/share/classes/com/sun/media/sound/PortMixer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/PortMixer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,7 +41,7 @@
  *
  * @author Florian Bomers
  */
-class PortMixer extends AbstractMixer {
+final class PortMixer extends AbstractMixer {
 
     // CONSTANTS
     private static final int SRC_UNKNOWN      = 0x01;
@@ -228,8 +228,10 @@
     /**
      * Private inner class representing a Port for the PortMixer.
      */
-    private static class PortMixerPort extends AbstractLine implements Port {
-        private int portIndex;
+    private static final class PortMixerPort extends AbstractLine
+            implements Port {
+
+        private final int portIndex;
         private long id;
 
         // CONSTRUCTOR
@@ -342,9 +344,9 @@
     /**
      * Private inner class representing a BooleanControl for PortMixerPort
      */
-    private static class BoolCtrl extends BooleanControl {
+    private static final class BoolCtrl extends BooleanControl {
         // the handle to the native control function
-        private long controlID;
+        private final long controlID;
         private boolean closed = false;
 
         private static BooleanControl.Type createType(String name) {
@@ -386,7 +388,7 @@
         /**
          * inner class for custom types
          */
-        private static class BCT extends BooleanControl.Type {
+        private static final class BCT extends BooleanControl.Type {
             private BCT(String name) {
                 super(name);
             }
@@ -396,7 +398,7 @@
     /**
      * Private inner class representing a CompoundControl for PortMixerPort
      */
-    private static class CompCtrl extends CompoundControl {
+    private static final class CompCtrl extends CompoundControl {
         private CompCtrl(String name, Control[] controls) {
             super(new CCT(name), controls);
         }
@@ -404,7 +406,7 @@
         /**
          * inner class for custom compound control types
          */
-        private static class CCT extends CompoundControl.Type {
+        private static final class CCT extends CompoundControl.Type {
             private CCT(String name) {
                 super(name);
             }
@@ -414,9 +416,9 @@
     /**
      * Private inner class representing a BooleanControl for PortMixerPort
      */
-    private static class FloatCtrl extends FloatControl {
+    private static final class FloatCtrl extends FloatControl {
         // the handle to the native control function
-        private long controlID;
+        private final long controlID;
         private boolean closed = false;
 
         // predefined float control types. See also Ports.h
@@ -462,7 +464,7 @@
         /**
          * inner class for custom types
          */
-        private static class FCT extends FloatControl.Type {
+        private static final class FCT extends FloatControl.Type {
             private FCT(String name) {
                 super(name);
             }
@@ -472,7 +474,7 @@
     /**
      * Private inner class representing a port info
      */
-    private static class PortInfo extends Port.Info {
+    private static final class PortInfo extends Port.Info {
         private PortInfo(String name, boolean isSource) {
             super(Port.class, name, isSource);
         }
--- a/jdk/src/share/classes/com/sun/media/sound/PortMixerProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/PortMixerProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,6 @@
 
 package com.sun.media.sound;
 
-import java.util.Vector;
-
 import javax.sound.sampled.Mixer;
 import javax.sound.sampled.spi.MixerProvider;
 
@@ -36,7 +34,7 @@
  *
  * @author Florian Bomers
  */
-public class PortMixerProvider extends MixerProvider {
+public final class PortMixerProvider extends MixerProvider {
 
     // STATIC VARIABLES
 
@@ -66,16 +64,17 @@
      * Required public no-arg constructor.
      */
     public PortMixerProvider() {
-        //if (Printer.trace) Printer.trace("PortMixerProvider: constructor");
-        if (Platform.isPortsEnabled()) {
-            init();
-        } else {
-            infos = new PortMixerInfo[0];
-            devices = new PortMixer[0];
+        synchronized (PortMixerProvider.class) {
+            if (Platform.isPortsEnabled()) {
+                init();
+            } else {
+                infos = new PortMixerInfo[0];
+                devices = new PortMixer[0];
+            }
         }
     }
 
-    private static synchronized void init() {
+    private static void init() {
         // get the number of input devices
         int numDevices = nGetNumDevices();
 
@@ -95,23 +94,28 @@
     }
 
     public Mixer.Info[] getMixerInfo() {
-        Mixer.Info[] localArray = new Mixer.Info[infos.length];
-        System.arraycopy(infos, 0, localArray, 0, infos.length);
-        return localArray;
+        synchronized (PortMixerProvider.class) {
+            Mixer.Info[] localArray = new Mixer.Info[infos.length];
+            System.arraycopy(infos, 0, localArray, 0, infos.length);
+            return localArray;
+        }
     }
 
 
     public Mixer getMixer(Mixer.Info info) {
-        for (int i = 0; i < infos.length; i++) {
-            if (infos[i].equals(info)) {
-                return getDevice(infos[i]);
+        synchronized (PortMixerProvider.class) {
+            for (int i = 0; i < infos.length; i++) {
+                if (infos[i].equals(info)) {
+                    return getDevice(infos[i]);
+                }
             }
         }
-        throw new IllegalArgumentException("Mixer " + info.toString() + " not supported by this provider.");
+        throw new IllegalArgumentException("Mixer " + info.toString()
+                                           + " not supported by this provider.");
     }
 
 
-    private Mixer getDevice(PortMixerInfo info) {
+    private static Mixer getDevice(PortMixerInfo info) {
         int index = info.getIndex();
         if (devices[index] == null) {
             devices[index] = new PortMixer(info);
@@ -127,8 +131,8 @@
      * making native references to a particular device.
      * This constructor is called from native.
      */
-    static class PortMixerInfo extends Mixer.Info {
-        private int index;
+    static final class PortMixerInfo extends Mixer.Info {
+        private final int index;
 
         private PortMixerInfo(int index, String name, String vendor, String description, String version) {
             super("Port " + name, vendor, description, version);
--- a/jdk/src/share/classes/com/sun/media/sound/Printer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/Printer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,7 +32,7 @@
  * @author David Rivas
  * @author Kara Kytle
  */
-class Printer {
+final class Printer {
 
     static final boolean err = false;
     static final boolean debug = false;
@@ -68,6 +68,12 @@
       release = on;
       }*/
 
+    /**
+     * Suppresses default constructor, ensuring non-instantiability.
+     */
+    private Printer() {
+    }
+
     public static void err(String str) {
 
         if (err)
--- a/jdk/src/share/classes/com/sun/media/sound/RIFFInvalidDataException.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/RIFFInvalidDataException.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +29,7 @@
  *
  * @author Karl Helgason
  */
-public class RIFFInvalidDataException extends InvalidDataException {
+public final class RIFFInvalidDataException extends InvalidDataException {
 
     private static final long serialVersionUID = 1L;
 
--- a/jdk/src/share/classes/com/sun/media/sound/RIFFInvalidFormatException.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/RIFFInvalidFormatException.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,7 +30,7 @@
  *
  * @author Karl Helgason
  */
-public class RIFFInvalidFormatException extends InvalidFormatException {
+public final class RIFFInvalidFormatException extends InvalidFormatException {
 
     private static final long serialVersionUID = 1L;
 
--- a/jdk/src/share/classes/com/sun/media/sound/RIFFReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/RIFFReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,11 +33,11 @@
  *
  * @author Karl Helgason
  */
-public class RIFFReader extends InputStream {
+public final class RIFFReader extends InputStream {
 
-    private RIFFReader root;
+    private final RIFFReader root;
     private long filepointer = 0;
-    private String fourcc;
+    private final String fourcc;
     private String riff_type = null;
     private long ckSize = 0;
     private InputStream stream;
--- a/jdk/src/share/classes/com/sun/media/sound/RIFFWriter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/RIFFWriter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,7 +35,7 @@
  *
  * @author Karl Helgason
  */
-public class RIFFWriter extends OutputStream {
+public final class RIFFWriter extends OutputStream {
 
     private interface RandomAccessWriter {
 
@@ -60,11 +60,11 @@
 
         RandomAccessFile raf;
 
-        public RandomAccessFileWriter(File file) throws FileNotFoundException {
+        RandomAccessFileWriter(File file) throws FileNotFoundException {
             this.raf = new RandomAccessFile(file, "rw");
         }
 
-        public RandomAccessFileWriter(String name) throws FileNotFoundException {
+        RandomAccessFileWriter(String name) throws FileNotFoundException {
             this.raf = new RandomAccessFile(name, "rw");
         }
 
@@ -107,9 +107,9 @@
         int length = 0;
         int pos = 0;
         byte[] s;
-        OutputStream stream;
+        final OutputStream stream;
 
-        public RandomAccessByteWriter(OutputStream stream) {
+        RandomAccessByteWriter(OutputStream stream) {
             this.stream = stream;
         }
 
@@ -163,8 +163,8 @@
     }
     private int chunktype = 0; // 0=RIFF, 1=LIST; 2=CHUNK
     private RandomAccessWriter raf;
-    private long chunksizepointer;
-    private long startpointer;
+    private final long chunksizepointer;
+    private final long startpointer;
     private RIFFWriter childchunk = null;
     private boolean open = true;
     private boolean writeoverride = false;
--- a/jdk/src/share/classes/com/sun/media/sound/RealTimeSequencer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/RealTimeSequencer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,14 +25,13 @@
 
 package com.sun.media.sound;
 
-import java.io.ByteArrayOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.DataOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Map;
+import java.util.WeakHashMap;
 
 import javax.sound.midi.*;
 
@@ -46,7 +45,8 @@
 /* TODO:
  * - rename PlayThread to PlayEngine (because isn't a thread)
  */
-class RealTimeSequencer extends AbstractMidiDevice implements Sequencer, AutoConnectSequencer {
+final class RealTimeSequencer extends AbstractMidiDevice
+        implements Sequencer, AutoConnectSequencer {
 
     // STATIC VARIABLES
 
@@ -58,7 +58,8 @@
      * Event Dispatcher thread. Should be using a shared event
      * dispatcher instance with a factory in EventDispatcher
      */
-    private static final EventDispatcher eventDispatcher;
+    private static final Map<ThreadGroup, EventDispatcher> dispatchers =
+            new WeakHashMap<>();
 
     /**
      * All RealTimeSequencers share this info object.
@@ -66,11 +67,11 @@
     static final RealTimeSequencerInfo info = new RealTimeSequencerInfo();
 
 
-    private static Sequencer.SyncMode[] masterSyncModes = { Sequencer.SyncMode.INTERNAL_CLOCK };
-    private static Sequencer.SyncMode[] slaveSyncModes  = { Sequencer.SyncMode.NO_SYNC };
+    private static final Sequencer.SyncMode[] masterSyncModes = { Sequencer.SyncMode.INTERNAL_CLOCK };
+    private static final Sequencer.SyncMode[] slaveSyncModes  = { Sequencer.SyncMode.NO_SYNC };
 
-    private static Sequencer.SyncMode masterSyncMode    = Sequencer.SyncMode.INTERNAL_CLOCK;
-    private static Sequencer.SyncMode slaveSyncMode     = Sequencer.SyncMode.NO_SYNC;
+    private static final Sequencer.SyncMode masterSyncMode    = Sequencer.SyncMode.INTERNAL_CLOCK;
+    private static final Sequencer.SyncMode slaveSyncMode     = Sequencer.SyncMode.NO_SYNC;
 
 
     /**
@@ -100,7 +101,7 @@
     private boolean[] trackSolo = null;
 
     /** tempo cache for getMicrosecondPosition */
-    private MidiUtils.TempoCache tempoCache = new MidiUtils.TempoCache();
+    private final MidiUtils.TempoCache tempoCache = new MidiUtils.TempoCache();
 
     /**
      * True if the sequence is running.
@@ -121,7 +122,7 @@
     /**
      * List of tracks to which we're recording
      */
-    private List recordingTracks = new ArrayList();
+    private final List recordingTracks = new ArrayList();
 
 
     private long loopStart = 0;
@@ -132,13 +133,13 @@
     /**
      * Meta event listeners
      */
-    private ArrayList metaEventListeners = new ArrayList();
+    private final ArrayList metaEventListeners = new ArrayList();
 
 
     /**
      * Control change listeners
      */
-    private ArrayList controllerEventListeners = new ArrayList();
+    private final ArrayList controllerEventListeners = new ArrayList();
 
 
     /** automatic connection support */
@@ -151,16 +152,9 @@
     Receiver autoConnectedReceiver = null;
 
 
-    static {
-        // create and start the global event thread
-        eventDispatcher = new EventDispatcher();
-        eventDispatcher.start();
-    }
-
-
     /* ****************************** CONSTRUCTOR ****************************** */
 
-    protected RealTimeSequencer() throws MidiUnavailableException {
+    RealTimeSequencer() throws MidiUnavailableException {
         super(info);
 
         if (Printer.trace) Printer.trace(">> RealTimeSequencer CONSTRUCTOR");
@@ -574,7 +568,7 @@
         return returnedModes;
     }
 
-    protected int getTrackCount() {
+    int getTrackCount() {
         Sequence seq = getSequence();
         if (seq != null) {
             // $$fb wish there was a nicer way to get the number of tracks...
@@ -872,7 +866,7 @@
         if (Printer.trace) Printer.trace("<< RealTimeSequencer: implClose() completed");
     }
 
-    protected void implStart() {
+    void implStart() {
         if (Printer.trace) Printer.trace(">> RealTimeSequencer: implStart()");
 
         if (playThread == null) {
@@ -889,7 +883,7 @@
     }
 
 
-    protected void implStop() {
+    void implStop() {
         if (Printer.trace) Printer.trace(">> RealTimeSequencer: implStop()");
 
         if (playThread == null) {
@@ -905,22 +899,36 @@
         if (Printer.trace) Printer.trace("<< RealTimeSequencer: implStop() completed");
     }
 
+    private static EventDispatcher getEventDispatcher() {
+        // create and start the global event thread
+        //TODO  need a way to stop this thread when the engine is done
+        final ThreadGroup tg = Thread.currentThread().getThreadGroup();
+        synchronized (dispatchers) {
+            EventDispatcher eventDispatcher = dispatchers.get(tg);
+            if (eventDispatcher == null) {
+                eventDispatcher = new EventDispatcher();
+                dispatchers.put(tg, eventDispatcher);
+                eventDispatcher.start();
+            }
+            return eventDispatcher;
+        }
+    }
 
     /**
      * Send midi player events.
      * must not be synchronized on "this"
      */
-    protected void sendMetaEvents(MidiMessage message) {
+    void sendMetaEvents(MidiMessage message) {
         if (metaEventListeners.size() == 0) return;
 
         //if (Printer.debug) Printer.debug("sending a meta event");
-        eventDispatcher.sendAudioEvents(message, metaEventListeners);
+        getEventDispatcher().sendAudioEvents(message, metaEventListeners);
     }
 
     /**
      * Send midi player events.
      */
-    protected void sendControllerEvents(MidiMessage message) {
+    void sendControllerEvents(MidiMessage message) {
         int size = controllerEventListeners.size();
         if (size == 0) return;
 
@@ -942,7 +950,7 @@
                 }
             }
         }
-        eventDispatcher.sendAudioEvents(message, sendToListeners);
+        getEventDispatcher().sendAudioEvents(message, sendToListeners);
     }
 
 
@@ -1024,7 +1032,7 @@
     }
 
 
-    class SequencerReceiver extends AbstractReceiver {
+    final class SequencerReceiver extends AbstractReceiver {
 
         void implSend(MidiMessage message, long timeStamp) {
             if (recording) {
@@ -1092,7 +1100,7 @@
         //       easier to deal with than turning all the
         //       ints into objects to use a Vector
         int []  controllers;
-        ControllerEventListener listener;
+        final ControllerEventListener listener;
 
         private ControllerListElement(ControllerEventListener listener, int[] controllers) {
 
@@ -1197,7 +1205,7 @@
 
     static class RecordingTrack {
 
-        private Track track;
+        private final Track track;
         private int channel;
 
         RecordingTrack(Track track, int channel) {
@@ -1237,15 +1245,15 @@
     }
 
 
-    class PlayThread implements Runnable {
+    final class PlayThread implements Runnable {
         private Thread thread;
-        private Object lock = new Object();
+        private final Object lock = new Object();
 
         /** true if playback is interrupted (in close) */
         boolean interrupted = false;
         boolean isPumping = false;
 
-        private DataPump dataPump = new DataPump();
+        private final DataPump dataPump = new DataPump();
 
 
         PlayThread() {
--- a/jdk/src/share/classes/com/sun/media/sound/RealTimeSequencerProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/RealTimeSequencerProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,7 +34,7 @@
  *
  * @author Florian Bomers
  */
-public class RealTimeSequencerProvider extends MidiDeviceProvider {
+public final class RealTimeSequencerProvider extends MidiDeviceProvider {
 
 
     public MidiDevice.Info[] getDeviceInfo() {
--- a/jdk/src/share/classes/com/sun/media/sound/SF2GlobalRegion.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SF2GlobalRegion.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,5 +29,5 @@
  *
  * @author Karl Helgason
  */
-public class SF2GlobalRegion extends SF2Region {
+public final class SF2GlobalRegion extends SF2Region {
 }
--- a/jdk/src/share/classes/com/sun/media/sound/SF2Instrument.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SF2Instrument.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,16 +36,16 @@
  *
  * @author Karl Helgason
  */
-public class SF2Instrument extends ModelInstrument {
+public final class SF2Instrument extends ModelInstrument {
 
-    protected String name = "";
-    protected int preset = 0;
-    protected int bank = 0;
-    protected long library = 0;
-    protected long genre = 0;
-    protected long morphology = 0;
-    protected SF2GlobalRegion globalregion = null;
-    protected List<SF2InstrumentRegion> regions
+    String name = "";
+    int preset = 0;
+    int bank = 0;
+    long library = 0;
+    long genre = 0;
+    long morphology = 0;
+    SF2GlobalRegion globalregion = null;
+    List<SF2InstrumentRegion> regions
             = new ArrayList<SF2InstrumentRegion>();
 
     public SF2Instrument() {
@@ -730,7 +730,7 @@
         return msrc;
     }
 
-    protected static ModelDestination convertDestination(int dst,
+    static ModelDestination convertDestination(int dst,
             double[] amountcorrection, ModelSource[] extrasrc) {
         ModelIdentifier id = null;
         switch (dst) {
--- a/jdk/src/share/classes/com/sun/media/sound/SF2InstrumentRegion.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SF2InstrumentRegion.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,9 +29,9 @@
  *
  * @author Karl Helgason
  */
-public class SF2InstrumentRegion extends SF2Region {
+public final class SF2InstrumentRegion extends SF2Region {
 
-    protected SF2Layer layer;
+    SF2Layer layer;
 
     public SF2Layer getLayer() {
         return layer;
--- a/jdk/src/share/classes/com/sun/media/sound/SF2Layer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SF2Layer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,11 +34,11 @@
  *
  * @author Karl Helgason
  */
-public class SF2Layer extends SoundbankResource {
+public final class SF2Layer extends SoundbankResource {
 
-    protected String name = "";
-    protected SF2GlobalRegion globalregion = null;
-    protected List<SF2LayerRegion> regions = new ArrayList<SF2LayerRegion>();
+    String name = "";
+    SF2GlobalRegion globalregion = null;
+    List<SF2LayerRegion> regions = new ArrayList<SF2LayerRegion>();
 
     public SF2Layer(SF2Soundbank soundBank) {
         super(soundBank, null, null);
--- a/jdk/src/share/classes/com/sun/media/sound/SF2LayerRegion.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SF2LayerRegion.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,9 +29,9 @@
  *
  * @author Karl Helgason
  */
-public class SF2LayerRegion extends SF2Region {
+public final class SF2LayerRegion extends SF2Region {
 
-    protected SF2Sample sample;
+    SF2Sample sample;
 
     public SF2Sample getSample() {
         return sample;
--- a/jdk/src/share/classes/com/sun/media/sound/SF2Modulator.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SF2Modulator.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +29,7 @@
  *
  * @author Karl Helgason
  */
-public class SF2Modulator {
+public final class SF2Modulator {
 
     public final static int SOURCE_NONE = 0;
     public final static int SOURCE_NOTE_ON_VELOCITY = 2;
@@ -49,11 +49,11 @@
     public final static int SOURCE_TYPE_SWITCH = 1024 * 3;
     public final static int TRANSFORM_LINEAR = 0;
     public final static int TRANSFORM_ABSOLUTE = 2;
-    protected int sourceOperator;
-    protected int destinationOperator;
-    protected short amount;
-    protected int amountSourceOperator;
-    protected int transportOperator;
+    int sourceOperator;
+    int destinationOperator;
+    short amount;
+    int amountSourceOperator;
+    int transportOperator;
 
     public short getAmount() {
         return amount;
--- a/jdk/src/share/classes/com/sun/media/sound/SF2Sample.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SF2Sample.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,18 +36,18 @@
  *
  * @author Karl Helgason
  */
-public class SF2Sample extends SoundbankResource {
+public final class SF2Sample extends SoundbankResource {
 
-    protected String name = "";
-    protected long startLoop = 0;
-    protected long endLoop = 0;
-    protected long sampleRate = 44100;
-    protected int originalPitch = 60;
-    protected byte pitchCorrection = 0;
-    protected int sampleLink = 0;
-    protected int sampleType = 0;
-    protected ModelByteBuffer data;
-    protected ModelByteBuffer data24;
+    String name = "";
+    long startLoop = 0;
+    long endLoop = 0;
+    long sampleRate = 44100;
+    int originalPitch = 60;
+    byte pitchCorrection = 0;
+    int sampleLink = 0;
+    int sampleType = 0;
+    ModelByteBuffer data;
+    ModelByteBuffer data24;
 
     public SF2Sample(Soundbank soundBank) {
         super(soundBank, null, AudioInputStream.class);
--- a/jdk/src/share/classes/com/sun/media/sound/SF2Soundbank.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SF2Soundbank.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -50,40 +50,40 @@
  *
  * @author Karl Helgason
  */
-public class SF2Soundbank implements Soundbank {
+public final class SF2Soundbank implements Soundbank {
 
     // version of the Sound Font RIFF file
-    protected int major = 2;
-    protected int minor = 1;
+    int major = 2;
+    int minor = 1;
     // target Sound Engine
-    protected String targetEngine = "EMU8000";
+    String targetEngine = "EMU8000";
     // Sound Font Bank Name
-    protected String name = "untitled";
+    String name = "untitled";
     // Sound ROM Name
-    protected String romName = null;
+    String romName = null;
     // Sound ROM Version
-    protected int romVersionMajor = -1;
-    protected int romVersionMinor = -1;
+    int romVersionMajor = -1;
+    int romVersionMinor = -1;
     // Date of Creation of the Bank
-    protected String creationDate = null;
+    String creationDate = null;
     // Sound Designers and Engineers for the Bank
-    protected String engineers = null;
+    String engineers = null;
     // Product for which the Bank was intended
-    protected String product = null;
+    String product = null;
     // Copyright message
-    protected String copyright = null;
+    String copyright = null;
     // Comments
-    protected String comments = null;
+    String comments = null;
     // The SoundFont tools used to create and alter the bank
-    protected String tools = null;
+    String tools = null;
     // The Sample Data loaded from the SoundFont
     private ModelByteBuffer sampleData = null;
     private ModelByteBuffer sampleData24 = null;
     private File sampleFile = null;
     private boolean largeFormat = false;
-    private List<SF2Instrument> instruments = new ArrayList<SF2Instrument>();
-    private List<SF2Layer> layers = new ArrayList<SF2Layer>();
-    private List<SF2Sample> samples = new ArrayList<SF2Sample>();
+    private final List<SF2Instrument> instruments = new ArrayList<SF2Instrument>();
+    private final List<SF2Layer> layers = new ArrayList<SF2Layer>();
+    private final List<SF2Sample> samples = new ArrayList<SF2Sample>();
 
     public SF2Soundbank() {
     }
--- a/jdk/src/share/classes/com/sun/media/sound/SF2SoundbankReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SF2SoundbankReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,7 +38,7 @@
  *
  * @author Karl Helgason
  */
-public class SF2SoundbankReader extends SoundbankReader {
+public final class SF2SoundbankReader extends SoundbankReader {
 
     public Soundbank getSoundbank(URL url)
             throws InvalidMidiDataException, IOException {
--- a/jdk/src/share/classes/com/sun/media/sound/SoftAbstractResampler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftAbstractResampler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -67,7 +67,7 @@
         float samplerateconv = 1;
         float pitchcorrection = 0;
 
-        public ModelAbstractResamplerStream() {
+        ModelAbstractResamplerStream() {
             pad = getPadding();
             pad2 = getPadding() * 2;
             ibuffer = new float[2][sector_size + pad2];
@@ -384,7 +384,7 @@
             float in_end, float[] pitch, float pitchstep, float[] out,
             int[] out_offset, int out_end);
 
-    public SoftResamplerStreamer openStreamer() {
+    public final SoftResamplerStreamer openStreamer() {
         return new ModelAbstractResamplerStream();
     }
 }
--- a/jdk/src/share/classes/com/sun/media/sound/SoftAudioBuffer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftAudioBuffer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,7 +33,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftAudioBuffer {
+public final class SoftAudioBuffer {
 
     private int size;
     private float[] buffer;
--- a/jdk/src/share/classes/com/sun/media/sound/SoftAudioPusher.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftAudioPusher.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,13 +34,13 @@
  *
  * @author Karl Helgason
  */
-public class SoftAudioPusher implements Runnable {
+public final class SoftAudioPusher implements Runnable {
 
     private volatile boolean active = false;
     private SourceDataLine sourceDataLine = null;
     private Thread audiothread;
-    private AudioInputStream ais;
-    private byte[] buffer;
+    private final AudioInputStream ais;
+    private final byte[] buffer;
 
     public SoftAudioPusher(SourceDataLine sourceDataLine, AudioInputStream ais,
             int workbuffersizer) {
--- a/jdk/src/share/classes/com/sun/media/sound/SoftChannel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftChannel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -39,7 +39,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftChannel implements MidiChannel, ModelDirectedPlayer {
+public final class SoftChannel implements MidiChannel, ModelDirectedPlayer {
 
     private static boolean[] dontResetControls = new boolean[128];
     static {
@@ -90,15 +90,15 @@
     private static final int RPN_NULL_VALUE = (127 << 7) + 127;
     private int rpn_control = RPN_NULL_VALUE;
     private int nrpn_control = RPN_NULL_VALUE;
-    protected double portamento_time = 1; // keyschanges per control buffer time
-    protected int[] portamento_lastnote = new int[128];
-    protected int portamento_lastnote_ix = 0;
+    double portamento_time = 1; // keyschanges per control buffer time
+    int[] portamento_lastnote = new int[128];
+    int portamento_lastnote_ix = 0;
     private boolean portamento = false;
     private boolean mono = false;
     private boolean mute = false;
     private boolean solo = false;
     private boolean solomute = false;
-    private Object control_mutex;
+    private final Object control_mutex;
     private int channel;
     private SoftVoice[] voices;
     private int bank;
@@ -111,21 +111,21 @@
     private int pitchbend;
     private double[] co_midi_pitch = new double[1];
     private double[] co_midi_channel_pressure = new double[1];
-    protected SoftTuning tuning = new SoftTuning();
-    protected int tuning_bank = 0;
-    protected int tuning_program = 0;
-    protected SoftInstrument current_instrument = null;
-    protected ModelChannelMixer current_mixer = null;
-    protected ModelDirector current_director = null;
+    SoftTuning tuning = new SoftTuning();
+    int tuning_bank = 0;
+    int tuning_program = 0;
+    SoftInstrument current_instrument = null;
+    ModelChannelMixer current_mixer = null;
+    ModelDirector current_director = null;
 
     // Controller Destination Settings
-    protected int cds_control_number = -1;
-    protected ModelConnectionBlock[] cds_control_connections = null;
-    protected ModelConnectionBlock[] cds_channelpressure_connections = null;
-    protected ModelConnectionBlock[] cds_polypressure_connections = null;
-    protected boolean sustain = false;
-    protected boolean[][] keybasedcontroller_active = null;
-    protected double[][] keybasedcontroller_value = null;
+    int cds_control_number = -1;
+    ModelConnectionBlock[] cds_control_connections = null;
+    ModelConnectionBlock[] cds_channelpressure_connections = null;
+    ModelConnectionBlock[] cds_polypressure_connections = null;
+    boolean sustain = false;
+    boolean[][] keybasedcontroller_active = null;
+    double[][] keybasedcontroller_value = null;
 
     private class MidiControlObject implements SoftControl {
         double[] pitch = co_midi_pitch;
@@ -336,7 +336,7 @@
 
     }
 
-    protected void initVoice(SoftVoice voice, SoftPerformer p, int voiceID,
+    void initVoice(SoftVoice voice, SoftPerformer p, int voiceID,
             int noteNumber, int velocity, int delay, ModelConnectionBlock[] connectionBlocks,
             ModelChannelMixer channelmixer, boolean releaseTriggered) {
         if (voice.active) {
@@ -414,7 +414,7 @@
     /* A special noteOn with delay parameter, which is used to
      * start note within control buffers.
      */
-    protected void noteOn(int noteNumber, int velocity, int delay) {
+    void noteOn(int noteNumber, int velocity, int delay) {
         noteNumber = restrict7Bit(noteNumber);
         velocity = restrict7Bit(velocity);
         noteOn_internal(noteNumber, velocity, delay);
@@ -707,7 +707,7 @@
         }
     }
 
-    protected void applyInstrumentCustomization() {
+    void applyInstrumentCustomization() {
         if (cds_control_connections == null
                 && cds_channelpressure_connections == null
                 && cds_polypressure_connections == null) {
--- a/jdk/src/share/classes/com/sun/media/sound/SoftChannelProxy.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftChannelProxy.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,7 +32,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftChannelProxy implements MidiChannel {
+public final class SoftChannelProxy implements MidiChannel {
 
     private MidiChannel channel = null;
 
--- a/jdk/src/share/classes/com/sun/media/sound/SoftChorus.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftChorus.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,11 +32,11 @@
  *
  * @author Karl Helgason
  */
-public class SoftChorus implements SoftAudioProcessor {
+public final class SoftChorus implements SoftAudioProcessor {
 
     private static class VariableDelay {
 
-        private float[] delaybuffer;
+        private final float[] delaybuffer;
         private int rovepos = 0;
         private float gain = 1;
         private float rgain = 0;
@@ -44,7 +44,7 @@
         private float lastdelay = 0;
         private float feedback = 0;
 
-        public VariableDelay(int maxbuffersize) {
+        VariableDelay(int maxbuffersize) {
             delaybuffer = new float[maxbuffersize];
         }
 
@@ -119,10 +119,10 @@
         private double phase_step = 0;
         private double depth = 0;
         private VariableDelay vdelay;
-        private double samplerate;
-        private double controlrate;
+        private final double samplerate;
+        private final double controlrate;
 
-        public LFODelay(double samplerate, double controlrate) {
+        LFODelay(double samplerate, double controlrate) {
             this.samplerate = samplerate;
             this.controlrate = controlrate;
             // vdelay = new VariableDelay((int)(samplerate*4));
--- a/jdk/src/share/classes/com/sun/media/sound/SoftCubicResampler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftCubicResampler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +29,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftCubicResampler extends SoftAbstractResampler {
+public final class SoftCubicResampler extends SoftAbstractResampler {
 
     public int getPadding() {
         return 3;
--- a/jdk/src/share/classes/com/sun/media/sound/SoftEnvelopeGenerator.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftEnvelopeGenerator.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +29,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftEnvelopeGenerator implements SoftProcess {
+public final class SoftEnvelopeGenerator implements SoftProcess {
 
     public final static int EG_OFF = 0;
     public final static int EG_DELAY = 1;
@@ -42,23 +42,23 @@
     public final static int EG_END = 8;
     int max_count = 10;
     int used_count = 0;
-    private int[] stage = new int[max_count];
-    private int[] stage_ix = new int[max_count];
-    private double[] stage_v = new double[max_count];
-    private int[] stage_count = new int[max_count];
-    private double[][] on = new double[max_count][1];
-    private double[][] active = new double[max_count][1];
-    private double[][] out = new double[max_count][1];
-    private double[][] delay = new double[max_count][1];
-    private double[][] attack = new double[max_count][1];
-    private double[][] hold = new double[max_count][1];
-    private double[][] decay = new double[max_count][1];
-    private double[][] sustain = new double[max_count][1];
-    private double[][] release = new double[max_count][1];
-    private double[][] shutdown = new double[max_count][1];
-    private double[][] release2 = new double[max_count][1];
-    private double[][] attack2 = new double[max_count][1];
-    private double[][] decay2 = new double[max_count][1];
+    private final int[] stage = new int[max_count];
+    private final int[] stage_ix = new int[max_count];
+    private final double[] stage_v = new double[max_count];
+    private final int[] stage_count = new int[max_count];
+    private final double[][] on = new double[max_count][1];
+    private final double[][] active = new double[max_count][1];
+    private final double[][] out = new double[max_count][1];
+    private final double[][] delay = new double[max_count][1];
+    private final double[][] attack = new double[max_count][1];
+    private final double[][] hold = new double[max_count][1];
+    private final double[][] decay = new double[max_count][1];
+    private final double[][] sustain = new double[max_count][1];
+    private final double[][] release = new double[max_count][1];
+    private final double[][] shutdown = new double[max_count][1];
+    private final double[][] release2 = new double[max_count][1];
+    private final double[][] attack2 = new double[max_count][1];
+    private final double[][] decay2 = new double[max_count][1];
     private double control_time = 0;
 
     public void reset() {
--- a/jdk/src/share/classes/com/sun/media/sound/SoftFilter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftFilter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,7 +33,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftFilter {
+public final class SoftFilter {
 
     public final static int FILTERTYPE_LP6 = 0x00;
     public final static int FILTERTYPE_LP12 = 0x01;
@@ -55,7 +55,7 @@
     // 0x30 = NP, Notch or Band Elimination Filter
     //
     private int filtertype = FILTERTYPE_LP6;
-    private float samplerate;
+    private final float samplerate;
     private float x1;
     private float x2;
     private float y1;
--- a/jdk/src/share/classes/com/sun/media/sound/SoftInstrument.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftInstrument.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,12 +32,12 @@
  *
  * @author Karl Helgason
  */
-public class SoftInstrument extends Instrument {
+public final class SoftInstrument extends Instrument {
 
     private SoftPerformer[] performers;
     private ModelPerformer[] modelperformers;
-    private Object data;
-    private ModelInstrument ins;
+    private final Object data;
+    private final ModelInstrument ins;
 
     public SoftInstrument(ModelInstrument ins) {
         super(ins.getSoundbank(), ins.getPatch(), ins.getName(),
--- a/jdk/src/share/classes/com/sun/media/sound/SoftJitterCorrector.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftJitterCorrector.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,7 +36,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftJitterCorrector extends AudioInputStream {
+public final class SoftJitterCorrector extends AudioInputStream {
 
     private static class JitterStream extends InputStream {
 
@@ -48,7 +48,7 @@
         int writepos = 0;
         int readpos = 0;
         byte[][] buffers;
-        Object buffers_mutex = new Object();
+        private final Object buffers_mutex = new Object();
 
         // Adapative Drift Statistics
         int w_count = 1000;
@@ -112,7 +112,7 @@
             }
         }
 
-        public JitterStream(AudioInputStream s, int buffersize,
+        JitterStream(AudioInputStream s, int buffersize,
                 int smallbuffersize) {
             this.w_count = 10 * (buffersize / smallbuffersize);
             if (w_count < 100)
--- a/jdk/src/share/classes/com/sun/media/sound/SoftLanczosResampler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftLanczosResampler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +29,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftLanczosResampler extends SoftAbstractResampler {
+public final class SoftLanczosResampler extends SoftAbstractResampler {
 
     float[][] sinc_table;
     int sinc_table_fsize = 2000;
--- a/jdk/src/share/classes/com/sun/media/sound/SoftLimiter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftLimiter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,7 +30,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftLimiter implements SoftAudioProcessor {
+public final class SoftLimiter implements SoftAudioProcessor {
 
     float lastmax = 0;
     float gain = 1;
--- a/jdk/src/share/classes/com/sun/media/sound/SoftLinearResampler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftLinearResampler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +29,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftLinearResampler extends SoftAbstractResampler {
+public final class SoftLinearResampler extends SoftAbstractResampler {
 
     public int getPadding() {
         return 2;
--- a/jdk/src/share/classes/com/sun/media/sound/SoftLinearResampler2.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftLinearResampler2.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,7 +31,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftLinearResampler2 extends SoftAbstractResampler {
+public final class SoftLinearResampler2 extends SoftAbstractResampler {
 
     public int getPadding() {
         return 2;
--- a/jdk/src/share/classes/com/sun/media/sound/SoftLowFrequencyOscillator.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftLowFrequencyOscillator.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,21 +29,21 @@
  *
  * @author Karl Helgason
  */
-public class SoftLowFrequencyOscillator implements SoftProcess {
+public final class SoftLowFrequencyOscillator implements SoftProcess {
 
-    private int max_count = 10;
+    private final int max_count = 10;
     private int used_count = 0;
-    private double[][] out = new double[max_count][1];
-    private double[][] delay = new double[max_count][1];
-    private double[][] delay2 = new double[max_count][1];
-    private double[][] freq = new double[max_count][1];
-    private int[] delay_counter = new int[max_count];
-    private double[] sin_phase = new double[max_count];
-    private double[] sin_stepfreq = new double[max_count];
-    private double[] sin_step = new double[max_count];
+    private final double[][] out = new double[max_count][1];
+    private final double[][] delay = new double[max_count][1];
+    private final double[][] delay2 = new double[max_count][1];
+    private final double[][] freq = new double[max_count][1];
+    private final int[] delay_counter = new int[max_count];
+    private final double[] sin_phase = new double[max_count];
+    private final double[] sin_stepfreq = new double[max_count];
+    private final double[] sin_step = new double[max_count];
     private double control_time = 0;
     private double sin_factor = 0;
-    private static double PI2 = 2.0 * Math.PI;
+    private static final double PI2 = 2.0 * Math.PI;
 
     public SoftLowFrequencyOscillator() {
         // If sin_step is 0 then sin_stepfreq must be -INF
--- a/jdk/src/share/classes/com/sun/media/sound/SoftMainMixer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftMainMixer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,7 +43,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftMainMixer {
+public final class SoftMainMixer {
 
     // A private class thats contains a ModelChannelMixer and it's private buffers.
     // This becomes necessary when we want to have separate delay buffers for each channel mixer.
@@ -67,13 +67,13 @@
     public final static int CHANNEL_RIGHT_DRY = 11;
     public final static int CHANNEL_SCRATCH1 = 12;
     public final static int CHANNEL_SCRATCH2 = 13;
-    protected boolean active_sensing_on = false;
+    boolean active_sensing_on = false;
     private long msec_last_activity = -1;
     private boolean pusher_silent = false;
     private int pusher_silent_count = 0;
     private long sample_pos = 0;
-    protected boolean readfully = true;
-    private Object control_mutex;
+    boolean readfully = true;
+    private final Object control_mutex;
     private SoftSynthesizer synth;
     private float samplerate = 44100;
     private int nrofchannels = 2;
@@ -84,7 +84,7 @@
     private SoftAudioProcessor agc;
     private long msec_buffer_len = 0;
     private int buffer_len = 0;
-    protected TreeMap<Long, Object> midimessages = new TreeMap<Long, Object>();
+    TreeMap<Long, Object> midimessages = new TreeMap<Long, Object>();
     private int delay_midievent = 0;
     private int max_delay_midievent = 0;
     double last_volume_left = 1.0;
@@ -97,7 +97,7 @@
     private Set<SoftChannelMixerContainer> registeredMixers = null;
     private Set<ModelChannelMixer> stoppedMixers = null;
     private SoftChannelMixerContainer[] cur_registeredMixers = null;
-    protected SoftControl co_master = new SoftControl() {
+    SoftControl co_master = new SoftControl() {
 
         double[] balance = co_master_balance;
         double[] volume = co_master_volume;
@@ -438,7 +438,7 @@
         delay_midievent = 0;
     }
 
-    protected void processAudioBuffers() {
+    void processAudioBuffers() {
 
         if(synth.weakstream != null && synth.weakstream.silent_samples != 0)
         {
@@ -859,16 +859,16 @@
 
         InputStream in = new InputStream() {
 
-            private SoftAudioBuffer[] buffers = SoftMainMixer.this.buffers;
-            private int nrofchannels
+            private final SoftAudioBuffer[] buffers = SoftMainMixer.this.buffers;
+            private final int nrofchannels
                     = SoftMainMixer.this.synth.getFormat().getChannels();
-            private int buffersize = buffers[0].getSize();
-            private byte[] bbuffer = new byte[buffersize
+            private final int buffersize = buffers[0].getSize();
+            private final byte[] bbuffer = new byte[buffersize
                     * (SoftMainMixer.this.synth.getFormat()
                         .getSampleSizeInBits() / 8)
                     * nrofchannels];
             private int bbuffer_pos = 0;
-            private byte[] single = new byte[1];
+            private final byte[] single = new byte[1];
 
             public void fillBuffer() {
                 /*
--- a/jdk/src/share/classes/com/sun/media/sound/SoftMidiAudioFileReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftMidiAudioFileReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -50,7 +50,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftMidiAudioFileReader extends AudioFileReader {
+public final class SoftMidiAudioFileReader extends AudioFileReader {
 
     public static final Type MIDI = new Type("MIDI", "mid");
     private static AudioFormat format = new AudioFormat(44100, 16, 2, true, false);
--- a/jdk/src/share/classes/com/sun/media/sound/SoftMixingClip.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftMixingClip.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,7 +42,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftMixingClip extends SoftMixingDataLine implements Clip {
+public final class SoftMixingClip extends SoftMixingDataLine implements Clip {
 
     private AudioFormat format;
 
@@ -50,7 +50,7 @@
 
     private byte[] data;
 
-    private InputStream datastream = new InputStream() {
+    private final InputStream datastream = new InputStream() {
 
         public int read() throws IOException {
             byte[] b = new byte[1];
@@ -162,7 +162,7 @@
 
     private AudioFloatInputStream afis;
 
-    protected SoftMixingClip(SoftMixingMixer mixer, DataLine.Info info) {
+    SoftMixingClip(SoftMixingMixer mixer, DataLine.Info info) {
         super(mixer, info);
     }
 
--- a/jdk/src/share/classes/com/sun/media/sound/SoftMixingDataLine.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftMixingDataLine.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -50,22 +50,22 @@
             "Chorus Send") {
     };
 
-    protected static class AudioFloatInputStreamResampler extends
+    protected static final class AudioFloatInputStreamResampler extends
             AudioFloatInputStream {
 
-        private AudioFloatInputStream ais;
+        private final AudioFloatInputStream ais;
 
-        private AudioFormat targetFormat;
+        private final AudioFormat targetFormat;
 
         private float[] skipbuffer;
 
         private SoftAbstractResampler resampler;
 
-        private float[] pitch = new float[1];
+        private final float[] pitch = new float[1];
 
-        private float[] ibuffer2;
+        private final float[] ibuffer2;
 
-        private float[][] ibuffer;
+        private final float[][] ibuffer;
 
         private float ibuffer_index = 0;
 
@@ -75,15 +75,15 @@
 
         private float[][] cbuffer;
 
-        private int buffer_len = 512;
+        private final int buffer_len = 512;
 
-        private int pad;
+        private final int pad;
 
-        private int pad2;
+        private final int pad2;
 
-        private float[] ix = new float[1];
+        private final float[] ix = new float[1];
 
-        private int[] ox = new int[1];
+        private final int[] ox = new int[1];
 
         private float[][] mark_ibuffer = null;
 
@@ -294,7 +294,7 @@
 
     }
 
-    private class Gain extends FloatControl {
+    private final class Gain extends FloatControl {
 
         private Gain() {
 
@@ -308,7 +308,7 @@
         }
     }
 
-    private class Mute extends BooleanControl {
+    private final class Mute extends BooleanControl {
 
         private Mute() {
             super(BooleanControl.Type.MUTE, false, "True", "False");
@@ -320,7 +320,7 @@
         }
     }
 
-    private class ApplyReverb extends BooleanControl {
+    private final class ApplyReverb extends BooleanControl {
 
         private ApplyReverb() {
             super(BooleanControl.Type.APPLY_REVERB, false, "True", "False");
@@ -333,7 +333,7 @@
 
     }
 
-    private class Balance extends FloatControl {
+    private final class Balance extends FloatControl {
 
         private Balance() {
             super(FloatControl.Type.BALANCE, -1.0f, 1.0f, (1.0f / 128.0f), -1,
@@ -347,7 +347,7 @@
 
     }
 
-    private class Pan extends FloatControl {
+    private final class Pan extends FloatControl {
 
         private Pan() {
             super(FloatControl.Type.PAN, -1.0f, 1.0f, (1.0f / 128.0f), -1,
@@ -365,7 +365,7 @@
 
     }
 
-    private class ReverbSend extends FloatControl {
+    private final class ReverbSend extends FloatControl {
 
         private ReverbSend() {
             super(FloatControl.Type.REVERB_SEND, -80f, 6.0206f, 80f / 128.0f,
@@ -379,7 +379,7 @@
 
     }
 
-    private class ChorusSend extends FloatControl {
+    private final class ChorusSend extends FloatControl {
 
         private ChorusSend() {
             super(CHORUS_SEND, -80f, 6.0206f, 80f / 128.0f, -1, -80f, "dB",
@@ -393,43 +393,43 @@
 
     }
 
-    private Gain gain_control = new Gain();
+    private final Gain gain_control = new Gain();
 
-    private Mute mute_control = new Mute();
+    private final Mute mute_control = new Mute();
 
-    private Balance balance_control = new Balance();
+    private final Balance balance_control = new Balance();
 
-    private Pan pan_control = new Pan();
+    private final Pan pan_control = new Pan();
 
-    private ReverbSend reverbsend_control = new ReverbSend();
+    private final ReverbSend reverbsend_control = new ReverbSend();
 
-    private ChorusSend chorussend_control = new ChorusSend();
+    private final ChorusSend chorussend_control = new ChorusSend();
 
-    private ApplyReverb apply_reverb = new ApplyReverb();
+    private final ApplyReverb apply_reverb = new ApplyReverb();
 
-    private Control[] controls;
+    private final Control[] controls;
 
-    protected float leftgain = 1;
+    float leftgain = 1;
 
-    protected float rightgain = 1;
+    float rightgain = 1;
 
-    protected float eff1gain = 0;
+    float eff1gain = 0;
 
-    protected float eff2gain = 0;
+    float eff2gain = 0;
 
-    protected List<LineListener> listeners = new ArrayList<LineListener>();
+    List<LineListener> listeners = new ArrayList<LineListener>();
 
-    protected Object control_mutex;
+    final Object control_mutex;
 
-    protected SoftMixingMixer mixer;
+    SoftMixingMixer mixer;
 
-    protected DataLine.Info info;
+    DataLine.Info info;
 
     protected abstract void processControlLogic();
 
     protected abstract void processAudioLogic(SoftAudioBuffer[] buffers);
 
-    protected SoftMixingDataLine(SoftMixingMixer mixer, DataLine.Info info) {
+    SoftMixingDataLine(SoftMixingMixer mixer, DataLine.Info info) {
         this.mixer = mixer;
         this.info = info;
         this.control_mutex = mixer.control_mutex;
@@ -440,7 +440,7 @@
         calcVolume();
     }
 
-    protected void calcVolume() {
+    final void calcVolume() {
         synchronized (control_mutex) {
             double gain = Math.pow(10.0, gain_control.getValue() / 20.0);
             if (mute_control.getValue())
@@ -466,7 +466,7 @@
         }
     }
 
-    protected void sendEvent(LineEvent event) {
+    final void sendEvent(LineEvent event) {
         if (listeners.size() == 0)
             return;
         LineListener[] listener_array = listeners
@@ -476,23 +476,23 @@
         }
     }
 
-    public void addLineListener(LineListener listener) {
+    public final void addLineListener(LineListener listener) {
         synchronized (control_mutex) {
             listeners.add(listener);
         }
     }
 
-    public void removeLineListener(LineListener listener) {
+    public final void removeLineListener(LineListener listener) {
         synchronized (control_mutex) {
             listeners.add(listener);
         }
     }
 
-    public javax.sound.sampled.Line.Info getLineInfo() {
+    public final javax.sound.sampled.Line.Info getLineInfo() {
         return info;
     }
 
-    public Control getControl(Type control) {
+    public final Control getControl(Type control) {
         if (control != null) {
             for (int i = 0; i < controls.length; i++) {
                 if (controls[i].getType() == control) {
@@ -504,11 +504,11 @@
                 + control);
     }
 
-    public Control[] getControls() {
+    public final Control[] getControls() {
         return Arrays.copyOf(controls, controls.length);
     }
 
-    public boolean isControlSupported(Type control) {
+    public final boolean isControlSupported(Type control) {
         if (control != null) {
             for (int i = 0; i < controls.length; i++) {
                 if (controls[i].getType() == control) {
--- a/jdk/src/share/classes/com/sun/media/sound/SoftMixingMainMixer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftMixingMainMixer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,7 +37,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftMixingMainMixer {
+public final class SoftMixingMainMixer {
 
     public final static int CHANNEL_LEFT = 0;
 
@@ -63,23 +63,23 @@
 
     public final static int CHANNEL_CHANNELMIXER_RIGHT = 15;
 
-    private SoftMixingMixer mixer;
+    private final SoftMixingMixer mixer;
 
-    private AudioInputStream ais;
+    private final AudioInputStream ais;
 
-    private SoftAudioBuffer[] buffers;
+    private final SoftAudioBuffer[] buffers;
 
-    private SoftAudioProcessor reverb;
+    private final SoftAudioProcessor reverb;
 
-    private SoftAudioProcessor chorus;
+    private final SoftAudioProcessor chorus;
 
-    private SoftAudioProcessor agc;
+    private final SoftAudioProcessor agc;
 
-    private int nrofchannels;
+    private final int nrofchannels;
 
-    private Object control_mutex;
+    private final Object control_mutex;
 
-    private List<SoftMixingDataLine> openLinesList = new ArrayList<SoftMixingDataLine>();
+    private final List<SoftMixingDataLine> openLinesList = new ArrayList<SoftMixingDataLine>();
 
     private SoftMixingDataLine[] openLines = new SoftMixingDataLine[0];
 
@@ -87,7 +87,7 @@
         return ais;
     }
 
-    protected void processAudioBuffers() {
+    void processAudioBuffers() {
         for (int i = 0; i < buffers.length; i++) {
             buffers[i].clear();
         }
@@ -162,20 +162,20 @@
 
         InputStream in = new InputStream() {
 
-            private SoftAudioBuffer[] buffers = SoftMixingMainMixer.this.buffers;
+            private final SoftAudioBuffer[] buffers = SoftMixingMainMixer.this.buffers;
 
-            private int nrofchannels = SoftMixingMainMixer.this.mixer
+            private final int nrofchannels = SoftMixingMainMixer.this.mixer
                     .getFormat().getChannels();
 
-            private int buffersize = buffers[0].getSize();
+            private final int buffersize = buffers[0].getSize();
 
-            private byte[] bbuffer = new byte[buffersize
+            private final byte[] bbuffer = new byte[buffersize
                     * (SoftMixingMainMixer.this.mixer.getFormat()
                             .getSampleSizeInBits() / 8) * nrofchannels];
 
             private int bbuffer_pos = 0;
 
-            private byte[] single = new byte[1];
+            private final byte[] single = new byte[1];
 
             public void fillBuffer() {
                 processAudioBuffers();
--- a/jdk/src/share/classes/com/sun/media/sound/SoftMixingMixer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftMixingMixer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -48,27 +48,27 @@
  *
  * @author Karl Helgason
  */
-public class SoftMixingMixer implements Mixer {
+public final class SoftMixingMixer implements Mixer {
 
     private static class Info extends Mixer.Info {
-        public Info() {
+        Info() {
             super(INFO_NAME, INFO_VENDOR, INFO_DESCRIPTION, INFO_VERSION);
         }
     }
 
-    protected static final String INFO_NAME = "Gervill Sound Mixer";
+    static final String INFO_NAME = "Gervill Sound Mixer";
 
-    protected static final String INFO_VENDOR = "OpenJDK Proposal";
+    static final String INFO_VENDOR = "OpenJDK Proposal";
 
-    protected static final String INFO_DESCRIPTION = "Software Sound Mixer";
+    static final String INFO_DESCRIPTION = "Software Sound Mixer";
 
-    protected static final String INFO_VERSION = "1.0";
+    static final String INFO_VERSION = "1.0";
 
-    protected final static Mixer.Info info = new Info();
+    static final Mixer.Info info = new Info();
 
-    protected Object control_mutex = this;
+    final Object control_mutex = this;
 
-    protected boolean implicitOpen = false;
+    boolean implicitOpen = false;
 
     private boolean open = false;
 
@@ -82,15 +82,15 @@
 
     private AudioInputStream pusher_stream = null;
 
-    private float controlrate = 147f;
+    private final float controlrate = 147f;
 
-    private long latency = 100000; // 100 msec
+    private final long latency = 100000; // 100 msec
 
-    private boolean jitter_correction = false;
+    private final boolean jitter_correction = false;
 
-    private List<LineListener> listeners = new ArrayList<LineListener>();
+    private final List<LineListener> listeners = new ArrayList<LineListener>();
 
-    private javax.sound.sampled.Line.Info[] sourceLineInfo;
+    private final javax.sound.sampled.Line.Info[] sourceLineInfo;
 
     public SoftMixingMixer() {
 
@@ -516,11 +516,11 @@
         }
     }
 
-    protected float getControlRate() {
+    float getControlRate() {
         return controlrate;
     }
 
-    protected SoftMixingMainMixer getMainMixer() {
+    SoftMixingMainMixer getMainMixer() {
         if (!isOpen())
             return null;
         return mainmixer;
--- a/jdk/src/share/classes/com/sun/media/sound/SoftMixingMixerProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftMixingMixerProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,13 +33,13 @@
  *
  * @author Karl Helgason
  */
-public class SoftMixingMixerProvider extends MixerProvider {
+public final class SoftMixingMixerProvider extends MixerProvider {
 
     static SoftMixingMixer globalmixer = null;
 
     static Thread lockthread = null;
 
-    protected final static Object mutex = new Object();
+    static final Object mutex = new Object();
 
     public Mixer getMixer(Info info) {
         if (!(info == null || info == SoftMixingMixer.info)) {
--- a/jdk/src/share/classes/com/sun/media/sound/SoftMixingSourceDataLine.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftMixingSourceDataLine.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,8 +41,8 @@
  *
  * @author Karl Helgason
  */
-public class SoftMixingSourceDataLine extends SoftMixingDataLine implements
-        SourceDataLine {
+public final class SoftMixingSourceDataLine extends SoftMixingDataLine
+        implements SourceDataLine {
 
     private boolean open = false;
 
@@ -72,7 +72,7 @@
             AudioFloatInputStream {
         AudioFloatInputStream ais;
 
-        public NonBlockingFloatInputStream(AudioFloatInputStream ais) {
+        NonBlockingFloatInputStream(AudioFloatInputStream ais) {
             this.ais = ais;
         }
 
@@ -120,7 +120,7 @@
 
     }
 
-    protected SoftMixingSourceDataLine(SoftMixingMixer mixer, DataLine.Info info) {
+    SoftMixingSourceDataLine(SoftMixingMixer mixer, DataLine.Info info) {
         super(mixer, info);
     }
 
--- a/jdk/src/share/classes/com/sun/media/sound/SoftPerformer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftPerformer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,7 +37,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftPerformer {
+public final class SoftPerformer {
 
     static ModelConnectionBlock[] defaultconnections
             = new ModelConnectionBlock[42];
--- a/jdk/src/share/classes/com/sun/media/sound/SoftPointResampler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftPointResampler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,7 +29,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftPointResampler extends SoftAbstractResampler {
+public final class SoftPointResampler extends SoftAbstractResampler {
 
     public int getPadding() {
         return 100;
--- a/jdk/src/share/classes/com/sun/media/sound/SoftProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,10 +34,10 @@
  *
  * @author Karl Helgason
  */
-public class SoftProvider extends MidiDeviceProvider {
+public final class SoftProvider extends MidiDeviceProvider {
 
-    protected final static Info softinfo = SoftSynthesizer.info;
-    private static Info[] softinfos = {softinfo};
+    static final Info softinfo = SoftSynthesizer.info;
+    private static final Info[] softinfos = {softinfo};
 
     public MidiDevice.Info[] getDeviceInfo() {
         return Arrays.copyOf(softinfos, softinfos.length);
--- a/jdk/src/share/classes/com/sun/media/sound/SoftReceiver.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftReceiver.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,13 +36,13 @@
  *
  * @author Karl Helgason
  */
-public class SoftReceiver implements MidiDeviceReceiver {
+public final class SoftReceiver implements MidiDeviceReceiver {
 
-    protected boolean open = true;
-    private Object control_mutex;
-    private SoftSynthesizer synth;
-    protected TreeMap<Long, Object> midimessages;
-    protected SoftMainMixer mainmixer;
+    boolean open = true;
+    private final Object control_mutex;
+    private final SoftSynthesizer synth;
+    TreeMap<Long, Object> midimessages;
+    SoftMainMixer mainmixer;
 
     public SoftReceiver(SoftSynthesizer synth) {
         this.control_mutex = synth.control_mutex;
--- a/jdk/src/share/classes/com/sun/media/sound/SoftReverb.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftReverb.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,14 +33,14 @@
  *
  * @author Karl Helgason
  */
-public class SoftReverb implements SoftAudioProcessor {
+public final class SoftReverb implements SoftAudioProcessor {
 
     private final static class Delay {
 
         private float[] delaybuffer;
         private int rovepos = 0;
 
-        public Delay() {
+        Delay() {
             delaybuffer = null;
         }
 
@@ -77,7 +77,7 @@
         private int rovepos = 0;
         private float feedback;
 
-        public AllPass(int size) {
+        AllPass(int size) {
             delaybuffer = new float[size];
             delaybuffersize = size;
         }
@@ -127,7 +127,7 @@
         private float filtercoeff1 = 0;
         private float filtercoeff2 = 1;
 
-        public Comb(int size) {
+        Comb(int size) {
             delaybuffer = new float[size];
             delaybuffersize = size;
         }
--- a/jdk/src/share/classes/com/sun/media/sound/SoftShortMessage.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftShortMessage.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,7 +32,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftShortMessage extends ShortMessage {
+public final class SoftShortMessage extends ShortMessage {
 
     int channel = 0;
 
--- a/jdk/src/share/classes/com/sun/media/sound/SoftSincResampler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftSincResampler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,7 +31,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftSincResampler extends SoftAbstractResampler {
+public final class SoftSincResampler extends SoftAbstractResampler {
 
     float[][][] sinc_table;
     int sinc_scale_size = 100;
--- a/jdk/src/share/classes/com/sun/media/sound/SoftSynthesizer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftSynthesizer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -66,10 +66,10 @@
  *
  * @author Karl Helgason
  */
-public class SoftSynthesizer implements AudioSynthesizer,
+public final class SoftSynthesizer implements AudioSynthesizer,
         ReferenceCountingDevice {
 
-    protected static class WeakAudioStream extends InputStream
+    protected static final class WeakAudioStream extends InputStream
     {
         private volatile AudioInputStream stream;
         public SoftAudioPusher pusher = null;
@@ -166,39 +166,39 @@
     }
 
     private static class Info extends MidiDevice.Info {
-        public Info() {
+        Info() {
             super(INFO_NAME, INFO_VENDOR, INFO_DESCRIPTION, INFO_VERSION);
         }
     }
 
-    protected static final String INFO_NAME = "Gervill";
-    protected static final String INFO_VENDOR = "OpenJDK";
-    protected static final String INFO_DESCRIPTION = "Software MIDI Synthesizer";
-    protected static final String INFO_VERSION = "1.0";
-    protected final static MidiDevice.Info info = new Info();
+    static final String INFO_NAME = "Gervill";
+    static final String INFO_VENDOR = "OpenJDK";
+    static final String INFO_DESCRIPTION = "Software MIDI Synthesizer";
+    static final String INFO_VERSION = "1.0";
+    final static MidiDevice.Info info = new Info();
 
     private static SourceDataLine testline = null;
 
     private static Soundbank defaultSoundBank = null;
 
-    protected WeakAudioStream weakstream = null;
+    WeakAudioStream weakstream = null;
 
-    protected Object control_mutex = this;
+    final Object control_mutex = this;
 
-    protected int voiceIDCounter = 0;
+    int voiceIDCounter = 0;
 
     // 0: default
     // 1: DLS Voice Allocation
-    protected int voice_allocation_mode = 0;
+    int voice_allocation_mode = 0;
 
-    protected boolean load_default_soundbank = false;
-    protected boolean reverb_light = true;
-    protected boolean reverb_on = true;
-    protected boolean chorus_on = true;
-    protected boolean agc_on = true;
+    boolean load_default_soundbank = false;
+    boolean reverb_light = true;
+    boolean reverb_on = true;
+    boolean chorus_on = true;
+    boolean agc_on = true;
 
-    protected SoftChannel[] channels;
-    protected SoftChannelProxy[] external_channels = null;
+    SoftChannel[] channels;
+    SoftChannelProxy[] external_channels = null;
 
     private boolean largemode = false;
 
@@ -371,7 +371,7 @@
         this.format = format;
     }
 
-    protected void removeReceiver(Receiver recv) {
+    void removeReceiver(Receiver recv) {
         boolean perform_close = false;
         synchronized (control_mutex) {
             if (recvslist.remove(recv)) {
@@ -383,13 +383,13 @@
             close();
     }
 
-    protected SoftMainMixer getMainMixer() {
+    SoftMainMixer getMainMixer() {
         if (!isOpen())
             return null;
         return mainmixer;
     }
 
-    protected SoftInstrument findInstrument(int program, int bank, int channel) {
+    SoftInstrument findInstrument(int program, int bank, int channel) {
 
         // Add support for GM2 banks 0x78 and 0x79
         // as specified in DLS 2.2 in Section 1.4.6
@@ -450,31 +450,31 @@
         return null;
     }
 
-    protected int getVoiceAllocationMode() {
+    int getVoiceAllocationMode() {
         return voice_allocation_mode;
     }
 
-    protected int getGeneralMidiMode() {
+    int getGeneralMidiMode() {
         return gmmode;
     }
 
-    protected void setGeneralMidiMode(int gmmode) {
+    void setGeneralMidiMode(int gmmode) {
         this.gmmode = gmmode;
     }
 
-    protected int getDeviceID() {
+    int getDeviceID() {
         return deviceid;
     }
 
-    protected float getControlRate() {
+    float getControlRate() {
         return controlrate;
     }
 
-    protected SoftVoice[] getVoices() {
+    SoftVoice[] getVoices() {
         return voices;
     }
 
-    protected SoftTuning getTuning(Patch patch) {
+    SoftTuning getTuning(Patch patch) {
         String t_id = patchToString(patch);
         SoftTuning tuning = tunings.get(t_id);
         if (tuning == null) {
--- a/jdk/src/share/classes/com/sun/media/sound/SoftTuning.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftTuning.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,10 +35,10 @@
  *
  * @author Karl Helgason
  */
-public class SoftTuning {
+public final class SoftTuning {
 
     private String name = null;
-    private double[] tuning = new double[128];
+    private final double[] tuning = new double[128];
     private Patch patch = null;
 
     public SoftTuning() {
--- a/jdk/src/share/classes/com/sun/media/sound/SoftVoice.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SoftVoice.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,7 +36,7 @@
  *
  * @author Karl Helgason
  */
-public class SoftVoice extends VoiceStatus {
+public final class SoftVoice extends VoiceStatus {
 
     public int exclusiveClass = 0;
     public boolean releaseTriggered = false;
@@ -44,32 +44,32 @@
     private int noteOn_velocity = 0;
     private int noteOff_velocity = 0;
     private int delay = 0;
-    protected ModelChannelMixer channelmixer = null;
-    protected double tunedKey = 0;
-    protected SoftTuning tuning = null;
-    protected SoftChannel stealer_channel = null;
-    protected ModelConnectionBlock[] stealer_extendedConnectionBlocks = null;
-    protected SoftPerformer stealer_performer = null;
-    protected ModelChannelMixer stealer_channelmixer = null;
-    protected int stealer_voiceID = -1;
-    protected int stealer_noteNumber = 0;
-    protected int stealer_velocity = 0;
-    protected boolean stealer_releaseTriggered = false;
-    protected int voiceID = -1;
-    protected boolean sustain = false;
-    protected boolean sostenuto = false;
-    protected boolean portamento = false;
-    private SoftFilter filter_left;
-    private SoftFilter filter_right;
-    private SoftProcess eg = new SoftEnvelopeGenerator();
-    private SoftProcess lfo = new SoftLowFrequencyOscillator();
-    protected Map<String, SoftControl> objects =
+    ModelChannelMixer channelmixer = null;
+    double tunedKey = 0;
+    SoftTuning tuning = null;
+    SoftChannel stealer_channel = null;
+    ModelConnectionBlock[] stealer_extendedConnectionBlocks = null;
+    SoftPerformer stealer_performer = null;
+    ModelChannelMixer stealer_channelmixer = null;
+    int stealer_voiceID = -1;
+    int stealer_noteNumber = 0;
+    int stealer_velocity = 0;
+    boolean stealer_releaseTriggered = false;
+    int voiceID = -1;
+    boolean sustain = false;
+    boolean sostenuto = false;
+    boolean portamento = false;
+    private final SoftFilter filter_left;
+    private final SoftFilter filter_right;
+    private final SoftProcess eg = new SoftEnvelopeGenerator();
+    private final SoftProcess lfo = new SoftLowFrequencyOscillator();
+    Map<String, SoftControl> objects =
             new HashMap<String, SoftControl>();
-    protected SoftSynthesizer synthesizer;
-    protected SoftInstrument instrument;
-    protected SoftPerformer performer;
-    protected SoftChannel softchannel = null;
-    protected boolean on = false;
+    SoftSynthesizer synthesizer;
+    SoftInstrument instrument;
+    SoftPerformer performer;
+    SoftChannel softchannel = null;
+    boolean on = false;
     private boolean audiostarted = false;
     private boolean started = false;
     private boolean stopping = false;
@@ -87,7 +87,7 @@
     private float last_out_mixer_right = 0;
     private float last_out_mixer_effect1 = 0;
     private float last_out_mixer_effect2 = 0;
-    protected ModelConnectionBlock[] extendedConnectionBlocks = null;
+    ModelConnectionBlock[] extendedConnectionBlocks = null;
     private ModelConnectionBlock[] connections;
     // Last value added to destination
     private double[] connections_last = new double[50];
@@ -100,10 +100,10 @@
     private boolean soundoff = false;
     private float lastMuteValue = 0;
     private float lastSoloMuteValue = 0;
-    protected double[] co_noteon_keynumber = new double[1];
-    protected double[] co_noteon_velocity = new double[1];
-    protected double[] co_noteon_on = new double[1];
-    private SoftControl co_noteon = new SoftControl() {
+    double[] co_noteon_keynumber = new double[1];
+    double[] co_noteon_velocity = new double[1];
+    double[] co_noteon_on = new double[1];
+    private final SoftControl co_noteon = new SoftControl() {
         double[] keynumber = co_noteon_keynumber;
         double[] velocity = co_noteon_velocity;
         double[] on = co_noteon_on;
@@ -119,13 +119,13 @@
             return null;
         }
     };
-    private double[] co_mixer_active = new double[1];
-    private double[] co_mixer_gain = new double[1];
-    private double[] co_mixer_pan = new double[1];
-    private double[] co_mixer_balance = new double[1];
-    private double[] co_mixer_reverb = new double[1];
-    private double[] co_mixer_chorus = new double[1];
-    private SoftControl co_mixer = new SoftControl() {
+    private final double[] co_mixer_active = new double[1];
+    private final double[] co_mixer_gain = new double[1];
+    private final double[] co_mixer_pan = new double[1];
+    private final double[] co_mixer_balance = new double[1];
+    private final double[] co_mixer_reverb = new double[1];
+    private final double[] co_mixer_chorus = new double[1];
+    private final SoftControl co_mixer = new SoftControl() {
         double[] active = co_mixer_active;
         double[] gain = co_mixer_gain;
         double[] pan = co_mixer_pan;
@@ -150,8 +150,8 @@
             return null;
         }
     };
-    private double[] co_osc_pitch = new double[1];
-    private SoftControl co_osc = new SoftControl() {
+    private final double[] co_osc_pitch = new double[1];
+    private final SoftControl co_osc = new SoftControl() {
         double[] pitch = co_osc_pitch;
         public double[] get(int instance, String name) {
             if (name == null)
@@ -161,10 +161,10 @@
             return null;
         }
     };
-    private double[] co_filter_freq = new double[1];
-    private double[] co_filter_type = new double[1];
-    private double[] co_filter_q = new double[1];
-    private SoftControl co_filter = new SoftControl() {
+    private final double[] co_filter_freq = new double[1];
+    private final double[] co_filter_type = new double[1];
+    private final double[] co_filter_q = new double[1];
+    private final SoftControl co_filter = new SoftControl() {
         double[] freq = co_filter_freq;
         double[] ftype = co_filter_type;
         double[] q = co_filter_q;
@@ -180,8 +180,8 @@
             return null;
         }
     };
-    protected SoftResamplerStreamer resampler;
-    private int nrofchannels;
+    SoftResamplerStreamer resampler;
+    private final int nrofchannels;
 
     public SoftVoice(SoftSynthesizer synth) {
         synthesizer = synth;
@@ -278,7 +278,7 @@
         // co_mixer_gain[0] = 0;
     }
 
-    protected void updateTuning(SoftTuning newtuning) {
+    void updateTuning(SoftTuning newtuning) {
         tuning = newtuning;
         tunedKey = tuning.getTuning(note) / 100.0;
         if (!portamento) {
@@ -293,12 +293,12 @@
         }
     }
 
-    protected void setNote(int noteNumber) {
+    void setNote(int noteNumber) {
         note = noteNumber;
         tunedKey = tuning.getTuning(noteNumber) / 100.0;
     }
 
-    protected void noteOn(int noteNumber, int velocity, int delay) {
+    void noteOn(int noteNumber, int velocity, int delay) {
 
         sustain = false;
         sostenuto = false;
@@ -435,7 +435,7 @@
 
     }
 
-    protected void setPolyPressure(int pressure) {
+    void setPolyPressure(int pressure) {
         if(performer == null)
             return;
         int[] c = performer.midi_connections[2];
@@ -445,7 +445,7 @@
             processConnection(c[i]);
     }
 
-    protected void setChannelPressure(int pressure) {
+    void setChannelPressure(int pressure) {
         if(performer == null)
             return;
         int[] c = performer.midi_connections[1];
@@ -455,7 +455,7 @@
             processConnection(c[i]);
     }
 
-    protected void controlChange(int controller, int value) {
+    void controlChange(int controller, int value) {
         if(performer == null)
             return;
         int[] c = performer.midi_ctrl_connections[controller];
@@ -465,7 +465,7 @@
             processConnection(c[i]);
     }
 
-    protected void nrpnChange(int controller, int value) {
+    void nrpnChange(int controller, int value) {
         if(performer == null)
             return;
         int[] c = performer.midi_nrpn_connections.get(controller);
@@ -475,7 +475,7 @@
             processConnection(c[i]);
     }
 
-    protected void rpnChange(int controller, int value) {
+    void rpnChange(int controller, int value) {
         if(performer == null)
             return;
         int[] c = performer.midi_rpn_connections.get(controller);
@@ -485,7 +485,7 @@
             processConnection(c[i]);
     }
 
-    protected void setPitchBend(int bend) {
+    void setPitchBend(int bend) {
         if(performer == null)
             return;
         int[] c = performer.midi_connections[0];
@@ -495,19 +495,19 @@
             processConnection(c[i]);
     }
 
-    protected void setMute(boolean mute) {
+    void setMute(boolean mute) {
         co_mixer_gain[0] -= lastMuteValue;
         lastMuteValue = mute ? -960 : 0;
         co_mixer_gain[0] += lastMuteValue;
     }
 
-    protected void setSoloMute(boolean mute) {
+    void setSoloMute(boolean mute) {
         co_mixer_gain[0] -= lastSoloMuteValue;
         lastSoloMuteValue = mute ? -960 : 0;
         co_mixer_gain[0] += lastSoloMuteValue;
     }
 
-    protected void shutdown() {
+    void shutdown() {
         if (co_noteon_on[0] < -0.5)
             return;
         on = false;
@@ -523,12 +523,12 @@
             processConnection(c[i]);
     }
 
-    protected void soundOff() {
+    void soundOff() {
         on = false;
         soundoff = true;
     }
 
-    protected void noteOff(int velocity) {
+    void noteOff(int velocity) {
         if (!on)
             return;
         on = false;
@@ -553,7 +553,7 @@
             processConnection(c[i]);
     }
 
-    protected void redamp() {
+    void redamp() {
         if (co_noteon_on[0] > 0.5)
             return;
         if (co_noteon_on[0] < -0.5)
@@ -571,7 +571,7 @@
             processConnection(c[i]);
     }
 
-    protected void processControlLogic() {
+    void processControlLogic() {
         if (stopping) {
             active = false;
             stopping = false;
@@ -760,9 +760,9 @@
 
     }
 
-    protected void mixAudioStream(SoftAudioBuffer in, SoftAudioBuffer out,
-            SoftAudioBuffer dout,
-            float amp_from, float amp_to) {
+    void mixAudioStream(SoftAudioBuffer in, SoftAudioBuffer out,
+                                SoftAudioBuffer dout, float amp_from,
+                                float amp_to) {
         int bufferlen = in.getSize();
         if (amp_from < 0.000000001 && amp_to < 0.000000001)
             return;
@@ -815,7 +815,7 @@
 
     }
 
-    protected void processAudioLogic(SoftAudioBuffer[] buffer) {
+    void processAudioLogic(SoftAudioBuffer[] buffer) {
         if (!audiostarted)
             return;
 
--- a/jdk/src/share/classes/com/sun/media/sound/StandardMidiFileReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/StandardMidiFileReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,22 +26,13 @@
 package com.sun.media.sound;
 
 import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.SequenceInputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.InputStream;
 import java.io.IOException;
 import java.io.EOFException;
-import java.io.OutputStream;
-import java.io.RandomAccessFile;
 import java.io.BufferedInputStream;
 import java.net.URL;
-import java.net.MalformedURLException;
 
 import javax.sound.midi.MidiFileFormat;
 import javax.sound.midi.InvalidMidiDataException;
@@ -49,7 +40,6 @@
 import javax.sound.midi.MidiEvent;
 import javax.sound.midi.MidiMessage;
 import javax.sound.midi.Sequence;
-import javax.sound.midi.ShortMessage;
 import javax.sound.midi.SysexMessage;
 import javax.sound.midi.Track;
 import javax.sound.midi.spi.MidiFileReader;
@@ -64,23 +54,12 @@
  * @author Florian Bomers
  */
 
-public class StandardMidiFileReader extends MidiFileReader {
+public final class StandardMidiFileReader extends MidiFileReader {
 
     private static final int MThd_MAGIC = 0x4d546864;  // 'MThd'
 
-    private static final int MIDI_TYPE_0 = 0;
-    private static final int MIDI_TYPE_1 = 1;
-
     private static final int bisBufferSize = 1024; // buffer size in buffered input streams
 
-    /**
-     * MIDI parser types
-     */
-    private static final int types[] = {
-        MIDI_TYPE_0,
-        MIDI_TYPE_1
-    };
-
     public MidiFileFormat getMidiFileFormat(InputStream stream) throws InvalidMidiDataException, IOException {
         return getMidiFileFormatFromStream(stream, MidiFileFormat.UNKNOWN_LENGTH, null);
     }
@@ -253,7 +232,7 @@
 /**
  * State variables during parsing of a MIDI file
  */
-class SMFParser {
+final class SMFParser {
     private static final int MTrk_MAGIC = 0x4d54726b;  // 'MTrk'
 
     // set to true to not allow corrupt MIDI files tombe loaded
@@ -268,7 +247,7 @@
     private byte[] trackData = null;
     private int pos = 0;
 
-    public SMFParser() {
+    SMFParser() {
     }
 
     private int readUnsigned() throws IOException {
--- a/jdk/src/share/classes/com/sun/media/sound/StandardMidiFileWriter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/StandardMidiFileWriter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 
 package com.sun.media.sound;
 
-import java.io.DataInputStream;
 import java.io.DataOutputStream;
 import java.io.PipedInputStream;
 import java.io.PipedOutputStream;
@@ -34,18 +33,13 @@
 import java.io.SequenceInputStream;
 import java.io.File;
 import java.io.FileOutputStream;
-import java.io.BufferedOutputStream;
 import java.io.InputStream;
 import java.io.IOException;
-import java.lang.IllegalArgumentException;
 import java.io.OutputStream;
-import java.util.Vector;
 
-import javax.sound.midi.MidiFileFormat;
 import javax.sound.midi.InvalidMidiDataException;
 import javax.sound.midi.MidiEvent;
 import javax.sound.midi.MetaMessage;
-import javax.sound.midi.MidiMessage;
 import javax.sound.midi.Sequence;
 import javax.sound.midi.ShortMessage;
 import javax.sound.midi.SysexMessage;
@@ -59,7 +53,7 @@
  * @author Kara Kytle
  * @author Jan Borgersen
  */
-public class StandardMidiFileWriter extends MidiFileWriter {
+public final class StandardMidiFileWriter extends MidiFileWriter {
 
     private static final int MThd_MAGIC = 0x4d546864;  // 'MThd'
     private static final int MTrk_MAGIC = 0x4d54726b;  // 'MTrk'
--- a/jdk/src/share/classes/com/sun/media/sound/SunCodec.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SunCodec.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,6 @@
 
 package com.sun.media.sound;
 
-import java.io.InputStream;
-
 import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.AudioInputStream;
 
@@ -48,14 +46,14 @@
  */
 abstract class SunCodec extends FormatConversionProvider {
 
-    AudioFormat.Encoding[] inputEncodings;
-    AudioFormat.Encoding[] outputEncodings;
+    private final AudioFormat.Encoding[] inputEncodings;
+    private final AudioFormat.Encoding[] outputEncodings;
 
     /**
      * Constructs a new codec object.
      */
-    protected SunCodec(AudioFormat.Encoding[] inputEncodings, AudioFormat.Encoding[] outputEncodings) {
-
+    SunCodec(final AudioFormat.Encoding[] inputEncodings,
+             final AudioFormat.Encoding[] outputEncodings) {
         this.inputEncodings = inputEncodings;
         this.outputEncodings = outputEncodings;
     }
@@ -63,16 +61,14 @@
 
     /**
      */
-    public AudioFormat.Encoding[] getSourceEncodings() {
-
+    public final AudioFormat.Encoding[] getSourceEncodings() {
         AudioFormat.Encoding[] encodings = new AudioFormat.Encoding[inputEncodings.length];
         System.arraycopy(inputEncodings, 0, encodings, 0, inputEncodings.length);
         return encodings;
     }
     /**
      */
-    public AudioFormat.Encoding[] getTargetEncodings() {
-
+    public final AudioFormat.Encoding[] getTargetEncodings() {
         AudioFormat.Encoding[] encodings = new AudioFormat.Encoding[outputEncodings.length];
         System.arraycopy(outputEncodings, 0, encodings, 0, outputEncodings.length);
         return encodings;
--- a/jdk/src/share/classes/com/sun/media/sound/SunFileReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SunFileReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -27,7 +27,6 @@
 
 import java.io.File;
 import java.io.InputStream;
-import java.io.OutputStream;
 import java.io.IOException;
 import java.io.DataInputStream;
 import java.net.URL;
@@ -52,7 +51,7 @@
     /**
      * Constructs a new SunFileReader object.
      */
-    public SunFileReader() {
+    SunFileReader() {
     }
 
 
@@ -167,7 +166,7 @@
      * @return 32 bits swapped value.
      * @exception IOException
      */
-    protected int rllong(DataInputStream dis) throws IOException {
+    final int rllong(DataInputStream dis) throws IOException {
 
         int b1, b2, b3, b4 ;
         int i = 0;
@@ -190,7 +189,7 @@
      * @param int
      * @return 32 bits swapped value
      */
-    protected int big2little(int i) {
+    final int big2little(int i) {
 
         int b1, b2, b3, b4 ;
 
@@ -211,7 +210,7 @@
      * @return the swapped value.
      * @exception IOException
      */
-    protected short rlshort(DataInputStream dis)  throws IOException {
+    final short rlshort(DataInputStream dis)  throws IOException {
 
         short s=0;
         short high, low;
@@ -232,7 +231,7 @@
      * @param int
      * @return 16 bits swapped value
      */
-    protected short big2littleShort(short i) {
+    final short big2littleShort(short i) {
 
         short high, low;
 
@@ -244,16 +243,14 @@
         return i;
     }
 
-
-        /** Calculates the frame size for PCM frames.
-         * Note that this method is appropriate for non-packed samples.
-         * For instance, 12 bit, 2 channels will return 4 bytes, not 3.
-         * @param sampleSizeInBits the size of a single sample in bits
-         * @param channels the number of channels
-         * @return the size of a PCM frame in bytes.
-         */
-        protected static int calculatePCMFrameSize(int sampleSizeInBits,
-                                                                                        int channels) {
-                return ((sampleSizeInBits + 7) / 8) * channels;
-        }
+    /** Calculates the frame size for PCM frames.
+     * Note that this method is appropriate for non-packed samples.
+     * For instance, 12 bit, 2 channels will return 4 bytes, not 3.
+     * @param sampleSizeInBits the size of a single sample in bits
+     * @param channels the number of channels
+     * @return the size of a PCM frame in bytes.
+     */
+    static final int calculatePCMFrameSize(int sampleSizeInBits, int channels) {
+        return ((sampleSizeInBits + 7) / 8) * channels;
+    }
 }
--- a/jdk/src/share/classes/com/sun/media/sound/SunFileWriter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/SunFileWriter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,8 +69,7 @@
 
     // new, 10.27.99
 
-    public AudioFileFormat.Type[] getAudioFileTypes(){
-
+    public final AudioFileFormat.Type[] getAudioFileTypes(){
         AudioFileFormat.Type[] localArray = new AudioFileFormat.Type[types.length];
         System.arraycopy(types, 0, localArray, 0, types.length);
         return localArray;
@@ -95,7 +94,7 @@
      * @return 32 bits swapped value.
      * @exception IOException
      */
-    protected int rllong(DataInputStream dis) throws IOException {
+    final int rllong(DataInputStream dis) throws IOException {
 
         int b1, b2, b3, b4 ;
         int i = 0;
@@ -118,7 +117,7 @@
      * @param int
      * @return 32 bits swapped value
      */
-    protected int big2little(int i) {
+    final int big2little(int i) {
 
         int b1, b2, b3, b4 ;
 
@@ -139,7 +138,7 @@
      * @return the swapped value.
      * @exception IOException
      */
-    protected short rlshort(DataInputStream dis)  throws IOException {
+    final short rlshort(DataInputStream dis)  throws IOException {
 
         short s=0;
         short high, low;
@@ -160,7 +159,7 @@
      * @param int
      * @return 16 bits swapped value
      */
-    protected short big2littleShort(short i) {
+    final short big2littleShort(short i) {
 
         short high, low;
 
@@ -177,10 +176,10 @@
      * The class is usefull for use with SequenceInputStream to prevent
      * closing of the source input streams.
      */
-    protected class NoCloseInputStream extends InputStream {
+    final class NoCloseInputStream extends InputStream {
         private final InputStream in;
 
-        public NoCloseInputStream(InputStream in) {
+        NoCloseInputStream(InputStream in) {
             this.in = in;
         }
 
--- a/jdk/src/share/classes/com/sun/media/sound/Toolkit.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/Toolkit.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,8 +35,13 @@
  * @author Kara Kytle
  * @author Florian Bomers
  */
-public class Toolkit {
+public final class Toolkit {
 
+    /**
+     * Suppresses default constructor, ensuring non-instantiability.
+     */
+    private Toolkit() {
+    }
 
     /**
      * Converts bytes from signed to unsigned.
--- a/jdk/src/share/classes/com/sun/media/sound/UlawCodec.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/UlawCodec.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 
 package com.sun.media.sound;
 
-import java.io.InputStream;
 import java.io.IOException;
 
 import java.util.Vector;
@@ -40,12 +39,12 @@
  *
  * @author Kara Kytle
  */
-public class UlawCodec extends SunCodec {
+public final class UlawCodec extends SunCodec {
 
     /* Tables used for U-law decoding */
 
-    final static byte ULAW_TABH[] = new byte[256];
-    final static byte ULAW_TABL[] = new byte[256];
+    private final static byte[] ULAW_TABH = new byte[256];
+    private final static byte[] ULAW_TABL = new byte[256];
 
     private static final AudioFormat.Encoding[] ulawEncodings = {AudioFormat.Encoding.ULAW,
                                                                  AudioFormat.Encoding.PCM_SIGNED};
--- a/jdk/src/share/classes/com/sun/media/sound/WaveExtensibleFileReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/WaveExtensibleFileReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
  *
  * @author Karl Helgason
  */
-public class WaveExtensibleFileReader extends AudioFileReader {
+public final class WaveExtensibleFileReader extends AudioFileReader {
 
     static private class GUID {
         long i1;
@@ -74,7 +74,7 @@
         private GUID() {
         }
 
-        public GUID(long i1, int s1, int s2, int x1, int x2, int x3, int x4,
+        GUID(long i1, int s1, int s2, int x1, int x2, int x3, int x4,
                 int x5, int x6, int x7, int x8) {
             this.i1 = i1;
             this.s1 = s1;
@@ -140,13 +140,13 @@
 
     }
 
-    private static String[] channelnames = { "FL", "FR", "FC", "LF",
+    private static final String[] channelnames = { "FL", "FR", "FC", "LF",
             "BL",
             "BR", // 5.1
             "FLC", "FLR", "BC", "SL", "SR", "TC", "TFL", "TFC", "TFR", "TBL",
             "TBC", "TBR" };
 
-    private static String[] allchannelnames = { "w1", "w2", "w3", "w4", "w5",
+    private static final String[] allchannelnames = { "w1", "w2", "w3", "w4", "w5",
             "w6", "w7", "w8", "w9", "w10", "w11", "w12", "w13", "w14", "w15",
             "w16", "w17", "w18", "w19", "w20", "w21", "w22", "w23", "w24",
             "w25", "w26", "w27", "w28", "w29", "w30", "w31", "w32", "w33",
@@ -155,10 +155,10 @@
             "w52", "w53", "w54", "w55", "w56", "w57", "w58", "w59", "w60",
             "w61", "w62", "w63", "w64" };
 
-    private static GUID SUBTYPE_PCM = new GUID(0x00000001, 0x0000, 0x0010,
+    private static final GUID SUBTYPE_PCM = new GUID(0x00000001, 0x0000, 0x0010,
             0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
 
-    private static GUID SUBTYPE_IEEE_FLOAT = new GUID(0x00000003, 0x0000,
+    private static final GUID SUBTYPE_IEEE_FLOAT = new GUID(0x00000003, 0x0000,
             0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
 
     private String decodeChannelMask(long channelmask) {
--- a/jdk/src/share/classes/com/sun/media/sound/WaveFileFormat.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/WaveFileFormat.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,24 +25,8 @@
 
 package com.sun.media.sound;
 
-import java.util.Vector;
-import java.io.File;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.IOException;
-import java.lang.IllegalArgumentException;
-
-import java.io.BufferedOutputStream;
-import java.io.DataOutputStream;
-import java.io.FileOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.SequenceInputStream;
-
 import javax.sound.sampled.AudioFileFormat;
-import javax.sound.sampled.AudioInputStream;
 import javax.sound.sampled.AudioFormat;
-import javax.sound.sampled.AudioSystem;
 
 
 /**
@@ -51,12 +35,12 @@
  * @author Jan Borgersen
  */
 
-class WaveFileFormat extends AudioFileFormat {
+final class WaveFileFormat extends AudioFileFormat {
 
     /**
      * Wave format type.
      */
-    private int waveType;
+    private final int waveType;
 
     //$$fb 2001-07-13: added management of header size in this class
     //$$fb 2002-04-16: Fix for 4636355: RIFF audio headers could be _more_ spec compliant
--- a/jdk/src/share/classes/com/sun/media/sound/WaveFileReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/WaveFileReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,28 +25,17 @@
 
 package com.sun.media.sound;
 
-import java.util.Vector;
+import java.io.DataInputStream;
+import java.io.EOFException;
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
 import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.IOException;
-import java.io.EOFException;
 import java.net.URL;
-import java.net.MalformedURLException;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.DataInputStream;
-import java.io.FileInputStream;
-import java.io.DataOutputStream;
-import java.io.FileOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.SequenceInputStream;
 
 import javax.sound.sampled.AudioFileFormat;
+import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.AudioInputStream;
-import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.UnsupportedAudioFileException;
 
@@ -59,20 +48,11 @@
  * @author Jan Borgersen
  * @author Florian Bomers
  */
-public class WaveFileReader extends SunFileReader {
+public final class WaveFileReader extends SunFileReader {
 
     private static final int MAX_READ_LENGTH = 12;
 
     /**
-     * WAVE reader type
-     */
-
-    public static final AudioFileFormat.Type types[] = {
-        AudioFileFormat.Type.WAVE
-    };
-
-
-    /**
      * Constructs a new WaveFileReader object.
      */
     public WaveFileReader() {
--- a/jdk/src/share/classes/com/sun/media/sound/WaveFileWriter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/WaveFileWriter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -50,7 +50,7 @@
  *
  * @author Jan Borgersen
  */
-public class WaveFileWriter extends SunFileWriter {
+public final class WaveFileWriter extends SunFileWriter {
 
     // magic numbers
     static  final int RIFF_MAGIC = 1380533830;
@@ -74,18 +74,10 @@
     static final int WAVE_FORMAT_SX7383    = 0x1C07;
 
     /**
-     * WAVE type
-     */
-    private static final AudioFileFormat.Type waveTypes[] = {
-        AudioFileFormat.Type.WAVE
-    };
-
-
-    /**
      * Constructs a new WaveFileWriter object.
      */
     public WaveFileWriter() {
-        super(waveTypes);
+        super(new AudioFileFormat.Type[]{AudioFileFormat.Type.WAVE});
     }
 
 
--- a/jdk/src/share/classes/com/sun/media/sound/WaveFloatFileReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/WaveFloatFileReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -44,7 +44,7 @@
  *
  * @author Karl Helgason
  */
-public class WaveFloatFileReader extends AudioFileReader {
+public final class WaveFloatFileReader extends AudioFileReader {
 
     public AudioFileFormat getAudioFileFormat(InputStream stream)
             throws UnsupportedAudioFileException, IOException {
--- a/jdk/src/share/classes/com/sun/media/sound/WaveFloatFileWriter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/media/sound/WaveFloatFileWriter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,7 +41,7 @@
  *
  * @author Karl Helgason
  */
-public class WaveFloatFileWriter extends AudioFileWriter {
+public final class WaveFloatFileWriter extends AudioFileWriter {
 
     public Type[] getAudioFileTypes() {
         return new Type[] { Type.WAVE };
@@ -86,9 +86,9 @@
     }
 
     private static class NoCloseOutputStream extends OutputStream {
-        OutputStream out;
+        final OutputStream out;
 
-        public NoCloseOutputStream(OutputStream out) {
+        NoCloseOutputStream(OutputStream out) {
             this.out = out;
         }
 
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/Init.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/Init.java	Wed Jul 05 19:00:49 2017 +0200
@@ -2,38 +2,43 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security;
 
 import java.io.InputStream;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.XMLConstants;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 
 import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
 import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
 import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
-import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolver;
 import com.sun.org.apache.xml.internal.security.transforms.Transform;
+import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.I18n;
-//import com.sun.org.apache.xml.internal.security.utils.PRNG;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
 import org.w3c.dom.Attr;
@@ -47,367 +52,317 @@
  * the mapping of Canonicalization and Transform algorithms. Initialization is
  * done by calling {@link Init#init} which should be done in any static block
  * of the files of this library. We ensure that this call is only executed once.
- *
- * @author $Author: mullan $
  */
-public final class Init {
+public class Init {
 
-  /** {@link java.util.logging} logging facility */
-  static java.util.logging.Logger log =
+    /** The namespace for CONF file **/
+    public static final String CONF_NS = "http://www.xmlsecurity.org/NS/#configuration";
+
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(Init.class.getName());
 
-   /** Field _initialized */
-   private static boolean _alreadyInitialized = false;
+    /** Field alreadyInitialized */
+    private static boolean alreadyInitialized = false;
 
-   /** The namespace for CONF file **/
-   public static final String CONF_NS="http://www.xmlsecurity.org/NS/#configuration";
+    /**
+     * Method isInitialized
+     * @return true if the library is already initialized.
+     */
+    public static synchronized final boolean isInitialized() {
+        return Init.alreadyInitialized;
+    }
+
+    /**
+     * Method init
+     *
+     */
+    public static synchronized void init() {
+        if (alreadyInitialized) {
+            return;
+        }
 
-   /**
-    * Method isInitialized
-    * @return true if the librairy is already initialized.
-    *
-    */
-   public static final boolean isInitialized() {
-      return Init._alreadyInitialized;
-   }
+        InputStream is =
+            AccessController.doPrivileged(
+                new PrivilegedAction<InputStream>() {
+                    public InputStream run() {
+                        String cfile =
+                            System.getProperty("com.sun.org.apache.xml.internal.security.resource.config");
+                        if (cfile == null) {
+                            return null;
+                        }
+                        return getClass().getResourceAsStream(cfile);
+                    }
+                });
+        if (is == null) {
+            dynamicInit();
+        } else {
+            fileInit(is);
+        }
 
-   /**
-    * Method init
-    *
-    */
-   public synchronized static void init() {
+        alreadyInitialized = true;
+    }
+
+    /**
+     * Dynamically initialise the library by registering the default algorithms/implementations
+     */
+    private static void dynamicInit() {
+        //
+        // Load the Resource Bundle - the default is the English resource bundle.
+        // To load another resource bundle, call I18n.init(...) before calling this
+        // method.
+        //
+        I18n.init("en", "US");
 
-      if (_alreadyInitialized) {
-        return;
-      }
-      long XX_configure_i18n_end=0;
-      long XX_configure_reg_c14n_start=0;
-      long XX_configure_reg_c14n_end=0;
-      long XX_configure_reg_jcemapper_end=0;
-      long XX_configure_reg_keyInfo_start=0;
-      long XX_configure_reg_keyResolver_end=0;
-      long XX_configure_reg_prefixes_start=0;
-      long XX_configure_reg_resourceresolver_start=0;
-      long XX_configure_reg_sigalgos_end=0;
-      long XX_configure_reg_transforms_end=0;
-      long XX_configure_reg_keyInfo_end=0;
-      long XX_configure_reg_keyResolver_start=0;
-         _alreadyInitialized = true;
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Registering default algorithms");
+        }
+        try {
+            //
+            // Bind the default prefixes
+            //
+            ElementProxy.registerDefaultPrefixes();
+
+            //
+            // Set the default Transforms
+            //
+            Transform.registerDefaultAlgorithms();
+
+            //
+            // Set the default signature algorithms
+            //
+            SignatureAlgorithm.registerDefaultAlgorithms();
+
+            //
+            // Set the default JCE algorithms
+            //
+            JCEMapper.registerDefaultAlgorithms();
 
-         try {
-            long XX_init_start = System.currentTimeMillis();
-            long XX_prng_start = System.currentTimeMillis();
+            //
+            // Set the default c14n algorithms
+            //
+            Canonicalizer.registerDefaultAlgorithms();
 
-            //PRNG.init(new java.security.SecureRandom());
+            //
+            // Register the default resolvers
+            //
+            ResourceResolver.registerDefaultResolvers();
 
-            long XX_prng_end = System.currentTimeMillis();
+            //
+            // Register the default key resolvers
+            //
+            KeyResolver.registerDefaultResolvers();
+        } catch (Exception ex) {
+            log.log(java.util.logging.Level.SEVERE, ex.getMessage(), ex);
+            ex.printStackTrace();
+        }
+    }
 
+    /**
+     * Initialise the library from a configuration file
+     */
+    private static void fileInit(InputStream is) {
+        try {
             /* read library configuration file */
-            long XX_parsing_start = System.currentTimeMillis();
             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
 
             dbf.setNamespaceAware(true);
             dbf.setValidating(false);
 
             DocumentBuilder db = dbf.newDocumentBuilder();
-            // We don't allow users to override the Apache XML Security
-            // configuration in the JRE. Users should use the standard security
-            // provider mechanism instead if implementing their own
-            // transform or canonicalization algorithms.
-            // InputStream is = Class.forName("com.sun.org.apache.xml.internal.security.Init").getResourceAsStream("resource/config.xml");
-            InputStream is = AccessController.doPrivileged(
-                new PrivilegedAction<InputStream>() {
-                    public InputStream run() {
-//                        String cfile = System.getProperty
-//                            ("com.sun.org.apache.xml.internal.security.resource.config");
-                        return getClass().getResourceAsStream
-//                            (cfile != null ? cfile : "resource/config.xml");
-                            ("resource/config.xml");
-                    }
-                });
-
             Document doc = db.parse(is);
-            long XX_parsing_end = System.currentTimeMillis();
-            long XX_configure_i18n_start = 0;
-
-            {
-                XX_configure_reg_keyInfo_start = System.currentTimeMillis();
-               try {
-                  KeyInfo.init();
-               } catch (Exception e) {
-                  e.printStackTrace();
-
-                  throw e;
-               }
-               XX_configure_reg_keyInfo_end = System.currentTimeMillis();
-            }
-
-                        long XX_configure_reg_transforms_start=0;
-                        long XX_configure_reg_jcemapper_start=0;
-                        long XX_configure_reg_sigalgos_start=0;
-                        long XX_configure_reg_resourceresolver_end=0;
-                        long XX_configure_reg_prefixes_end=0;
-            Node config=doc.getFirstChild();
-            for (;config!=null;config=config.getNextSibling()) {
+            Node config = doc.getFirstChild();
+            for (; config != null; config = config.getNextSibling()) {
                 if ("Configuration".equals(config.getLocalName())) {
-                        break;
+                    break;
                 }
             }
-            for (Node el=config.getFirstChild();el!=null;el=el.getNextSibling()) {
-                if (el.getNodeType() != Node.ELEMENT_NODE) {
-                        continue;
+            if (config == null) {
+                log.log(java.util.logging.Level.SEVERE, "Error in reading configuration file - Configuration element not found");
+                return;
+            }
+            for (Node el = config.getFirstChild(); el != null; el = el.getNextSibling()) {
+                if (Node.ELEMENT_NODE != el.getNodeType()) {
+                    continue;
+                }
+                String tag = el.getLocalName();
+                if (tag.equals("ResourceBundles")) {
+                    Element resource = (Element)el;
+                    /* configure internationalization */
+                    Attr langAttr = resource.getAttributeNode("defaultLanguageCode");
+                    Attr countryAttr = resource.getAttributeNode("defaultCountryCode");
+                    String languageCode =
+                        (langAttr == null) ? null : langAttr.getNodeValue();
+                    String countryCode =
+                        (countryAttr == null) ? null : countryAttr.getNodeValue();
+                    I18n.init(languageCode, countryCode);
                 }
-                String tag=el.getLocalName();
-//
-// Commented out: not supported in the JDK. We use the default locale.
-//
-//            if (tag.equals("ResourceBundles")){
-//                XX_configure_i18n_start = System.currentTimeMillis();
-//                Element resource=(Element)el;
-//               /* configure internationalization */
-//               Attr langAttr = resource.getAttributeNode("defaultLanguageCode");
-//               Attr countryAttr = resource.getAttributeNode("defaultCountryCode");
-//               String languageCode = (langAttr == null)
-//                                     ? null
-//                                     : langAttr.getNodeValue();
-//               String countryCode = (countryAttr == null)
-//                                    ? null
-//                                    : countryAttr.getNodeValue();
-//
-//               I18n.init(languageCode, countryCode);
-//               XX_configure_i18n_end = System.currentTimeMillis();
-//            }
+
+                if (tag.equals("CanonicalizationMethods")) {
+                    Element[] list =
+                        XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "CanonicalizationMethod");
+
+                    for (int i = 0; i < list.length; i++) {
+                        String uri = list[i].getAttributeNS(null, "URI");
+                        String javaClass =
+                            list[i].getAttributeNS(null, "JAVACLASS");
+                        try {
+                            Canonicalizer.register(uri, javaClass);
+                            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                                log.log(java.util.logging.Level.FINE, "Canonicalizer.register(" + uri + ", " + javaClass + ")");
+                            }
+                        } catch (ClassNotFoundException e) {
+                            Object exArgs[] = { uri, javaClass };
+                            log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist", exArgs));
+                        }
+                    }
+                }
+
+                if (tag.equals("TransformAlgorithms")) {
+                    Element[] tranElem =
+                        XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "TransformAlgorithm");
 
-            if (tag.equals("CanonicalizationMethods")){
-                XX_configure_reg_c14n_start = System.currentTimeMillis();
-               Canonicalizer.init();
-               Element[] list=XMLUtils.selectNodes(el.getFirstChild(),CONF_NS,"CanonicalizationMethod");
+                    for (int i = 0; i < tranElem.length; i++) {
+                        String uri = tranElem[i].getAttributeNS(null, "URI");
+                        String javaClass =
+                            tranElem[i].getAttributeNS(null, "JAVACLASS");
+                        try {
+                            Transform.register(uri, javaClass);
+                            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                                log.log(java.util.logging.Level.FINE, "Transform.register(" + uri + ", " + javaClass + ")");
+                            }
+                        } catch (ClassNotFoundException e) {
+                            Object exArgs[] = { uri, javaClass };
 
-               for (int i = 0; i < list.length; i++) {
-                  String URI = list[i].getAttributeNS(null,
-                                  "URI");
-                  String JAVACLASS =
-                     list[i].getAttributeNS(null,
-                        "JAVACLASS");
-                  try {
-                      Class.forName(JAVACLASS);
-/*                     Method methods[] = c.getMethods();
+                            log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist", exArgs));
+                        } catch (NoClassDefFoundError ex) {
+                            log.log(java.util.logging.Level.WARNING, "Not able to found dependencies for algorithm, I'll keep working.");
+                        }
+                    }
+                }
 
-                     for (int j = 0; j < methods.length; j++) {
-                        Method currMeth = methods[j];
-
-                        if (currMeth.getDeclaringClass().getName()
-                                .equals(JAVACLASS)) {
-                           log.log(java.util.logging.Level.FINE, currMeth.getDe claringClass().toString());
+                if ("JCEAlgorithmMappings".equals(tag)) {
+                    Node algorithmsNode = ((Element)el).getElementsByTagName("Algorithms").item(0);
+                    if (algorithmsNode != null) {
+                        Element[] algorithms =
+                            XMLUtils.selectNodes(algorithmsNode.getFirstChild(), CONF_NS, "Algorithm");
+                        for (int i = 0; i < algorithms.length; i++) {
+                            Element element = algorithms[i];
+                            String id = element.getAttribute("URI");
+                            JCEMapper.register(id, new JCEMapper.Algorithm(element));
                         }
-                     }*/
-                      if (log.isLoggable(java.util.logging.Level.FINE))
-                        log.log(java.util.logging.Level.FINE, "Canonicalizer.register(" + URI + ", "
-                            + JAVACLASS + ")");
-                     Canonicalizer.register(URI, JAVACLASS);
-                  } catch (ClassNotFoundException e) {
-                     Object exArgs[] = { URI, JAVACLASS };
+                    }
+                }
+
+                if (tag.equals("SignatureAlgorithms")) {
+                    Element[] sigElems =
+                        XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "SignatureAlgorithm");
+
+                    for (int i = 0; i < sigElems.length; i++) {
+                        String uri = sigElems[i].getAttributeNS(null, "URI");
+                        String javaClass =
+                            sigElems[i].getAttributeNS(null, "JAVACLASS");
+
+                        /** $todo$ handle registering */
 
-                     log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist",
-                                              exArgs));
-                  }
-               }
-               XX_configure_reg_c14n_end = System.currentTimeMillis();
-            }
+                        try {
+                            SignatureAlgorithm.register(uri, javaClass);
+                            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                                log.log(java.util.logging.Level.FINE, "SignatureAlgorithm.register(" + uri + ", "
+                                          + javaClass + ")");
+                            }
+                        } catch (ClassNotFoundException e) {
+                            Object exArgs[] = { uri, javaClass };
 
-            if (tag.equals("TransformAlgorithms")){
-               XX_configure_reg_transforms_start = System.currentTimeMillis();
-               Transform.init();
+                            log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist", exArgs));
+                        }
+                    }
+                }
 
-               Element[] tranElem = XMLUtils.selectNodes(el.getFirstChild(),CONF_NS,"TransformAlgorithm");
+                if (tag.equals("ResourceResolvers")) {
+                    Element[]resolverElem =
+                        XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver");
+
+                    for (int i = 0; i < resolverElem.length; i++) {
+                        String javaClass =
+                            resolverElem[i].getAttributeNS(null, "JAVACLASS");
+                        String description =
+                            resolverElem[i].getAttributeNS(null, "DESCRIPTION");
 
-               for (int i = 0; i < tranElem.length; i++) {
-                  String URI = tranElem[i].getAttributeNS(null,
-                                  "URI");
-                  String JAVACLASS =
-                     tranElem[i].getAttributeNS(null,
-                        "JAVACLASS");
-                  try {
-                     Class.forName(JAVACLASS);
-                     if (log.isLoggable(java.util.logging.Level.FINE))
-                        log.log(java.util.logging.Level.FINE, "Transform.register(" + URI + ", " + JAVACLASS + ")");
-                     Transform.register(URI, JAVACLASS);
-                  } catch (ClassNotFoundException e) {
-                     Object exArgs[] = { URI, JAVACLASS };
+                        if ((description != null) && (description.length() > 0)) {
+                            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                                log.log(java.util.logging.Level.FINE, "Register Resolver: " + javaClass + ": "
+                                          + description);
+                            }
+                        } else {
+                            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                                log.log(java.util.logging.Level.FINE, "Register Resolver: " + javaClass
+                                          + ": For unknown purposes");
+                            }
+                        }
+                        try {
+                            ResourceResolver.register(javaClass);
+                        } catch (Throwable e) {
+                            log.log(java.util.logging.Level.WARNING,
+                                 "Cannot register:" + javaClass
+                                 + " perhaps some needed jars are not installed",
+                                 e
+                             );
+                        }
+                    }
+                }
 
-                     log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist",
-                                              exArgs));
+                if (tag.equals("KeyResolver")){
+                    Element[] resolverElem =
+                        XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver");
+                    List<String> classNames = new ArrayList<String>(resolverElem.length);
+                    for (int i = 0; i < resolverElem.length; i++) {
+                        String javaClass =
+                            resolverElem[i].getAttributeNS(null, "JAVACLASS");
+                        String description =
+                            resolverElem[i].getAttributeNS(null, "DESCRIPTION");
 
-                  } catch (NoClassDefFoundError ex) {
-                                          log.log(java.util.logging.Level.WARNING, "Not able to found dependecies for algorithm, I'm keep working.");
-                  }
-               }
-               XX_configure_reg_transforms_end = System.currentTimeMillis();
-            }
-
-
-            if ("JCEAlgorithmMappings".equals(tag)){
-               XX_configure_reg_jcemapper_start = System.currentTimeMillis();
-               JCEMapper.init((Element)el);
-               XX_configure_reg_jcemapper_end = System.currentTimeMillis();
-            }
-
+                        if ((description != null) && (description.length() > 0)) {
+                            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                                log.log(java.util.logging.Level.FINE, "Register Resolver: " + javaClass + ": "
+                                          + description);
+                            }
+                        } else {
+                            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                                log.log(java.util.logging.Level.FINE, "Register Resolver: " + javaClass
+                                          + ": For unknown purposes");
+                            }
+                        }
+                        classNames.add(javaClass);
+                    }
+                    KeyResolver.registerClassNames(classNames);
+                }
 
 
-            if (tag.equals("SignatureAlgorithms")){
-               XX_configure_reg_sigalgos_start = System.currentTimeMillis();
-               SignatureAlgorithm.providerInit();
-
-               Element[] sigElems = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS,
-                  "SignatureAlgorithm");
-
-               for (int i = 0; i < sigElems.length; i++) {
-                  String URI = sigElems[i].getAttributeNS(null,
-                                  "URI");
-                  String JAVACLASS =
-                    sigElems[i].getAttributeNS(null,
-                        "JAVACLASS");
-
-                  /** $todo$ handle registering */
-
-                  try {
-                      Class.forName(JAVACLASS);
- //                    Method methods[] = c.getMethods();
-
-//                     for (int j = 0; j < methods.length; j++) {
-//                        Method currMeth = methods[j];
-//
-//                        if (currMeth.getDeclaringClass().getName()
-//                                .equals(JAVACLASS)) {
-//                           log.log(java.util.logging.Level.FINE, currMeth.getDe claringClass().toString());
-//                        }
-//                     }
-                      if (log.isLoggable(java.util.logging.Level.FINE))
-                        log.log(java.util.logging.Level.FINE, "SignatureAlgorithm.register(" + URI + ", " + JAVACLASS + ")");
-                     SignatureAlgorithm.register(URI, JAVACLASS);
-                  } catch (ClassNotFoundException e) {
-                     Object exArgs[] = { URI, JAVACLASS };
-
-                     log.log(java.util.logging.Level.SEVERE, I18n.translate("algorithm.classDoesNotExist",
-                                              exArgs));
+                if (tag.equals("PrefixMappings")){
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, "Now I try to bind prefixes:");
+                    }
 
-                  }
-               }
-               XX_configure_reg_sigalgos_end = System.currentTimeMillis();
-            }
-
-
-
-            if (tag.equals("ResourceResolvers")){
-               XX_configure_reg_resourceresolver_start = System.currentTimeMillis();
-               ResourceResolver.init();
-
-               Element[]resolverElem = XMLUtils.selectNodes(el.getFirstChild(),CONF_NS,
-                  "Resolver");
-
-               for (int i = 0; i < resolverElem.length; i++) {
-                  String JAVACLASS =
-                      resolverElem[i].getAttributeNS(null,
-                        "JAVACLASS");
-                  String Description =
-                     resolverElem[i].getAttributeNS(null,
-                        "DESCRIPTION");
-
-                  if ((Description != null) && (Description.length() > 0)) {
-                    if (log.isLoggable(java.util.logging.Level.FINE))
-                        log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " + Description);
-                  } else {
-                    if (log.isLoggable(java.util.logging.Level.FINE))
-                        log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": For unknown purposes");
-                  }
-                                  try {
-                                          ResourceResolver.register(JAVACLASS);
-                                  } catch (Throwable e) {
-                                          log.log(java.util.logging.Level.WARNING, "Cannot register:"+JAVACLASS+" perhaps some needed jars are not installed",e);
-                                  }
-                  XX_configure_reg_resourceresolver_end =
-                    System.currentTimeMillis();
-               }
+                    Element[] nl =
+                        XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "PrefixMapping");
 
-            }
-
-
-
-
-
-
-            if (tag.equals("KeyResolver")){
-               XX_configure_reg_keyResolver_start =System.currentTimeMillis();
-               KeyResolver.init();
-
-               Element[] resolverElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS,"Resolver");
-
-               for (int i = 0; i < resolverElem.length; i++) {
-                  String JAVACLASS =
-                     resolverElem[i].getAttributeNS(null,
-                        "JAVACLASS");
-                  String Description =
-                     resolverElem[i].getAttributeNS(null,
-                        "DESCRIPTION");
-
-                  if ((Description != null) && (Description.length() > 0)) {
-                    if (log.isLoggable(java.util.logging.Level.FINE))
-                        log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " + Description);
-                  } else {
-                    if (log.isLoggable(java.util.logging.Level.FINE))
-                        log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": For unknown purposes");
-                  }
-
-                  KeyResolver.register(JAVACLASS);
-               }
-               XX_configure_reg_keyResolver_end = System.currentTimeMillis();
+                    for (int i = 0; i < nl.length; i++) {
+                        String namespace = nl[i].getAttributeNS(null, "namespace");
+                        String prefix = nl[i].getAttributeNS(null, "prefix");
+                        if (log.isLoggable(java.util.logging.Level.FINE)) {
+                            log.log(java.util.logging.Level.FINE, "Now I try to bind " + prefix + " to " + namespace);
+                        }
+                        ElementProxy.setDefaultPrefix(namespace, prefix);
+                    }
+                }
             }
-
-
-            if (tag.equals("PrefixMappings")){
-                XX_configure_reg_prefixes_start = System.currentTimeMillis();
-                if (log.isLoggable(java.util.logging.Level.FINE))
-                    log.log(java.util.logging.Level.FINE, "Now I try to bind prefixes:");
-
-               Element[] nl = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS,"PrefixMapping");
-
-               for (int i = 0; i < nl.length; i++) {
-                  String namespace = nl[i].getAttributeNS(null,
-                                        "namespace");
-                  String prefix = nl[i].getAttributeNS(null,
-                                     "prefix");
-                  if (log.isLoggable(java.util.logging.Level.FINE))
-                      log.log(java.util.logging.Level.FINE, "Now I try to bind " + prefix + " to " + namespace);
-                  com.sun.org.apache.xml.internal.security.utils.ElementProxy
-                     .setDefaultPrefix(namespace, prefix);
-               }
-               XX_configure_reg_prefixes_end = System.currentTimeMillis();
-            }
-            }
-
-            long XX_init_end = System.currentTimeMillis();
-
-            //J-
-            if (log.isLoggable(java.util.logging.Level.FINE)) {
-                log.log(java.util.logging.Level.FINE, "XX_init                             " + ((int)(XX_init_end - XX_init_start)) + " ms");
-                log.log(java.util.logging.Level.FINE, "  XX_prng                           " + ((int)(XX_prng_end - XX_prng_start)) + " ms");
-                log.log(java.util.logging.Level.FINE, "  XX_parsing                        " + ((int)(XX_parsing_end - XX_parsing_start)) + " ms");
-                log.log(java.util.logging.Level.FINE, "  XX_configure_i18n                 " + ((int)(XX_configure_i18n_end- XX_configure_i18n_start)) + " ms");
-                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_c14n             " + ((int)(XX_configure_reg_c14n_end- XX_configure_reg_c14n_start)) + " ms");
-                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_jcemapper        " + ((int)(XX_configure_reg_jcemapper_end- XX_configure_reg_jcemapper_start)) + " ms");
-                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_keyInfo          " + ((int)(XX_configure_reg_keyInfo_end- XX_configure_reg_keyInfo_start)) + " ms");
-                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_keyResolver      " + ((int)(XX_configure_reg_keyResolver_end- XX_configure_reg_keyResolver_start)) + " ms");
-                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_prefixes         " + ((int)(XX_configure_reg_prefixes_end- XX_configure_reg_prefixes_start)) + " ms");
-                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_resourceresolver " + ((int)(XX_configure_reg_resourceresolver_end- XX_configure_reg_resourceresolver_start)) + " ms");
-                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_sigalgos         " + ((int)(XX_configure_reg_sigalgos_end- XX_configure_reg_sigalgos_start)) + " ms");
-                log.log(java.util.logging.Level.FINE, "  XX_configure_reg_transforms       " + ((int)(XX_configure_reg_transforms_end- XX_configure_reg_transforms_start)) + " ms");
-            }
-         } catch (Exception e) {
+        } catch (Exception e) {
             log.log(java.util.logging.Level.SEVERE, "Bad: ", e);
             e.printStackTrace();
-         }
-
-   }
-
+        }
+    }
 
 }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/ClassLoaderUtils.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,280 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package com.sun.org.apache.xml.internal.security.algorithms;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+
+/**
+ * This class is extremely useful for loading resources and classes in a fault
+ * tolerant manner that works across different applications servers. Do not
+ * touch this unless you're a grizzled classloading guru veteran who is going to
+ * verify any change on 6 different application servers.
+ */
+// NOTE! This is a duplicate of utils.ClassLoaderUtils with public
+// modifiers changed to package-private. Make sure to integrate any future
+// changes to utils.ClassLoaderUtils to this file.
+final class ClassLoaderUtils {
+
+    /** {@link org.apache.commons.logging} logging facility */
+    private static final java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(ClassLoaderUtils.class.getName());
+
+    private ClassLoaderUtils() {
+    }
+
+    /**
+     * Load a given resource. <p/> This method will try to load the resource
+     * using the following methods (in order):
+     * <ul>
+     * <li>From Thread.currentThread().getContextClassLoader()
+     * <li>From ClassLoaderUtil.class.getClassLoader()
+     * <li>callingClass.getClassLoader()
+     * </ul>
+     *
+     * @param resourceName The name of the resource to load
+     * @param callingClass The Class object of the calling object
+     */
+    static URL getResource(String resourceName, Class<?> callingClass) {
+        URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
+        if (url == null && resourceName.startsWith("/")) {
+            //certain classloaders need it without the leading /
+            url =
+                Thread.currentThread().getContextClassLoader().getResource(
+                    resourceName.substring(1)
+                );
+        }
+
+        ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
+        if (cluClassloader == null) {
+            cluClassloader = ClassLoader.getSystemClassLoader();
+        }
+        if (url == null) {
+            url = cluClassloader.getResource(resourceName);
+        }
+        if (url == null && resourceName.startsWith("/")) {
+            //certain classloaders need it without the leading /
+            url = cluClassloader.getResource(resourceName.substring(1));
+        }
+
+        if (url == null) {
+            ClassLoader cl = callingClass.getClassLoader();
+
+            if (cl != null) {
+                url = cl.getResource(resourceName);
+            }
+        }
+
+        if (url == null) {
+            url = callingClass.getResource(resourceName);
+        }
+
+        if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) {
+            return getResource('/' + resourceName, callingClass);
+        }
+
+        return url;
+    }
+
+    /**
+     * Load a given resources. <p/> This method will try to load the resources
+     * using the following methods (in order):
+     * <ul>
+     * <li>From Thread.currentThread().getContextClassLoader()
+     * <li>From ClassLoaderUtil.class.getClassLoader()
+     * <li>callingClass.getClassLoader()
+     * </ul>
+     *
+     * @param resourceName The name of the resource to load
+     * @param callingClass The Class object of the calling object
+     */
+    static List<URL> getResources(String resourceName, Class<?> callingClass) {
+        List<URL> ret = new ArrayList<URL>();
+        Enumeration<URL> urls = new Enumeration<URL>() {
+            public boolean hasMoreElements() {
+                return false;
+            }
+            public URL nextElement() {
+                return null;
+            }
+
+        };
+        try {
+            urls = Thread.currentThread().getContextClassLoader().getResources(resourceName);
+        } catch (IOException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+            //ignore
+        }
+        if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
+            //certain classloaders need it without the leading /
+            try {
+                urls =
+                    Thread.currentThread().getContextClassLoader().getResources(
+                        resourceName.substring(1)
+                    );
+            } catch (IOException e) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                }
+                // ignore
+            }
+        }
+
+        ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
+        if (cluClassloader == null) {
+            cluClassloader = ClassLoader.getSystemClassLoader();
+        }
+        if (!urls.hasMoreElements()) {
+            try {
+                urls = cluClassloader.getResources(resourceName);
+            } catch (IOException e) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                }
+                // ignore
+            }
+        }
+        if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
+            //certain classloaders need it without the leading /
+            try {
+                urls = cluClassloader.getResources(resourceName.substring(1));
+            } catch (IOException e) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                }
+                // ignore
+            }
+        }
+
+        if (!urls.hasMoreElements()) {
+            ClassLoader cl = callingClass.getClassLoader();
+
+            if (cl != null) {
+                try {
+                    urls = cl.getResources(resourceName);
+                } catch (IOException e) {
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                    }
+                    // ignore
+                }
+            }
+        }
+
+        if (!urls.hasMoreElements()) {
+            URL url = callingClass.getResource(resourceName);
+            if (url != null) {
+                ret.add(url);
+            }
+        }
+        while (urls.hasMoreElements()) {
+            ret.add(urls.nextElement());
+        }
+
+
+        if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) {
+            return getResources('/' + resourceName, callingClass);
+        }
+        return ret;
+    }
+
+
+    /**
+     * This is a convenience method to load a resource as a stream. <p/> The
+     * algorithm used to find the resource is given in getResource()
+     *
+     * @param resourceName The name of the resource to load
+     * @param callingClass The Class object of the calling object
+     */
+    static InputStream getResourceAsStream(String resourceName, Class<?> callingClass) {
+        URL url = getResource(resourceName, callingClass);
+
+        try {
+            return (url != null) ? url.openStream() : null;
+        } catch (IOException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+            return null;
+        }
+    }
+
+    /**
+     * Load a class with a given name. <p/> It will try to load the class in the
+     * following order:
+     * <ul>
+     * <li>From Thread.currentThread().getContextClassLoader()
+     * <li>Using the basic Class.forName()
+     * <li>From ClassLoaderUtil.class.getClassLoader()
+     * <li>From the callingClass.getClassLoader()
+     * </ul>
+     *
+     * @param className The name of the class to load
+     * @param callingClass The Class object of the calling object
+     * @throws ClassNotFoundException If the class cannot be found anywhere.
+     */
+    static Class<?> loadClass(String className, Class<?> callingClass)
+        throws ClassNotFoundException {
+        try {
+            ClassLoader cl = Thread.currentThread().getContextClassLoader();
+
+            if (cl != null) {
+                return cl.loadClass(className);
+            }
+        } catch (ClassNotFoundException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+            //ignore
+        }
+        return loadClass2(className, callingClass);
+    }
+
+    private static Class<?> loadClass2(String className, Class<?> callingClass)
+        throws ClassNotFoundException {
+        try {
+            return Class.forName(className);
+        } catch (ClassNotFoundException ex) {
+            try {
+                if (ClassLoaderUtils.class.getClassLoader() != null) {
+                    return ClassLoaderUtils.class.getClassLoader().loadClass(className);
+                }
+            } catch (ClassNotFoundException exc) {
+                if (callingClass != null && callingClass.getClassLoader() != null) {
+                    return callingClass.getClassLoader().loadClass(className);
+                }
+            }
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+            }
+            throw ex;
+        }
+    }
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java	Wed Jul 05 19:00:49 2017 +0200
@@ -2,167 +2,316 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.algorithms;
 
-
-
-import java.util.HashMap;
 import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
 
-
-import com.sun.org.apache.xml.internal.security.Init;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import com.sun.org.apache.xml.internal.security.encryption.XMLCipher;
+import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
 import org.w3c.dom.Element;
 
 
-
 /**
  * This class maps algorithm identifier URIs to JAVA JCE class names.
- *
- * @author $Author: mullan $
  */
 public class JCEMapper {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(JCEMapper.class.getName());
 
-
-
-   private static Map<String, String> uriToJCEName;
-
-   private static Map<String, Algorithm> algorithmsMap;
+    private static Map<String, Algorithm> algorithmsMap =
+        new ConcurrentHashMap<String, Algorithm>();
 
-   private static String providerName = null;
-   /**
-    * Method init
-    *
-    * @param mappingElement
-    * @throws Exception
-    */
-   public static void init(Element mappingElement) throws Exception {
-
-      loadAlgorithms((Element)mappingElement.getElementsByTagName("Algorithms").item(0));
-   }
+    private static String providerName = null;
 
-   static void loadAlgorithms( Element algorithmsEl) {
-       Element[] algorithms = XMLUtils.selectNodes(algorithmsEl.getFirstChild(),Init.CONF_NS,"Algorithm");
-       uriToJCEName = new HashMap<String, String>( algorithms.length * 2);
-       algorithmsMap = new HashMap<String, Algorithm>( algorithms.length * 2);
-       for (int i = 0 ;i < algorithms.length ;i ++) {
-           Element el = algorithms[i];
-           String id = el.getAttribute("URI");
-           String jceName = el.getAttribute("JCEName");
-           uriToJCEName.put(id, jceName);
-           algorithmsMap.put(id, new Algorithm(el));
-       }
-
-   }
-
-   static Algorithm getAlgorithmMapping(String algoURI) {
-           return algorithmsMap.get(algoURI);
-   }
-
-   /**
-    * Method translateURItoJCEID
-    *
-    * @param AlgorithmURI
-    * @return the JCE standard name corresponding to the given URI
-    *
-    */
-   public static String translateURItoJCEID(String AlgorithmURI) {
-      if (log.isLoggable(java.util.logging.Level.FINE))
-          log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI);
-
-      String jceName = uriToJCEName.get(AlgorithmURI);
-      return jceName;
-   }
+    /**
+     * Method register
+     *
+     * @param id
+     * @param algorithm
+     */
+    public static void register(String id, Algorithm algorithm) {
+        algorithmsMap.put(id, algorithm);
+    }
 
-   /**
-    * Method getAlgorithmClassFromURI
-    * NOTE(Raul Benito) It seems a buggy function the loop doesn't do
-    * anything??
-    * @param AlgorithmURI
-    * @return the class name that implements this algorithm
-    *
-    */
-   public static String getAlgorithmClassFromURI(String AlgorithmURI) {
-       if (log.isLoggable(java.util.logging.Level.FINE))
-           log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI);
-
-       return (algorithmsMap.get(AlgorithmURI)).algorithmClass;
-   }
-
-   /**
-    * Returns the keylength in bit for a particular algorithm.
-    *
-    * @param AlgorithmURI
-    * @return The length of the key used in the alogrithm
-    */
-   public static int getKeyLengthFromURI(String AlgorithmURI) {
-       return Integer.parseInt((algorithmsMap.get(AlgorithmURI)).keyLength);
-   }
+    /**
+     * This method registers the default algorithms.
+     */
+    public static void registerDefaultAlgorithms() {
+        algorithmsMap.put(
+            MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5,
+            new Algorithm("", "MD5", "MessageDigest")
+        );
+        algorithmsMap.put(
+            MessageDigestAlgorithm.ALGO_ID_DIGEST_RIPEMD160,
+            new Algorithm("", "RIPEMD160", "MessageDigest")
+        );
+        algorithmsMap.put(
+            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1,
+            new Algorithm("", "SHA-1", "MessageDigest")
+        );
+        algorithmsMap.put(
+            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256,
+            new Algorithm("", "SHA-256", "MessageDigest")
+        );
+        algorithmsMap.put(
+            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA384,
+            new Algorithm("", "SHA-384", "MessageDigest")
+        );
+        algorithmsMap.put(
+            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA512,
+            new Algorithm("", "SHA-512", "MessageDigest")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_DSA,
+            new Algorithm("", "SHA1withDSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5,
+            new Algorithm("", "MD5withRSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160,
+            new Algorithm("", "RIPEMD160withRSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1,
+            new Algorithm("", "SHA1withRSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256,
+            new Algorithm("", "SHA256withRSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384,
+            new Algorithm("", "SHA384withRSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512,
+            new Algorithm("", "SHA512withRSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1,
+            new Algorithm("", "SHA1withECDSA", "Signature")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5,
+            new Algorithm("", "HmacMD5", "Mac")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160,
+            new Algorithm("", "HMACRIPEMD160", "Mac")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
+            new Algorithm("", "HmacSHA1", "Mac")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_SHA256,
+            new Algorithm("", "HmacSHA256", "Mac")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_SHA384,
+            new Algorithm("", "HmacSHA384", "Mac")
+        );
+        algorithmsMap.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_SHA512,
+            new Algorithm("", "HmacSHA512", "Mac")
+        );
+        algorithmsMap.put(
+            XMLCipher.TRIPLEDES,
+            new Algorithm("DESede", "DESede/CBC/ISO10126Padding", "BlockEncryption", 192)
+        );
+        algorithmsMap.put(
+            XMLCipher.AES_128,
+            new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 128)
+        );
+        algorithmsMap.put(
+            XMLCipher.AES_192,
+            new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 192)
+        );
+        algorithmsMap.put(
+            XMLCipher.AES_256,
+            new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 256)
+        );
+        algorithmsMap.put(
+            XMLCipher.RSA_v1dot5,
+            new Algorithm("RSA", "RSA/ECB/PKCS1Padding", "KeyTransport")
+        );
+        algorithmsMap.put(
+            XMLCipher.RSA_OAEP,
+            new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport")
+        );
+        algorithmsMap.put(
+            XMLCipher.DIFFIE_HELLMAN,
+            new Algorithm("", "", "KeyAgreement")
+        );
+        algorithmsMap.put(
+            XMLCipher.TRIPLEDES_KeyWrap,
+            new Algorithm("DESede", "DESedeWrap", "SymmetricKeyWrap", 192)
+        );
+        algorithmsMap.put(
+            XMLCipher.AES_128_KeyWrap,
+            new Algorithm("AES", "AESWrap", "SymmetricKeyWrap", 128)
+        );
+        algorithmsMap.put(
+            XMLCipher.AES_192_KeyWrap,
+            new Algorithm("AES", "AESWrap", "SymmetricKeyWrap", 192)
+        );
+        algorithmsMap.put(
+            XMLCipher.AES_256_KeyWrap,
+            new Algorithm("AES", "AESWrap", "SymmetricKeyWrap", 256)
+        );
+    }
 
-   /**
-    * Method getJCEKeyAlgorithmFromURI
-    *
-    * @param AlgorithmURI
-    * @return The KeyAlgorithm for the given URI.
-    *
-    */
-   public static String getJCEKeyAlgorithmFromURI(String AlgorithmURI) {
+    /**
+     * Method translateURItoJCEID
+     *
+     * @param algorithmURI
+     * @return the JCE standard name corresponding to the given URI
+     */
+    public static String translateURItoJCEID(String algorithmURI) {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Request for URI " + algorithmURI);
+        }
 
-        return  (algorithmsMap.get(AlgorithmURI)).requiredKey;
+        Algorithm algorithm = algorithmsMap.get(algorithmURI);
+        if (algorithm != null) {
+            return algorithm.jceName;
+        }
+        return null;
+    }
 
-   }
+    /**
+     * Method getAlgorithmClassFromURI
+     * @param algorithmURI
+     * @return the class name that implements this algorithm
+     */
+    public static String getAlgorithmClassFromURI(String algorithmURI) {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Request for URI " + algorithmURI);
+        }
+
+        Algorithm algorithm = algorithmsMap.get(algorithmURI);
+        if (algorithm != null) {
+            return algorithm.algorithmClass;
+        }
+        return null;
+    }
 
-   /**
-    * Gets the default Provider for obtaining the security algorithms
-    * @return the default providerId.
-    */
-   public static String getProviderId() {
-                return providerName;
-   }
+    /**
+     * Returns the keylength in bits for a particular algorithm.
+     *
+     * @param algorithmURI
+     * @return The length of the key used in the algorithm
+     */
+    public static int getKeyLengthFromURI(String algorithmURI) {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Request for URI " + algorithmURI);
+        }
+        Algorithm algorithm = algorithmsMap.get(algorithmURI);
+        if (algorithm != null) {
+            return algorithm.keyLength;
+        }
+        return 0;
+    }
 
-   /**
-    * Sets the default Provider for obtaining the security algorithms
-    * @param provider the default providerId.
-    */
-   public static void setProviderId(String provider) {
-                providerName=provider;
-   }
+    /**
+     * Method getJCEKeyAlgorithmFromURI
+     *
+     * @param algorithmURI
+     * @return The KeyAlgorithm for the given URI.
+     */
+    public static String getJCEKeyAlgorithmFromURI(String algorithmURI) {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Request for URI " + algorithmURI);
+        }
+        Algorithm algorithm = algorithmsMap.get(algorithmURI);
+        if (algorithm != null) {
+            return algorithm.requiredKey;
+        }
+        return null;
+    }
 
-   /**
-    * Represents the Algorithm xml element
-    */
-   public static class Algorithm {
-            String algorithmClass;
-            String keyLength;
-            String requiredKey;
+    /**
+     * Gets the default Provider for obtaining the security algorithms
+     * @return the default providerId.
+     */
+    public static String getProviderId() {
+        return providerName;
+    }
+
+    /**
+     * Sets the default Provider for obtaining the security algorithms
+     * @param provider the default providerId.
+     */
+    public static void setProviderId(String provider) {
+        providerName = provider;
+    }
+
+    /**
+     * Represents the Algorithm xml element
+     */
+    public static class Algorithm {
+
+        final String requiredKey;
+        final String jceName;
+        final String algorithmClass;
+        final int keyLength;
+
         /**
          * Gets data from element
          * @param el
          */
         public Algorithm(Element el) {
-                algorithmClass=el.getAttribute("AlgorithmClass");
-            keyLength=el.getAttribute("KeyLength");
-            requiredKey=el.getAttribute("RequiredKey");
+            requiredKey = el.getAttribute("RequiredKey");
+            jceName = el.getAttribute("JCEName");
+            algorithmClass = el.getAttribute("AlgorithmClass");
+            if (el.hasAttribute("KeyLength")) {
+                keyLength = Integer.parseInt(el.getAttribute("KeyLength"));
+            } else {
+                keyLength = 0;
+            }
+        }
+
+        public Algorithm(String requiredKey, String jceName) {
+            this(requiredKey, jceName, null, 0);
         }
-   }
+
+        public Algorithm(String requiredKey, String jceName, String algorithmClass) {
+            this(requiredKey, jceName, algorithmClass, 0);
+        }
+
+        public Algorithm(String requiredKey, String jceName, int keyLength) {
+            this(requiredKey, jceName, null, keyLength);
+        }
+
+        public Algorithm(String requiredKey, String jceName, String algorithmClass, int keyLength) {
+            this.requiredKey = requiredKey;
+            this.jceName = jceName;
+            this.algorithmClass = algorithmClass;
+            this.keyLength = keyLength;
+        }
+    }
+
 }
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java	Wed Jul 05 19:00:49 2017 +0200
@@ -2,460 +2,445 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.algorithms;
 
-
 import java.security.Key;
 import java.security.SecureRandom;
 import java.security.spec.AlgorithmParameterSpec;
-import java.util.HashMap;
 import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
 
 import com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac;
+import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA;
+import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureDSA;
+import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA;
 import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
+import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-
 /**
- * Allows selection of digital signature's algorithm, private keys, other security parameters, and algorithm's ID.
+ * Allows selection of digital signature's algorithm, private keys, other
+ * security parameters, and algorithm's ID.
  *
  * @author Christian Geuer-Pollmann
  */
 public class SignatureAlgorithm extends Algorithm {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(SignatureAlgorithm.class.getName());
 
-   /** Field _alreadyInitialized */
-   static boolean _alreadyInitialized = false;
+    /** All available algorithm classes are registered here */
+    private static Map<String, Class<? extends SignatureAlgorithmSpi>> algorithmHash =
+        new ConcurrentHashMap<String, Class<? extends SignatureAlgorithmSpi>>();
 
-   /** All available algorithm classes are registered here */
-   static Map<String, Class<? extends SignatureAlgorithmSpi>> _algorithmHash = null;
+    /** Field signatureAlgorithm */
+    private final SignatureAlgorithmSpi signatureAlgorithm;
+
+    private final String algorithmURI;
 
-   static ThreadLocal<Map<String, SignatureAlgorithmSpi>> instancesSigning=new ThreadLocal<Map<String, SignatureAlgorithmSpi>>() {
-           protected Map<String, SignatureAlgorithmSpi> initialValue() {
-                   return new HashMap<String, SignatureAlgorithmSpi>();
-           };
-   };
+    /**
+     * Constructor SignatureAlgorithm
+     *
+     * @param doc
+     * @param algorithmURI
+     * @throws XMLSecurityException
+     */
+    public SignatureAlgorithm(Document doc, String algorithmURI) throws XMLSecurityException {
+        super(doc, algorithmURI);
+        this.algorithmURI = algorithmURI;
 
-   static ThreadLocal<Map<String, SignatureAlgorithmSpi>> instancesVerify=new ThreadLocal<Map<String, SignatureAlgorithmSpi>>() {
-           protected Map<String, SignatureAlgorithmSpi> initialValue() {
-                   return new HashMap<String, SignatureAlgorithmSpi>();
-           };
-   };
+        signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
+        signatureAlgorithm.engineGetContextFromElement(this._constructionElement);
+    }
 
-   static ThreadLocal<Map<String, Key>> keysSigning=new ThreadLocal<Map<String, Key>>() {
-           protected Map<String, Key> initialValue() {
-                   return new HashMap<String, Key>();
-           };
-   };
-   static ThreadLocal<Map<String, Key>> keysVerify=new ThreadLocal<Map<String, Key>>() {
-           protected Map<String, Key> initialValue() {
-                   return new HashMap<String, Key>();
-           };
-   };
-//   boolean isForSigning=false;
+    /**
+     * Constructor SignatureAlgorithm
+     *
+     * @param doc
+     * @param algorithmURI
+     * @param hmacOutputLength
+     * @throws XMLSecurityException
+     */
+    public SignatureAlgorithm(
+        Document doc, String algorithmURI, int hmacOutputLength
+    ) throws XMLSecurityException {
+        super(doc, algorithmURI);
+        this.algorithmURI = algorithmURI;
 
-   /** Field _signatureAlgorithm */
-   protected SignatureAlgorithmSpi _signatureAlgorithm = null;
+        signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
+        signatureAlgorithm.engineGetContextFromElement(this._constructionElement);
 
-   private String algorithmURI;
+        signatureAlgorithm.engineSetHMACOutputLength(hmacOutputLength);
+        ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(_constructionElement);
+    }
 
-   /**
-    * Constructor SignatureAlgorithm
-    *
-    * @param doc
-    * @param algorithmURI
-    * @throws XMLSecurityException
-    */
-   public SignatureAlgorithm(Document doc, String algorithmURI)
-           throws XMLSecurityException {
-      super(doc, algorithmURI);
-      this.algorithmURI = algorithmURI;
-   }
+    /**
+     * Constructor SignatureAlgorithm
+     *
+     * @param element
+     * @param baseURI
+     * @throws XMLSecurityException
+     */
+    public SignatureAlgorithm(Element element, String baseURI) throws XMLSecurityException {
+        this(element, baseURI, false);
+    }
 
+    /**
+     * Constructor SignatureAlgorithm
+     *
+     * @param element
+     * @param baseURI
+     * @param secureValidation
+     * @throws XMLSecurityException
+     */
+    public SignatureAlgorithm(
+        Element element, String baseURI, boolean secureValidation
+    ) throws XMLSecurityException {
+        super(element, baseURI);
+        algorithmURI = this.getURI();
 
-   private void initializeAlgorithm(boolean isForSigning) throws XMLSignatureException {
-           if (_signatureAlgorithm!=null) {
-                   return;
-           }
-           _signatureAlgorithm=isForSigning ? getInstanceForSigning(algorithmURI) : getInstanceForVerify(algorithmURI);
-                this._signatureAlgorithm
-                      .engineGetContextFromElement(this._constructionElement);
-   }
-   private static SignatureAlgorithmSpi getInstanceForSigning(String algorithmURI) throws XMLSignatureException {
-           SignatureAlgorithmSpi result= instancesSigning.get().get(algorithmURI);
-           if (result!=null) {
-                   result.reset();
-                   return result;
-           }
-           result=buildSigner(algorithmURI, result);
-           instancesSigning.get().put(algorithmURI,result);
-           return result;
-   }
-   private static SignatureAlgorithmSpi getInstanceForVerify(String algorithmURI) throws XMLSignatureException {
-           SignatureAlgorithmSpi result= instancesVerify.get().get(algorithmURI);
-           if (result!=null) {
-                   result.reset();
-                   return result;
-           }
-           result=buildSigner(algorithmURI, result);
-           instancesVerify.get().put(algorithmURI,result);
-           return result;
-   }
+        Attr attr = element.getAttributeNodeNS(null, "Id");
+        if (attr != null) {
+            element.setIdAttributeNode(attr, true);
+        }
+
+        if (secureValidation && (XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(algorithmURI)
+            || XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(algorithmURI))) {
+            Object exArgs[] = { algorithmURI };
+
+            throw new XMLSecurityException("signature.signatureAlgorithm", exArgs);
+        }
 
-   private static SignatureAlgorithmSpi buildSigner(String algorithmURI, SignatureAlgorithmSpi result) throws XMLSignatureException {
+        signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
+        signatureAlgorithm.engineGetContextFromElement(this._constructionElement);
+    }
+
+    /**
+     * Get a SignatureAlgorithmSpi object corresponding to the algorithmURI argument
+     */
+    private static SignatureAlgorithmSpi getSignatureAlgorithmSpi(String algorithmURI)
+        throws XMLSignatureException {
         try {
-         Class<? extends SignatureAlgorithmSpi> implementingClass =
-            SignatureAlgorithm.getImplementingClass(algorithmURI);
-         if (log.isLoggable(java.util.logging.Level.FINE))
+            Class<? extends SignatureAlgorithmSpi> implementingClass =
+                algorithmHash.get(algorithmURI);
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
                 log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
                    + implementingClass + "\"");
-         result= implementingClass.newInstance();
-         return   result;
-      }  catch (IllegalAccessException ex) {
-         Object exArgs[] = { algorithmURI, ex.getMessage() };
-
-         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
-                                         ex);
-      } catch (InstantiationException ex) {
-         Object exArgs[] = { algorithmURI, ex.getMessage() };
-
-         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
-                                         ex);
-      } catch (NullPointerException ex) {
-         Object exArgs[] = { algorithmURI, ex.getMessage() };
-
-         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
-                                         ex);
-      }
-}
+            }
+            return implementingClass.newInstance();
+        }  catch (IllegalAccessException ex) {
+            Object exArgs[] = { algorithmURI, ex.getMessage() };
+            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex);
+        } catch (InstantiationException ex) {
+            Object exArgs[] = { algorithmURI, ex.getMessage() };
+            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex);
+        } catch (NullPointerException ex) {
+            Object exArgs[] = { algorithmURI, ex.getMessage() };
+            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex);
+        }
+    }
 
-   /**
-    * Constructor SignatureAlgorithm
-    *
-    * @param doc
-    * @param algorithmURI
-    * @param HMACOutputLength
-    * @throws XMLSecurityException
-    */
-   public SignatureAlgorithm(
-           Document doc, String algorithmURI, int HMACOutputLength)
-              throws XMLSecurityException {
 
-      this(doc, algorithmURI);
-      this.algorithmURI=algorithmURI;
-      initializeAlgorithm(true);
-      this._signatureAlgorithm.engineSetHMACOutputLength(HMACOutputLength);
-      ((IntegrityHmac)this._signatureAlgorithm)
-         .engineAddContextToElement(this._constructionElement);
-   }
+    /**
+     * Proxy method for {@link java.security.Signature#sign()}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @return the result of the {@link java.security.Signature#sign()} method
+     * @throws XMLSignatureException
+     */
+    public byte[] sign() throws XMLSignatureException {
+        return signatureAlgorithm.engineSign();
+    }
 
-   /**
-    * Constructor SignatureAlgorithm
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public SignatureAlgorithm(Element element, String BaseURI)
-           throws XMLSecurityException {
+    /**
+     * Proxy method for {@link java.security.Signature#getAlgorithm}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @return the result of the {@link java.security.Signature#getAlgorithm} method
+     */
+    public String getJCEAlgorithmString() {
+        return signatureAlgorithm.engineGetJCEAlgorithmString();
+    }
 
-      super(element, BaseURI);
-      algorithmURI = this.getURI();
-   }
+    /**
+     * Method getJCEProviderName
+     *
+     * @return The Provider of this Signature Algorithm
+     */
+    public String getJCEProviderName() {
+        return signatureAlgorithm.engineGetJCEProviderName();
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#sign()}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @return the result of the {@link java.security.Signature#sign()} method
-    * @throws XMLSignatureException
-    */
-   public byte[] sign() throws XMLSignatureException {
-      return this._signatureAlgorithm.engineSign();
-   }
+    /**
+     * Proxy method for {@link java.security.Signature#update(byte[])}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param input
+     * @throws XMLSignatureException
+     */
+    public void update(byte[] input) throws XMLSignatureException {
+        signatureAlgorithm.engineUpdate(input);
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#getAlgorithm}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @return the result of the {@link java.security.Signature#getAlgorithm} method
-    */
-   public String getJCEAlgorithmString() {
-      try {
-                return getInstanceForVerify(algorithmURI).engineGetJCEAlgorithmString();
-        } catch (XMLSignatureException e) {
-                //Ignore.
-                return null;
-        }
-   }
+    /**
+     * Proxy method for {@link java.security.Signature#update(byte)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param input
+     * @throws XMLSignatureException
+     */
+    public void update(byte input) throws XMLSignatureException {
+        signatureAlgorithm.engineUpdate(input);
+    }
 
-   /**
-    * Method getJCEProviderName
-    *
-    * @return The Provider of this Signature Alogrithm
-    */
-   public String getJCEProviderName() {
-      try {
-                return getInstanceForVerify(algorithmURI).engineGetJCEProviderName();
-        } catch (XMLSignatureException e) {
-                return null;
-        }
-   }
+    /**
+     * Proxy method for {@link java.security.Signature#update(byte[], int, int)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param buf
+     * @param offset
+     * @param len
+     * @throws XMLSignatureException
+     */
+    public void update(byte buf[], int offset, int len) throws XMLSignatureException {
+        signatureAlgorithm.engineUpdate(buf, offset, len);
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#update(byte[])}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param input
-    * @throws XMLSignatureException
-    */
-   public void update(byte[] input) throws XMLSignatureException {
-      this._signatureAlgorithm.engineUpdate(input);
-   }
+    /**
+     * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param signingKey
+     * @throws XMLSignatureException
+     */
+    public void initSign(Key signingKey) throws XMLSignatureException {
+        signatureAlgorithm.engineInitSign(signingKey);
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#update(byte)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param input
-    * @throws XMLSignatureException
-    */
-   public void update(byte input) throws XMLSignatureException {
-      this._signatureAlgorithm.engineUpdate(input);
-   }
+    /**
+     * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey,
+     * java.security.SecureRandom)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param signingKey
+     * @param secureRandom
+     * @throws XMLSignatureException
+     */
+    public void initSign(Key signingKey, SecureRandom secureRandom) throws XMLSignatureException {
+        signatureAlgorithm.engineInitSign(signingKey, secureRandom);
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#update(byte[], int, int)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param buf
-    * @param offset
-    * @param len
-    * @throws XMLSignatureException
-    */
-   public void update(byte buf[], int offset, int len)
-           throws XMLSignatureException {
-      this._signatureAlgorithm.engineUpdate(buf, offset, len);
-   }
+    /**
+     * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param signingKey
+     * @param algorithmParameterSpec
+     * @throws XMLSignatureException
+     */
+    public void initSign(
+        Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
+    ) throws XMLSignatureException {
+        signatureAlgorithm.engineInitSign(signingKey, algorithmParameterSpec);
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param signingKey
-    * @throws XMLSignatureException
-    */
-   public void initSign(Key signingKey) throws XMLSignatureException {
-           initializeAlgorithm(true);
-           Map<String, Key> map=keysSigning.get();
-       if (map.get(this.algorithmURI)==signingKey) {
-           return;
-       }
-       map.put(this.algorithmURI,signingKey);
-           this._signatureAlgorithm.engineInitSign(signingKey);
-   }
+    /**
+     * Proxy method for {@link java.security.Signature#setParameter(
+     * java.security.spec.AlgorithmParameterSpec)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param params
+     * @throws XMLSignatureException
+     */
+    public void setParameter(AlgorithmParameterSpec params) throws XMLSignatureException {
+        signatureAlgorithm.engineSetParameter(params);
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey, java.security.SecureRandom)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param signingKey
-    * @param secureRandom
-    * @throws XMLSignatureException
-    */
-   public void initSign(Key signingKey, SecureRandom secureRandom)
-           throws XMLSignatureException {
-           initializeAlgorithm(true);
-      this._signatureAlgorithm.engineInitSign(signingKey, secureRandom);
-   }
+    /**
+     * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param verificationKey
+     * @throws XMLSignatureException
+     */
+    public void initVerify(Key verificationKey) throws XMLSignatureException {
+        signatureAlgorithm.engineInitVerify(verificationKey);
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param signingKey
-    * @param algorithmParameterSpec
-    * @throws XMLSignatureException
-    */
-   public void initSign(
-           Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
-              throws XMLSignatureException {
-           initializeAlgorithm(true);
-      this._signatureAlgorithm.engineInitSign(signingKey,
-                                              algorithmParameterSpec);
-   }
+    /**
+     * Proxy method for {@link java.security.Signature#verify(byte[])}
+     * which is executed on the internal {@link java.security.Signature} object.
+     *
+     * @param signature
+     * @return true if if the signature is valid.
+     *
+     * @throws XMLSignatureException
+     */
+    public boolean verify(byte[] signature) throws XMLSignatureException {
+        return signatureAlgorithm.engineVerify(signature);
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#setParameter(java.security.spec.AlgorithmParameterSpec)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param params
-    * @throws XMLSignatureException
-    */
-   public void setParameter(AlgorithmParameterSpec params)
-           throws XMLSignatureException {
-      this._signatureAlgorithm.engineSetParameter(params);
-   }
+    /**
+     * Returns the URI representation of Transformation algorithm
+     *
+     * @return the URI representation of Transformation algorithm
+     */
+    public final String getURI() {
+        return _constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+    }
 
-   /**
-    * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param verificationKey
-    * @throws XMLSignatureException
-    */
-   public void initVerify(Key verificationKey) throws XMLSignatureException {
-           initializeAlgorithm(false);
-           Map<String, Key> map=keysVerify.get();
-           if (map.get(this.algorithmURI)==verificationKey) {
-           return;
-       }
-           map.put(this.algorithmURI,verificationKey);
-           this._signatureAlgorithm.engineInitVerify(verificationKey);
-   }
+    /**
+     * Registers implementing class of the Transform algorithm with algorithmURI
+     *
+     * @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>.
+     * @param implementingClass <code>implementingClass</code> the implementing class of
+     * {@link SignatureAlgorithmSpi}
+     * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
+     * @throws XMLSignatureException
+     */
+    @SuppressWarnings("unchecked")
+    public static void register(String algorithmURI, String implementingClass)
+       throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
+           XMLSignatureException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
+        }
 
-   /**
-    * Proxy method for {@link java.security.Signature#verify(byte[])}
-    * which is executed on the internal {@link java.security.Signature} object.
-    *
-    * @param signature
-    * @return true if if the signature is valid.
-    *
-    * @throws XMLSignatureException
-    */
-   public boolean verify(byte[] signature) throws XMLSignatureException {
-      return this._signatureAlgorithm.engineVerify(signature);
-   }
+        // are we already registered?
+        Class<? extends SignatureAlgorithmSpi> registeredClass = algorithmHash.get(algorithmURI);
+        if (registeredClass != null) {
+            Object exArgs[] = { algorithmURI, registeredClass };
+            throw new AlgorithmAlreadyRegisteredException(
+                "algorithm.alreadyRegistered", exArgs
+            );
+        }
+        try {
+            Class<? extends SignatureAlgorithmSpi> clazz =
+                (Class<? extends SignatureAlgorithmSpi>)
+                    ClassLoaderUtils.loadClass(implementingClass, SignatureAlgorithm.class);
+            algorithmHash.put(algorithmURI, clazz);
+        } catch (NullPointerException ex) {
+            Object exArgs[] = { algorithmURI, ex.getMessage() };
+            throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex);
+        }
+    }
 
-   /**
-    * Returns the URI representation of Transformation algorithm
-    *
-    * @return the URI representation of Transformation algorithm
-    */
-   public final String getURI() {
-      return this._constructionElement.getAttributeNS(null,
-              Constants._ATT_ALGORITHM);
-   }
-
-   /**
-    * Initalizes for this {@link com.sun.org.apache.xml.internal.security.transforms.Transform}
-    *
-    */
-   public static void providerInit() {
-
-      if (SignatureAlgorithm.log == null) {
-         SignatureAlgorithm.log =
-            java.util.logging.Logger
-               .getLogger(SignatureAlgorithm.class.getName());
-      }
-
-      log.log(java.util.logging.Level.FINE, "Init() called");
+    /**
+     * Registers implementing class of the Transform algorithm with algorithmURI
+     *
+     * @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>.
+     * @param implementingClass <code>implementingClass</code> the implementing class of
+     * {@link SignatureAlgorithmSpi}
+     * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
+     * @throws XMLSignatureException
+     */
+    public static void register(String algorithmURI, Class<? extends SignatureAlgorithmSpi> implementingClass)
+       throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
+           XMLSignatureException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
+        }
 
-      if (!SignatureAlgorithm._alreadyInitialized) {
-         SignatureAlgorithm._algorithmHash = new HashMap<String, Class<? extends SignatureAlgorithmSpi>>(10);
-         SignatureAlgorithm._alreadyInitialized = true;
-      }
-   }
-
-   /**
-    * Registers implementing class of the Transform algorithm with algorithmURI
-    *
-    * @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>.
-    * @param implementingClass <code>implementingClass</code> the implementing class of {@link SignatureAlgorithmSpi}
-    * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
-    * @throws XMLSignatureException
-    */
-   @SuppressWarnings("unchecked")
-   public static void register(String algorithmURI, String implementingClass)
-           throws AlgorithmAlreadyRegisteredException,XMLSignatureException {
-
-      {
-         if (log.isLoggable(java.util.logging.Level.FINE))
-                log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
-
-         // are we already registered?
-         Class<? extends SignatureAlgorithmSpi> registeredClassClass =
-            SignatureAlgorithm.getImplementingClass(algorithmURI);
-                 if (registeredClassClass!=null) {
-                         String registeredClass = registeredClassClass.getName();
-
-                         if ((registeredClass != null) && (registeredClass.length() != 0)) {
-                                 Object exArgs[] = { algorithmURI, registeredClass };
-
-                                 throw new AlgorithmAlreadyRegisteredException(
-                                                 "algorithm.alreadyRegistered", exArgs);
-                         }
-                 }
-                 try {
-                         SignatureAlgorithm._algorithmHash.put(algorithmURI, (Class <? extends SignatureAlgorithmSpi>)Class.forName(implementingClass));
-              } catch (ClassNotFoundException ex) {
-                 Object exArgs[] = { algorithmURI, ex.getMessage() };
+        // are we already registered?
+        Class<? extends SignatureAlgorithmSpi> registeredClass = algorithmHash.get(algorithmURI);
+        if (registeredClass != null) {
+            Object exArgs[] = { algorithmURI, registeredClass };
+            throw new AlgorithmAlreadyRegisteredException(
+                "algorithm.alreadyRegistered", exArgs
+            );
+        }
+        algorithmHash.put(algorithmURI, implementingClass);
+    }
 
-                 throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
-                                                 ex);
-              } catch (NullPointerException ex) {
-                 Object exArgs[] = { algorithmURI, ex.getMessage() };
-
-                 throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
-                                                 ex);
-              }
-
-      }
-   }
-
-   /**
-    * Method getImplementingClass
-    *
-    * @param URI
-    * @return the class that implements the URI
-    */
-   private static Class<? extends SignatureAlgorithmSpi> getImplementingClass(String URI) {
+    /**
+     * This method registers the default algorithms.
+     */
+    public static void registerDefaultAlgorithms() {
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_DSA, SignatureDSA.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, SignatureBaseRSA.SignatureRSASHA1.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_SHA1, IntegrityHmac.IntegrityHmacSHA1.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5,
+            SignatureBaseRSA.SignatureRSAMD5.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160,
+            SignatureBaseRSA.SignatureRSARIPEMD160.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256, SignatureBaseRSA.SignatureRSASHA256.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384, SignatureBaseRSA.SignatureRSASHA384.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512, SignatureBaseRSA.SignatureRSASHA512.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, SignatureECDSA.SignatureECDSASHA1.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, IntegrityHmac.IntegrityHmacMD5.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160, IntegrityHmac.IntegrityHmacRIPEMD160.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_SHA256, IntegrityHmac.IntegrityHmacSHA256.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_SHA384, IntegrityHmac.IntegrityHmacSHA384.class
+        );
+        algorithmHash.put(
+            XMLSignature.ALGO_ID_MAC_HMAC_SHA512, IntegrityHmac.IntegrityHmacSHA512.class
+        );
+    }
 
-      if (SignatureAlgorithm._algorithmHash == null) {
-         return null;
-      }
-
-      return SignatureAlgorithm._algorithmHash.get(URI);
-   }
+    /**
+     * Method getBaseNamespace
+     *
+     * @return URI of this element
+     */
+    public String getBaseNamespace() {
+        return Constants.SignatureSpecNS;
+    }
 
-   /**
-    * Method getBaseNamespace
-    *
-    * @return URI of this element
-    */
-   public String getBaseNamespace() {
-      return Constants.SignatureSpecNS;
-   }
-
-   /**
-    * Method getBaseLocalName
-    *
-    * @return Local name
-    */
-   public String getBaseLocalName() {
-      return Constants._TAG_SIGNATUREMETHOD;
-   }
+    /**
+     * Method getBaseLocalName
+     *
+     * @return Local name
+     */
+    public String getBaseLocalName() {
+        return Constants._TAG_SIGNATUREMETHOD;
+    }
 }
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -2,34 +2,43 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2008 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.c14n;
 
 import java.io.ByteArrayInputStream;
+import java.io.InputStream;
 import java.io.OutputStream;
-import java.util.HashMap;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 
+import javax.xml.XMLConstants;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.xpath.XPath;
 
+import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments;
+import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_WithComments;
+import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclOmitComments;
+import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclWithComments;
+import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315OmitComments;
+import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315WithComments;
 import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
@@ -46,7 +55,7 @@
     public static final String ENCODING = "UTF8";
 
     /**
-     * XPath Expresion for selecting every node and continuous comments joined
+     * XPath Expression for selecting every node and continuous comments joined
      * in only one node
      */
     public static final String XPATH_C14N_WITH_COMMENTS_SINGLE_NODE =
@@ -83,22 +92,10 @@
     public static final String ALGO_ID_C14N11_WITH_COMMENTS =
         ALGO_ID_C14N11_OMIT_COMMENTS + "#WithComments";
 
-    static boolean _alreadyInitialized = false;
-    static Map<String,Class<? extends CanonicalizerSpi>> _canonicalizerHash = null;
-
-    protected CanonicalizerSpi canonicalizerSpi = null;
+    private static Map<String, Class<? extends CanonicalizerSpi>> canonicalizerHash =
+        new ConcurrentHashMap<String, Class<? extends CanonicalizerSpi>>();
 
-    /**
-     * Method init
-     *
-     */
-    public static void init() {
-
-        if (!Canonicalizer._alreadyInitialized) {
-            Canonicalizer._canonicalizerHash = new HashMap<String, Class<? extends CanonicalizerSpi>>(10);
-            Canonicalizer._alreadyInitialized = true;
-        }
-    }
+    private final CanonicalizerSpi canonicalizerSpi;
 
     /**
      * Constructor Canonicalizer
@@ -106,21 +103,18 @@
      * @param algorithmURI
      * @throws InvalidCanonicalizerException
      */
-    private Canonicalizer(String algorithmURI)
-           throws InvalidCanonicalizerException {
-
+    private Canonicalizer(String algorithmURI) throws InvalidCanonicalizerException {
         try {
             Class<? extends CanonicalizerSpi> implementingClass =
-                getImplementingClass(algorithmURI);
+                canonicalizerHash.get(algorithmURI);
 
-            this.canonicalizerSpi =
-                 implementingClass.newInstance();
-            this.canonicalizerSpi.reset=true;
+            canonicalizerSpi = implementingClass.newInstance();
+            canonicalizerSpi.reset = true;
         } catch (Exception e) {
             Object exArgs[] = { algorithmURI };
-
             throw new InvalidCanonicalizerException(
-               "signature.Canonicalizer.UnknownCanonicalizer", exArgs);
+                "signature.Canonicalizer.UnknownCanonicalizer", exArgs, e
+            );
         }
     }
 
@@ -128,15 +122,12 @@
      * Method getInstance
      *
      * @param algorithmURI
-     * @return a Conicicalizer instance ready for the job
+     * @return a Canonicalizer instance ready for the job
      * @throws InvalidCanonicalizerException
      */
     public static final Canonicalizer getInstance(String algorithmURI)
-           throws InvalidCanonicalizerException {
-
-        Canonicalizer c14nizer = new Canonicalizer(algorithmURI);
-
-        return c14nizer;
+        throws InvalidCanonicalizerException {
+        return new Canonicalizer(algorithmURI);
     }
 
     /**
@@ -148,23 +139,69 @@
      */
     @SuppressWarnings("unchecked")
     public static void register(String algorithmURI, String implementingClass)
-           throws AlgorithmAlreadyRegisteredException {
+        throws AlgorithmAlreadyRegisteredException, ClassNotFoundException {
+        // check whether URI is already registered
+        Class<? extends CanonicalizerSpi> registeredClass =
+            canonicalizerHash.get(algorithmURI);
+
+        if (registeredClass != null)  {
+            Object exArgs[] = { algorithmURI, registeredClass };
+            throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs);
+        }
 
+        canonicalizerHash.put(
+            algorithmURI, (Class<? extends CanonicalizerSpi>)Class.forName(implementingClass)
+        );
+    }
+
+    /**
+     * Method register
+     *
+     * @param algorithmURI
+     * @param implementingClass
+     * @throws AlgorithmAlreadyRegisteredException
+     */
+    public static void register(String algorithmURI, Class<CanonicalizerSpi> implementingClass)
+        throws AlgorithmAlreadyRegisteredException, ClassNotFoundException {
         // check whether URI is already registered
-        Class<? extends CanonicalizerSpi> registeredClass = getImplementingClass(algorithmURI);
+        Class<? extends CanonicalizerSpi> registeredClass = canonicalizerHash.get(algorithmURI);
 
         if (registeredClass != null)  {
             Object exArgs[] = { algorithmURI, registeredClass };
-
-            throw new AlgorithmAlreadyRegisteredException(
-                "algorithm.alreadyRegistered", exArgs);
+            throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs);
         }
 
-        try {
-            _canonicalizerHash.put(algorithmURI, (Class<? extends CanonicalizerSpi>) Class.forName(implementingClass));
-        } catch (ClassNotFoundException e) {
-            throw new RuntimeException("c14n class not found");
-        }
+        canonicalizerHash.put(algorithmURI, implementingClass);
+    }
+
+    /**
+     * This method registers the default algorithms.
+     */
+    public static void registerDefaultAlgorithms() {
+        canonicalizerHash.put(
+            Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS,
+            Canonicalizer20010315OmitComments.class
+        );
+        canonicalizerHash.put(
+            Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS,
+            Canonicalizer20010315WithComments.class
+        );
+        canonicalizerHash.put(
+            Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS,
+            Canonicalizer20010315ExclOmitComments.class
+        );
+        canonicalizerHash.put(
+            Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS,
+            Canonicalizer20010315ExclWithComments.class
+        );
+        canonicalizerHash.put(
+            Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS,
+            Canonicalizer11_OmitComments.class
+        );
+        canonicalizerHash.put(
+            Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS,
+            Canonicalizer11_WithComments.class
+        );
     }
 
     /**
@@ -173,7 +210,7 @@
      * @return the URI defined for this c14n instance.
      */
     public final String getURI() {
-        return this.canonicalizerSpi.engineGetURI();
+        return canonicalizerSpi.engineGetURI();
     }
 
     /**
@@ -182,7 +219,7 @@
      * @return true if the c14n respect the comments.
      */
     public boolean getIncludeComments() {
-        return this.canonicalizerSpi.engineGetIncludeComments();
+        return canonicalizerSpi.engineGetIncludeComments();
     }
 
     /**
@@ -191,33 +228,32 @@
      * wrapped with a <CODE>&gt;a&lt;...&gt;/a&lt;</CODE>.
      *
      * @param inputBytes
-     * @return the result of the conicalization.
+     * @return the result of the canonicalization.
      * @throws CanonicalizationException
      * @throws java.io.IOException
      * @throws javax.xml.parsers.ParserConfigurationException
      * @throws org.xml.sax.SAXException
      */
     public byte[] canonicalize(byte[] inputBytes)
-           throws javax.xml.parsers.ParserConfigurationException,
-                  java.io.IOException, org.xml.sax.SAXException,
-                  CanonicalizationException {
-
-        ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes);
+        throws javax.xml.parsers.ParserConfigurationException,
+        java.io.IOException, org.xml.sax.SAXException, CanonicalizationException {
+        InputStream bais = new ByteArrayInputStream(inputBytes);
         InputSource in = new InputSource(bais);
         DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
+        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
 
         dfactory.setNamespaceAware(true);
 
-        // needs to validate for ID attribute nomalization
+        // needs to validate for ID attribute normalization
         dfactory.setValidating(true);
 
         DocumentBuilder db = dfactory.newDocumentBuilder();
 
         /*
          * for some of the test vectors from the specification,
-         * there has to be a validatin parser for ID attributes, default
+         * there has to be a validating parser for ID attributes, default
          * attribute values, NMTOKENS, etc.
-         * Unfortunaltely, the test vectors do use different DTDs or
+         * Unfortunately, the test vectors do use different DTDs or
          * even no DTD. So Xerces 1.3.1 fires many warnings about using
          * ErrorHandlers.
          *
@@ -233,28 +269,23 @@
          * declaration are used to help create the canonical form, even
          * though the document type declaration is not retained in the
          * canonical form.
-         *
          */
-        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils
-            .IgnoreAllErrorHandler());
+        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());
 
         Document document = db.parse(in);
-        byte result[] = this.canonicalizeSubtree(document);
-
-        return result;
+        return this.canonicalizeSubtree(document);
     }
 
     /**
      * Canonicalizes the subtree rooted by <CODE>node</CODE>.
      *
-     * @param node The node to canicalize
+     * @param node The node to canonicalize
      * @return the result of the c14n.
      *
      * @throws CanonicalizationException
      */
-    public byte[] canonicalizeSubtree(Node node)
-           throws CanonicalizationException {
-        return this.canonicalizerSpi.engineCanonicalizeSubTree(node);
+    public byte[] canonicalizeSubtree(Node node) throws CanonicalizationException {
+        return canonicalizerSpi.engineCanonicalizeSubTree(node);
     }
 
     /**
@@ -266,9 +297,8 @@
      * @throws CanonicalizationException
      */
     public byte[] canonicalizeSubtree(Node node, String inclusiveNamespaces)
-           throws CanonicalizationException {
-        return this.canonicalizerSpi.engineCanonicalizeSubTree(node,
-              inclusiveNamespaces);
+        throws CanonicalizationException {
+        return canonicalizerSpi.engineCanonicalizeSubTree(node, inclusiveNamespaces);
     }
 
     /**
@@ -280,8 +310,8 @@
      * @throws CanonicalizationException
      */
     public byte[] canonicalizeXPathNodeSet(NodeList xpathNodeSet)
-           throws CanonicalizationException {
-        return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
+        throws CanonicalizationException {
+        return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
     }
 
     /**
@@ -294,10 +324,10 @@
      * @throws CanonicalizationException
      */
     public byte[] canonicalizeXPathNodeSet(
-           NodeList xpathNodeSet, String inclusiveNamespaces)
-              throws CanonicalizationException {
-        return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet,
-              inclusiveNamespaces);
+        NodeList xpathNodeSet, String inclusiveNamespaces
+    ) throws CanonicalizationException {
+        return
+            canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces);
     }
 
     /**
@@ -308,8 +338,8 @@
      * @throws CanonicalizationException
      */
     public byte[] canonicalizeXPathNodeSet(Set<Node> xpathNodeSet)
-           throws CanonicalizationException {
-        return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
+        throws CanonicalizationException {
+        return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet);
     }
 
     /**
@@ -320,10 +350,11 @@
      * @return the result of the c14n.
      * @throws CanonicalizationException
      */
-    public byte[] canonicalizeXPathNodeSet(Set<Node> xpathNodeSet,
-        String inclusiveNamespaces) throws CanonicalizationException {
-        return this.canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet,
-            inclusiveNamespaces);
+    public byte[] canonicalizeXPathNodeSet(
+        Set<Node> xpathNodeSet, String inclusiveNamespaces
+    ) throws CanonicalizationException {
+        return
+            canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces);
     }
 
     /**
@@ -332,7 +363,7 @@
      * @param os
      */
     public void setWriter(OutputStream os) {
-        this.canonicalizerSpi.setWriter(os);
+        canonicalizerSpi.setWriter(os);
     }
 
     /**
@@ -341,23 +372,14 @@
      * @return the name of the implementing {@link CanonicalizerSpi} class
      */
     public String getImplementingCanonicalizerClass() {
-        return this.canonicalizerSpi.getClass().getName();
-    }
-
-    /**
-     * Method getImplementingClass
-     *
-     * @param URI
-     * @return the name of the class that implements the given URI
-     */
-    private static Class<? extends CanonicalizerSpi> getImplementingClass(String URI) {
-        return _canonicalizerHash.get(URI);
+        return canonicalizerSpi.getClass().getName();
     }
 
     /**
      * Set the canonicalizer behaviour to not reset.
      */
     public void notReset() {
-        this.canonicalizerSpi.reset = false;
+        canonicalizerSpi.reset = false;
     }
+
 }
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java	Wed Jul 05 19:00:49 2017 +0200
@@ -26,6 +26,7 @@
 import java.io.OutputStream;
 import java.util.Set;
 
+import javax.xml.XMLConstants;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.xpath.XPath;
@@ -67,6 +68,7 @@
       java.io.ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes);
       InputSource in = new InputSource(bais);
       DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
+      dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
 
       // needs to validate for ID attribute nomalization
       dfactory.setNamespaceAware(true);
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java	Wed Jul 05 19:00:49 2017 +0200
@@ -41,6 +41,7 @@
 import javax.crypto.IllegalBlockSizeException;
 import javax.crypto.NoSuchPaddingException;
 import javax.crypto.spec.IvParameterSpec;
+import javax.xml.XMLConstants;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
@@ -1981,22 +1982,23 @@
             try {
                 DocumentBuilderFactory dbf =
                     DocumentBuilderFactory.newInstance();
-                                dbf.setNamespaceAware(true);
-                                dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE);
-                                DocumentBuilder db = dbf.newDocumentBuilder();
-                                Document d = db.parse(
-                                    new InputSource(new StringReader(fragment)));
-
-                                Element fragElt = (Element) _contextDocument.importNode(
+                dbf.setNamespaceAware(true);
+                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+                dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE);
+                DocumentBuilder db = dbf.newDocumentBuilder();
+                Document d = db.parse(
+                    new InputSource(new StringReader(fragment)));
+
+                Element fragElt = (Element) _contextDocument.importNode(
                                                  d.getDocumentElement(), true);
-                                result = _contextDocument.createDocumentFragment();
-                                Node child = fragElt.getFirstChild();
-                                while (child != null) {
-                                        fragElt.removeChild(child);
-                                        result.appendChild(child);
-                                        child = fragElt.getFirstChild();
-                                }
-                                // String outp = serialize(d);
+                result = _contextDocument.createDocumentFragment();
+                Node child = fragElt.getFirstChild();
+                while (child != null) {
+                    fragElt.removeChild(child);
+                    result.appendChild(child);
+                    child = fragElt.getFirstChild();
+                }
+                // String outp = serialize(d);
 
             } catch (SAXException se) {
                 throw new XMLEncryptionException("empty", se);
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java	Wed Jul 05 19:00:49 2017 +0200
@@ -54,6 +54,7 @@
 import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -128,8 +129,11 @@
     */
    public KeyInfo(Element element, String BaseURI) throws XMLSecurityException {
       super(element, BaseURI);
-     // _storageResolvers.add(null);
 
+      Attr attr = element.getAttributeNodeNS(null, "Id");
+      if (attr != null) {
+          element.setIdAttributeNode(attr, true);
+      }
    }
 
    /**
@@ -139,9 +143,8 @@
     */
    public void setId(String Id) {
 
-      if ((Id != null)) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
-         IdResolver.registerElementById(this._constructionElement, Id);
+      if (Id != null) {
+          setLocalIdAttribute(Constants._ATT_ID, Id);
       }
    }
 
@@ -719,42 +722,36 @@
       return null;
    }
 
-   /**
-    * Searches the library wide keyresolvers for public keys
-    *
-    * @return The publick contained in this Node.
-    * @throws KeyResolverException
-    */
-   PublicKey getPublicKeyFromStaticResolvers() throws KeyResolverException {
-          int length=KeyResolver.length();
-          int storageLength=this._storageResolvers.size();
-          Iterator<KeyResolverSpi> it= KeyResolver.iterator();
-      for (int i = 0; i < length; i++) {
-         KeyResolverSpi keyResolver = it.next();
-         Node currentChild=this._constructionElement.getFirstChild();
-         String uri= this.getBaseURI();
-         while (currentChild!=null)      {
-            if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
-                  for (int k = 0; k < storageLength; k++) {
-                     StorageResolver storage =
-                        this._storageResolvers.get(k);
+    /**
+     * Searches the library wide keyresolvers for public keys
+     *
+     * @return The public key contained in this Node.
+     * @throws KeyResolverException
+     */
+    PublicKey getPublicKeyFromStaticResolvers() throws KeyResolverException {
+        Iterator<KeyResolverSpi> it = KeyResolver.iterator();
+        while (it.hasNext()) {
+            KeyResolverSpi keyResolver = it.next();
+            Node currentChild = this._constructionElement.getFirstChild();
+            String uri = this.getBaseURI();
+            while (currentChild != null) {
+                if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
+                    for (StorageResolver storage : _storageResolvers) {
+                        PublicKey pk =
+                            keyResolver.engineLookupAndResolvePublicKey(
+                                (Element) currentChild, uri, storage
+                            );
 
-                     PublicKey pk =
-                           keyResolver.engineLookupAndResolvePublicKey((Element) currentChild,
-                                                       uri,
-                                                        storage);
-
-                     if (pk != null) {
-                         KeyResolver.hit(it);
-                         return pk;
-                     }
-                  }
+                        if (pk != null) {
+                            return pk;
+                        }
+                    }
+                }
+                currentChild = currentChild.getNextSibling();
             }
-            currentChild=currentChild.getNextSibling();
-         }
-      }
-      return null;
-   }
+        }
+        return null;
+    }
 
    /**
     * Searches the per-KeyInfo keyresolvers for public keys
@@ -829,81 +826,83 @@
       return null;
    }
 
-   /**
-    * This method uses each System-wide {@link KeyResolver} to search the
-    * child elements. Each combination of {@link KeyResolver} and child element
-    * is checked against all {@link StorageResolver}s.
-    *
-    * @return The certificate contined in this KeyInfo
-    * @throws KeyResolverException
-    */
-   X509Certificate getX509CertificateFromStaticResolvers()
-           throws KeyResolverException {
-      if (log.isLoggable(java.util.logging.Level.FINE))
-        log.log(java.util.logging.Level.FINE, "Start getX509CertificateFromStaticResolvers() with "
-                + KeyResolver.length() + " resolvers");
-      String uri=this.getBaseURI();
-      int length= KeyResolver.length();
-      int storageLength=this._storageResolvers.size();
-      Iterator<KeyResolverSpi> it = KeyResolver.iterator();
-      for (int i = 0; i <length; i++) {
-         KeyResolverSpi keyResolver =  it.next();
-         X509Certificate cert= applyCurrentResolver(uri, storageLength, keyResolver);
-         if (cert!=null) {
-                 KeyResolver.hit(it);
-                 return cert;
-         }
-      }
-      return null;
-   }
-
-   private X509Certificate applyCurrentResolver(String uri, int storageLength, KeyResolverSpi keyResolver) throws KeyResolverException {
-           Node currentChild=this._constructionElement.getFirstChild();
-           while (currentChild!=null)      {
-                   if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
-               for (int k = 0; k < storageLength; k++) {
-                   StorageResolver storage =
-                      this._storageResolvers.get(k);
+    /**
+     * This method uses each System-wide {@link KeyResolver} to search the
+     * child elements. Each combination of {@link KeyResolver} and child element
+     * is checked against all {@link StorageResolver}s.
+     *
+     * @return The certificate contained in this KeyInfo
+     * @throws KeyResolverException
+     */
+    X509Certificate getX509CertificateFromStaticResolvers()
+        throws KeyResolverException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE,
+                "Start getX509CertificateFromStaticResolvers() with " + KeyResolver.length()
+                + " resolvers"
+            );
+        }
+        String uri = this.getBaseURI();
+        Iterator<KeyResolverSpi> it = KeyResolver.iterator();
+        while (it.hasNext()) {
+            KeyResolverSpi keyResolver = it.next();
+            X509Certificate cert = applyCurrentResolver(uri, keyResolver);
+            if (cert != null) {
+                return cert;
+            }
+        }
+        return null;
+    }
 
-                   X509Certificate cert = keyResolver
-                        .engineLookupResolveX509Certificate((Element) currentChild, uri,
-                                        storage);
+    private X509Certificate applyCurrentResolver(
+        String uri, KeyResolverSpi keyResolver
+    ) throws KeyResolverException {
+        Node currentChild = this._constructionElement.getFirstChild();
+        while (currentChild != null)      {
+            if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
+                for (StorageResolver storage : _storageResolvers) {
+                    X509Certificate cert =
+                        keyResolver.engineLookupResolveX509Certificate(
+                            (Element) currentChild, uri, storage
+                        );
 
-                   if (cert != null) {
-                       return cert;
-                  }
-               }
+                    if (cert != null) {
+                        return cert;
+                    }
+                }
             }
-            currentChild=currentChild.getNextSibling();
-         }
-         return null;
-   }
+            currentChild = currentChild.getNextSibling();
+        }
+        return null;
+    }
 
-   /**
-    * Method getX509CertificateFromInternalResolvers
-    *
-    * @return The certificate contined in this KeyInfo
-    * @throws KeyResolverException
-    */
-   X509Certificate getX509CertificateFromInternalResolvers()
-           throws KeyResolverException {
-      if (log.isLoggable(java.util.logging.Level.FINE))
-        log.log(java.util.logging.Level.FINE, "Start getX509CertificateFromInternalResolvers() with "
-                + this.lengthInternalKeyResolver() + " resolvers");
-      String uri=this.getBaseURI();
-      int storageLength=this._storageResolvers.size();
-      for (int i = 0; i < this.lengthInternalKeyResolver(); i++) {
-         KeyResolverSpi keyResolver = this.itemInternalKeyResolver(i);
-         if (log.isLoggable(java.util.logging.Level.FINE))
+    /**
+     * Method getX509CertificateFromInternalResolvers
+     *
+     * @return The certificate contined in this KeyInfo
+     * @throws KeyResolverException
+     */
+    X509Certificate getX509CertificateFromInternalResolvers()
+        throws KeyResolverException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE,
+                "Start getX509CertificateFromInternalResolvers() with "
+                + this.lengthInternalKeyResolver() + " resolvers"
+            );
+        }
+        String uri = this.getBaseURI();
+        for (KeyResolverSpi keyResolver : _internalKeyResolvers) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
                 log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
-         X509Certificate cert= applyCurrentResolver(uri, storageLength, keyResolver);
-         if (cert!=null) {
-                 return cert;
-         }
-      }
+            }
+            X509Certificate cert = applyCurrentResolver(uri, keyResolver);
+            if (cert != null) {
+                return cert;
+            }
+        }
 
-      return null;
-   }
+        return null;
+    }
 
    /**
     * This method returns a secret (symmetric) key. This is for XML Encryption.
@@ -1012,7 +1011,7 @@
    /**
     * Stores the individual (per-KeyInfo) {@link KeyResolver}s
     */
-   List<KeyResolverSpi> _internalKeyResolvers = null;
+   List<KeyResolverSpi> _internalKeyResolvers = new ArrayList<KeyResolverSpi>();
 
    /**
     * This method is used to add a custom {@link KeyResolverSpi} to a KeyInfo
@@ -1048,7 +1047,7 @@
    }
 
    /** Field _storageResolvers */
-   List<StorageResolver> _storageResolvers = nullList;
+   private List<StorageResolver> _storageResolvers = nullList;
 
    /**
     * Method addStorageResolver
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java	Wed Jul 05 19:00:49 2017 +0200
@@ -2,357 +2,402 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.keys.keyresolver;
 
-
-
 import java.security.PublicKey;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
 
 import javax.crypto.SecretKey;
 
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DSAKeyValueResolver;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RSAKeyValueResolver;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RetrievalMethodResolver;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509CertificateResolver;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509IssuerSerialResolver;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SKIResolver;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SubjectNameResolver;
 import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
-
 /**
  * KeyResolver is factory class for subclass of KeyResolverSpi that
  * represent child element of KeyInfo.
- *
- * @author $Author: mullan $
- * @version %I%, %G%
  */
 public class KeyResolver {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(KeyResolver.class.getName());
 
-   /** Field _alreadyInitialized */
-   static boolean _alreadyInitialized = false;
+    /** Field resolverVector */
+    private static List<KeyResolver> resolverVector = new CopyOnWriteArrayList<KeyResolver>();
 
-   /** Field _resolverVector */
-   static List<KeyResolver> _resolverVector = null;
+    /** Field resolverSpi */
+    private final KeyResolverSpi resolverSpi;
 
-   /** Field _resolverSpi */
-   protected KeyResolverSpi _resolverSpi = null;
+    /**
+     * Constructor.
+     *
+     * @param keyResolverSpi a KeyResolverSpi instance
+     */
+    private KeyResolver(KeyResolverSpi keyResolverSpi) {
+        resolverSpi = keyResolverSpi;
+    }
 
-   /** Field _storage */
-   protected StorageResolver _storage = null;
+    /**
+     * Method length
+     *
+     * @return the length of resolvers registered
+     */
+    public static int length() {
+        return resolverVector.size();
+    }
 
-   /**
-    * Constructor ResourceResolver
-    *
-    * @param className
-    * @throws ClassNotFoundException
-    * @throws IllegalAccessException
-    * @throws InstantiationException
-    */
-   private KeyResolver(String className)
-           throws ClassNotFoundException, IllegalAccessException,
-                  InstantiationException {
-      this._resolverSpi =
-         (KeyResolverSpi) Class.forName(className).newInstance();
-      this._resolverSpi.setGlobalResolver(true);
-   }
+    /**
+     * Method getX509Certificate
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return The certificate represented by the element.
+     *
+     * @throws KeyResolverException
+     */
+    public static final X509Certificate getX509Certificate(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        for (KeyResolver resolver : resolverVector) {
+            if (resolver == null) {
+                Object exArgs[] = {
+                                   (((element != null)
+                                       && (element.getNodeType() == Node.ELEMENT_NODE))
+                                       ? element.getTagName() : "null")
+                };
+
+                throw new KeyResolverException("utils.resolver.noClass", exArgs);
+            }
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver.getClass());
+            }
+
+            X509Certificate cert = resolver.resolveX509Certificate(element, baseURI, storage);
+            if (cert != null) {
+                return cert;
+            }
+        }
+
+        Object exArgs[] = {
+                           (((element != null) && (element.getNodeType() == Node.ELEMENT_NODE))
+                           ? element.getTagName() : "null")
+                          };
 
-   /**
-    * Method length
-    *
-    * @return the length of resolvers registed
-    */
-   public static int length() {
-      return KeyResolver._resolverVector.size();
-   }
+        throw new KeyResolverException("utils.resolver.noClass", exArgs);
+    }
+
+    /**
+     * Method getPublicKey
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return the public key contained in the element
+     *
+     * @throws KeyResolverException
+     */
+    public static final PublicKey getPublicKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        for (KeyResolver resolver : resolverVector) {
+            if (resolver == null) {
+                Object exArgs[] = {
+                                   (((element != null)
+                                       && (element.getNodeType() == Node.ELEMENT_NODE))
+                                       ? element.getTagName() : "null")
+                };
+
+                throw new KeyResolverException("utils.resolver.noClass", exArgs);
+            }
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver.getClass());
+            }
 
-   public static void hit(Iterator<KeyResolverSpi> hintI) {
-           ResolverIterator hint = (ResolverIterator) hintI;
-           int i = hint.i;
-           if (i!=1 && hint.res ==_resolverVector) {
-                   List<KeyResolver> resolverVector=getResolverVectorClone();
-                KeyResolver ob=resolverVector.remove(i-1);
-                resolverVector.add(0,ob);
-                 _resolverVector=resolverVector;
-         } else {
-                 //System.out.println("KeyResolver hitting");
-         }
-   }
+            PublicKey cert = resolver.resolvePublicKey(element, baseURI, storage);
+            if (cert != null) {
+                return cert;
+            }
+        }
+
+        Object exArgs[] = {
+                           (((element != null) && (element.getNodeType() == Node.ELEMENT_NODE))
+                           ? element.getTagName() : "null")
+                          };
+
+        throw new KeyResolverException("utils.resolver.noClass", exArgs);
+    }
 
-   /**
-    * Method getInstance
-    *
-    * @param element
-    * @param BaseURI
-    * @param storage
-    * @return The certificate represented by the element.
-    *
-    * @throws KeyResolverException
-    */
-   public static final X509Certificate getX509Certificate(
-           Element element, String BaseURI, StorageResolver storage)
-              throws KeyResolverException {
+    /**
+     * This method is used for registering {@link KeyResolverSpi}s which are
+     * available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
+     * personalized {@link KeyResolverSpi}s should only be registered directly
+     * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
+     * {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
+     * Please note that this method will create a new copy of the underlying array, as the
+     * underlying collection is a CopyOnWriteArrayList.
+     *
+     * @param className
+     * @param globalResolver Whether the KeyResolverSpi is a global resolver or not
+     * @throws InstantiationException
+     * @throws IllegalAccessException
+     * @throws ClassNotFoundException
+     */
+    public static void register(String className, boolean globalResolver)
+        throws ClassNotFoundException, IllegalAccessException, InstantiationException {
+        KeyResolverSpi keyResolverSpi =
+            (KeyResolverSpi) Class.forName(className).newInstance();
+        keyResolverSpi.setGlobalResolver(globalResolver);
+        register(keyResolverSpi, false);
+    }
 
-          // use the old vector to not be hit by updates
-          List<KeyResolver> resolverVector = KeyResolver._resolverVector;
-      for (KeyResolver resolver : resolverVector) {
-         if (resolver==null) {
-            Object exArgs[] = {
-               (((element != null)
-                 && (element.getNodeType() == Node.ELEMENT_NODE))
-                ? element.getTagName()
-                : "null") };
+    /**
+     * This method is used for registering {@link KeyResolverSpi}s which are
+     * available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
+     * personalized {@link KeyResolverSpi}s should only be registered directly
+     * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
+     * {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
+     * Please note that this method will create a new copy of the underlying array, as the
+     * underlying collection is a CopyOnWriteArrayList.
+     *
+     * @param className
+     * @param globalResolver Whether the KeyResolverSpi is a global resolver or not
+     */
+    public static void registerAtStart(String className, boolean globalResolver) {
+        KeyResolverSpi keyResolverSpi = null;
+        Exception ex = null;
+        try {
+            keyResolverSpi = (KeyResolverSpi) Class.forName(className).newInstance();
+        } catch (ClassNotFoundException e) {
+            ex = e;
+        } catch (IllegalAccessException e) {
+            ex = e;
+        } catch (InstantiationException e) {
+            ex = e;
+        }
 
-            throw new KeyResolverException("utils.resolver.noClass", exArgs);
-         }
-         if (log.isLoggable(java.util.logging.Level.FINE))
-                log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver.getClass());
+        if (ex != null) {
+            throw (IllegalArgumentException) new
+            IllegalArgumentException("Invalid KeyResolver class name").initCause(ex);
+        }
+        keyResolverSpi.setGlobalResolver(globalResolver);
+        register(keyResolverSpi, true);
+    }
 
-         X509Certificate cert=resolver.resolveX509Certificate(element, BaseURI, storage);
-         if (cert!=null) {
-            return cert;
-         }
-      }
-
-      Object exArgs[] = {
-         (((element != null) && (element.getNodeType() == Node.ELEMENT_NODE))
-          ? element.getTagName()
-          : "null") };
+    /**
+     * This method is used for registering {@link KeyResolverSpi}s which are
+     * available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
+     * personalized {@link KeyResolverSpi}s should only be registered directly
+     * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
+     * {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
+     * Please note that this method will create a new copy of the underlying array, as the
+     * underlying collection is a CopyOnWriteArrayList.
+     *
+     * @param keyResolverSpi a KeyResolverSpi instance to register
+     * @param start whether to register the KeyResolverSpi at the start of the list or not
+     */
+    public static void register(
+        KeyResolverSpi keyResolverSpi,
+        boolean start
+    ) {
+        KeyResolver resolver = new KeyResolver(keyResolverSpi);
+        if (start) {
+            resolverVector.add(0, resolver);
+        } else {
+            resolverVector.add(resolver);
+        }
+    }
 
-      throw new KeyResolverException("utils.resolver.noClass", exArgs);
-   }
-   /**
-    * Method getInstance
-    *
-    * @param element
-    * @param BaseURI
-    * @param storage
-    * @return the public key contained in the element
-    *
-    * @throws KeyResolverException
-    */
-   public static final PublicKey getPublicKey(
-           Element element, String BaseURI, StorageResolver storage)
-              throws KeyResolverException {
+    /**
+     * This method is used for registering {@link KeyResolverSpi}s which are
+     * available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
+     * personalized {@link KeyResolverSpi}s should only be registered directly
+     * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
+     * {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
+     * The KeyResolverSpi instances are not registered as a global resolver.
+     *
+     *
+     * @param classNames
+     * @throws InstantiationException
+     * @throws IllegalAccessException
+     * @throws ClassNotFoundException
+     */
+    public static void registerClassNames(List<String> classNames)
+        throws ClassNotFoundException, IllegalAccessException, InstantiationException {
+        List<KeyResolver> keyResolverList = new ArrayList<KeyResolver>(classNames.size());
+        for (String className : classNames) {
+            KeyResolverSpi keyResolverSpi =
+                (KeyResolverSpi) Class.forName(className).newInstance();
+            keyResolverSpi.setGlobalResolver(false);
+            keyResolverList.add(new KeyResolver(keyResolverSpi));
+        }
+        resolverVector.addAll(keyResolverList);
+    }
 
-          List<KeyResolver> resolverVector = KeyResolver._resolverVector;
-      for (KeyResolver resolver : resolverVector) {
+    /**
+     * This method registers the default resolvers.
+     */
+    public static void registerDefaultResolvers() {
 
-                  if (resolver==null) {
-            Object exArgs[] = {
-               (((element != null)
-                 && (element.getNodeType() == Node.ELEMENT_NODE))
-                ? element.getTagName()
-                : "null") };
+        List<KeyResolver> keyResolverList = new ArrayList<KeyResolver>();
+        keyResolverList.add(new KeyResolver(new RSAKeyValueResolver()));
+        keyResolverList.add(new KeyResolver(new DSAKeyValueResolver()));
+        keyResolverList.add(new KeyResolver(new X509CertificateResolver()));
+        keyResolverList.add(new KeyResolver(new X509SKIResolver()));
+        keyResolverList.add(new KeyResolver(new RetrievalMethodResolver()));
+        keyResolverList.add(new KeyResolver(new X509SubjectNameResolver()));
+        keyResolverList.add(new KeyResolver(new X509IssuerSerialResolver()));
+
+        resolverVector.addAll(keyResolverList);
+    }
 
-            throw new KeyResolverException("utils.resolver.noClass", exArgs);
-         }
-         if (log.isLoggable(java.util.logging.Level.FINE))
-                log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver.getClass());
+    /**
+     * Method resolvePublicKey
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return resolved public key from the registered from the elements
+     *
+     * @throws KeyResolverException
+     */
+    public PublicKey resolvePublicKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        return resolverSpi.engineLookupAndResolvePublicKey(element, baseURI, storage);
+    }
+
+    /**
+     * Method resolveX509Certificate
+     *
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return resolved X509certificate key from the registered from the elements
+     *
+     * @throws KeyResolverException
+     */
+    public X509Certificate resolveX509Certificate(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        return resolverSpi.engineLookupResolveX509Certificate(element, baseURI, storage);
+    }
 
-         PublicKey cert=resolver.resolvePublicKey(element, BaseURI, storage);
-         if (cert!=null) {
-                 if (resolverVector.indexOf(resolver)!=0 && resolverVector==_resolverVector) {
-                         //update resolver.
-                         resolverVector=getResolverVectorClone();
-                                 resolverVector.remove(resolver);
-                                 resolverVector.add(0,resolver);
-                                 _resolverVector=resolverVector;
-                 }
-                 return cert;
-         }
-      }
+    /**
+     * @param element
+     * @param baseURI
+     * @param storage
+     * @return resolved SecretKey key from the registered from the elements
+     * @throws KeyResolverException
+     */
+    public SecretKey resolveSecretKey(
+        Element element, String baseURI, StorageResolver storage
+    ) throws KeyResolverException {
+        return resolverSpi.engineLookupAndResolveSecretKey(element, baseURI, storage);
+    }
 
-      Object exArgs[] = {
-         (((element != null) && (element.getNodeType() == Node.ELEMENT_NODE))
-          ? element.getTagName()
-          : "null") };
+    /**
+     * Method setProperty
+     *
+     * @param key
+     * @param value
+     */
+    public void setProperty(String key, String value) {
+        resolverSpi.engineSetProperty(key, value);
+    }
 
-      throw new KeyResolverException("utils.resolver.noClass", exArgs);
-   }
+    /**
+     * Method getProperty
+     *
+     * @param key
+     * @return the property set for this resolver
+     */
+    public String getProperty(String key) {
+        return resolverSpi.engineGetProperty(key);
+    }
 
 
-   @SuppressWarnings("unchecked")
-   private static List<KeyResolver> getResolverVectorClone() {
-       return (List<KeyResolver>)((ArrayList<KeyResolver>)_resolverVector).clone();
-   }
-
-   /**
-    * The init() function is called by com.sun.org.apache.xml.internal.security.Init.init()
-    */
-   public static void init() {
-
-      if (!KeyResolver._alreadyInitialized) {
-         KeyResolver._resolverVector = new ArrayList<KeyResolver>(10);
-         _alreadyInitialized = true;
-      }
-   }
-
-   /**
-    * This method is used for registering {@link KeyResolverSpi}s which are
-    * available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
-    * personalized {@link KeyResolverSpi}s should only be registered directly
-    * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
-    * {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
-    *
-    * @param className
- * @throws InstantiationException
- * @throws IllegalAccessException
- * @throws ClassNotFoundException
-    */
-   public static void register(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
-      KeyResolver._resolverVector.add(new KeyResolver(className));
-   }
-
-   /**
-    * This method is used for registering {@link KeyResolverSpi}s which are
-    * available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
-    * personalized {@link KeyResolverSpi}s should only be registered directly
-    * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
-    *
-    * @param className
-    */
-   public static void registerAtStart(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
-       register(className);
-   }
-
-   /**
-    * Method resolve
-    *
-    * @param element
-    * @param BaseURI
-    * @param storage
-    * @return resolved public key from the registered from the elements
-    *
-    * @throws KeyResolverException
-    */
-   public PublicKey resolvePublicKey(
-           Element element, String BaseURI, StorageResolver storage)
-              throws KeyResolverException {
-      return this._resolverSpi.engineLookupAndResolvePublicKey(element, BaseURI, storage);
-   }
-
-   /**
-    * Method resolveX509Certificate
-    *
-    * @param element
-    * @param BaseURI
-    * @param storage
-    * @return resolved X509certificate key from the registered from the elements
-    *
-    * @throws KeyResolverException
-    */
-   public X509Certificate resolveX509Certificate(
-           Element element, String BaseURI, StorageResolver storage)
-              throws KeyResolverException {
-      return this._resolverSpi.engineLookupResolveX509Certificate(element, BaseURI,
-              storage);
-   }
-
-   /**
-    * @param element
-    * @param BaseURI
-    * @param storage
-    * @return resolved SecretKey key from the registered from the elements
-    * @throws KeyResolverException
-    */
-   public SecretKey resolveSecretKey(
-           Element element, String BaseURI, StorageResolver storage)
-              throws KeyResolverException {
-      return this._resolverSpi.engineLookupAndResolveSecretKey(element, BaseURI,
-              storage);
-   }
-
-   /**
-    * Method setProperty
-    *
-    * @param key
-    * @param value
-    */
-   public void setProperty(String key, String value) {
-      this._resolverSpi.engineSetProperty(key, value);
-   }
-
-   /**
-    * Method getProperty
-    *
-    * @param key
-    * @return the property setted for this resolver
-    */
-   public String getProperty(String key) {
-      return this._resolverSpi.engineGetProperty(key);
-   }
+    /**
+     * Method understandsProperty
+     *
+     * @param propertyToTest
+     * @return true if the resolver understands property propertyToTest
+     */
+    public boolean understandsProperty(String propertyToTest) {
+        return resolverSpi.understandsProperty(propertyToTest);
+    }
 
 
-   /**
-    * Method understandsProperty
-    *
-    * @param propertyToTest
-    * @return true if the resolver understands property propertyToTest
-    */
-   public boolean understandsProperty(String propertyToTest) {
-      return this._resolverSpi.understandsProperty(propertyToTest);
-   }
+    /**
+     * Method resolverClassName
+     *
+     * @return the name of the resolver.
+     */
+    public String resolverClassName() {
+        return resolverSpi.getClass().getName();
+    }
 
+    /**
+     * Iterate over the KeyResolverSpi instances
+     */
+    static class ResolverIterator implements Iterator<KeyResolverSpi> {
+        List<KeyResolver> res;
+        Iterator<KeyResolver> it;
 
-   /**
-    * Method resolverClassName
-    *
-    * @return the name of the resolver.
-    */
-   public String resolverClassName() {
-      return this._resolverSpi.getClass().getName();
-   }
+        public ResolverIterator(List<KeyResolver> list) {
+            res = list;
+            it = res.iterator();
+        }
 
-   static class ResolverIterator implements Iterator<KeyResolverSpi> {
-                List<KeyResolver> res;
-                Iterator<KeyResolver> it;
-                int i;
-           public ResolverIterator(List<KeyResolver> list) {
-                res = list;
-                it = res.iterator();
+        public boolean hasNext() {
+            return it.hasNext();
         }
-                public boolean hasNext() {
-                        // TODO Auto-generated method stub
-                        return it.hasNext();
-                }
+
+        public KeyResolverSpi next() {
+            KeyResolver resolver = it.next();
+            if (resolver == null) {
+                throw new RuntimeException("utils.resolver.noClass");
+            }
 
-                public KeyResolverSpi next() {
-                        i++;
-                        KeyResolver resolver =  it.next();
-                      if (resolver==null) {
-                         throw new RuntimeException("utils.resolver.noClass");
-                      }
-
-                      return resolver._resolverSpi;
-                }
+            return resolver.resolverSpi;
+        }
 
-                public void remove() {
-                        // TODO Auto-generated method stub
-
-                }
+        public void remove() {
+            throw new UnsupportedOperationException("Can't remove resolvers using the iterator");
+        }
+    };
 
-        };
-        public static Iterator<KeyResolverSpi> iterator() {
-                return new ResolverIterator(_resolverVector);
-   }
+    public static Iterator<KeyResolverSpi> iterator() {
+        return new ResolverIterator(resolverVector);
+    }
 }
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java	Wed Jul 05 19:00:49 2017 +0200
@@ -34,6 +34,7 @@
 import java.util.ListIterator;
 import java.util.Set;
 
+import javax.xml.XMLConstants;
 import javax.xml.parsers.ParserConfigurationException;
 
 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
@@ -251,6 +252,7 @@
       try {
          javax.xml.parsers.DocumentBuilderFactory dbf =javax.xml.parsers.DocumentBuilderFactory.newInstance();
          dbf.setNamespaceAware(true);
+         dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
          javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
          org.w3c.dom.Document doc =
             db.parse(new java.io.ByteArrayInputStream(bytes));
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -1,123 +1,126 @@
-algorithm.alreadyRegistered = URI {0} already assigned to class {1}
-algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH
-algorithm.ClassDoesNotExist = Class {0} does not exist
-algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2}
-algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures.
-algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures.
-algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs.
-algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms
-algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1}
-algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm
-algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1}
-algorithms.operationOnlyVerification = A public key can only used for verification of a signature.
-algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed.
-attributeValueIllegal = The attribute {0} has value {1} but must be {2}
-c14n.Canonicalizer.Exception = Exception during Canonicalization:  Original Message was {0}
-c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1}
-c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0}
-c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization:  Original Message was {0}
-c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}"
-c14n.Canonicalizer.SAXException = SAXException during Canonicalization:  Original Message was {0}
-c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0}
-c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0}
-c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation
-c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document)
-certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0}
-certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString
-certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier
-defaultNamespaceCannotBeSetHere = Default namespace cannot be set here
-ElementProxy.nullElement = Cannot create an ElementProxy from a null argument
-empty = {0}
-encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0}
-encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams
-encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt
-encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap
-encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit
-encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this.
-encryption.RSAOAEP.dataHashWrong = data hash wrong
-encryption.RSAOAEP.dataStartWrong = data wrong start {0}
-encryption.RSAOAEP.dataTooShort = data too short
-encryption.RSAPKCS15.blockTruncated = block truncated
-encryption.RSAPKCS15.noDataInBlock = no data in block
-encryption.RSAPKCS15.unknownBlockType = unknown block type
-encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers
-endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at <http://xml.apache.org/security/Java/installation.html> how to solve this problem.
-errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution.
-errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed.
-errorMessages.IOException = Other file I/O and similar exceptions.
-errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again.
-errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again.
-errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0}
-errorMessages.NotYetImplementedException = Functionality not yet there.
-errorMessages.XMLSignatureException = Verification failed for some other reason.
-decoding.divisible.four = It should be divisible by four
-decoding.general = Error while decoding
-FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented.
-FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0}
-FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1}
-FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0}
-generic.dontHaveConstructionElement = I do not have a construction Element
-generic.EmptyMessage = {0}
-generic.NotYetImplemented = {0} Not YET implemented ;-((
-java.security.InvalidKeyException = Invalid key
-java.security.NoSuchProviderException = Unknown or unsupported provider
-java.security.UnknownKeyType = Unknown or unsupported key type {0}
-KeyInfo.needKeyResolver = More than one keyResovler have to be registered
-KeyInfo.nokey = Cannot get key from {0}
-KeyInfo.noKey = Cannot get the public key
-KeyInfo.wrongNumberOfObject = Need {0} keyObjects
-KeyInfo.wrongUse = This object was made for getting {0}
-keyResolver.alreadyRegistered = {1} class has already been registered for {0}
-KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0}
-KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0}
-KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0}
-KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0}
-KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0}
-KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0}
-KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0}
-KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0}
-KeyResoverSpiImpl.wrongKeyObject =  Need {1} type of KeyObject for generation Element in implement class{0}
-KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0}
-KeyStore.alreadyRegistered = {0} Class has already been registered for {1}
-KeyStore.register = {1} type class register error  in class {0}
-KeyStore.registerStore.register = Registeration error for type {0}
-KeyValue.IllegalArgument = Cannot create a {0} from {1}
-namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1}
-notYetInitialized = The module {0} is not yet initialized
-prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2}
-signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0}
-signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature
-signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first
-signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set
-signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform
-signature.Transform.NotYetImplemented = Transform {0} not yet implemented
-signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug?
-signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0}
-signature.Transform.node = Current Node: {0}
-signature.Transform.nodeAndType = Current Node: {0}, type: {1} 
-signature.Util.BignumNonPositive = bigInteger.signum() must be positive
-signature.Util.NonTextNode = Not a text node
-signature.Util.TooManyChilds = Too many childs of Type {0} in {1}
-signature.Verification.certificateError = Certificate error
-signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References
-signature.Verification.internalError = Internal error
-signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0}
-signature.Verification.keyStore = KeyStore error
-signature.Verification.MissingID = Cannot resolve element with ID {0}
-signature.Verification.MissingResources = Cannot resolve external resource {0}
-signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1}
-signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput
-signature.Verification.SignatureError = Signature error
-signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0}
-signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it
-signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference
-transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream.
-transform.init.NotInitialized =
-transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization
-utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4
-Base64Decoding = Error while decoding
-utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1}
-xml.WrongContent = Cannot find {0} in {1}
-xml.WrongElement = Cannot create a {0} from a {1} element
-xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node
-xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0}
+algorithm.alreadyRegistered = URI {0} already assigned to class {1}
+algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH
+algorithm.ClassDoesNotExist = Class {0} does not exist
+algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2}
+algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures.
+algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures.
+algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs.
+algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms
+algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1}
+algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm
+algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1}
+algorithms.operationOnlyVerification = A public key can only used for verification of a signature.
+algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed.
+attributeValueIllegal = The attribute {0} has value {1} but must be {2}
+c14n.Canonicalizer.Exception = Exception during Canonicalization:  Original Message was {0}
+c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1}
+c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0}
+c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization:  Original Message was {0}
+c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}"
+c14n.Canonicalizer.SAXException = SAXException during Canonicalization:  Original Message was {0}
+c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0}
+c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0}
+c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation
+c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document)
+certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0}
+certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString
+certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier
+defaultNamespaceCannotBeSetHere = Default namespace cannot be set here
+ElementProxy.nullElement = Cannot create an ElementProxy from a null argument
+empty = {0}
+encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0}
+encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams
+encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt
+encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap
+encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit
+encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this.
+encryption.RSAOAEP.dataHashWrong = data hash wrong
+encryption.RSAOAEP.dataStartWrong = data wrong start {0}
+encryption.RSAOAEP.dataTooShort = data too short
+encryption.RSAPKCS15.blockTruncated = block truncated
+encryption.RSAPKCS15.noDataInBlock = no data in block
+encryption.RSAPKCS15.unknownBlockType = unknown block type
+encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers
+endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at <http://xml.apache.org/security/Java/installation.html> how to solve this problem.
+errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution.
+errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed.
+errorMessages.IOException = Other file I/O and similar exceptions.
+errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again.
+errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again.
+errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0}
+errorMessages.NotYetImplementedException = Functionality not yet there.
+errorMessages.XMLSignatureException = Verification failed for some other reason.
+decoding.divisible.four = It should be divisible by four
+decoding.general = Error while decoding
+FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented.
+FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0}
+FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1}
+FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0}
+generic.dontHaveConstructionElement = I do not have a construction Element
+generic.EmptyMessage = {0}
+generic.NotYetImplemented = {0} Not YET implemented ;-((
+java.security.InvalidKeyException = Invalid key
+java.security.NoSuchProviderException = Unknown or unsupported provider
+java.security.UnknownKeyType = Unknown or unsupported key type {0}
+KeyInfo.needKeyResolver = More than one keyResovler have to be registered
+KeyInfo.nokey = Cannot get key from {0}
+KeyInfo.noKey = Cannot get the public key
+KeyInfo.wrongNumberOfObject = Need {0} keyObjects
+KeyInfo.wrongUse = This object was made for getting {0}
+keyResolver.alreadyRegistered = {1} class has already been registered for {0}
+KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0}
+KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0}
+KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0}
+KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0}
+KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0}
+KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0}
+KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0}
+KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0}
+KeyResoverSpiImpl.wrongKeyObject =  Need {1} type of KeyObject for generation Element in implement class{0}
+KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0}
+KeyStore.alreadyRegistered = {0} Class has already been registered for {1}
+KeyStore.register = {1} type class register error  in class {0}
+KeyStore.registerStore.register = Registeration error for type {0}
+KeyValue.IllegalArgument = Cannot create a {0} from {1}
+namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1}
+notYetInitialized = The module {0} is not yet initialized
+prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2}
+signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0}
+signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature
+signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first
+signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled
+signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled
+signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set
+signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform
+signature.Transform.NotYetImplemented = Transform {0} not yet implemented
+signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug?
+signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0}
+signature.Transform.node = Current Node: {0}
+signature.Transform.nodeAndType = Current Node: {0}, type: {1} 
+signature.Util.BignumNonPositive = bigInteger.signum() must be positive
+signature.Util.NonTextNode = Not a text node
+signature.Util.TooManyChilds = Too many childs of Type {0} in {1}
+signature.Verification.certificateError = Certificate error
+signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References
+signature.Verification.internalError = Internal error
+signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0}
+signature.Verification.keyStore = KeyStore error
+signature.Verification.MissingID = Cannot resolve element with ID {0}
+signature.Verification.MissingResources = Cannot resolve external resource {0}
+signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected
+signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1}
+signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput
+signature.Verification.SignatureError = Signature error
+signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0}
+signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it
+signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference
+transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream.
+transform.init.NotInitialized =
+transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization
+utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4
+Base64Decoding = Error while decoding
+utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1}
+xml.WrongContent = Cannot find {0} in {1}
+xml.WrongElement = Cannot create a {0} from a {1} element
+xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node
+xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -43,6 +43,7 @@
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
+import org.w3c.dom.Attr;
 import org.w3c.dom.DOMException;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -101,6 +102,11 @@
 
       super(element, BaseURI);
 
+      Attr attr = element.getAttributeNodeNS(null, "Id");
+      if (attr != null) {
+          element.setIdAttributeNode(attr, true);
+      }
+
       // check out Reference children
       this._referencesEl = XMLUtils.selectDsNodes(this._constructionElement.getFirstChild(),
          Constants._TAG_REFERENCE);
@@ -121,6 +127,11 @@
       this._references = new ArrayList<Reference>(le);
 
       for (int i = 0; i < le; i++) {
+         Element refElem = this._referencesEl[i];
+         Attr refAttr = refElem.getAttributeNodeNS(null, "Id");
+         if (refAttr != null) {
+             refElem.setIdAttributeNode(refAttr, true);
+         }
          this._references.add(null);
       }
    }
@@ -221,8 +232,7 @@
    public void setId(String Id) {
 
       if (Id != null) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
-         IdResolver.registerElementById(this._constructionElement, Id);
+          setLocalIdAttribute(Constants._ATT_ID, Id);
       }
    }
 
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -68,9 +68,8 @@
     */
    public void setId(String Id) {
 
-      if ((Id != null)) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
-         IdResolver.registerElementById(this._constructionElement, Id);
+      if (Id != null) {
+          setLocalIdAttribute(Constants._ATT_ID, Id);
       }
    }
 
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java	Wed Jul 05 19:00:49 2017 +0200
@@ -284,8 +284,7 @@
    public void setId(String Id) {
 
       if ( Id != null ) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
-         IdResolver.registerElementById(this._constructionElement, Id);
+          setLocalIdAttribute(Constants._ATT_ID, Id);
       }
    }
 
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java	Wed Jul 05 19:00:49 2017 +0200
@@ -25,6 +25,7 @@
 import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
@@ -61,6 +62,21 @@
    public SignatureProperties(Element element, String BaseURI)
            throws XMLSecurityException {
       super(element, BaseURI);
+
+      Attr attr = element.getAttributeNodeNS(null, "Id");
+      if (attr != null) {
+          element.setIdAttributeNode(attr, true);
+      }
+
+      int length = getLength();
+      for (int i = 0; i < length; i++) {
+          Element propertyElem =
+              XMLUtils.selectDsNode(getElement(), Constants._TAG_SIGNATUREPROPERTY, i);
+          Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
+          if (propertyAttr != null) {
+              propertyElem.setIdAttributeNode(propertyAttr, true);
+          }
+      }
    }
 
    /**
@@ -109,9 +125,8 @@
     */
    public void setId(String Id) {
 
-      if ((Id != null)) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
-         IdResolver.registerElementById(this._constructionElement, Id);
+      if (Id != null) {
+          setLocalIdAttribute(Constants._ATT_ID, Id);
       }
    }
 
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java	Wed Jul 05 19:00:49 2017 +0200
@@ -80,9 +80,8 @@
     */
    public void setId(String Id) {
 
-      if ((Id != null)) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
-         IdResolver.registerElementById(this._constructionElement, Id);
+      if (Id != null) {
+          setLocalIdAttribute(Constants._ATT_ID, Id);
       }
    }
 
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java	Wed Jul 05 19:00:49 2017 +0200
@@ -25,6 +25,7 @@
 import java.io.OutputStream;
 import javax.crypto.SecretKey;
 import javax.crypto.spec.SecretKeySpec;
+import javax.xml.XMLConstants;
 import javax.xml.parsers.ParserConfigurationException;
 
 import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
@@ -186,8 +187,10 @@
                 javax.xml.parsers.DocumentBuilderFactory dbf =
                     javax.xml.parsers.DocumentBuilderFactory.newInstance();
                 dbf.setNamespaceAware(true);
+                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
+                               Boolean.TRUE);
                 javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
-                org.w3c.dom.Document newdoc =
+                Document newdoc =
                     db.parse(new ByteArrayInputStream(this._c14nizedBytes));
                 Node imported =
                     this._doc.importNode(newdoc.getDocumentElement(), true);
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java	Wed Jul 05 19:00:49 2017 +0200
@@ -49,9 +49,11 @@
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
+import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
 import org.w3c.dom.Text;
 
 
@@ -201,14 +203,13 @@
 
       super(doc);
 
-      String xmlnsDsPrefix =
-         getDefaultPrefixBindings(Constants.SignatureSpecNS);
+      String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
       if (xmlnsDsPrefix == null) {
          this._constructionElement.setAttributeNS
             (Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS);
       } else {
          this._constructionElement.setAttributeNS
-            (Constants.NamespaceSpecNS, xmlnsDsPrefix, Constants.SignatureSpecNS);
+            (Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS);
       }
       XMLUtils.addReturnToElement(this._constructionElement);
 
@@ -242,14 +243,13 @@
 
       super(doc);
 
-      String xmlnsDsPrefix =
-         getDefaultPrefixBindings(Constants.SignatureSpecNS);
+      String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
       if (xmlnsDsPrefix == null) {
          this._constructionElement.setAttributeNS
             (Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS);
       } else {
          this._constructionElement.setAttributeNS
-            (Constants.NamespaceSpecNS, xmlnsDsPrefix, Constants.SignatureSpecNS);
+            (Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS);
       }
       XMLUtils.addReturnToElement(this._constructionElement);
 
@@ -308,6 +308,10 @@
 
          throw new XMLSignatureException("xml.WrongContent", exArgs);
       }
+      Attr signatureValueAttr = signatureValueElement.getAttributeNodeNS(null, "Id");
+      if (signatureValueAttr != null) {
+          signatureValueElement.setIdAttributeNode(signatureValueAttr, true);
+      }
 
       // <element ref="ds:KeyInfo" minOccurs="0"/>
       Element keyInfoElem = XMLUtils.getNextElement(signatureValueElement.getNextSibling());//XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
@@ -318,6 +322,34 @@
                   keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) ) {
          this._keyInfo = new KeyInfo(keyInfoElem, BaseURI);
       }
+
+      // <element ref="ds:Object" minOccurs="0" maxOccurs="unbounded"/>
+      Element objectElem =
+          XMLUtils.getNextElement(signatureValueElement.getNextSibling());
+      while (objectElem != null) {
+          Attr objectAttr = objectElem.getAttributeNodeNS(null, "Id");
+          if (objectAttr != null) {
+              objectElem.setIdAttributeNode(objectAttr, true);
+          }
+
+          NodeList nodes = objectElem.getChildNodes();
+          int length = nodes.getLength();
+          // Register Ids of the Object child elements
+          for (int i = 0; i < length; i++) {
+              Node child = nodes.item(i);
+              if (child.getNodeType() == Node.ELEMENT_NODE) {
+                  Element childElem = (Element)child;
+                  String tag = childElem.getLocalName();
+                  if (tag.equals("Manifest")) {
+                      new Manifest(childElem, BaseURI);
+                  } else if (tag.equals("SignatureProperties")) {
+                      new SignatureProperties(childElem, BaseURI);
+                  }
+              }
+          }
+
+          objectElem = XMLUtils.getNextElement(objectElem.getNextSibling());
+      }
    }
 
    /**
@@ -327,9 +359,8 @@
     */
    public void setId(String Id) {
 
-      if ( (Id != null)) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
-         IdResolver.registerElementById(this._constructionElement, Id);
+      if (Id != null) {
+          setLocalIdAttribute(Constants._ATT_ID, Id);
       }
    }
 
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java	Wed Jul 05 19:00:49 2017 +0200
@@ -27,10 +27,11 @@
 import java.io.OutputStream;
 import java.io.UnsupportedEncodingException;
 import java.util.ArrayList;
-import java.util.HashSet;
+import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Set;
 
+import javax.xml.XMLConstants;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
@@ -244,13 +245,13 @@
             if (circumvent) {
                 XMLUtils.circumventBug2650(XMLUtils.getOwnerDocument(_subNode));
             }
-            this._inputNodeSet = new HashSet<Node>();
+            this._inputNodeSet = new LinkedHashSet<Node>();
             XMLUtils.getSet(_subNode,this._inputNodeSet, excludeNode, this.excludeComments);
 
             return this._inputNodeSet;
         } else if (this.isOctetStream()) {
             convertToNodes();
-            HashSet<Node> result=new HashSet<Node>();
+            LinkedHashSet<Node> result = new LinkedHashSet<Node>();
             XMLUtils.getSet(_subNode, result,null,false);
             //this._inputNodeSet=result;
             return result;
@@ -603,6 +604,8 @@
         DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
         dfactory.setValidating(false);
         dfactory.setNamespaceAware(true);
+        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
+                            Boolean.TRUE);
         DocumentBuilder db = dfactory.newDocumentBuilder();
         // select all nodes, also the comments.
         try {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/ClassLoaderUtils.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,280 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package com.sun.org.apache.xml.internal.security.transforms;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+
+/**
+ * This class is extremely useful for loading resources and classes in a fault
+ * tolerant manner that works across different applications servers. Do not
+ * touch this unless you're a grizzled classloading guru veteran who is going to
+ * verify any change on 6 different application servers.
+ */
+// NOTE! This is a duplicate of utils.ClassLoaderUtils with public
+// modifiers changed to package-private. Make sure to integrate any future
+// changes to utils.ClassLoaderUtils to this file.
+final class ClassLoaderUtils {
+
+    /** {@link org.apache.commons.logging} logging facility */
+    private static final java.util.logging.Logger log =
+        java.util.logging.Logger.getLogger(ClassLoaderUtils.class.getName());
+
+    private ClassLoaderUtils() {
+    }
+
+    /**
+     * Load a given resource. <p/> This method will try to load the resource
+     * using the following methods (in order):
+     * <ul>
+     * <li>From Thread.currentThread().getContextClassLoader()
+     * <li>From ClassLoaderUtil.class.getClassLoader()
+     * <li>callingClass.getClassLoader()
+     * </ul>
+     *
+     * @param resourceName The name of the resource to load
+     * @param callingClass The Class object of the calling object
+     */
+    static URL getResource(String resourceName, Class<?> callingClass) {
+        URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
+        if (url == null && resourceName.startsWith("/")) {
+            //certain classloaders need it without the leading /
+            url =
+                Thread.currentThread().getContextClassLoader().getResource(
+                    resourceName.substring(1)
+                );
+        }
+
+        ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
+        if (cluClassloader == null) {
+            cluClassloader = ClassLoader.getSystemClassLoader();
+        }
+        if (url == null) {
+            url = cluClassloader.getResource(resourceName);
+        }
+        if (url == null && resourceName.startsWith("/")) {
+            //certain classloaders need it without the leading /
+            url = cluClassloader.getResource(resourceName.substring(1));
+        }
+
+        if (url == null) {
+            ClassLoader cl = callingClass.getClassLoader();
+
+            if (cl != null) {
+                url = cl.getResource(resourceName);
+            }
+        }
+
+        if (url == null) {
+            url = callingClass.getResource(resourceName);
+        }
+
+        if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) {
+            return getResource('/' + resourceName, callingClass);
+        }
+
+        return url;
+    }
+
+    /**
+     * Load a given resources. <p/> This method will try to load the resources
+     * using the following methods (in order):
+     * <ul>
+     * <li>From Thread.currentThread().getContextClassLoader()
+     * <li>From ClassLoaderUtil.class.getClassLoader()
+     * <li>callingClass.getClassLoader()
+     * </ul>
+     *
+     * @param resourceName The name of the resource to load
+     * @param callingClass The Class object of the calling object
+     */
+    static List<URL> getResources(String resourceName, Class<?> callingClass) {
+        List<URL> ret = new ArrayList<URL>();
+        Enumeration<URL> urls = new Enumeration<URL>() {
+            public boolean hasMoreElements() {
+                return false;
+            }
+            public URL nextElement() {
+                return null;
+            }
+
+        };
+        try {
+            urls = Thread.currentThread().getContextClassLoader().getResources(resourceName);
+        } catch (IOException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+            //ignore
+        }
+        if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
+            //certain classloaders need it without the leading /
+            try {
+                urls =
+                    Thread.currentThread().getContextClassLoader().getResources(
+                        resourceName.substring(1)
+                    );
+            } catch (IOException e) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                }
+                // ignore
+            }
+        }
+
+        ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
+        if (cluClassloader == null) {
+            cluClassloader = ClassLoader.getSystemClassLoader();
+        }
+        if (!urls.hasMoreElements()) {
+            try {
+                urls = cluClassloader.getResources(resourceName);
+            } catch (IOException e) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                }
+                // ignore
+            }
+        }
+        if (!urls.hasMoreElements() && resourceName.startsWith("/")) {
+            //certain classloaders need it without the leading /
+            try {
+                urls = cluClassloader.getResources(resourceName.substring(1));
+            } catch (IOException e) {
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                }
+                // ignore
+            }
+        }
+
+        if (!urls.hasMoreElements()) {
+            ClassLoader cl = callingClass.getClassLoader();
+
+            if (cl != null) {
+                try {
+                    urls = cl.getResources(resourceName);
+                } catch (IOException e) {
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+                    }
+                    // ignore
+                }
+            }
+        }
+
+        if (!urls.hasMoreElements()) {
+            URL url = callingClass.getResource(resourceName);
+            if (url != null) {
+                ret.add(url);
+            }
+        }
+        while (urls.hasMoreElements()) {
+            ret.add(urls.nextElement());
+        }
+
+
+        if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) {
+            return getResources('/' + resourceName, callingClass);
+        }
+        return ret;
+    }
+
+
+    /**
+     * This is a convenience method to load a resource as a stream. <p/> The
+     * algorithm used to find the resource is given in getResource()
+     *
+     * @param resourceName The name of the resource to load
+     * @param callingClass The Class object of the calling object
+     */
+    static InputStream getResourceAsStream(String resourceName, Class<?> callingClass) {
+        URL url = getResource(resourceName, callingClass);
+
+        try {
+            return (url != null) ? url.openStream() : null;
+        } catch (IOException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+            return null;
+        }
+    }
+
+    /**
+     * Load a class with a given name. <p/> It will try to load the class in the
+     * following order:
+     * <ul>
+     * <li>From Thread.currentThread().getContextClassLoader()
+     * <li>Using the basic Class.forName()
+     * <li>From ClassLoaderUtil.class.getClassLoader()
+     * <li>From the callingClass.getClassLoader()
+     * </ul>
+     *
+     * @param className The name of the class to load
+     * @param callingClass The Class object of the calling object
+     * @throws ClassNotFoundException If the class cannot be found anywhere.
+     */
+    static Class<?> loadClass(String className, Class<?> callingClass)
+        throws ClassNotFoundException {
+        try {
+            ClassLoader cl = Thread.currentThread().getContextClassLoader();
+
+            if (cl != null) {
+                return cl.loadClass(className);
+            }
+        } catch (ClassNotFoundException e) {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+            }
+            //ignore
+        }
+        return loadClass2(className, callingClass);
+    }
+
+    private static Class<?> loadClass2(String className, Class<?> callingClass)
+        throws ClassNotFoundException {
+        try {
+            return Class.forName(className);
+        } catch (ClassNotFoundException ex) {
+            try {
+                if (ClassLoaderUtils.class.getClassLoader() != null) {
+                    return ClassLoaderUtils.class.getClassLoader().loadClass(className);
+                }
+            } catch (ClassNotFoundException exc) {
+                if (callingClass != null && callingClass.getClassLoader() != null) {
+                    return callingClass.getClassLoader().loadClass(className);
+                }
+            }
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+            }
+            throw ex;
+        }
+    }
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java	Wed Jul 05 19:00:49 2017 +0200
@@ -2,29 +2,29 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.transforms;
 
 import java.io.IOException;
 import java.io.OutputStream;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.HashMap;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.Map;
 import javax.xml.parsers.ParserConfigurationException;
 
@@ -33,6 +33,17 @@
 import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
+import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode;
+import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14N;
+import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14N11;
+import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14N11_WithComments;
+import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14NExclusive;
+import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14NExclusiveWithComments;
+import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14NWithComments;
+import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformEnvelopedSignature;
+import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXPath;
+import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXPath2Filter;
+import com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXSLT;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.HelperNodeList;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
@@ -54,112 +65,31 @@
  * @author Christian Geuer-Pollmann
  * @see Transforms
  * @see TransformSpi
- *
  */
 public final class Transform extends SignatureElementProxy {
 
-    /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(Transform.class.getName());
 
-    /** Field _alreadyInitialized */
-    private static boolean alreadyInitialized = false;
-
     /** All available Transform classes are registered here */
-    private static Map<String, Class<?>> transformClassHash = null;
-
-    private static Map<String, TransformSpi> transformSpiHash = new HashMap<String, TransformSpi>();
-
-    private TransformSpi transformSpi = null;
-
-    /**
-     * Constructs {@link Transform}
-     *
-     * @param doc the {@link Document} in which <code>Transform</code> will be
-     * placed
-     * @param algorithmURI URI representation of
-     * <code>Transform algorithm</code> which will be specified as parameter of
-     * {@link #getInstance(Document, String)}, when generated. </br>
-     * @param contextNodes the child node list of <code>Transform</code> element
-     * @throws InvalidTransformException
-     */
-    public Transform(Document doc, String algorithmURI, NodeList contextNodes)
-        throws InvalidTransformException {
-
-        super(doc);
-
-        this._constructionElement.setAttributeNS
-            (null, Constants._ATT_ALGORITHM, algorithmURI);
-
-        transformSpi = getTransformSpi(algorithmURI);
-        if (transformSpi == null) {
-             Object exArgs[] = { algorithmURI };
-             throw new InvalidTransformException(
-                "signature.Transform.UnknownTransform", exArgs);
-        }
-
-        if (log.isLoggable(java.util.logging.Level.FINE)) {
-            log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
-                   + transformSpi.getClass() + "\"");
-            log.log(java.util.logging.Level.FINE, "The NodeList is " + contextNodes);
-        }
+    private static Map<String, Class<? extends TransformSpi>> transformSpiHash =
+        new ConcurrentHashMap<String, Class<? extends TransformSpi>>();
 
-        // give it to the current document
-        if (contextNodes != null) {
-            for (int i = 0; i < contextNodes.getLength(); i++) {
-               this._constructionElement.appendChild
-                   (contextNodes.item(i).cloneNode(true));
-            }
-        }
-    }
-
-    /**
-     * This constructor can only be called from the {@link Transforms} object,
-     * so it's protected.
-     *
-     * @param element <code>ds:Transform</code> element
-     * @param BaseURI the URI of the resource where the XML instance was stored
-     * @throws InvalidTransformException
-     * @throws TransformationException
-     * @throws XMLSecurityException
-     */
-    public Transform(Element element, String BaseURI)
-        throws InvalidTransformException, TransformationException,
-               XMLSecurityException {
-
-        super(element, BaseURI);
-
-        // retrieve Algorithm Attribute from ds:Transform
-        String algorithmURI = element.getAttributeNS(null, Constants._ATT_ALGORITHM);
-
-        if (algorithmURI == null || algorithmURI.length() == 0) {
-            Object exArgs[] = { Constants._ATT_ALGORITHM,
-                                Constants._TAG_TRANSFORM };
-            throw new TransformationException("xml.WrongContent", exArgs);
-        }
-
-        transformSpi = getTransformSpi(algorithmURI);
-        if (transformSpi == null) {
-            Object exArgs[] = { algorithmURI };
-            throw new InvalidTransformException(
-                "signature.Transform.UnknownTransform", exArgs);
-        }
-    }
+    private final TransformSpi transformSpi;
 
     /**
      * Generates a Transform object that implements the specified
      * <code>Transform algorithm</code> URI.
      *
+     * @param doc the proxy {@link Document}
      * @param algorithmURI <code>Transform algorithm</code> URI representation,
      * such as specified in
      * <a href=http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg>Transform algorithm </a>
-     * @param doc the proxy {@link Document}
-     * @return <code>{@link Transform}</code> object
      * @throws InvalidTransformException
      */
-    public static Transform getInstance(
-        Document doc, String algorithmURI) throws InvalidTransformException {
-        return getInstance(doc, algorithmURI, (NodeList) null);
+    public Transform(Document doc, String algorithmURI) throws InvalidTransformException {
+        this(doc, algorithmURI, (NodeList)null);
     }
 
     /**
@@ -171,82 +101,160 @@
      * <a href=http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg>Transform algorithm </a>
      * @param contextChild the child element of <code>Transform</code> element
      * @param doc the proxy {@link Document}
-     * @return <code>{@link Transform}</code> object
      * @throws InvalidTransformException
      */
-    public static Transform getInstance(
-        Document doc, String algorithmURI, Element contextChild)
+    public Transform(Document doc, String algorithmURI, Element contextChild)
         throws InvalidTransformException {
+        super(doc);
+        HelperNodeList contextNodes = null;
 
-        HelperNodeList contextNodes = new HelperNodeList();
+        if (contextChild != null) {
+            contextNodes = new HelperNodeList();
+
+            XMLUtils.addReturnToElement(doc, contextNodes);
+            contextNodes.appendChild(contextChild);
+            XMLUtils.addReturnToElement(doc, contextNodes);
+        }
 
-        XMLUtils.addReturnToElement(doc, contextNodes);
-        contextNodes.appendChild(contextChild);
-        XMLUtils.addReturnToElement(doc, contextNodes);
+        transformSpi = initializeTransform(algorithmURI, contextNodes);
+    }
 
-        return getInstance(doc, algorithmURI, contextNodes);
+    /**
+     * Constructs {@link Transform}
+     *
+     * @param doc the {@link Document} in which <code>Transform</code> will be
+     * placed
+     * @param algorithmURI URI representation of <code>Transform algorithm</code>
+     * @param contextNodes the child node list of <code>Transform</code> element
+     * @throws InvalidTransformException
+     */
+    public Transform(Document doc, String algorithmURI, NodeList contextNodes)
+        throws InvalidTransformException {
+        super(doc);
+        transformSpi = initializeTransform(algorithmURI, contextNodes);
     }
 
     /**
-     * Generates a Transform object that implements the specified
-     * <code>Transform algorithm</code> URI.
-     *
-     * @param algorithmURI <code>Transform algorithm</code> URI form, such as
-     * specified in <a href=http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg>
-     * Transform algorithm </a>
-     * @param contextNodes the child node list of <code>Transform</code> element
-     * @param doc the proxy {@link Document}
-     * @return <code>{@link Transform}</code> object
+     * @param element <code>ds:Transform</code> element
+     * @param BaseURI the URI of the resource where the XML instance was stored
      * @throws InvalidTransformException
+     * @throws TransformationException
+     * @throws XMLSecurityException
      */
-    public static Transform getInstance(
-        Document doc, String algorithmURI, NodeList contextNodes)
-        throws InvalidTransformException {
-        return new Transform(doc, algorithmURI, contextNodes);
-    }
+    public Transform(Element element, String BaseURI)
+        throws InvalidTransformException, TransformationException, XMLSecurityException {
+        super(element, BaseURI);
+
+        // retrieve Algorithm Attribute from ds:Transform
+        String algorithmURI = element.getAttributeNS(null, Constants._ATT_ALGORITHM);
+
+        if (algorithmURI == null || algorithmURI.length() == 0) {
+            Object exArgs[] = { Constants._ATT_ALGORITHM, Constants._TAG_TRANSFORM };
+            throw new TransformationException("xml.WrongContent", exArgs);
+        }
 
-    /**
-     * Initalizes for this {@link Transform}.
-     */
-    public static void init() {
-        if (!alreadyInitialized) {
-            transformClassHash = new HashMap<String,Class<?>>(10);
-            // make sure builtin algorithms are all registered first
-            com.sun.org.apache.xml.internal.security.Init.init();
-            alreadyInitialized = true;
+        Class<? extends TransformSpi> transformSpiClass = transformSpiHash.get(algorithmURI);
+        if (transformSpiClass == null) {
+            Object exArgs[] = { algorithmURI };
+            throw new InvalidTransformException("signature.Transform.UnknownTransform", exArgs);
+        }
+        try {
+            transformSpi = transformSpiClass.newInstance();
+        } catch (InstantiationException ex) {
+            Object exArgs[] = { algorithmURI };
+            throw new InvalidTransformException(
+                "signature.Transform.UnknownTransform", exArgs, ex
+            );
+        } catch (IllegalAccessException ex) {
+            Object exArgs[] = { algorithmURI };
+            throw new InvalidTransformException(
+                "signature.Transform.UnknownTransform", exArgs, ex
+            );
         }
     }
 
     /**
      * Registers implementing class of the Transform algorithm with algorithmURI
      *
-     * @param algorithmURI algorithmURI URI representation of
-     * <code>Transform algorithm</code> will be specified as parameter of
-     * {@link #getInstance(Document, String)}, when generate. </br>
+     * @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>
+     * @param implementingClass <code>implementingClass</code> the implementing
+     * class of {@link TransformSpi}
+     * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
+     * is already registered
+     */
+    @SuppressWarnings("unchecked")
+    public static void register(String algorithmURI, String implementingClass)
+        throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
+            InvalidTransformException {
+        // are we already registered?
+        Class<? extends TransformSpi> transformSpi = transformSpiHash.get(algorithmURI);
+        if (transformSpi != null) {
+            Object exArgs[] = { algorithmURI, transformSpi };
+            throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs);
+        }
+        Class<? extends TransformSpi> transformSpiClass =
+            (Class<? extends TransformSpi>)
+                ClassLoaderUtils.loadClass(implementingClass, Transform.class);
+        transformSpiHash.put(algorithmURI, transformSpiClass);
+    }
+
+    /**
+     * Registers implementing class of the Transform algorithm with algorithmURI
+     *
+     * @param algorithmURI algorithmURI URI representation of <code>Transform algorithm</code>
      * @param implementingClass <code>implementingClass</code> the implementing
      * class of {@link TransformSpi}
      * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
      * is already registered
      */
-    public static void register(String algorithmURI, String implementingClass)
+    public static void register(String algorithmURI, Class<? extends TransformSpi> implementingClass)
         throws AlgorithmAlreadyRegisteredException {
-
         // are we already registered?
-        Class<? extends TransformSpi> registeredClass = getImplementingClass(algorithmURI);
-        if ((registeredClass != null) ) {
-            Object exArgs[] = { algorithmURI, registeredClass };
-            throw new AlgorithmAlreadyRegisteredException(
-               "algorithm.alreadyRegistered", exArgs);
+        Class<? extends TransformSpi> transformSpi = transformSpiHash.get(algorithmURI);
+        if (transformSpi != null) {
+            Object exArgs[] = { algorithmURI, transformSpi };
+            throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs);
         }
-
-        ClassLoader cl = Thread.currentThread().getContextClassLoader();
+        transformSpiHash.put(algorithmURI, implementingClass);
+    }
 
-        try {
-            transformClassHash.put
-                (algorithmURI, Class.forName(implementingClass, true, cl));
-        } catch (ClassNotFoundException e) {
-            throw new RuntimeException(e);
-        }
+    /**
+     * This method registers the default algorithms.
+     */
+    public static void registerDefaultAlgorithms() {
+        transformSpiHash.put(
+            Transforms.TRANSFORM_BASE64_DECODE, TransformBase64Decode.class
+        );
+        transformSpiHash.put(
+            Transforms.TRANSFORM_C14N_OMIT_COMMENTS, TransformC14N.class
+        );
+        transformSpiHash.put(
+            Transforms.TRANSFORM_C14N_WITH_COMMENTS, TransformC14NWithComments.class
+        );
+        transformSpiHash.put(
+            Transforms.TRANSFORM_C14N11_OMIT_COMMENTS, TransformC14N11.class
+        );
+        transformSpiHash.put(
+            Transforms.TRANSFORM_C14N11_WITH_COMMENTS, TransformC14N11_WithComments.class
+        );
+        transformSpiHash.put(
+            Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS, TransformC14NExclusive.class
+        );
+        transformSpiHash.put(
+            Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS, TransformC14NExclusiveWithComments.class
+        );
+        transformSpiHash.put(
+            Transforms.TRANSFORM_XPATH, TransformXPath.class
+        );
+        transformSpiHash.put(
+            Transforms.TRANSFORM_ENVELOPED_SIGNATURE, TransformEnvelopedSignature.class
+        );
+        transformSpiHash.put(
+            Transforms.TRANSFORM_XSLT, TransformXSLT.class
+        );
+        transformSpiHash.put(
+            Transforms.TRANSFORM_XPATH2FILTER, TransformXPath2Filter.class
+        );
     }
 
     /**
@@ -255,8 +263,7 @@
      * @return the URI representation of Transformation algorithm
      */
     public String getURI() {
-        return this._constructionElement.getAttributeNS
-            (null, Constants._ATT_ALGORITHM);
+        return this._constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
     }
 
     /**
@@ -272,30 +279,15 @@
      * @throws TransformationException
      */
     public XMLSignatureInput performTransform(XMLSignatureInput input)
-         throws IOException, CanonicalizationException,
-                InvalidCanonicalizerException, TransformationException {
-
-        XMLSignatureInput result = null;
-
-        try {
-            result = transformSpi.enginePerformTransform(input, this);
-        } catch (ParserConfigurationException ex) {
-            Object exArgs[] = { this.getURI(), "ParserConfigurationException" };
-            throw new CanonicalizationException(
-                "signature.Transform.ErrorDuringTransform", exArgs, ex);
-        } catch (SAXException ex) {
-            Object exArgs[] = { this.getURI(), "SAXException" };
-            throw new CanonicalizationException(
-                "signature.Transform.ErrorDuringTransform", exArgs, ex);
-        }
-
-        return result;
+        throws IOException, CanonicalizationException,
+               InvalidCanonicalizerException, TransformationException {
+        return performTransform(input, null);
     }
 
     /**
      * Transforms the input, and generates {@link XMLSignatureInput} as output.
      *
-     * @param input input {@link XMLSignatureInput} which can supplied Octet
+     * @param input input {@link XMLSignatureInput} which can supplied Octect
      * Stream and NodeSet as Input of Transformation
      * @param os where to output the result of the last transformation
      * @return the {@link XMLSignatureInput} class as the result of
@@ -305,10 +297,10 @@
      * @throws InvalidCanonicalizerException
      * @throws TransformationException
      */
-    public XMLSignatureInput performTransform(XMLSignatureInput input,
-        OutputStream os) throws IOException, CanonicalizationException,
+    public XMLSignatureInput performTransform(
+        XMLSignatureInput input, OutputStream os
+    ) throws IOException, CanonicalizationException,
         InvalidCanonicalizerException, TransformationException {
-
         XMLSignatureInput result = null;
 
         try {
@@ -326,44 +318,52 @@
         return result;
     }
 
-    /**
-     * Method getImplementingClass
-     *
-     * @param URI
-     * @return The name of the class implementing the URI.
-     */
-    @SuppressWarnings("unchecked")
-    private static Class<? extends TransformSpi> getImplementingClass(String URI) {
-        return (Class<? extends TransformSpi>)transformClassHash.get(URI);
-    }
-
-    private static TransformSpi getTransformSpi(String URI)
-        throws InvalidTransformException {
-        try {
-            TransformSpi value = transformSpiHash.get(URI);
-            if (value != null) {
-                return value;
-            }
-            Class<? extends TransformSpi> cl = getImplementingClass(URI);
-            if (cl != null) {
-                TransformSpi tr = cl.newInstance();
-                transformSpiHash.put(URI, tr);
-                return tr;
-            }
-        } catch (InstantiationException ex) {
-            Object exArgs[] = { URI };
-            throw new InvalidTransformException(
-                "signature.Transform.UnknownTransform", exArgs, ex);
-        } catch (IllegalAccessException ex) {
-            Object exArgs[] = { URI };
-            throw new InvalidTransformException(
-                "signature.Transform.UnknownTransform", exArgs, ex);
-        }
-        return null;
-    }
-
     /** @inheritDoc */
     public String getBaseLocalName() {
         return Constants._TAG_TRANSFORM;
     }
+
+    /**
+     * Initialize the transform object.
+     */
+    private TransformSpi initializeTransform(String algorithmURI, NodeList contextNodes)
+        throws InvalidTransformException {
+
+        this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI);
+
+        Class<? extends TransformSpi> transformSpiClass = transformSpiHash.get(algorithmURI);
+        if (transformSpiClass == null) {
+            Object exArgs[] = { algorithmURI };
+            throw new InvalidTransformException("signature.Transform.UnknownTransform", exArgs);
+        }
+        TransformSpi newTransformSpi = null;
+        try {
+            newTransformSpi = transformSpiClass.newInstance();
+        } catch (InstantiationException ex) {
+            Object exArgs[] = { algorithmURI };
+            throw new InvalidTransformException(
+                "signature.Transform.UnknownTransform", exArgs, ex
+            );
+        } catch (IllegalAccessException ex) {
+            Object exArgs[] = { algorithmURI };
+            throw new InvalidTransformException(
+                "signature.Transform.UnknownTransform", exArgs, ex
+            );
+        }
+
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
+                      + newTransformSpi.getClass() + "\"");
+            log.log(java.util.logging.Level.FINE, "The NodeList is " + contextNodes);
+        }
+
+        // give it to the current document
+        if (contextNodes != null) {
+            for (int i = 0; i < contextNodes.getLength(); i++) {
+                this._constructionElement.appendChild(contextNodes.item(i).cloneNode(true));
+            }
+        }
+        return newTransformSpi;
+    }
+
 }
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java	Wed Jul 05 19:00:49 2017 +0200
@@ -158,8 +158,7 @@
             if (log.isLoggable(java.util.logging.Level.FINE))
                 log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")");
 
-            Transform transform =
-                Transform.getInstance(this._doc, transformURI);
+            Transform transform = new Transform(this._doc, transformURI);
 
             this.addTransform(transform);
         } catch (InvalidTransformException ex) {
@@ -184,8 +183,7 @@
             if (log.isLoggable(java.util.logging.Level.FINE))
                 log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")");
 
-            Transform transform =
-                Transform.getInstance(this._doc, transformURI, contextElement);
+            Transform transform = new Transform(this._doc, transformURI, contextElement);
 
             this.addTransform(transform);
         } catch (InvalidTransformException ex) {
@@ -207,8 +205,7 @@
            throws TransformationException {
 
         try {
-            Transform transform =
-                Transform.getInstance(this._doc, transformURI, contextNodes);
+            Transform transform = new Transform(this._doc, transformURI, contextNodes);
             this.addTransform(transform);
         } catch (InvalidTransformException ex) {
             throw new TransformationException("empty", ex);
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java	Wed Jul 05 19:00:49 2017 +0200
@@ -26,6 +26,7 @@
 import java.io.IOException;
 import java.io.OutputStream;
 
+import javax.xml.XMLConstants;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 
@@ -145,11 +146,13 @@
       }
 
          try {
-            //Exceptional case there is current not text case testing this(Before it was a
-                    //a common case).
+            // Exceptional case there is current not text case testing this
+            // (before it was a a common case).
+            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
+                           Boolean.TRUE);
             Document doc =
-               DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
-                  input.getOctetStream());
+                dbf.newDocumentBuilder().parse(input.getOctetStream());
 
             Element rootNode = doc.getDocumentElement();
             StringBuffer sb = new StringBuffer();
@@ -157,13 +160,13 @@
             byte[] decodedBytes = Base64.decode(sb.toString());
 
             return new XMLSignatureInput(decodedBytes);
-                  } catch (ParserConfigurationException e) {
-                          throw new TransformationException("c14n.Canonicalizer.Exception",e);
-                  } catch (SAXException e) {
-                          throw new TransformationException("SAX exception", e);
-                  }
+         } catch (ParserConfigurationException e) {
+            throw new TransformationException("c14n.Canonicalizer.Exception",e);
+         } catch (SAXException e) {
+            throw new TransformationException("SAX exception", e);
+         }
         } catch (Base64DecodingException e) {
-        throw new TransformationException("Base64Decoding", e);
+            throw new TransformationException("Base64Decoding", e);
         }
    }
 
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java	Wed Jul 05 19:00:49 2017 +0200
@@ -26,6 +26,7 @@
 import java.io.OutputStream;
 import java.lang.reflect.Method;
 
+import javax.xml.XMLConstants;
 import javax.xml.transform.Source;
 import javax.xml.transform.Transformer;
 import javax.xml.transform.TransformerConfigurationException;
@@ -109,7 +110,8 @@
          TransformerFactory tFactory = TransformerFactory.newInstance();
 
          // Process XSLT stylesheets in a secure manner
-         tFactory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", Boolean.TRUE);
+         tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
+                             Boolean.TRUE);
          /*
           * This transform requires an octet stream as input. If the actual
           * input is an XPath node-set, then the signature application should
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java	Wed Jul 05 19:00:49 2017 +0200
@@ -2,28 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright 1999-2008 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
-
-
 import java.math.BigInteger;
-import java.util.HashMap;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.Map;
 
 import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
@@ -35,466 +35,432 @@
 import org.w3c.dom.NodeList;
 import org.w3c.dom.Text;
 
-
 /**
  * This is the base class to all Objects which have a direct 1:1 mapping to an
  * Element in a particular namespace.
- *
- * @author $Author: mullan $
  */
 public abstract class ElementProxy {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    protected static final java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(ElementProxy.class.getName());
 
-   /**
-    * Returns the namespace of the Elements of the sub-class.
-    *
-    * @return the namespace of the Elements of the sub-class.
-    */
-   public abstract String getBaseNamespace();
+    /** Field constructionElement */
+    protected Element _constructionElement = null;
+
+    /** Field baseURI */
+    protected String _baseURI = null;
+
+    /** Field doc */
+    protected Document _doc = null;
+
+    /** Field prefixMappings */
+    private static Map<String, String> prefixMappings = new ConcurrentHashMap<String, String>();
 
-   /**
-    * Returns the localname of the Elements of the sub-class.
-    *
-    * @return the localname of the Elements of the sub-class.
-    */
-   public abstract String getBaseLocalName();
+    /**
+     * Constructor ElementProxy
+     *
+     */
+    public ElementProxy() {
+    }
+
+    /**
+     * Constructor ElementProxy
+     *
+     * @param doc
+     */
+    public ElementProxy(Document doc) {
+        if (doc == null) {
+            throw new RuntimeException("Document is null");
+        }
+
+        this._doc = doc;
+        this._constructionElement =
+            createElementForFamilyLocal(this._doc, this.getBaseNamespace(), this.getBaseLocalName());
+    }
 
-   /** Field _constructionElement */
-   protected Element _constructionElement = null;
+    /**
+     * Constructor ElementProxy
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public ElementProxy(Element element, String BaseURI) throws XMLSecurityException {
+        if (element == null) {
+            throw new XMLSecurityException("ElementProxy.nullElement");
+        }
 
-   /** Field _baseURI */
-   protected String _baseURI = null;
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "setElement(\"" + element.getTagName() + "\", \"" + BaseURI + "\")");
+        }
 
-   /** Field _doc */
-   protected Document _doc = null;
+        this._doc = element.getOwnerDocument();
+        this._constructionElement = element;
+        this._baseURI = BaseURI;
+
+        this.guaranteeThatElementInCorrectSpace();
+    }
 
-   /**
-    * Constructor ElementProxy
-    *
-    */
-   public ElementProxy() {
-   }
+    /**
+     * Returns the namespace of the Elements of the sub-class.
+     *
+     * @return the namespace of the Elements of the sub-class.
+     */
+    public abstract String getBaseNamespace();
+
+    /**
+     * Returns the localname of the Elements of the sub-class.
+     *
+     * @return the localname of the Elements of the sub-class.
+     */
+    public abstract String getBaseLocalName();
+
 
-   /**
-    * Constructor ElementProxy
-    *
-    * @param doc
-    */
-   public ElementProxy(Document doc) {
-      if (doc == null) {
-         throw new RuntimeException("Document is null");
-      }
+    protected Element createElementForFamilyLocal(
+        Document doc, String namespace, String localName
+    ) {
+        Element result = null;
+        if (namespace == null) {
+            result = doc.createElementNS(null, localName);
+        } else {
+            String baseName = this.getBaseNamespace();
+            String prefix = ElementProxy.getDefaultPrefix(baseName);
+            if ((prefix == null) || (prefix.length() == 0)) {
+                result = doc.createElementNS(namespace, localName);
+                result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", namespace);
+            } else {
+                result = doc.createElementNS(namespace, prefix + ":" + localName);
+                result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix, namespace);
+            }
+        }
+        return result;
+    }
+
 
-      this._doc = doc;
-      this._constructionElement = createElementForFamilyLocal(this._doc,
-                  this.getBaseNamespace(), this.getBaseLocalName());
-   }
-   protected Element createElementForFamilyLocal(Document doc, String namespace,
-           String localName) {
-                  Element result = null;
-              if (namespace == null) {
-                 result = doc.createElementNS(null, localName);
-              } else {
-                  String baseName=this.getBaseNamespace();
-                  String prefix=ElementProxy.getDefaultPrefix(baseName);
-                 if ((prefix == null) || (prefix.length() == 0)) {
-                    result = doc.createElementNS(namespace, localName);
+    /**
+     * This method creates an Element in a given namespace with a given localname.
+     * It uses the {@link ElementProxy#getDefaultPrefix} method to decide whether
+     * a particular prefix is bound to that namespace.
+     * <BR />
+     * This method was refactored out of the constructor.
+     *
+     * @param doc
+     * @param namespace
+     * @param localName
+     * @return The element created.
+     */
+    public static Element createElementForFamily(Document doc, String namespace, String localName) {
+        Element result = null;
+        String prefix = ElementProxy.getDefaultPrefix(namespace);
 
-                    result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns",
-                                          namespace);
-                 } else {
-                         String tagName=null;
-                         String defaultPrefixNaming=ElementProxy.getDefaultPrefixBindings(baseName);
-                         StringBuffer sb=new StringBuffer(prefix);
-                         sb.append(':');
-                         sb.append(localName);
-                         tagName=sb.toString();
-                    result = doc.createElementNS(namespace, tagName );
+        if (namespace == null) {
+            result = doc.createElementNS(null, localName);
+        } else {
+            if ((prefix == null) || (prefix.length() == 0)) {
+                result = doc.createElementNS(namespace, localName);
+                result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", namespace);
+            } else {
+                result = doc.createElementNS(namespace, prefix + ":" + localName);
+                result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix, namespace);
+            }
+        }
+
+        return result;
+    }
 
-                    result.setAttributeNS(Constants.NamespaceSpecNS,  defaultPrefixNaming,
-                                          namespace);
-                 }
-              }
-              return result;
-}
+    /**
+     * Method setElement
+     *
+     * @param element
+     * @param BaseURI
+     * @throws XMLSecurityException
+     */
+    public void setElement(Element element, String BaseURI) throws XMLSecurityException {
+        if (element == null) {
+            throw new XMLSecurityException("ElementProxy.nullElement");
+        }
+
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "setElement(" + element.getTagName() + ", \"" + BaseURI + "\"");
+        }
+
+        this._doc = element.getOwnerDocument();
+        this._constructionElement = element;
+        this._baseURI = BaseURI;
+    }
 
 
-   /**
-    * This method creates an Element in a given namespace with a given localname.
-    * It uses the {@link ElementProxy#getDefaultPrefix} method to decide whether
-    * a particular prefix is bound to that namespace.
-    * <BR />
-    * This method was refactored out of the constructor.
-    *
-    * @param doc
-    * @param namespace
-    * @param localName
-    * @return The element created.
-    */
-   public static Element createElementForFamily(Document doc, String namespace,
-           String localName) {
-       //Element nscontext = XMLUtils.createDSctx(doc, "x", namespace);
-      Element result = null;
-      String prefix = ElementProxy.getDefaultPrefix(namespace);
+    /**
+     * Returns the Element which was constructed by the Object.
+     *
+     * @return the Element which was constructed by the Object.
+     */
+    public final Element getElement() {
+        return this._constructionElement;
+    }
 
-      if (namespace == null) {
-         result = doc.createElementNS(null, localName);
-      } else {
-         if ((prefix == null) || (prefix.length() == 0)) {
-            result = doc.createElementNS(namespace, localName);
+    /**
+     * Returns the Element plus a leading and a trailing CarriageReturn Text node.
+     *
+     * @return the Element which was constructed by the Object.
+     */
+    public final NodeList getElementPlusReturns() {
 
-            result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns",
-                                  namespace);
-         } else {
-            result = doc.createElementNS(namespace, prefix + ":" + localName);
+        HelperNodeList nl = new HelperNodeList();
 
-            result.setAttributeNS(Constants.NamespaceSpecNS,  ElementProxy.getDefaultPrefixBindings(namespace),
-                                  namespace);
-         }
-      }
+        nl.appendChild(this._doc.createTextNode("\n"));
+        nl.appendChild(this.getElement());
+        nl.appendChild(this._doc.createTextNode("\n"));
 
-      return result;
-   }
+        return nl;
+    }
 
-   /**
-    * Method setElement
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public void setElement(Element element, String BaseURI)
-           throws XMLSecurityException {
+    /**
+     * Method getDocument
+     *
+     * @return the Document where this element is contained.
+     */
+    public Document getDocument() {
+        return this._doc;
+    }
 
-      if (element == null) {
-         throw new XMLSecurityException("ElementProxy.nullElement");
-      }
-
-      if (log.isLoggable(java.util.logging.Level.FINE)) {
-        log.log(java.util.logging.Level.FINE, "setElement(" + element.getTagName() + ", \"" + BaseURI + "\"");
-      }
-
-      this._doc = element.getOwnerDocument();
-      this._constructionElement = element;
-      this._baseURI = BaseURI;
-   }
+    /**
+     * Method getBaseURI
+     *
+     * @return the base uri of the namespace of this element
+     */
+    public String getBaseURI() {
+        return this._baseURI;
+    }
 
-   /**
-    * Constructor ElementProxy
-    *
-    * @param element
-    * @param BaseURI
-    * @throws XMLSecurityException
-    */
-   public ElementProxy(Element element, String BaseURI)
-           throws XMLSecurityException {
-      if (element == null) {
-         throw new XMLSecurityException("ElementProxy.nullElement");
-      }
+    /**
+     * Method guaranteeThatElementInCorrectSpace
+     *
+     * @throws XMLSecurityException
+     */
+    void guaranteeThatElementInCorrectSpace() throws XMLSecurityException {
+
+        String expectedLocalName = this.getBaseLocalName();
+        String expectedNamespaceUri = this.getBaseNamespace();
 
-      if (log.isLoggable(java.util.logging.Level.FINE)) {
-        log.log(java.util.logging.Level.FINE, "setElement(\"" + element.getTagName() + "\", \"" + BaseURI
-                + "\")");
-      }
+        String actualLocalName = this._constructionElement.getLocalName();
+        String actualNamespaceUri = this._constructionElement.getNamespaceURI();
 
-      this._doc = element.getOwnerDocument();
-      this._constructionElement = element;
-      this._baseURI = BaseURI;
-
-      this.guaranteeThatElementInCorrectSpace();
-   }
+        if(!expectedNamespaceUri.equals(actualNamespaceUri)
+            && !expectedLocalName.equals(actualLocalName)) {
+            Object exArgs[] = { actualNamespaceUri + ":" + actualLocalName,
+                                expectedNamespaceUri + ":" + expectedLocalName};
+            throw new XMLSecurityException("xml.WrongElement", exArgs);
+        }
+    }
 
-   /**
-    * Returns the Element which was constructed by the Object.
-    *
-    * @return the Element which was constructed by the Object.
-    */
-   public final Element getElement() {
-      return this._constructionElement;
-   }
+    /**
+     * Method addBigIntegerElement
+     *
+     * @param bi
+     * @param localname
+     */
+    public void addBigIntegerElement(BigInteger bi, String localname) {
+        if (bi != null) {
+            Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname);
 
-   /**
-    * Returns the Element plus a leading and a trailing CarriageReturn Text node.
-    *
-    * @return the Element which was constructed by the Object.
-    */
-   public final NodeList getElementPlusReturns() {
-
-      HelperNodeList nl = new HelperNodeList();
-
-      nl.appendChild(this._doc.createTextNode("\n"));
-      nl.appendChild(this.getElement());
-      nl.appendChild(this._doc.createTextNode("\n"));
+            Base64.fillElementWithBigInteger(e, bi);
+            this._constructionElement.appendChild(e);
+            XMLUtils.addReturnToElement(this._constructionElement);
+        }
+    }
 
-      return nl;
-   }
+    /**
+     * Method addBase64Element
+     *
+     * @param bytes
+     * @param localname
+     */
+    public void addBase64Element(byte[] bytes, String localname) {
+        if (bytes != null) {
+            Element e = Base64.encodeToElement(this._doc, localname, bytes);
 
-   /**
-    * Method getDocument
-    *
-    * @return the Document where this element is contained.
-    */
-   public Document getDocument() {
-      return this._doc;
-   }
-
-   /**
-    * Method getBaseURI
-    *
-    * @return the base uri of the namespace of this element
-    */
-   public String getBaseURI() {
-      return this._baseURI;
-   }
-
-   static ElementChecker checker = new ElementCheckerImpl.InternedNsChecker();
+            this._constructionElement.appendChild(e);
+            if (!XMLUtils.ignoreLineBreaks()) {
+                this._constructionElement.appendChild(this._doc.createTextNode("\n"));
+            }
+        }
+    }
 
-   /**
-    * Method guaranteeThatElementInCorrectSpace
-    *
-    * @throws XMLSecurityException
-    */
-   void guaranteeThatElementInCorrectSpace()
-           throws XMLSecurityException {
-
-          checker.guaranteeThatElementInCorrectSpace(this,this._constructionElement);
-
-   }
+    /**
+     * Method addTextElement
+     *
+     * @param text
+     * @param localname
+     */
+    public void addTextElement(String text, String localname) {
+        Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname);
+        Text t = this._doc.createTextNode(text);
 
-   /**
-    * Method setVal
-    *
-    * @param bi
-    * @param localname
-    */
-   public void addBigIntegerElement(BigInteger bi, String localname) {
-
-      if (bi != null) {
-         Element e = XMLUtils.createElementInSignatureSpace(this._doc,
-                        localname);
+        e.appendChild(t);
+        this._constructionElement.appendChild(e);
+        XMLUtils.addReturnToElement(this._constructionElement);
+    }
 
-         Base64.fillElementWithBigInteger(e, bi);
-         this._constructionElement.appendChild(e);
-         XMLUtils.addReturnToElement(this._constructionElement);
-      }
-   }
-
-   /**
-    * Method addBase64Element
-    *
-    * @param bytes
-    * @param localname
-    */
-   public void addBase64Element(byte[] bytes, String localname) {
-
-      if (bytes != null) {
+    /**
+     * Method addBase64Text
+     *
+     * @param bytes
+     */
+    public void addBase64Text(byte[] bytes) {
+        if (bytes != null) {
+            Text t = XMLUtils.ignoreLineBreaks()
+                ? this._doc.createTextNode(Base64.encode(bytes))
+                : this._doc.createTextNode("\n" + Base64.encode(bytes) + "\n");
+            this._constructionElement.appendChild(t);
+        }
+    }
 
-         Element e = Base64.encodeToElement(this._doc, localname, bytes);
-
-         this._constructionElement.appendChild(e);
-         if (!XMLUtils.ignoreLineBreaks()) {
-            this._constructionElement.appendChild(this._doc.createTextNode("\n"));
-         }
-      }
-   }
-
-   /**
-    * Method addTextElement
-    *
-    * @param text
-    * @param localname
-    */
-   public void addTextElement(String text, String localname) {
+    /**
+     * Method addText
+     *
+     * @param text
+     */
+    public void addText(String text) {
+        if (text != null) {
+            Text t = this._doc.createTextNode(text);
 
-      Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname);
-      Text t = this._doc.createTextNode(text);
-
-      e.appendChild(t);
-      this._constructionElement.appendChild(e);
-      XMLUtils.addReturnToElement(this._constructionElement);
-   }
-
-   /**
-    * Method addBase64Text
-    *
-    * @param bytes
-    */
-   public void addBase64Text(byte[] bytes) {
+            this._constructionElement.appendChild(t);
+        }
+    }
 
-      if (bytes != null) {
-         Text t = XMLUtils.ignoreLineBreaks()
-             ? this._doc.createTextNode(Base64.encode(bytes))
-             : this._doc.createTextNode("\n" + Base64.encode(bytes) + "\n");
-         this._constructionElement.appendChild(t);
-      }
-   }
-
-   /**
-    * Method addText
-    *
-    * @param text
-    */
-   public void addText(String text) {
-
-      if (text != null) {
-         Text t = this._doc.createTextNode(text);
-
-         this._constructionElement.appendChild(t);
-      }
-   }
+    /**
+     * Method getVal
+     *
+     * @param localname
+     * @param namespace
+     * @return The biginteger contained in the given element
+     * @throws Base64DecodingException
+     */
+    public BigInteger getBigIntegerFromChildElement(
+        String localname, String namespace
+    ) throws Base64DecodingException {
+        return Base64.decodeBigIntegerFromText(
+            XMLUtils.selectNodeText(
+                this._constructionElement.getFirstChild(), namespace, localname, 0
+            )
+        );
+    }
 
-   /**
-    * Method getVal
-    *
-    * @param localname
-    * @param namespace
-    * @return The biginter contained in the given element
- * @throws Base64DecodingException
-    */
-   public BigInteger getBigIntegerFromChildElement(
-           String localname, String namespace) throws Base64DecodingException {
+    /**
+     * Method getBytesFromChildElement
+     * @deprecated
+     * @param localname
+     * @param namespace
+     * @return the bytes
+     * @throws XMLSecurityException
+     */
+    @Deprecated
+    public byte[] getBytesFromChildElement(String localname, String namespace)
+        throws XMLSecurityException {
+        Element e =
+            XMLUtils.selectNode(
+                this._constructionElement.getFirstChild(), namespace, localname, 0
+            );
 
-                return Base64.decodeBigIntegerFromText(
-                                XMLUtils.selectNodeText(this._constructionElement.getFirstChild(),
-                                                namespace,localname,0));
-
-   }
+        return Base64.decode(e);
+    }
 
-   /**
-    * Method getBytesFromChildElement
-    * @deprecated
-    * @param localname
-    * @param namespace
-    * @return the bytes
-    * @throws XMLSecurityException
-    */
-   @Deprecated
-   public byte[] getBytesFromChildElement(String localname, String namespace)
-           throws XMLSecurityException {
-
-         Element e =
-             XMLUtils.selectNode(
-                 this._constructionElement.getFirstChild(),
-                 namespace,
-                 localname,
-                 0);
+    /**
+     * Method getTextFromChildElement
+     *
+     * @param localname
+     * @param namespace
+     * @return the Text of the textNode
+     */
+    public String getTextFromChildElement(String localname, String namespace) {
+        return XMLUtils.selectNode(
+                this._constructionElement.getFirstChild(),
+                namespace,
+                localname,
+                0).getTextContent();
+    }
 
-         return Base64.decode(e);
-   }
-
-   /**
-    * Method getTextFromChildElement
-    *
-    * @param localname
-    * @param namespace
-    * @return the Text of the textNode
-    */
-   public String getTextFromChildElement(String localname, String namespace) {
-
-         return     XMLUtils.selectNode(
-                    this._constructionElement.getFirstChild(),
-                    namespace,
-                    localname,
-                    0).getFirstChild().getNodeValue();
-
-   }
+    /**
+     * Method getBytesFromTextChild
+     *
+     * @return The base64 bytes from the text children of this element
+     * @throws XMLSecurityException
+     */
+    public byte[] getBytesFromTextChild() throws XMLSecurityException {
+        return Base64.decode(XMLUtils.getFullTextChildrenFromElement(this._constructionElement));
+    }
 
-   /**
-    * Method getBytesFromTextChild
-    *
-    * @return The base64 bytes from the text children of this element
-    * @throws XMLSecurityException
-    */
-   public byte[] getBytesFromTextChild() throws XMLSecurityException {
-      return Base64.decode
-         (XMLUtils.getFullTextChildrenFromElement(this._constructionElement));
-   }
-
-   /**
-    * Method getTextFromTextChild
-    *
-    * @return the Text obtained by concatenating all the text nodes of this
-    *    element
-    */
-   public String getTextFromTextChild() {
-      return XMLUtils.getFullTextChildrenFromElement(this._constructionElement);
-   }
+    /**
+     * Method getTextFromTextChild
+     *
+     * @return the Text obtained by concatenating all the text nodes of this
+     *    element
+     */
+    public String getTextFromTextChild() {
+        return XMLUtils.getFullTextChildrenFromElement(this._constructionElement);
+    }
 
-   /**
-    * Method length
-    *
-    * @param namespace
-    * @param localname
-    * @return the number of elements {namespace}:localname under this element
-    */
-   public int length(String namespace, String localname) {
-            int number=0;
-            Node sibling=this._constructionElement.getFirstChild();
-            while (sibling!=null) {
-                if (localname.equals(sibling.getLocalName())
-                                &&
-                                        namespace==sibling.getNamespaceURI() ) {
-                        number++;
-                }
-                sibling=sibling.getNextSibling();
+    /**
+     * Method length
+     *
+     * @param namespace
+     * @param localname
+     * @return the number of elements {namespace}:localname under this element
+     */
+    public int length(String namespace, String localname) {
+        int number = 0;
+        Node sibling = this._constructionElement.getFirstChild();
+        while (sibling != null) {
+            if (localname.equals(sibling.getLocalName())
+                && namespace.equals(sibling.getNamespaceURI())) {
+                number++;
             }
-            return number;
-     }
+            sibling = sibling.getNextSibling();
+        }
+        return number;
+    }
 
-   /**
-    * Adds an xmlns: definition to the Element. This can be called as follows:
-    *
-    * <PRE>
-    * // set namespace with ds prefix
-    * xpathContainer.setXPathNamespaceContext("ds", "http://www.w3.org/2000/09/xmldsig#");
-    * xpathContainer.setXPathNamespaceContext("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
-    * </PRE>
-    *
-    * @param prefix
-    * @param uri
-    * @throws XMLSecurityException
-    */
-   public void setXPathNamespaceContext(String prefix, String uri)
-           throws XMLSecurityException {
-
-      String ns;
+    /**
+     * Adds an xmlns: definition to the Element. This can be called as follows:
+     *
+     * <PRE>
+     * // set namespace with ds prefix
+     * xpathContainer.setXPathNamespaceContext("ds", "http://www.w3.org/2000/09/xmldsig#");
+     * xpathContainer.setXPathNamespaceContext("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
+     * </PRE>
+     *
+     * @param prefix
+     * @param uri
+     * @throws XMLSecurityException
+     */
+    public void setXPathNamespaceContext(String prefix, String uri)
+        throws XMLSecurityException {
+        String ns;
 
-      if ((prefix == null) || (prefix.length() == 0)) {
-       throw new XMLSecurityException("defaultNamespaceCannotBeSetHere");
-      } else if (prefix.equals("xmlns")) {
-        throw new XMLSecurityException("defaultNamespaceCannotBeSetHere");
-      } else if (prefix.startsWith("xmlns:")) {
-         ns = prefix;//"xmlns:" + prefix.substring("xmlns:".length());
-      } else {
-         ns = "xmlns:" + prefix;
-      }
+        if ((prefix == null) || (prefix.length() == 0)) {
+            throw new XMLSecurityException("defaultNamespaceCannotBeSetHere");
+        } else if (prefix.equals("xmlns")) {
+            throw new XMLSecurityException("defaultNamespaceCannotBeSetHere");
+        } else if (prefix.startsWith("xmlns:")) {
+            ns = prefix;//"xmlns:" + prefix.substring("xmlns:".length());
+        } else {
+            ns = "xmlns:" + prefix;
+        }
 
-
-
-      Attr a = this._constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns);
+        Attr a = this._constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns);
 
-      if (a != null) {
-       if (!a.getNodeValue().equals(uri)) {
-         Object exArgs[] = { ns,
-                             this._constructionElement.getAttributeNS(null,
-                                                                      ns) };
+        if (a != null) {
+            if (!a.getNodeValue().equals(uri)) {
+                Object exArgs[] = { ns, this._constructionElement.getAttributeNS(null, ns) };
 
-         throw new XMLSecurityException("namespacePrefixAlreadyUsedByOtherURI",
-                                        exArgs);
-       }
-       return;
-      }
+                throw new XMLSecurityException("namespacePrefixAlreadyUsedByOtherURI", exArgs);
+            }
+            return;
+        }
 
-      this._constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns,
-                                               uri);
-   }
-
-   /** Field _prefixMappings */
-   static Map<String, String> _prefixMappings = new HashMap<String,String>();
-   static Map<String, String> _prefixMappingsBindings = new HashMap<String,String>();
+        this._constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns, uri);
+    }
 
     /**
      * Method setDefaultPrefix
@@ -505,26 +471,39 @@
      */
     public static void setDefaultPrefix(String namespace, String prefix)
         throws XMLSecurityException {
-
-        if (ElementProxy._prefixMappings.containsValue(prefix)) {
-
-            Object storedNamespace=ElementProxy._prefixMappings.get(namespace);
-            if (!storedNamespace.equals(prefix)) {
-                Object exArgs[] = { prefix, namespace, storedNamespace };
+        if (prefixMappings.containsValue(prefix)) {
+            String storedPrefix = prefixMappings.get(namespace);
+            if (!storedPrefix.equals(prefix)) {
+                Object exArgs[] = { prefix, namespace, storedPrefix };
 
                 throw new XMLSecurityException("prefix.AlreadyAssigned", exArgs);
             }
         }
+
         if (Constants.SignatureSpecNS.equals(namespace)) {
-            XMLUtils.dsPrefix=prefix;
+            XMLUtils.setDsPrefix(prefix);
+        }
+        if (EncryptionConstants.EncryptionSpecNS.equals(namespace)) {
+            XMLUtils.setXencPrefix(prefix);
         }
-        ElementProxy._prefixMappings.put(namespace, prefix.intern());
-        if (prefix.length() == 0) {
-            ElementProxy._prefixMappingsBindings.put(namespace, "xmlns");
-        } else {
-            ElementProxy._prefixMappingsBindings.put(namespace, ("xmlns:"+prefix).intern());
-        }
-   }
+        prefixMappings.put(namespace, prefix);
+    }
+
+    /**
+     * This method registers the default prefixes.
+     */
+    public static void registerDefaultPrefixes() throws XMLSecurityException {
+        setDefaultPrefix("http://www.w3.org/2000/09/xmldsig#", "ds");
+        setDefaultPrefix("http://www.w3.org/2001/04/xmlenc#", "xenc");
+        setDefaultPrefix("http://www.w3.org/2009/xmlenc11#", "xenc11");
+        setDefaultPrefix("http://www.xmlsecurity.org/experimental#", "experimental");
+        setDefaultPrefix("http://www.w3.org/2002/04/xmldsig-filter2", "dsig-xpath-old");
+        setDefaultPrefix("http://www.w3.org/2002/06/xmldsig-filter2", "dsig-xpath");
+        setDefaultPrefix("http://www.w3.org/2001/10/xml-exc-c14n#", "ec");
+        setDefaultPrefix(
+            "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter", "xx"
+        );
+    }
 
     /**
      * Method getDefaultPrefix
@@ -533,10 +512,19 @@
      * @return the default prefix bind to this element.
      */
     public static String getDefaultPrefix(String namespace) {
-        return ElementProxy._prefixMappings.get(namespace);
+        return prefixMappings.get(namespace);
     }
 
-    public static String getDefaultPrefixBindings(String namespace) {
-        return ElementProxy._prefixMappingsBindings.get(namespace);
+    protected void setLocalIdAttribute(String attrName, String value) {
+
+        if (value != null) {
+            Attr attr = getDocument().createAttributeNS(null, attrName);
+            attr.setValue(value);
+            getElement().setAttributeNodeNS(attr);
+            getElement().setIdAttributeNode(attr, true);
+        }
+        else {
+            getElement().removeAttributeNS(null, attrName);
+        }
     }
 }
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/I18n.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/I18n.java	Wed Jul 05 19:00:49 2017 +0200
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils;
 
@@ -31,202 +33,136 @@
  */
 public class I18n {
 
-   /** Field NOT_INITIALIZED_MSG */
-   public static final String NOT_INITIALIZED_MSG =
-      "You must initialize the xml-security library correctly before you use it. "
-      + "Call the static method \"com.sun.org.apache.xml.internal.security.Init.init();\" to do that "
-      + "before you use any functionality from that library.";
+    /** Field NOT_INITIALIZED_MSG */
+    public static final String NOT_INITIALIZED_MSG =
+        "You must initialize the xml-security library correctly before you use it. "
+        + "Call the static method \"com.sun.org.apache.xml.internal.security.Init.init();\" to do that "
+        + "before you use any functionality from that library.";
 
-   /** Field defaultLanguageCode */
-   private static String defaultLanguageCode;    // will be set in static{} block
-
-   /** Field defaultCountryCode */
-   private static String defaultCountryCode;    // will be set in static{} block
-
-   /** Field resourceBundle */
-   private static ResourceBundle resourceBundle =
-       ResourceBundle.getBundle
-         (Constants.exceptionMessagesResourceBundleBase, Locale.US);
+    /** Field resourceBundle */
+    private static ResourceBundle resourceBundle;
 
-   /** Field alreadyInitialized */
-   private static boolean alreadyInitialized = false;
-
-   /** Field _languageCode */
-   private static String _languageCode = null;
-
-   /** Field _countryCode */
-   private static String _countryCode = null;
+    /** Field alreadyInitialized */
+    private static boolean alreadyInitialized = false;
 
-   /**
-    * Constructor I18n
-    *
-    */
-   private I18n() {
-
-      // we don't allow instantiation
-   }
+    /**
+     * Constructor I18n
+     *
+     */
+    private I18n() {
+        // we don't allow instantiation
+    }
 
-   /**
-    * Method translate
-    *
-    * translates a message ID into an internationalized String, see alse
-    * <CODE>XMLSecurityException.getExceptionMEssage()</CODE>. The strings are
-    * stored in the <CODE>ResourceBundle</CODE>, which is identified in
-    * <CODE>exceptionMessagesResourceBundleBase</CODE>
-    *
-    * @param message
-    * @param args is an <CODE>Object[]</CODE> array of strings which are inserted into the String which is retrieved from the <CODE>ResouceBundle</CODE>
-    * @return message translated
-    */
-   public static String translate(String message, Object[] args) {
-      return getExceptionMessage(message, args);
-   }
-
-   /**
-    * Method translate
-    *
-    * translates a message ID into an internationalized String, see alse
-    * <CODE>XMLSecurityException.getExceptionMEssage()</CODE>
-    *
-    * @param message
-    * @return message translated
-    */
-   public static String translate(String message) {
-      return getExceptionMessage(message);
-   }
+    /**
+     * Method translate
+     *
+     * translates a message ID into an internationalized String, see alse
+     * <CODE>XMLSecurityException.getExceptionMEssage()</CODE>. The strings are
+     * stored in the <CODE>ResourceBundle</CODE>, which is identified in
+     * <CODE>exceptionMessagesResourceBundleBase</CODE>
+     *
+     * @param message
+     * @param args is an <CODE>Object[]</CODE> array of strings which are inserted into
+     * the String which is retrieved from the <CODE>ResouceBundle</CODE>
+     * @return message translated
+     */
+    public static String translate(String message, Object[] args) {
+        return getExceptionMessage(message, args);
+    }
 
-   /**
-    * Method getExceptionMessage
-    *
-    * @param msgID
-    * @return message translated
-    *
-    */
-   public static String getExceptionMessage(String msgID) {
-
-      try {
-         String s = resourceBundle.getString(msgID);
-
-         return s;
-      } catch (Throwable t) {
-         if (com.sun.org.apache.xml.internal.security.Init.isInitialized()) {
-            return "No message with ID \"" + msgID
-                   + "\" found in resource bundle \""
-                   + Constants.exceptionMessagesResourceBundleBase + "\"";
-         }
-         return I18n.NOT_INITIALIZED_MSG;
-      }
-   }
-
-   /**
-    * Method getExceptionMessage
-    *
-    * @param msgID
-    * @param originalException
-    * @return message translated
-    */
-   public static String getExceptionMessage(String msgID,
-                                            Exception originalException) {
+    /**
+     * Method translate
+     *
+     * translates a message ID into an internationalized String, see also
+     * <CODE>XMLSecurityException.getExceptionMessage()</CODE>
+     *
+     * @param message
+     * @return message translated
+     */
+    public static String translate(String message) {
+        return getExceptionMessage(message);
+    }
 
-      try {
-         Object exArgs[] = { originalException.getMessage() };
-         String s = MessageFormat.format(resourceBundle.getString(msgID),
-                                         exArgs);
-
-         return s;
-      } catch (Throwable t) {
-         if (com.sun.org.apache.xml.internal.security.Init.isInitialized()) {
-            return "No message with ID \"" + msgID
-                   + "\" found in resource bundle \""
-                   + Constants.exceptionMessagesResourceBundleBase
-                   + "\". Original Exception was a "
-                   + originalException.getClass().getName() + " and message "
-                   + originalException.getMessage();
-         }
-          return I18n.NOT_INITIALIZED_MSG;
-      }
-   }
-
-   /**
-    * Method getExceptionMessage
-    *
-    * @param msgID
-    * @param exArgs
-    * @return message translated
-    */
-   public static String getExceptionMessage(String msgID, Object exArgs[]) {
-
-      try {
-         String s = MessageFormat.format(resourceBundle.getString(msgID),
-                                         exArgs);
-
-         return s;
-      } catch (Throwable t) {
-         if (com.sun.org.apache.xml.internal.security.Init.isInitialized()) {
-            return "No message with ID \"" + msgID
-                   + "\" found in resource bundle \""
-                   + Constants.exceptionMessagesResourceBundleBase + "\"";
-         }
-         return I18n.NOT_INITIALIZED_MSG;
-      }
-   }
+    /**
+     * Method getExceptionMessage
+     *
+     * @param msgID
+     * @return message translated
+     *
+     */
+    public static String getExceptionMessage(String msgID) {
+        try {
+            return resourceBundle.getString(msgID);
+        } catch (Throwable t) {
+            if (com.sun.org.apache.xml.internal.security.Init.isInitialized()) {
+                return "No message with ID \"" + msgID
+                + "\" found in resource bundle \""
+                + Constants.exceptionMessagesResourceBundleBase + "\"";
+            }
+            return I18n.NOT_INITIALIZED_MSG;
+        }
+    }
 
-//
-// Commented out because it modifies shared static
-// state which could be maliciously called by untrusted code
-//
-//   /**
-//    * Method init
-//    *
-//    * @param _defaultLanguageCode
-//    * @param _defaultCountryCode
-//    */
-//   public static void init(String _defaultLanguageCode,
-//                           String _defaultCountryCode) {
-//
-//      I18n.defaultLanguageCode = _defaultLanguageCode;
-//
-//      if (I18n.defaultLanguageCode == null) {
-//         I18n.defaultLanguageCode = Locale.getDefault().getLanguage();
-//      }
-//
-//      I18n.defaultCountryCode = _defaultCountryCode;
-//
-//      if (I18n.defaultCountryCode == null) {
-//         I18n.defaultCountryCode = Locale.getDefault().getCountry();
-//      }
-//
-//      initLocale(I18n.defaultLanguageCode, I18n.defaultCountryCode);
-//   }
+    /**
+     * Method getExceptionMessage
+     *
+     * @param msgID
+     * @param originalException
+     * @return message translated
+     */
+    public static String getExceptionMessage(String msgID, Exception originalException) {
+        try {
+            Object exArgs[] = { originalException.getMessage() };
+            return MessageFormat.format(resourceBundle.getString(msgID), exArgs);
+        } catch (Throwable t) {
+            if (com.sun.org.apache.xml.internal.security.Init.isInitialized()) {
+                return "No message with ID \"" + msgID
+                + "\" found in resource bundle \""
+                + Constants.exceptionMessagesResourceBundleBase
+                + "\". Original Exception was a "
+                + originalException.getClass().getName() + " and message "
+                + originalException.getMessage();
+            }
+            return I18n.NOT_INITIALIZED_MSG;
+        }
+    }
 
-//
-// Commented out because it modifies shared static
-// state which could be maliciously called by untrusted code
-//
-//   /**
-//    * Method initLocale
-//    *
-//    * @param languageCode
-//    * @param countryCode
-//    */
-//   public static void initLocale(String languageCode, String countryCode) {
-//
-//      if (alreadyInitialized && languageCode.equals(_languageCode)
-//              && countryCode.equals(_countryCode)) {
-//         return;
-//      }
-//
-//      if ((languageCode != null) && (countryCode != null)
-//              && (languageCode.length() > 0) && (countryCode.length() > 0)) {
-//         _languageCode = languageCode;
-//         _countryCode = countryCode;
-//      } else {
-//         _countryCode = I18n.defaultCountryCode;
-//         _languageCode = I18n.defaultLanguageCode;
-//      }
-//
-//      I18n.resourceBundle =
-//         ResourceBundle.getBundle(Constants.exceptionMessagesResourceBundleBase,
-//                                  new Locale(_languageCode, _countryCode));
-//   }
+    /**
+     * Method getExceptionMessage
+     *
+     * @param msgID
+     * @param exArgs
+     * @return message translated
+     */
+    public static String getExceptionMessage(String msgID, Object exArgs[]) {
+        try {
+            return MessageFormat.format(resourceBundle.getString(msgID), exArgs);
+        } catch (Throwable t) {
+            if (com.sun.org.apache.xml.internal.security.Init.isInitialized()) {
+                return "No message with ID \"" + msgID
+                + "\" found in resource bundle \""
+                + Constants.exceptionMessagesResourceBundleBase + "\"";
+            }
+            return I18n.NOT_INITIALIZED_MSG;
+        }
+    }
+
+    /**
+     * Method init
+     *
+     * @param languageCode
+     * @param countryCode
+     */
+    public synchronized static void init(String languageCode, String countryCode) {
+        if (alreadyInitialized) {
+            return;
+        }
+
+        I18n.resourceBundle =
+            ResourceBundle.getBundle(
+                Constants.exceptionMessagesResourceBundleBase,
+                new Locale(languageCode, countryCode)
+            );
+        alreadyInitialized = true;
+    }
 }
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java	Wed Jul 05 19:00:49 2017 +0200
@@ -21,14 +21,15 @@
 package com.sun.org.apache.xml.internal.security.utils;
 
 
-
 import java.io.IOException;
 import java.io.OutputStream;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
@@ -60,6 +61,12 @@
          }
       });
 
+    private static volatile String dsPrefix = "ds";
+    private static volatile String xencPrefix = "xenc";
+
+   private static final java.util.logging.Logger log =
+       java.util.logging.Logger.getLogger(XMLUtils.class.getName());
+
    /**
     * Constructor XMLUtils
     *
@@ -68,6 +75,23 @@
 
       // we don't allow instantiation
    }
+
+    /**
+     * Set the prefix for the digital signature namespace
+     * @param prefix the new prefix for the digital signature namespace
+     */
+    public static void setDsPrefix(String prefix) {
+        dsPrefix = prefix;
+    }
+
+    /**
+     * Set the prefix for the encryption namespace
+     * @param prefix the new prefix for the encryption namespace
+     */
+    public static void setXencPrefix(String prefix) {
+        xencPrefix = prefix;
+    }
+
    public static Element getNextElement(Node el) {
            while ((el!=null) && (el.getNodeType()!=Node.ELEMENT_NODE)) {
                    el=el.getNextSibling();
@@ -230,9 +254,8 @@
       return sb.toString();
    }
 
+   static Map<String, String> namePrefixes=new HashMap<String, String>();
 
-   static  String dsPrefix=null;
-   static Map<String, String> namePrefixes=new HashMap<String, String>();
    /**
     * Creates an Element in the XML Signature specification namespace.
     *
@@ -261,31 +284,38 @@
       return doc.createElementNS(Constants.SignatureSpecNS, namePrefix);
    }
 
-   /**
-    * Returns true if the element is in XML Signature namespace and the local
-    * name equals the supplied one.
-    *
-    * @param element
-    * @param localName
-    * @return true if the element is in XML Signature namespace and the local name equals the supplied one
-    */
-   public static boolean elementIsInSignatureSpace(Element element,
-           String localName) {
-      return ElementProxy.checker.isNamespaceElement(element, localName, Constants.SignatureSpecNS);
-   }
+    /**
+     * Returns true if the element is in XML Signature namespace and the local
+     * name equals the supplied one.
+     *
+     * @param element
+     * @param localName
+     * @return true if the element is in XML Signature namespace and the local name equals the supplied one
+     */
+    public static boolean elementIsInSignatureSpace(Element element, String localName) {
+        if (element == null) {
+            return false;
+        }
 
-   /**
-    * Returns true if the element is in XML Encryption namespace and the local
-    * name equals the supplied one.
-    *
-    * @param element
-    * @param localName
-    * @return true if the element is in XML Encryption namespace and the local name equals the supplied one
-    */
-   public static boolean elementIsInEncryptionSpace(Element element,
-           String localName) {
-           return ElementProxy.checker.isNamespaceElement(element, localName, EncryptionConstants.EncryptionSpecNS);
-   }
+        return Constants.SignatureSpecNS.equals(element.getNamespaceURI())
+            && element.getLocalName().equals(localName);
+    }
+
+    /**
+     * Returns true if the element is in XML Encryption namespace and the local
+     * name equals the supplied one.
+     *
+     * @param element
+     * @param localName
+     * @return true if the element is in XML Encryption namespace and the local name equals the supplied one
+     */
+    public static boolean elementIsInEncryptionSpace(Element element, String localName) {
+        if (element == null) {
+            return false;
+        }
+        return EncryptionConstants.EncryptionSpecNS.equals(element.getNamespaceURI())
+            && element.getLocalName().equals(localName);
+    }
 
    /**
     * This method returns the owner document of a particular node.
@@ -504,45 +534,45 @@
            } while (true);
    }
 
-   /**
-    * @param sibling
-    * @param nodeName
-    * @param number
-    * @return nodes with the constrain
-    */
-   public static Element selectDsNode(Node sibling, String nodeName, int number) {
-        while (sibling!=null) {
-                if (ElementProxy.checker.isNamespaceElement(sibling, nodeName, Constants.SignatureSpecNS )) {
-                        if (number==0){
-                                return (Element)sibling;
-                        }
-                        number--;
+    /**
+     * @param sibling
+     * @param nodeName
+     * @param number
+     * @return nodes with the constrain
+     */
+    public static Element selectDsNode(Node sibling, String nodeName, int number) {
+        while (sibling != null) {
+            if (Constants.SignatureSpecNS.equals(sibling.getNamespaceURI())
+                && sibling.getLocalName().equals(nodeName)) {
+                if (number == 0){
+                    return (Element)sibling;
                 }
-                sibling=sibling.getNextSibling();
+                number--;
+            }
+            sibling = sibling.getNextSibling();
         }
         return null;
-   }
-
-   /**
-    * @param sibling
-    * @param nodeName
-    * @param number
-    * @return nodes with the constrain
-    */
+    }
 
-   public static Element selectXencNode(Node sibling, String nodeName, int number) {
-        while (sibling!=null) {
-                if (ElementProxy.checker.isNamespaceElement(sibling, nodeName, EncryptionConstants.EncryptionSpecNS )) {
-                        if (number==0){
-                                return (Element)sibling;
-                        }
-                        number--;
+    /**
+     * @param sibling
+     * @param nodeName
+     * @param number
+     * @return nodes with the constrain
+     */
+    public static Element selectXencNode(Node sibling, String nodeName, int number) {
+        while (sibling != null) {
+            if (EncryptionConstants.EncryptionSpecNS.equals(sibling.getNamespaceURI())
+                && sibling.getLocalName().equals(nodeName)) {
+                if (number == 0){
+                    return (Element)sibling;
                 }
-                sibling=sibling.getNextSibling();
+                number--;
+            }
+            sibling = sibling.getNextSibling();
         }
         return null;
-   }
-
+    }
 
    /**
     * @param sibling
@@ -581,62 +611,53 @@
     return (Text)n;
    }
 
-   /**
-    * @param sibling
-    * @param uri
-    * @param nodeName
-    * @param number
-    * @return nodes with the constrain
-    */
-   public static Element selectNode(Node sibling, String uri,String nodeName, int number) {
-        while (sibling!=null) {
-                if (ElementProxy.checker.isNamespaceElement(sibling, nodeName, uri)) {
-                        if (number==0){
-                                return (Element)sibling;
-                        }
-                        number--;
+    /**
+     * @param sibling
+     * @param uri
+     * @param nodeName
+     * @param number
+     * @return nodes with the constrain
+     */
+    public static Element selectNode(Node sibling, String uri, String nodeName, int number) {
+        while (sibling != null) {
+            if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri)
+                && sibling.getLocalName().equals(nodeName)) {
+                if (number == 0){
+                    return (Element)sibling;
                 }
-                sibling=sibling.getNextSibling();
+                number--;
+            }
+            sibling = sibling.getNextSibling();
         }
         return null;
-   }
+    }
+
+    /**
+     * @param sibling
+     * @param nodeName
+     * @return nodes with the constrain
+     */
+    public static Element[] selectDsNodes(Node sibling, String nodeName) {
+        return selectNodes(sibling,Constants.SignatureSpecNS, nodeName);
+    }
 
-   /**
-    * @param sibling
-    * @param nodeName
-    * @return nodes with the constrain
-    */
-   public static Element[] selectDsNodes(Node sibling,String nodeName) {
-     return selectNodes(sibling,Constants.SignatureSpecNS,nodeName);
-   }
-   /**
-    * @param sibling
-    * @param uri
-    * @param nodeName
-    * @return nodes with the constrain
-    */
-    public static Element[] selectNodes(Node sibling,String uri,String nodeName) {
-        int size=20;
-        Element[] a= new Element[size];
-        int curr=0;
-        //List list=new ArrayList();
-        while (sibling!=null) {
-                if (ElementProxy.checker.isNamespaceElement(sibling, nodeName, uri)) {
-                        a[curr++]=(Element)sibling;
-                        if (size<=curr) {
-                                int cursize= size<<2;
-                                Element []cp=new Element[cursize];
-                                System.arraycopy(a,0,cp,0,size);
-                                a=cp;
-                                size=cursize;
-                        }
-                }
-                sibling=sibling.getNextSibling();
+    /**
+     * @param sibling
+     * @param uri
+     * @param nodeName
+     * @return nodes with the constrain
+     */
+     public static Element[] selectNodes(Node sibling, String uri, String nodeName) {
+        List<Element> list = new ArrayList<Element>();
+        while (sibling != null) {
+            if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri)
+                && sibling.getLocalName().equals(nodeName)) {
+                list.add((Element)sibling);
+            }
+            sibling = sibling.getNextSibling();
         }
-        Element []af=new Element[curr];
-        System.arraycopy(a,0,af,0,curr);
-        return af;
-   }
+        return list.toArray(new Element[list.size()]);
+    }
 
    /**
     * @param signatureElement
@@ -694,4 +715,127 @@
     public static boolean ignoreLineBreaks() {
         return ignoreLineBreaks;
     }
+
+    /**
+     * This method is a tree-search to help prevent against wrapping attacks.
+     * It checks that no two Elements have ID Attributes that match the "value"
+     * argument, if this is the case then "false" is returned. Note that a
+     * return value of "true" does not necessarily mean that a matching Element
+     * has been found, just that no wrapping attack has been detected.
+     */
+    public static boolean protectAgainstWrappingAttack(Node startNode,
+                                                       String value)
+    {
+        Node startParent = startNode.getParentNode();
+        Node processedNode = null;
+        Element foundElement = null;
+
+        String id = value.trim();
+        if (id.charAt(0) == '#') {
+            id = id.substring(1);
+        }
+
+        while (startNode != null) {
+            if (startNode.getNodeType() == Node.ELEMENT_NODE) {
+                Element se = (Element) startNode;
+
+                NamedNodeMap attributes = se.getAttributes();
+                if (attributes != null) {
+                    for (int i = 0; i < attributes.getLength(); i++) {
+                        Attr attr = (Attr)attributes.item(i);
+                        if (attr.isId() && id.equals(attr.getValue())) {
+                            if (foundElement == null) {
+                                // Continue searching to find duplicates
+                                foundElement = attr.getOwnerElement();
+                            } else {
+                                log.log(java.util.logging.Level.FINE, "Multiple elements with the same 'Id' attribute value!");
+                                return false;
+                            }
+                        }
+                    }
+                }
+            }
+
+            processedNode = startNode;
+            startNode = startNode.getFirstChild();
+
+            // no child, this node is done.
+            if (startNode == null) {
+                // close node processing, get sibling
+                startNode = processedNode.getNextSibling();
+            }
+
+            // no more siblings, get parent, all children
+            // of parent are processed.
+            while (startNode == null) {
+                processedNode = processedNode.getParentNode();
+                if (processedNode == startParent) {
+                    return true;
+                }
+                // close parent node processing (processed node now)
+                startNode = processedNode.getNextSibling();
+            }
+        }
+        return true;
+    }
+
+    /**
+     * This method is a tree-search to help prevent against wrapping attacks.
+     * It checks that no other Element than the given "knownElement" argument
+     * has an ID attribute that matches the "value" argument, which is the ID
+     * value of "knownElement". If this is the case then "false" is returned.
+     */
+    public static boolean protectAgainstWrappingAttack(Node startNode,
+                                                       Element knownElement,
+                                                       String value)
+    {
+        Node startParent = startNode.getParentNode();
+        Node processedNode = null;
+
+        String id = value.trim();
+        if (id.charAt(0) == '#') {
+            id = id.substring(1);
+        }
+
+        while (startNode != null) {
+            if (startNode.getNodeType() == Node.ELEMENT_NODE) {
+                Element se = (Element) startNode;
+
+                NamedNodeMap attributes = se.getAttributes();
+                if (attributes != null) {
+                    for (int i = 0; i < attributes.getLength(); i++) {
+                        Attr attr = (Attr)attributes.item(i);
+                        if (attr.isId() && id.equals(attr.getValue())
+                            && se != knownElement)
+                        {
+                            log.log(java.util.logging.Level.FINE, "Multiple elements with the same 'Id' attribute value!");
+                            return false;
+                        }
+                    }
+                }
+            }
+
+            processedNode = startNode;
+            startNode = startNode.getFirstChild();
+
+            // no child, this node is done.
+            if (startNode == null) {
+                // close node processing, get sibling
+                startNode = processedNode.getNextSibling();
+            }
+
+            // no more siblings, get parent, all children
+            // of parent are processed.
+            while (startNode == null) {
+                processedNode = processedNode.getParentNode();
+                if (processedNode == startParent) {
+                    return true;
+                }
+                // close parent node processing (processed node now)
+                startNode = processedNode.getNextSibling();
+            }
+        }
+        return true;
+    }
+
 }
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java	Wed Jul 05 19:00:49 2017 +0200
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.utils.resolver;
 
@@ -25,311 +27,318 @@
 import java.util.Map;
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
+import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverDirectHTTP;
+import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverFragment;
+import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverLocalFilesystem;
+import com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverXPointer;
 import org.w3c.dom.Attr;
 
 /**
  * During reference validation, we have to retrieve resources from somewhere.
  * This is done by retrieving a Resolver. The resolver needs two arguments: The
- * URI in which the link to the new resource is defined and the BaseURI of the
- * file/entity in which the URI occurs (the BaseURI is the same as the SystemId.
- *
- * <UL xml:lang="DE" LANG="DE">
- * <LI> Verschiedene Implementierungen k??nnen sich als Resolver registrieren.
- * <LI> Standardm????ig werden erste Implementierungen auf dem XML config file registrirt.
- * <LI> Der Benutzer kann bei Bedarf Implementierungen voranstellen oder anf??gen.
- * <LI> Implementierungen k??nnen mittels Features customized werden ??
- *      (z.B. um Proxy-Passworter ??bergeben zu k??nnen).
- * <LI> Jede Implementierung bekommt das URI Attribut und den Base URI
- *      ??bergeben und muss antworten, ob sie aufl??sen kann.
- * <LI> Die erste Implementierung, die die Aufgabe erf??llt, f??hrt die Aufl??sung durch.
- * </UL>
- *
- * @author $Author: mullan $
+ * URI in which the link to the new resource is defined and the baseURI of the
+ * file/entity in which the URI occurs (the baseURI is the same as the SystemId).
  */
 public class ResourceResolver {
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    /** {@link org.apache.commons.logging} logging facility */
+    private static java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(ResourceResolver.class.getName());
 
-   /** Field _alreadyInitialized */
-   static boolean _alreadyInitialized = false;
+    /** these are the system-wide resolvers */
+    private static List<ResourceResolver> resolverList = new ArrayList<ResourceResolver>();
 
-   /** these are the system-wide resolvers */
-   static List<ResourceResolver> _resolverVector = null;
-
-   static boolean allThreadSafeInList=true;
-
-   /** Field transformSpi */
-   protected ResourceResolverSpi _resolverSpi = null;
+    /** Field resolverSpi */
+    private final ResourceResolverSpi resolverSpi;
 
-   /**
-    * Constructor ResourceResolver
-    *
-    * @param className
-    * @throws ClassNotFoundException
-    * @throws IllegalAccessException
-    * @throws InstantiationException
-    */
-   private ResourceResolver(String className)
-           throws ClassNotFoundException, IllegalAccessException,
-                  InstantiationException {
-      this._resolverSpi =
-         (ResourceResolverSpi) Class.forName(className).newInstance();
-   }
+    /**
+     * Constructor ResourceResolver
+     *
+     * @param resourceResolver
+     */
+    public ResourceResolver(ResourceResolverSpi resourceResolver) {
+        this.resolverSpi = resourceResolver;
+    }
+
+    /**
+     * Method getInstance
+     *
+     * @param uri
+     * @param baseURI
+     * @return the instance
+     *
+     * @throws ResourceResolverException
+     */
+    public static final ResourceResolver getInstance(Attr uri, String baseURI)
+        throws ResourceResolverException {
+        return getInstance(uri, baseURI, false);
+    }
 
-   /**
-    * Constructor ResourceResolver
-    *
-    * @param resourceResolver
-    */
-   public ResourceResolver(ResourceResolverSpi resourceResolver) {
-      this._resolverSpi = resourceResolver;
-   }
-
+    /**
+     * Method getInstance
+     *
+     * @param uri
+     * @param baseURI
+     * @param secureValidation
+     * @return the instance
+     *
+     * @throws ResourceResolverException
+     */
+    public static final ResourceResolver getInstance(
+        Attr uri, String baseURI, boolean secureValidation
+    ) throws ResourceResolverException {
+        synchronized (resolverList) {
+            for (ResourceResolver resolver : resolverList) {
+                ResourceResolver resolverTmp = resolver;
+                if (!resolver.resolverSpi.engineIsThreadSafe()) {
+                    try {
+                        resolverTmp =
+                            new ResourceResolver(resolver.resolverSpi.getClass().newInstance());
+                    } catch (InstantiationException e) {
+                        throw new ResourceResolverException("", e, uri, baseURI);
+                    } catch (IllegalAccessException e) {
+                        throw new ResourceResolverException("", e, uri, baseURI);
+                    }
+                }
 
-   /**
-    * Method getInstance
-    *
-    * @param uri
-    * @param BaseURI
-    * @return the instnace
-    *
-    * @throws ResourceResolverException
-    */
-   public static final ResourceResolver getInstance(Attr uri, String BaseURI)
-           throws ResourceResolverException {
-      int length=ResourceResolver._resolverVector.size();
-      for (int i = 0; i < length; i++) {
-                  ResourceResolver resolver =
-            ResourceResolver._resolverVector.get(i);
-                  ResourceResolver resolverTmp=null;
-                  try {
-                        resolverTmp =  allThreadSafeInList || resolver._resolverSpi.engineIsThreadSafe() ? resolver :
-                                        new ResourceResolver((ResourceResolverSpi)resolver._resolverSpi.getClass().newInstance());
-                  } catch (InstantiationException e) {
-                          throw new ResourceResolverException("",e,uri,BaseURI);
-                  } catch (IllegalAccessException e) {
-                          throw new ResourceResolverException("",e,uri,BaseURI);
-                  }
-
-         if (log.isLoggable(java.util.logging.Level.FINE))
-                log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolver._resolverSpi.getClass().getName());
+                if (log.isLoggable(java.util.logging.Level.FINE)) {
+                    log.log(java.util.logging.Level.FINE,
+                        "check resolvability by class " + resolverTmp.getClass().getName()
+                    );
+                }
 
-         if ((resolver != null) && resolverTmp.canResolve(uri, BaseURI)) {
-                 if (i!=0) {
-                 //update resolver.
-                         //System.out.println("Swaping");
-                         List<ResourceResolver> resolverVector=getResolverVectorClone();
-                         resolverVector.remove(i);
-                         resolverVector.add(0,resolver);
-                         _resolverVector=resolverVector;
-                 } else {
-                         //System.out.println("hitting");
-                 }
+                resolverTmp.resolverSpi.secureValidation = secureValidation;
+                if ((resolverTmp != null) && resolverTmp.canResolve(uri, baseURI)) {
+                    // Check to see whether the Resolver is allowed
+                    if (secureValidation
+                        && (resolverTmp.resolverSpi instanceof ResolverLocalFilesystem
+                            || resolverTmp.resolverSpi instanceof ResolverDirectHTTP)) {
+                        Object exArgs[] = { resolverTmp.resolverSpi.getClass().getName() };
+                        throw new ResourceResolverException(
+                            "signature.Reference.ForbiddenResolver", exArgs, uri, baseURI
+                        );
+                    }
+                    return resolverTmp;
+                }
+            }
+        }
 
-            return resolverTmp;
-         }
-      }
+        Object exArgs[] = { ((uri != null) ? uri.getNodeValue() : "null"), baseURI };
 
-      Object exArgs[] = { ((uri != null)
-                           ? uri.getNodeValue()
-                           : "null"), BaseURI };
-
-      throw new ResourceResolverException("utils.resolver.noClass", exArgs,
-                                          uri, BaseURI);
-   }
+        throw new ResourceResolverException("utils.resolver.noClass", exArgs, uri, baseURI);
+    }
 
-   /**
-    * Method getResolverVectorClone
-    *
-    * @return clone of _resolverVector
-    */
-   @SuppressWarnings("unchecked")
-   private static List<ResourceResolver> getResolverVectorClone() {
-       return (List<ResourceResolver>)((ArrayList<ResourceResolver>)_resolverVector).clone();
-   }
+    /**
+     * Method getInstance
+     *
+     * @param uri
+     * @param baseURI
+     * @param individualResolvers
+     * @return the instance
+     *
+     * @throws ResourceResolverException
+     */
+    public static ResourceResolver getInstance(
+        Attr uri, String baseURI, List<ResourceResolver> individualResolvers
+    ) throws ResourceResolverException {
+        return getInstance(uri, baseURI, individualResolvers, false);
+    }
 
-   /**
-    * Method getInstance
-    *
-    * @param uri
-    * @param BaseURI
-    * @param individualResolvers
-    * @return the instance
-    *
-    * @throws ResourceResolverException
-    */
-   public static final ResourceResolver getInstance(
-           Attr uri, String BaseURI, List<ResourceResolver> individualResolvers)
-              throws ResourceResolverException {
-      if (log.isLoggable(java.util.logging.Level.FINE)) {
-
-        log.log(java.util.logging.Level.FINE, "I was asked to create a ResourceResolver and got " + (individualResolvers==null? 0 : individualResolvers.size()) );
-        log.log(java.util.logging.Level.FINE, " extra resolvers to my existing " + ResourceResolver._resolverVector.size() + " system-wide resolvers");
-      }
-
-      // first check the individual Resolvers
-          int size=0;
-      if ((individualResolvers != null) && ((size=individualResolvers.size()) > 0)) {
-         for (int i = 0; i < size; i++) {
-            ResourceResolver resolver =
-               individualResolvers.get(i);
+    /**
+     * Method getInstance
+     *
+     * @param uri
+     * @param baseURI
+     * @param individualResolvers
+     * @param secureValidation
+     * @return the instance
+     *
+     * @throws ResourceResolverException
+     */
+    public static ResourceResolver getInstance(
+        Attr uri, String baseURI, List<ResourceResolver> individualResolvers, boolean secureValidation
+    ) throws ResourceResolverException {
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE,
+                "I was asked to create a ResourceResolver and got "
+                + (individualResolvers == null ? 0 : individualResolvers.size())
+            );
+        }
 
-            if (resolver != null) {
-               String currentClass = resolver._resolverSpi.getClass().getName();
-               if (log.isLoggable(java.util.logging.Level.FINE))
-                log.log(java.util.logging.Level.FINE, "check resolvability by class " + currentClass);
+        // first check the individual Resolvers
+        if (individualResolvers != null) {
+            for (int i = 0; i < individualResolvers.size(); i++) {
+                ResourceResolver resolver = individualResolvers.get(i);
 
-               if (resolver.canResolve(uri, BaseURI)) {
-                  return resolver;
-               }
-            }
-         }
-      }
+                if (resolver != null) {
+                    if (log.isLoggable(java.util.logging.Level.FINE)) {
+                        String currentClass = resolver.resolverSpi.getClass().getName();
+                        log.log(java.util.logging.Level.FINE, "check resolvability by class " + currentClass);
+                    }
 
-          return getInstance(uri,BaseURI);
-   }
+                    resolver.resolverSpi.secureValidation = secureValidation;
+                    if (resolver.canResolve(uri, baseURI)) {
+                        return resolver;
+                    }
+                }
+            }
+        }
 
-   /**
-    * The init() function is called by com.sun.org.apache.xml.internal.security.Init.init()
-    */
-   public static void init() {
-
-      if (!ResourceResolver._alreadyInitialized) {
-         ResourceResolver._resolverVector = new ArrayList<ResourceResolver>(10);
-         _alreadyInitialized = true;
-      }
-   }
+        return getInstance(uri, baseURI, secureValidation);
+    }
 
     /**
      * Registers a ResourceResolverSpi class. This method logs a warning if
      * the class cannot be registered.
      *
-     * @param className the name of the ResourceResolverSpi class to be
-     *    registered
+     * @param className the name of the ResourceResolverSpi class to be registered
      */
+    @SuppressWarnings("unchecked")
     public static void register(String className) {
-        register(className, false);
+        try {
+            Class<ResourceResolverSpi> resourceResolverClass =
+                (Class<ResourceResolverSpi>) Class.forName(className);
+            register(resourceResolverClass, false);
+        } catch (ClassNotFoundException e) {
+            log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className + " disabling it");
+        }
     }
 
     /**
      * Registers a ResourceResolverSpi class at the beginning of the provider
      * list. This method logs a warning if the class cannot be registered.
      *
-     * @param className the name of the ResourceResolverSpi class to be
-     *    registered
+     * @param className the name of the ResourceResolverSpi class to be registered
      */
+    @SuppressWarnings("unchecked")
     public static void registerAtStart(String className) {
-        register(className, true);
+        try {
+            Class<ResourceResolverSpi> resourceResolverClass =
+                (Class<ResourceResolverSpi>) Class.forName(className);
+            register(resourceResolverClass, true);
+        } catch (ClassNotFoundException e) {
+            log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className + " disabling it");
+        }
     }
 
-    private static void register(String className, boolean start) {
+    /**
+     * Registers a ResourceResolverSpi class. This method logs a warning if the class
+     * cannot be registered.
+     * @param className
+     * @param start
+     */
+    public static void register(Class<? extends ResourceResolverSpi> className, boolean start) {
         try {
-            ResourceResolver resolver = new ResourceResolver(className);
+            ResourceResolverSpi resourceResolverSpi = className.newInstance();
+            register(resourceResolverSpi, start);
+        } catch (IllegalAccessException e) {
+            log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className + " disabling it");
+        } catch (InstantiationException e) {
+            log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className + " disabling it");
+        }
+    }
+
+    /**
+     * Registers a ResourceResolverSpi instance. This method logs a warning if the class
+     * cannot be registered.
+     * @param resourceResolverSpi
+     * @param start
+     */
+    public static void register(ResourceResolverSpi resourceResolverSpi, boolean start) {
+        synchronized(resolverList) {
             if (start) {
-                ResourceResolver._resolverVector.add(0, resolver);
-                log.log(java.util.logging.Level.FINE, "registered resolver");
+                resolverList.add(0, new ResourceResolver(resourceResolverSpi));
             } else {
-                ResourceResolver._resolverVector.add(resolver);
+                resolverList.add(new ResourceResolver(resourceResolverSpi));
             }
-            if (!resolver._resolverSpi.engineIsThreadSafe()) {
-                allThreadSafeInList=false;
+        }
+        if (log.isLoggable(java.util.logging.Level.FINE)) {
+            log.log(java.util.logging.Level.FINE, "Registered resolver: " + resourceResolverSpi.toString());
         }
-        } catch (Exception e) {
-            log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className +" disabling it");
-        } catch (NoClassDefFoundError e) {
-            log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className +" disabling it");
+    }
+
+    /**
+     * This method registers the default resolvers.
+     */
+    public static void registerDefaultResolvers() {
+        synchronized(resolverList) {
+            resolverList.add(new ResourceResolver(new ResolverFragment()));
+            resolverList.add(new ResourceResolver(new ResolverLocalFilesystem()));
+            resolverList.add(new ResourceResolver(new ResolverXPointer()));
+            resolverList.add(new ResourceResolver(new ResolverDirectHTTP()));
         }
     }
 
-   /**
-    * Method resolve
-    *
-    * @param uri
-    * @param BaseURI
-    * @return the resource
-    *
-    * @throws ResourceResolverException
-    */
-   public static XMLSignatureInput resolveStatic(Attr uri, String BaseURI)
-           throws ResourceResolverException {
-
-      ResourceResolver myResolver = ResourceResolver.getInstance(uri, BaseURI);
-
-      return myResolver.resolve(uri, BaseURI);
-   }
+    /**
+     * Method resolve
+     *
+     * @param uri
+     * @param baseURI
+     * @return the resource
+     *
+     * @throws ResourceResolverException
+     */
+    public XMLSignatureInput resolve(Attr uri, String baseURI)
+        throws ResourceResolverException {
+        return resolverSpi.engineResolve(uri, baseURI);
+    }
 
-   /**
-    * Method resolve
-    *
-    * @param uri
-    * @param BaseURI
-    * @return the resource
-    *
-    * @throws ResourceResolverException
-    */
-   public XMLSignatureInput resolve(Attr uri, String BaseURI)
-           throws ResourceResolverException {
-      return this._resolverSpi.engineResolve(uri, BaseURI);
-   }
+    /**
+     * Method setProperty
+     *
+     * @param key
+     * @param value
+     */
+    public void setProperty(String key, String value) {
+        resolverSpi.engineSetProperty(key, value);
+    }
 
-   /**
-    * Method setProperty
-    *
-    * @param key
-    * @param value
-    */
-   public void setProperty(String key, String value) {
-      this._resolverSpi.engineSetProperty(key, value);
-   }
+    /**
+     * Method getProperty
+     *
+     * @param key
+     * @return the value of the property
+     */
+    public String getProperty(String key) {
+        return resolverSpi.engineGetProperty(key);
+    }
 
-   /**
-    * Method getProperty
-    *
-    * @param key
-    * @return the value of the property
-    */
-   public String getProperty(String key) {
-      return this._resolverSpi.engineGetProperty(key);
-   }
+    /**
+     * Method addProperties
+     *
+     * @param properties
+     */
+    public void addProperties(Map<String, String> properties) {
+        resolverSpi.engineAddProperies(properties);
+    }
 
-   /**
-    * Method addProperties
-    *
-    * @param properties
-    */
-   public void addProperties(Map<String,String> properties) {
-      this._resolverSpi.engineAddProperies(properties);
-   }
+    /**
+     * Method getPropertyKeys
+     *
+     * @return all property keys.
+     */
+    public String[] getPropertyKeys() {
+        return resolverSpi.engineGetPropertyKeys();
+    }
 
-   /**
-    * Method getPropertyKeys
-    *
-    * @return all property keys.
-    */
-   public String[] getPropertyKeys() {
-      return this._resolverSpi.engineGetPropertyKeys();
-   }
+    /**
+     * Method understandsProperty
+     *
+     * @param propertyToTest
+     * @return true if the resolver understands the property
+     */
+    public boolean understandsProperty(String propertyToTest) {
+        return resolverSpi.understandsProperty(propertyToTest);
+    }
 
-   /**
-    * Method understandsProperty
-    *
-    * @param propertyToTest
-    * @return true if the resolver understands the property
-    */
-   public boolean understandsProperty(String propertyToTest) {
-      return this._resolverSpi.understandsProperty(propertyToTest);
-   }
-
-   /**
-    * Method canResolve
-    *
-    * @param uri
-    * @param BaseURI
-    * @return true if it can resolve the uri
-    */
-   private boolean canResolve(Attr uri, String BaseURI) {
-      return this._resolverSpi.engineCanResolve(uri, BaseURI);
-   }
+    /**
+     * Method canResolve
+     *
+     * @param uri
+     * @param baseURI
+     * @return true if it can resolve the uri
+     */
+    private boolean canResolve(Attr uri, String baseURI) {
+        return resolverSpi.engineCanResolve(uri, baseURI);
+    }
 }
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java	Wed Jul 05 19:00:49 2017 +0200
@@ -43,6 +43,8 @@
    /** Field _properties */
    protected java.util.Map<String,String> _properties = null;
 
+   protected boolean secureValidation;
+
    /**
     * This is the workhorse method used to resolve resources.
     *
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java	Wed Jul 05 19:00:49 2017 +0200
@@ -23,11 +23,12 @@
 
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
+import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
 
@@ -51,63 +52,68 @@
    /**
     * Method engineResolve
     *
-    * Wird das gleiche Dokument referenziert?
-    * Wird ein anderes Dokument referenziert?
     * @inheritDoc
     * @param uri
-    * @param BaseURI
-    *
+    * @param baseURI
     */
-   public XMLSignatureInput engineResolve(Attr uri, String BaseURI)
+   public XMLSignatureInput engineResolve(Attr uri, String baseURI)
        throws ResourceResolverException
    {
-
-      String uriNodeValue = uri.getNodeValue();
-      Document doc = uri.getOwnerElement().getOwnerDocument();
+        String uriNodeValue = uri.getNodeValue();
+        Document doc = uri.getOwnerElement().getOwnerDocument();
 
+        Node selectedElem = null;
+        if (uriNodeValue.equals("")) {
 
-      Node selectedElem = null;
-      if (uriNodeValue.equals("")) {
+           /*
+            * Identifies the node-set (minus any comment nodes) of the XML
+            * resource containing the signature
+            */
 
-         /*
-          * Identifies the node-set (minus any comment nodes) of the XML
-          * resource containing the signature
-          */
+            log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)");
+            selectedElem = doc;
+        } else {
 
-         log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)");
-         selectedElem = doc;
-      } else {
+            /*
+             * URI="#chapter1"
+             * Identifies a node-set containing the element with ID attribute
+             * value 'chapter1' of the XML resource containing the signature.
+             * XML Signature (and its applications) modify this node-set to
+             * include the element plus all descendents including namespaces and
+             * attributes -- but not comments.
+             */
+            String id = uriNodeValue.substring(1);
 
-         /*
-          * URI="#chapter1"
-          * Identifies a node-set containing the element with ID attribute
-          * value 'chapter1' of the XML resource containing the signature.
-          * XML Signature (and its applications) modify this node-set to
-          * include the element plus all descendents including namespaces and
-          * attributes -- but not comments.
-          */
-         String id = uriNodeValue.substring(1);
-
-         // Element selectedElem = doc.getElementById(id);
-         selectedElem = IdResolver.getElementById(doc, id);
-         if (selectedElem==null) {
+            selectedElem = doc.getElementById(id);
+            if (selectedElem == null) {
                 Object exArgs[] = { id };
-            throw new ResourceResolverException(
-               "signature.Verification.MissingID", exArgs, uri, BaseURI);
-         }
-         if (log.isLoggable(java.util.logging.Level.FINE))
+                throw new ResourceResolverException(
+                    "signature.Verification.MissingID", exArgs, uri, baseURI);
+            }
+            if (secureValidation) {
+                Element start = uri.getOwnerDocument().getDocumentElement();
+                if (!XMLUtils.protectAgainstWrappingAttack(start, id)) {
+                    Object exArgs[] = { id };
+                    throw new ResourceResolverException(
+                        "signature.Verification.MultipleIDs", exArgs,
+                        uri, baseURI);
+                }
+            }
+            if (log.isLoggable(java.util.logging.Level.FINE))
                 log.log(java.util.logging.Level.FINE, "Try to catch an Element with ID " + id + " and Element was " + selectedElem);
-      }
+        }
 
-      XMLSignatureInput result = new XMLSignatureInput(selectedElem);
-      result.setExcludeComments(true);
+        XMLSignatureInput result = new XMLSignatureInput(selectedElem);
+        result.setExcludeComments(true);
 
-      //log.log(java.util.logging.Level.FINE, "We return a nodeset with " + resultSet.size() + " nodes");
-      result.setMIMEType("text/xml");
-          result.setSourceURI((BaseURI != null) ? BaseURI.concat(uri.getNodeValue()) :
-                  uri.getNodeValue());
-      return result;
-   }
+        result.setMIMEType("text/xml");
+        if (baseURI != null && baseURI.length() > 0) {
+            result.setSourceURI(baseURI.concat(uri.getNodeValue()));
+        } else {
+            result.setSourceURI(uri.getNodeValue());
+        }
+        return result;
+    }
 
    /**
     * Method engineCanResolve
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -23,11 +23,12 @@
 
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
+import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
 
@@ -54,52 +55,55 @@
                             ResolverXPointer.class.getName());
 
     public boolean engineIsThreadSafe() {
-           return true;
-   }
-   /**
-    * @inheritDoc
-    */
-   public XMLSignatureInput engineResolve(Attr uri, String BaseURI)
+        return true;
+    }
+
+    /**
+     * @inheritDoc
+     */
+    public XMLSignatureInput engineResolve(Attr uri, String baseURI)
            throws ResourceResolverException {
 
-      Node resultNode = null;
-      Document doc = uri.getOwnerElement().getOwnerDocument();
+        Node resultNode = null;
+        Document doc = uri.getOwnerElement().getOwnerDocument();
 
-        String uriStr=uri.getNodeValue();
-         if (isXPointerSlash(uriStr)) {
+        String uriStr = uri.getNodeValue();
+        if (isXPointerSlash(uriStr)) {
             resultNode = doc;
 
-         } else if (isXPointerId(uriStr)) {
+        } else if (isXPointerId(uriStr)) {
             String id = getXPointerId(uriStr);
-            resultNode =IdResolver.getElementById(doc, id);
+            resultNode = doc.getElementById(id);
 
-            // log.log(java.util.logging.Level.FINE, "Use #xpointer(id('" + id + "')) on element " + selectedElem);
+            if (secureValidation) {
+                Element start = uri.getOwnerDocument().getDocumentElement();
+                if (!XMLUtils.protectAgainstWrappingAttack(start, id)) {
+                    Object exArgs[] = { id };
+                    throw new ResourceResolverException(
+                        "signature.Verification.MultipleIDs", exArgs,
+                        uri, baseURI);
+                }
+            }
 
             if (resultNode == null) {
                Object exArgs[] = { id };
 
                throw new ResourceResolverException(
-                  "signature.Verification.MissingID", exArgs, uri, BaseURI);
+                  "signature.Verification.MissingID", exArgs, uri, baseURI);
             }
-            /*
-            resultNodes =
-               cXPathAPI
-                  .selectNodeList(selectedElem, Canonicalizer
-                     .XPATH_C14N_WITH_COMMENTS_SINGLE_NODE);*/
-         }
+        }
 
+        XMLSignatureInput result = new XMLSignatureInput(resultNode);
 
-      XMLSignatureInput result = new XMLSignatureInput(resultNode);
+        result.setMIMEType("text/xml");
+        if (baseURI != null && baseURI.length() > 0) {
+            result.setSourceURI(baseURI.concat(uri.getNodeValue()));
+        } else {
+            result.setSourceURI(uri.getNodeValue());
+        }
 
-      result.setMIMEType("text/xml");
-      if (BaseURI != null && BaseURI.length() > 0) {
-          result.setSourceURI(BaseURI.concat(uri.getNodeValue()));
-      } else {
-          result.setSourceURI(uri.getNodeValue());
-      }
-
-      return result;
-   }
+        return result;
+    }
 
    /**
     * @inheritDoc
--- a/jdk/src/share/classes/com/sun/rowset/RowSetResourceBundle_zh_CN.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/rowset/RowSetResourceBundle_zh_CN.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -140,7 +140,7 @@
 #WebRowSetXmlReader exception
 wrsxmlreader.invalidcp = \u5DF2\u5230\u8FBE RowSet \u7684\u7ED3\u5C3E\u3002\u5149\u6807\u4F4D\u7F6E\u65E0\u6548
 wrsxmlreader.readxml = readXML: {0}
-wrsxmlreader.parseerr = ** \u8BED\u6CD5\u5206\u6790\u9519\u8BEF: {0}, \u884C: {1}, URI: {2}
+wrsxmlreader.parseerr = ** \u89E3\u6790\u9519\u8BEF: {0}, \u884C: {1}, URI: {2}
 
 #WebRowSetXmlWriter exceptions
 wrsxmlwriter.ioex = IOException: {0}
--- a/jdk/src/share/classes/com/sun/rowset/RowSetResourceBundle_zh_TW.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/rowset/RowSetResourceBundle_zh_TW.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -67,8 +67,8 @@
 cachedrowsetimpl.matchcols1 = \u5339\u914D\u6B04\u61C9\u5927\u65BC 0
 cachedrowsetimpl.matchcols2 = \u5339\u914D\u6B04\u61C9\u70BA\u7A7A\u767D\u5B57\u4E32\u6216\u7A7A\u503C\u5B57\u4E32
 cachedrowsetimpl.unsetmatch = \u53D6\u6D88\u8A2D\u5B9A\u7684\u6B04\u548C\u8A2D\u5B9A\u7684\u6B04\u4E0D\u540C
-cachedrowsetimpl.unsetmatch1 = \u4F7F\u7528\u6B04\u540D\u505A\u70BA unsetMatchColumn \u7684\u5F15\u6578
-cachedrowsetimpl.unsetmatch2 = \u4F7F\u7528\u6B04 ID \u505A\u70BA unsetMatchColumn \u7684\u5F15\u6578
+cachedrowsetimpl.unsetmatch1 = \u4F7F\u7528\u6B04\u540D\u4F5C\u70BA unsetMatchColumn \u7684\u5F15\u6578
+cachedrowsetimpl.unsetmatch2 = \u4F7F\u7528\u6B04 ID \u4F5C\u70BA unsetMatchColumn \u7684\u5F15\u6578
 cachedrowsetimpl.numrows = \u5217\u6578\u5C0F\u65BC\u96F6\u6216\u5C0F\u65BC\u64F7\u53D6\u5927\u5C0F
 cachedrowsetimpl.startpos = \u8D77\u59CB\u4F4D\u7F6E\u4E0D\u80FD\u70BA\u8CA0\u6578
 cachedrowsetimpl.nextpage = \u5728\u547C\u53EB\u4E4B\u524D\u690D\u5165\u8CC7\u6599 
@@ -108,8 +108,8 @@
 jdbcrowsetimpl.matchcols1 = \u5339\u914D\u6B04\u61C9\u5927\u65BC 0
 jdbcrowsetimpl.matchcols2 = \u5339\u914D\u6B04\u4E0D\u80FD\u70BA\u7A7A\u767D\u5B57\u4E32\u6216\u7A7A\u503C\u5B57\u4E32
 jdbcrowsetimpl.unsetmatch = \u53D6\u6D88\u8A2D\u5B9A\u7684\u6B04\u548C\u8A2D\u5B9A\u7684\u6B04\u4E0D\u540C
-jdbcrowsetimpl.usecolname = \u4F7F\u7528\u6B04\u540D\u505A\u70BA unsetMatchColumn \u7684\u5F15\u6578
-jdbcrowsetimpl.usecolid = \u4F7F\u7528\u6B04 ID \u505A\u70BA unsetMatchColumn \u7684\u5F15\u6578
+jdbcrowsetimpl.usecolname = \u4F7F\u7528\u6B04\u540D\u4F5C\u70BA unsetMatchColumn \u7684\u5F15\u6578
+jdbcrowsetimpl.usecolid = \u4F7F\u7528\u6B04 ID \u4F5C\u70BA unsetMatchColumn \u7684\u5F15\u6578
 jdbcrowsetimpl.resnotupd = ResultSet \u4E0D\u53EF\u66F4\u65B0
 jdbcrowsetimpl.opnotysupp = \u5C1A\u4E0D\u652F\u63F4\u8A72\u4F5C\u696D
 jdbcrowsetimpl.featnotsupp = \u4E0D\u652F\u63F4\u8A72\u529F\u80FD
--- a/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_pt_BR.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/basic/resources/basic_pt_BR.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -159,7 +159,7 @@
 ############ Abstract Document Strings ############
 AbstractDocument.styleChange.textAndMnemonic=altera\u00E7\u00E3o de estilo
 AbstractDocument.addition.textAndMnemonic=adi\u00E7\u00E3o
-AbstractDocument.deletion.textAndMnemonic=dele\u00E7\u00E3o
+AbstractDocument.deletion.textAndMnemonic=exclus\u00E3o
 AbstractDocument.undo.textAndMnemonic=Desfazer
 AbstractDocument.redo.textAndMnemonic=Refazer
 
--- a/jdk/src/share/classes/com/sun/tools/example/debug/tty/TTYResources_zh_CN.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/tools/example/debug/tty/TTYResources_zh_CN.java	Wed Jul 05 19:00:49 2017 +0200
@@ -240,7 +240,7 @@
         {"operation not yet supported", "\u5C1A\u4E0D\u652F\u6301\u8BE5\u64CD\u4F5C"},
         {"Owned by:", "  \u62E5\u6709\u8005: {0}, \u6761\u76EE\u8BA1\u6570: {1,number,integer}"},
         {"Owned monitor:", "  \u62E5\u6709\u7684\u76D1\u89C6\u5668: {0}"},
-        {"Parse exception:", "\u8BED\u6CD5\u5206\u6790\u5F02\u5E38\u9519\u8BEF: {0}"},
+        {"Parse exception:", "\u89E3\u6790\u5F02\u5E38\u9519\u8BEF: {0}"},
         {"printbreakpointcommandusage", "\u7528\u6CD5: {0} <class>:<line_number> \u6216\n       {1} <class>.<method_name>[(argument_type,...)]"},
         {"Removed:", "\u5DF2\u5220\u9664: {0}"},
         {"Requested stack frame is no longer active:", "\u8BF7\u6C42\u7684\u5806\u6808\u5E27\u4E0D\u518D\u6709\u6548: {0,number,integer}"},
--- a/jdk/src/share/classes/com/sun/tools/jdi/SDE.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/com/sun/tools/jdi/SDE.java	Wed Jul 05 19:00:49 2017 +0200
@@ -171,7 +171,7 @@
         }
 
         public boolean equals(Object obj) {
-            if ((obj != null) && (obj instanceof LineStratum)) {
+            if (obj instanceof LineStratum) {
                 LineStratum other = (LineStratum)obj;
                 return (lti == other.lti) &&
                        (sti == other.sti) &&
@@ -182,6 +182,11 @@
             }
         }
 
+        @Override
+        public int hashCode() {
+            return (lineNumber() * 17) ^ refType.hashCode();
+        }
+
         int lineNumber() {
             return stiLineNumber(sti, lti, jplsLine);
         }
--- a/jdk/src/share/classes/java/awt/AWTEvent.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/AWTEvent.java	Wed Jul 05 19:00:49 2017 +0200
@@ -297,11 +297,11 @@
                                     field.setAccessible(true);
                                     return field;
                                 } catch (SecurityException e) {
-                                    if (log.isLoggable(PlatformLogger.FINE)) {
+                                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                                         log.fine("AWTEvent.get_InputEvent_CanAccessSystemClipboard() got SecurityException ", e);
                                     }
                                 } catch (NoSuchFieldException e) {
-                                    if (log.isLoggable(PlatformLogger.FINE)) {
+                                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                                         log.fine("AWTEvent.get_InputEvent_CanAccessSystemClipboard() got NoSuchFieldException ", e);
                                     }
                                 }
@@ -594,7 +594,7 @@
                     boolean b = field.getBoolean(this);
                     field.setBoolean(that, b);
                 } catch(IllegalAccessException e) {
-                    if (log.isLoggable(PlatformLogger.FINE)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("AWTEvent.copyPrivateDataInto() got IllegalAccessException ", e);
                     }
                 }
@@ -610,7 +610,7 @@
                 try {
                     field.setBoolean(this, false);
                 } catch(IllegalAccessException e) {
-                    if (log.isLoggable(PlatformLogger.FINE)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("AWTEvent.dispatched() got IllegalAccessException ", e);
                     }
                 }
--- a/jdk/src/share/classes/java/awt/AttributeValue.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/AttributeValue.java	Wed Jul 05 19:00:49 2017 +0200
@@ -33,11 +33,11 @@
     private final String[] names;
 
     protected AttributeValue(int value, String[] names) {
-        if (log.isLoggable(PlatformLogger.FINEST)) {
+        if (log.isLoggable(PlatformLogger.Level.FINEST)) {
             log.finest("value = " + value + ", names = " + names);
         }
 
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             if ((value < 0) || (names == null) || (value >= names.length)) {
                 log.finer("Assertion failed");
             }
--- a/jdk/src/share/classes/java/awt/Component.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/Component.java	Wed Jul 05 19:00:49 2017 +0200
@@ -4707,12 +4707,12 @@
         // Check that this component belongs to this app-context
         AppContext compContext = appContext;
         if (compContext != null && !compContext.equals(AppContext.getAppContext())) {
-            if (eventLog.isLoggable(PlatformLogger.FINE)) {
+            if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
                 eventLog.fine("Event " + e + " is being dispatched on the wrong AppContext");
             }
         }
 
-        if (eventLog.isLoggable(PlatformLogger.FINEST)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
             eventLog.finest("{0}", e);
         }
 
@@ -4751,7 +4751,7 @@
                 return;
             }
         }
-        if ((e instanceof FocusEvent) && focusLog.isLoggable(PlatformLogger.FINEST)) {
+        if ((e instanceof FocusEvent) && focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
             focusLog.finest("" + e);
         }
         // MouseWheel may need to be retargeted here so that
@@ -4809,7 +4809,7 @@
                 if (inputContext != null) {
                     inputContext.dispatchEvent(e);
                     if (e.isConsumed()) {
-                        if ((e instanceof FocusEvent) && focusLog.isLoggable(PlatformLogger.FINEST)) {
+                        if ((e instanceof FocusEvent) && focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                             focusLog.finest("3579: Skipping " + e);
                         }
                         return;
@@ -4844,7 +4844,7 @@
               if (p != null) {
                   p.preProcessKeyEvent((KeyEvent)e);
                   if (e.isConsumed()) {
-                        if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+                        if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                             focusLog.finest("Pre-process consumed event");
                         }
                       return;
@@ -4977,7 +4977,7 @@
                                   // position relative to its parent.
         MouseWheelEvent newMWE;
 
-        if (eventLog.isLoggable(PlatformLogger.FINEST)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
             eventLog.finest("dispatchMouseWheelToAncestor");
             eventLog.finest("orig event src is of " + e.getSource().getClass());
         }
@@ -5000,7 +5000,7 @@
                 }
             }
 
-            if (eventLog.isLoggable(PlatformLogger.FINEST)) {
+            if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 eventLog.finest("new event src is " + anc.getClass());
             }
 
@@ -5500,7 +5500,7 @@
     // Should only be called while holding the tree lock
     int numListening(long mask) {
         // One mask or the other, but not neither or both.
-        if (eventLog.isLoggable(PlatformLogger.FINE)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
             if ((mask != AWTEvent.HIERARCHY_EVENT_MASK) &&
                 (mask != AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK))
             {
@@ -5541,7 +5541,7 @@
               break;
           case HierarchyEvent.ANCESTOR_MOVED:
           case HierarchyEvent.ANCESTOR_RESIZED:
-              if (eventLog.isLoggable(PlatformLogger.FINE)) {
+              if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
                   if (changeFlags != 0) {
                       eventLog.fine("Assertion (changeFlags == 0) failed");
                   }
@@ -5557,7 +5557,7 @@
               break;
           default:
               // assert false
-              if (eventLog.isLoggable(PlatformLogger.FINE)) {
+              if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
                   eventLog.fine("This code must never be reached");
               }
               break;
@@ -7643,7 +7643,7 @@
             }
         }
         if (!isRequestFocusAccepted(temporary, focusedWindowChangeAllowed, cause)) {
-            if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 focusLog.finest("requestFocus is not accepted");
             }
             return false;
@@ -7654,7 +7654,7 @@
         Component window = this;
         while ( (window != null) && !(window instanceof Window)) {
             if (!window.isVisible()) {
-                if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+                if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                     focusLog.finest("component is recurively invisible");
                 }
                 return false;
@@ -7666,14 +7666,14 @@
         Component heavyweight = (peer instanceof LightweightPeer)
             ? getNativeContainer() : this;
         if (heavyweight == null || !heavyweight.isVisible()) {
-            if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 focusLog.finest("Component is not a part of visible hierarchy");
             }
             return false;
         }
         peer = heavyweight.peer;
         if (peer == null) {
-            if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 focusLog.finest("Peer is null");
             }
             return false;
@@ -7694,11 +7694,11 @@
         if (!success) {
             KeyboardFocusManager.getCurrentKeyboardFocusManager
                 (appContext).dequeueKeyEvents(time, this);
-            if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 focusLog.finest("Peer request failed");
             }
         } else {
-            if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 focusLog.finest("Pass for " + this);
             }
         }
@@ -7710,7 +7710,7 @@
                                            CausedFocusEvent.Cause cause)
     {
         if (!isFocusable() || !isVisible()) {
-            if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 focusLog.finest("Not focusable or not visible");
             }
             return false;
@@ -7718,7 +7718,7 @@
 
         ComponentPeer peer = this.peer;
         if (peer == null) {
-            if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 focusLog.finest("peer is null");
             }
             return false;
@@ -7726,7 +7726,7 @@
 
         Window window = getContainingWindow();
         if (window == null || !window.isFocusableWindow()) {
-            if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 focusLog.finest("Component doesn't have toplevel");
             }
             return false;
@@ -7748,7 +7748,7 @@
             // Controller is supposed to verify focus transfers and for this it
             // should know both from and to components.  And it shouldn't verify
             // transfers from when these components are equal.
-            if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 focusLog.finest("focus owner is null or this");
             }
             return true;
@@ -7761,7 +7761,7 @@
             // most recent focus owner.  But most recent focus owner can be
             // changed by requestFocsuXXX() call only, so this transfer has
             // been already approved.
-            if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 focusLog.finest("cause is activation");
             }
             return true;
@@ -7772,7 +7772,7 @@
                                                                           temporary,
                                                                           focusedWindowChangeAllowed,
                                                                           cause);
-        if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
             focusLog.finest("RequestFocusController returns {0}", ret);
         }
 
@@ -7864,7 +7864,7 @@
     }
 
     boolean transferFocus(boolean clearOnFailure) {
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer("clearOnFailure = " + clearOnFailure);
         }
         Component toFocus = getNextFocusCandidate();
@@ -7873,12 +7873,12 @@
             res = toFocus.requestFocusInWindow(CausedFocusEvent.Cause.TRAVERSAL_FORWARD);
         }
         if (clearOnFailure && !res) {
-            if (focusLog.isLoggable(PlatformLogger.FINER)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                 focusLog.finer("clear global focus owner");
             }
             KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwnerPriv();
         }
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer("returning result: " + res);
         }
         return res;
@@ -7893,19 +7893,19 @@
             comp = rootAncestor;
             rootAncestor = comp.getFocusCycleRootAncestor();
         }
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer("comp = " + comp + ", root = " + rootAncestor);
         }
         Component candidate = null;
         if (rootAncestor != null) {
             FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy();
             Component toFocus = policy.getComponentAfter(rootAncestor, comp);
-            if (focusLog.isLoggable(PlatformLogger.FINER)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                 focusLog.finer("component after is " + toFocus);
             }
             if (toFocus == null) {
                 toFocus = policy.getDefaultComponent(rootAncestor);
-                if (focusLog.isLoggable(PlatformLogger.FINER)) {
+                if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                     focusLog.finer("default component is " + toFocus);
                 }
             }
@@ -7917,7 +7917,7 @@
             }
             candidate = toFocus;
         }
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer("Focus transfer candidate: " + candidate);
         }
         return candidate;
@@ -7954,12 +7954,12 @@
             }
         }
         if (clearOnFailure && !res) {
-            if (focusLog.isLoggable(PlatformLogger.FINER)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                 focusLog.finer("clear global focus owner");
             }
             KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwnerPriv();
         }
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer("returning result: " + res);
         }
         return res;
@@ -9740,7 +9740,7 @@
         checkTreeLock();
 
         if (!areBoundsValid()) {
-            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());
             }
             return;
@@ -9776,7 +9776,7 @@
                     }
                     this.compoundShape = shape;
                     Point compAbsolute = getLocationOnWindow();
-                    if (mixingLog.isLoggable(PlatformLogger.FINER)) {
+                    if (mixingLog.isLoggable(PlatformLogger.Level.FINER)) {
                         mixingLog.fine("this = " + this +
                                 "; compAbsolute=" + compAbsolute + "; shape=" + shape);
                     }
@@ -9910,7 +9910,7 @@
         checkTreeLock();
         Region s = getNormalShape();
 
-        if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+        if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
             mixingLog.fine("this = " + this + "; normalShape=" + s);
         }
 
@@ -9944,7 +9944,7 @@
             }
         }
 
-        if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+        if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
             mixingLog.fine("currentShape=" + s);
         }
 
@@ -9954,12 +9954,12 @@
     void applyCurrentShape() {
         checkTreeLock();
         if (!areBoundsValid()) {
-            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());
             }
             return; // Because applyCompoundShape() ignores such components anyway
         }
-        if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+        if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
             mixingLog.fine("this = " + this);
         }
         applyCompoundShape(calculateCurrentShape());
@@ -9968,7 +9968,7 @@
     final void subtractAndApplyShape(Region s) {
         checkTreeLock();
 
-        if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+        if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
             mixingLog.fine("this = " + this + "; s=" + s);
         }
 
@@ -10015,7 +10015,7 @@
 
     void mixOnShowing() {
         synchronized (getTreeLock()) {
-            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                 mixingLog.fine("this = " + this);
             }
             if (!isMixingNeeded()) {
@@ -10033,7 +10033,7 @@
         // We cannot be sure that the peer exists at this point, so we need the argument
         //    to find out whether the hiding component is (well, actually was) a LW or a HW.
         synchronized (getTreeLock()) {
-            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                 mixingLog.fine("this = " + this + "; isLightweight = " + isLightweight);
             }
             if (!isMixingNeeded()) {
@@ -10047,7 +10047,7 @@
 
     void mixOnReshaping() {
         synchronized (getTreeLock()) {
-            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                 mixingLog.fine("this = " + this);
             }
             if (!isMixingNeeded()) {
@@ -10066,7 +10066,7 @@
             boolean becameHigher = newZorder < oldZorder;
             Container parent = getContainer();
 
-            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                 mixingLog.fine("this = " + this +
                     "; oldZorder=" + oldZorder + "; newZorder=" + newZorder + "; parent=" + parent);
             }
@@ -10110,13 +10110,13 @@
 
     final boolean isMixingNeeded() {
         if (SunToolkit.getSunAwtDisableMixing()) {
-            if (mixingLog.isLoggable(PlatformLogger.FINEST)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 mixingLog.finest("this = " + this + "; Mixing disabled via sun.awt.disableMixing");
             }
             return false;
         }
         if (!areBoundsValid()) {
-            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());
             }
             return false;
@@ -10124,7 +10124,7 @@
         Window window = getContainingWindow();
         if (window != null) {
             if (!window.hasHeavyweightDescendants() || !window.hasLightweightDescendants() || window.isDisposing()) {
-                if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+                if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                     mixingLog.fine("containing window = " + window +
                             "; has h/w descendants = " + window.hasHeavyweightDescendants() +
                             "; has l/w descendants = " + window.hasLightweightDescendants() +
@@ -10133,7 +10133,7 @@
                 return false;
             }
         } else {
-            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                 mixingLog.fine("this = " + this + "; containing window is null");
             }
             return false;
--- a/jdk/src/share/classes/java/awt/Container.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/Container.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1320,7 +1320,7 @@
         int superListening = super.numListening(mask);
 
         if (mask == AWTEvent.HIERARCHY_EVENT_MASK) {
-            if (eventLog.isLoggable(PlatformLogger.FINE)) {
+            if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
                 // Verify listeningChildren is correct
                 int sum = 0;
                 for (Component comp : component) {
@@ -1332,7 +1332,7 @@
             }
             return listeningChildren + superListening;
         } else if (mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) {
-            if (eventLog.isLoggable(PlatformLogger.FINE)) {
+            if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
                 // Verify listeningBoundsChildren is correct
                 int sum = 0;
                 for (Component comp : component) {
@@ -1345,7 +1345,7 @@
             return listeningBoundsChildren + superListening;
         } else {
             // assert false;
-            if (eventLog.isLoggable(PlatformLogger.FINE)) {
+            if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
                 eventLog.fine("This code must never be reached");
             }
             return superListening;
@@ -1354,7 +1354,7 @@
 
     // Should only be called while holding tree lock
     void adjustListeningChildren(long mask, int num) {
-        if (eventLog.isLoggable(PlatformLogger.FINE)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
             boolean toAssert = (mask == AWTEvent.HIERARCHY_EVENT_MASK ||
                                 mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK ||
                                 mask == (AWTEvent.HIERARCHY_EVENT_MASK |
@@ -1395,7 +1395,7 @@
 
     // Should only be called while holding tree lock
     int countHierarchyMembers() {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             // Verify descendantsCount is correct
             int sum = 0;
             for (Component comp : component) {
@@ -4110,7 +4110,7 @@
 
     final void recursiveSubtractAndApplyShape(Region shape, int fromZorder, int toZorder) {
         checkTreeLock();
-        if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+        if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
             mixingLog.fine("this = " + this +
                 "; shape=" + shape + "; fromZ=" + fromZorder + "; toZ=" + toZorder);
         }
@@ -4147,7 +4147,7 @@
 
     final void recursiveApplyCurrentShape(int fromZorder, int toZorder) {
         checkTreeLock();
-        if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+        if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
             mixingLog.fine("this = " + this +
                 "; fromZ=" + fromZorder + "; toZ=" + toZorder);
         }
@@ -4264,7 +4264,7 @@
     @Override
     void mixOnShowing() {
         synchronized (getTreeLock()) {
-            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                 mixingLog.fine("this = " + this);
             }
 
@@ -4289,7 +4289,7 @@
     @Override
     void mixOnHiding(boolean isLightweight) {
         synchronized (getTreeLock()) {
-            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                 mixingLog.fine("this = " + this +
                         "; isLightweight=" + isLightweight);
             }
@@ -4303,7 +4303,7 @@
     @Override
     void mixOnReshaping() {
         synchronized (getTreeLock()) {
-            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                 mixingLog.fine("this = " + this);
             }
 
@@ -4338,7 +4338,7 @@
     @Override
     void mixOnZOrderChanging(int oldZorder, int newZorder) {
         synchronized (getTreeLock()) {
-            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                 mixingLog.fine("this = " + this +
                     "; oldZ=" + oldZorder + "; newZ=" + newZorder);
             }
@@ -4359,7 +4359,7 @@
     @Override
     void mixOnValidating() {
         synchronized (getTreeLock()) {
-            if (mixingLog.isLoggable(PlatformLogger.FINE)) {
+            if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
                 mixingLog.fine("this = " + this);
             }
 
@@ -4549,7 +4549,7 @@
             // This may send it somewhere that doesn't have MouseWheelEvents
             // enabled.  In this case, Component.dispatchEventImpl() will
             // retarget the event to a parent that DOES have the events enabled.
-            if (eventLog.isLoggable(PlatformLogger.FINEST) && (mouseOver != null)) {
+            if (eventLog.isLoggable(PlatformLogger.Level.FINEST) && (mouseOver != null)) {
                 eventLog.finest("retargeting mouse wheel to " +
                                 mouseOver.getName() + ", " +
                                 mouseOver.getClass());
--- a/jdk/src/share/classes/java/awt/ContainerOrderFocusTraversalPolicy.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/ContainerOrderFocusTraversalPolicy.java	Wed Jul 05 19:00:49 2017 +0200
@@ -165,7 +165,7 @@
                 if (getImplicitDownCycleTraversal()) {
                     retComp = cont.getFocusTraversalPolicy().getDefaultComponent(cont);
 
-                    if (retComp != null && log.isLoggable(PlatformLogger.FINE)) {
+                    if (retComp != null && log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("### Transfered focus down-cycle to " + retComp +
                                  " in the focus cycle root " + cont);
                     }
@@ -177,7 +177,7 @@
                            cont.getFocusTraversalPolicy().getDefaultComponent(cont) :
                            cont.getFocusTraversalPolicy().getLastComponent(cont));
 
-                if (retComp != null && log.isLoggable(PlatformLogger.FINE)) {
+                if (retComp != null && log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("### Transfered focus to " + retComp + " in the FTP provider " + cont);
                 }
             }
@@ -208,7 +208,7 @@
      *         aComponent is null
      */
     public Component getComponentAfter(Container aContainer, Component aComponent) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### Searching in " + aContainer + " for component after " + aComponent);
         }
 
@@ -238,7 +238,7 @@
             // See if the component is inside of policy provider.
             Container provider = getTopmostProvider(aContainer, aComponent);
             if (provider != null) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("### Asking FTP " + provider + " for component after " + aComponent);
                 }
 
@@ -249,7 +249,7 @@
                 // Null result means that we overstepped the limit of the FTP's cycle.
                 // In that case we must quit the cycle, otherwise return the component found.
                 if (afterComp != null) {
-                    if (log.isLoggable(PlatformLogger.FINE)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("### FTP returned " + afterComp);
                     }
                     return afterComp;
@@ -259,14 +259,14 @@
 
             List<Component> cycle = getFocusTraversalCycle(aContainer);
 
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("### Cycle is " + cycle + ", component is " + aComponent);
             }
 
             int index = getComponentIndex(cycle, aComponent);
 
             if (index < 0) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("### Didn't find component " + aComponent + " in a cycle " + aContainer);
                 }
                 return getFirstComponent(aContainer);
@@ -331,7 +331,7 @@
             // See if the component is inside of policy provider.
             Container provider = getTopmostProvider(aContainer, aComponent);
             if (provider != null) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("### Asking FTP " + provider + " for component after " + aComponent);
                 }
 
@@ -342,7 +342,7 @@
                 // Null result means that we overstepped the limit of the FTP's cycle.
                 // In that case we must quit the cycle, otherwise return the component found.
                 if (beforeComp != null) {
-                    if (log.isLoggable(PlatformLogger.FINE)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("### FTP returned " + beforeComp);
                     }
                     return beforeComp;
@@ -357,14 +357,14 @@
 
             List<Component> cycle = getFocusTraversalCycle(aContainer);
 
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("### Cycle is " + cycle + ", component is " + aComponent);
             }
 
             int index = getComponentIndex(cycle, aComponent);
 
             if (index < 0) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("### Didn't find component " + aComponent + " in a cycle " + aContainer);
                 }
                 return getLastComponent(aContainer);
@@ -411,7 +411,7 @@
     public Component getFirstComponent(Container aContainer) {
         List<Component> cycle;
 
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### Getting first component in " + aContainer);
         }
         if (aContainer == null) {
@@ -432,12 +432,12 @@
             }
 
             if (cycle.size() == 0) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("### Cycle is empty");
                 }
                 return null;
             }
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("### Cycle is " + cycle);
             }
 
@@ -467,7 +467,7 @@
      */
     public Component getLastComponent(Container aContainer) {
         List<Component> cycle;
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### Getting last component in " + aContainer);
         }
 
@@ -488,12 +488,12 @@
             }
 
             if (cycle.size() == 0) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("### Cycle is empty");
                 }
                 return null;
             }
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("### Cycle is " + cycle);
             }
 
--- a/jdk/src/share/classes/java/awt/Cursor.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/Cursor.java	Wed Jul 05 19:00:49 2017 +0200
@@ -310,7 +310,7 @@
             String key    = prefix + DotFileSuffix;
 
             if (!systemCustomCursorProperties.containsKey(key)) {
-                if (log.isLoggable(PlatformLogger.FINER)) {
+                if (log.isLoggable(PlatformLogger.Level.FINER)) {
                     log.finer("Cursor.getSystemCustomCursor(" + name + ") returned null");
                 }
                 return null;
@@ -365,7 +365,7 @@
             }
 
             if (cursor == null) {
-                if (log.isLoggable(PlatformLogger.FINER)) {
+                if (log.isLoggable(PlatformLogger.Level.FINER)) {
                     log.finer("Cursor.getSystemCustomCursor(" + name + ") returned null");
                 }
             } else {
--- a/jdk/src/share/classes/java/awt/DefaultKeyboardFocusManager.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/DefaultKeyboardFocusManager.java	Wed Jul 05 19:00:49 2017 +0200
@@ -285,10 +285,17 @@
         TimedWindowEvent we = (TimedWindowEvent)e;
         long time = we.getWhen();
         synchronized (this) {
-            for (KeyEvent ke: enqueuedKeyEvents) {
-                if (time >= ke.getWhen()) {
-                    SunToolkit.postEvent(AppContext.getAppContext(), new SequencedEvent(e));
-                    return true;
+            KeyEvent ke = enqueuedKeyEvents.isEmpty() ? null : enqueuedKeyEvents.getFirst();
+            if (ke != null && time >= ke.getWhen()) {
+                TypeAheadMarker marker = typeAheadMarkers.getFirst();
+                if (marker != null) {
+                    Window toplevel = marker.untilFocused.getContainingWindow();
+                    // Check that the component awaiting focus belongs to
+                    // the current focused window. See 8015454.
+                    if (toplevel != null && toplevel.isFocused()) {
+                        SunToolkit.postEvent(AppContext.getAppContext(), new SequencedEvent(e));
+                        return true;
+                    }
                 }
             }
         }
@@ -310,7 +317,7 @@
      *         <code>false</code> otherwise
      */
     public boolean dispatchEvent(AWTEvent e) {
-        if (focusLog.isLoggable(PlatformLogger.FINE) && (e instanceof WindowEvent || e instanceof FocusEvent)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINE) && (e instanceof WindowEvent || e instanceof FocusEvent)) {
             focusLog.fine("" + e);
         }
         switch (e.getID()) {
@@ -419,7 +426,7 @@
 
                     // The component which last has the focus when this window was focused
                     // should receive focus first
-                    if (focusLog.isLoggable(PlatformLogger.FINER)) {
+                    if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                         focusLog.finer("tempLost {0}, toFocus {1}",
                                        tempLost, toFocus);
                     }
@@ -488,7 +495,7 @@
                 Component oldFocusOwner = getGlobalFocusOwner();
                 Component newFocusOwner = fe.getComponent();
                 if (oldFocusOwner == newFocusOwner) {
-                    if (focusLog.isLoggable(PlatformLogger.FINE)) {
+                    if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
                         focusLog.fine("Skipping {0} because focus owner is the same", e);
                     }
                     // We can't just drop the event - there could be
@@ -607,7 +614,7 @@
                 FocusEvent fe = (FocusEvent)e;
                 Component currentFocusOwner = getGlobalFocusOwner();
                 if (currentFocusOwner == null) {
-                    if (focusLog.isLoggable(PlatformLogger.FINE))
+                    if (focusLog.isLoggable(PlatformLogger.Level.FINE))
                         focusLog.fine("Skipping {0} because focus owner is null", e);
                     break;
                 }
@@ -615,7 +622,7 @@
                 // If we make a mistake because of retargeting, then the
                 // FOCUS_GAINED handler will correct it.
                 if (currentFocusOwner == fe.getOppositeComponent()) {
-                    if (focusLog.isLoggable(PlatformLogger.FINE))
+                    if (focusLog.isLoggable(PlatformLogger.Level.FINE))
                         focusLog.fine("Skipping {0} because current focus owner is equal to opposite", e);
                     break;
                 }
@@ -688,7 +695,7 @@
                 Window losingFocusWindow = we.getWindow();
                 Window activeWindow = getGlobalActiveWindow();
                 Window oppositeWindow = we.getOppositeWindow();
-                if (focusLog.isLoggable(PlatformLogger.FINE))
+                if (focusLog.isLoggable(PlatformLogger.Level.FINE))
                     focusLog.fine("Active {0}, Current focused {1}, losing focus {2} opposite {3}",
                                   activeWindow, currentFocusedWindow,
                                   losingFocusWindow, oppositeWindow);
@@ -874,7 +881,7 @@
                         }
                     }
                     if (ke != null) {
-                        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+                        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                             focusLog.finer("Pumping approved event {0}", ke);
                         }
                         enqueuedKeyEvents.removeFirst();
@@ -891,7 +898,7 @@
      * Dumps the list of type-ahead queue markers to stderr
      */
     void dumpMarkers() {
-        if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
             focusLog.finest(">>> Markers dump, time: {0}", System.currentTimeMillis());
             synchronized (this) {
                 if (typeAheadMarkers.size() != 0) {
@@ -925,7 +932,7 @@
                         // The fix is rolled out.
 
                         if (ke.getWhen() > marker.after) {
-                            if (focusLog.isLoggable(PlatformLogger.FINER)) {
+                            if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                                 focusLog.finer("Storing event {0} because of marker {1}", ke, marker);
                             }
                             enqueuedKeyEvents.addLast(ke);
@@ -939,7 +946,7 @@
             }
 
             case FocusEvent.FOCUS_GAINED:
-                if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+                if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                     focusLog.finest("Markers before FOCUS_GAINED on {0}", target);
                 }
                 dumpMarkers();
@@ -968,7 +975,7 @@
                         }
                     } else {
                         // Exception condition - event without marker
-                        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+                        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                             focusLog.finer("Event without marker {0}", e);
                         }
                     }
@@ -1209,7 +1216,7 @@
             return;
         }
 
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer("Enqueue at {0} for {1}",
                        after, untilFocused);
         }
@@ -1251,7 +1258,7 @@
             return;
         }
 
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer("Dequeue at {0} for {1}",
                        after, untilFocused);
         }
--- a/jdk/src/share/classes/java/awt/EventDispatchThread.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/EventDispatchThread.java	Wed Jul 05 19:00:49 2017 +0200
@@ -138,7 +138,7 @@
     }
 
     void addEventFilter(EventFilter filter) {
-        if (eventLog.isLoggable(PlatformLogger.FINEST)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
             eventLog.finest("adding the event filter: " + filter);
         }
         synchronized (eventFilters) {
@@ -164,7 +164,7 @@
     }
 
     void removeEventFilter(EventFilter filter) {
-        if (eventLog.isLoggable(PlatformLogger.FINEST)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
             eventLog.finest("removing the event filter: " + filter);
         }
         synchronized (eventFilters) {
@@ -209,7 +209,7 @@
             }
             while (eventOK == false);
 
-            if (eventLog.isLoggable(PlatformLogger.FINEST)) {
+            if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 eventLog.finest("Dispatching: " + event);
             }
 
@@ -236,7 +236,7 @@
     }
 
     private void processException(Throwable e) {
-        if (eventLog.isLoggable(PlatformLogger.FINE)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
             eventLog.fine("Processing exception: " + e);
         }
         getUncaughtExceptionHandler().uncaughtException(this, e);
--- a/jdk/src/share/classes/java/awt/EventQueue.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/EventQueue.java	Wed Jul 05 19:00:49 2017 +0200
@@ -173,6 +173,11 @@
      */
     private volatile int waitForID;
 
+    /*
+     * AppContext corresponding to the queue.
+     */
+    private final AppContext appContext;
+
     private final String name = "AWT-EventQueue-" + threadInitNumber.getAndIncrement();
 
     private FwDispatcher fwDispatcher;
@@ -225,8 +230,9 @@
          * completes thus causing mess in thread group to appcontext mapping.
          */
 
-        pushPopLock = (Lock)AppContext.getAppContext().get(AppContext.EVENT_QUEUE_LOCK_KEY);
-        pushPopCond = (Condition)AppContext.getAppContext().get(AppContext.EVENT_QUEUE_COND_KEY);
+        appContext = AppContext.getAppContext();
+        pushPopLock = (Lock)appContext.get(AppContext.EVENT_QUEUE_LOCK_KEY);
+        pushPopCond = (Condition)appContext.get(AppContext.EVENT_QUEUE_COND_KEY);
     }
 
     /**
@@ -240,7 +246,7 @@
      * @throws NullPointerException if <code>theEvent</code> is <code>null</code>
      */
     public void postEvent(AWTEvent theEvent) {
-        SunToolkit.flushPendingEvents();
+        SunToolkit.flushPendingEvents(appContext);
         postEventPrivate(theEvent);
     }
 
@@ -525,7 +531,7 @@
              * of the synchronized block to avoid deadlock when
              * event queues are nested with push()/pop().
              */
-            SunToolkit.flushPendingEvents();
+            SunToolkit.flushPendingEvents(appContext);
             pushPopLock.lock();
             try {
                 AWTEvent event = getNextEventPrivate();
@@ -565,7 +571,7 @@
              * of the synchronized block to avoid deadlock when
              * event queues are nested with push()/pop().
              */
-            SunToolkit.flushPendingEvents();
+            SunToolkit.flushPendingEvents(appContext);
             pushPopLock.lock();
             try {
                 for (int i = 0; i < NUM_PRIORITIES; i++) {
@@ -745,7 +751,7 @@
                 dispatchThread.stopDispatching();
             }
         } else {
-            if (eventLog.isLoggable(PlatformLogger.FINE)) {
+            if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
                 eventLog.fine("Unable to dispatch event: " + event);
             }
         }
@@ -843,7 +849,7 @@
      * @since           1.2
      */
     public void push(EventQueue newEventQueue) {
-        if (eventLog.isLoggable(PlatformLogger.FINE)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
             eventLog.fine("EventQueue.push(" + newEventQueue + ")");
         }
 
@@ -869,7 +875,7 @@
                     // Use getNextEventPrivate() as it doesn't call flushPendingEvents()
                     newEventQueue.postEventPrivate(topQueue.getNextEventPrivate());
                 } catch (InterruptedException ie) {
-                    if (eventLog.isLoggable(PlatformLogger.FINE)) {
+                    if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
                         eventLog.fine("Interrupted push", ie);
                     }
                 }
@@ -884,7 +890,6 @@
             newEventQueue.previousQueue = topQueue;
             topQueue.nextQueue = newEventQueue;
 
-            AppContext appContext = AppContext.getAppContext();
             if (appContext.get(AppContext.EVENT_QUEUE_KEY) == topQueue) {
                 appContext.put(AppContext.EVENT_QUEUE_KEY, newEventQueue);
             }
@@ -909,7 +914,7 @@
      * @since           1.2
      */
     protected void pop() throws EmptyStackException {
-        if (eventLog.isLoggable(PlatformLogger.FINE)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
             eventLog.fine("EventQueue.pop(" + this + ")");
         }
 
@@ -932,7 +937,7 @@
                 try {
                     prevQueue.postEventPrivate(topQueue.getNextEventPrivate());
                 } catch (InterruptedException ie) {
-                    if (eventLog.isLoggable(PlatformLogger.FINE)) {
+                    if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
                         eventLog.fine("Interrupted pop", ie);
                     }
                 }
@@ -945,7 +950,6 @@
                 topQueue.dispatchThread.setEventQueue(prevQueue);
             }
 
-            AppContext appContext = AppContext.getAppContext();
             if (appContext.get(AppContext.EVENT_QUEUE_KEY) == this) {
                 appContext.put(AppContext.EVENT_QUEUE_KEY, prevQueue);
             }
@@ -1044,7 +1048,6 @@
     final void initDispatchThread() {
         pushPopLock.lock();
         try {
-            AppContext appContext = AppContext.getAppContext();
             if (dispatchThread == null && !threadGroup.isDestroyed() && !appContext.isDisposed()) {
                 dispatchThread = AccessController.doPrivileged(
                     new PrivilegedAction<EventDispatchThread>() {
@@ -1072,7 +1075,7 @@
         /*
          * Minimize discard possibility for non-posted events
          */
-        SunToolkit.flushPendingEvents();
+        SunToolkit.flushPendingEvents(appContext);
         /*
          * This synchronized block is to secure that the event dispatch
          * thread won't die in the middle of posting a new event to the
@@ -1131,7 +1134,7 @@
      * <code>removeNotify</code> method.
      */
     final void removeSourceEvents(Object source, boolean removeAllEvents) {
-        SunToolkit.flushPendingEvents();
+        SunToolkit.flushPendingEvents(appContext);
         pushPopLock.lock();
         try {
             for (int i = 0; i < NUM_PRIORITIES; i++) {
--- a/jdk/src/share/classes/java/awt/Font.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/Font.java	Wed Jul 05 19:00:49 2017 +0200
@@ -873,6 +873,33 @@
     public static Font createFont(int fontFormat, InputStream fontStream)
         throws java.awt.FontFormatException, java.io.IOException {
 
+        if (hasTempPermission()) {
+            return createFont0(fontFormat, fontStream, null);
+        }
+
+        // Otherwise, be extra conscious of pending temp file creation and
+        // resourcefully handle the temp file resources, among other things.
+        CreatedFontTracker tracker = CreatedFontTracker.getTracker();
+        boolean acquired = false;
+        try {
+            acquired = tracker.acquirePermit();
+            if (!acquired) {
+                throw new IOException("Timed out waiting for resources.");
+            }
+            return createFont0(fontFormat, fontStream, tracker);
+        } catch (InterruptedException e) {
+            throw new IOException("Problem reading font data.");
+        } finally {
+            if (acquired) {
+                tracker.releasePermit();
+            }
+        }
+    }
+
+    private static Font createFont0(int fontFormat, InputStream fontStream,
+                                    CreatedFontTracker tracker)
+        throws java.awt.FontFormatException, java.io.IOException {
+
         if (fontFormat != Font.TRUETYPE_FONT &&
             fontFormat != Font.TYPE1_FONT) {
             throw new IllegalArgumentException ("font format not recognized");
@@ -886,9 +913,11 @@
                     }
                 }
             );
+            if (tracker != null) {
+                tracker.add(tFile);
+            }
 
             int totalSize = 0;
-            CreatedFontTracker tracker = null;
             try {
                 final OutputStream outStream =
                     AccessController.doPrivileged(
@@ -898,8 +927,8 @@
                             }
                         }
                     );
-                if (!hasTempPermission()) {
-                    tracker = CreatedFontTracker.getTracker();
+                if (tracker != null) {
+                    tracker.set(tFile, outStream);
                 }
                 try {
                     byte[] buf = new byte[8192];
@@ -940,6 +969,9 @@
                 Font font = new Font(tFile, fontFormat, true, tracker);
                 return font;
             } finally {
+                if (tracker != null) {
+                    tracker.remove(tFile);
+                }
                 if (!copiedFontData) {
                     if (tracker != null) {
                         tracker.subBytes(totalSize);
--- a/jdk/src/share/classes/java/awt/KeyboardFocusManager.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/KeyboardFocusManager.java	Wed Jul 05 19:00:49 2017 +0200
@@ -652,7 +652,7 @@
     }
 
     void setNativeFocusOwner(Component comp) {
-        if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
             focusLog.finest("Calling peer {0} setCurrentFocusOwner for {1}",
                             String.valueOf(peer), String.valueOf(comp));
         }
@@ -961,7 +961,7 @@
             checkKFMSecurity();
 
             oldActiveWindow = getActiveWindow();
-            if (focusLog.isLoggable(PlatformLogger.FINER)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                 focusLog.finer("Setting global active window to " + activeWindow + ", old active " + oldActiveWindow);
             }
 
@@ -2196,7 +2196,7 @@
 
         HeavyweightFocusRequest(Component heavyweight, Component descendant,
                                 boolean temporary, CausedFocusEvent.Cause cause) {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 if (heavyweight == null) {
                     log.fine("Assertion (heavyweight != null) failed");
                 }
@@ -2208,7 +2208,7 @@
         }
         boolean addLightweightRequest(Component descendant,
                                       boolean temporary, CausedFocusEvent.Cause cause) {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 if (this == HeavyweightFocusRequest.CLEAR_GLOBAL_FOCUS_OWNER) {
                     log.fine("Assertion (this != HeavyweightFocusRequest.CLEAR_GLOBAL_FOCUS_OWNER) failed");
                 }
@@ -2386,7 +2386,7 @@
         (Component heavyweight, Component descendant, boolean temporary,
          boolean focusedWindowChangeAllowed, long time, CausedFocusEvent.Cause cause)
     {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             if (heavyweight == null) {
                 log.fine("Assertion (heavyweight != null) failed");
             }
@@ -2408,11 +2408,11 @@
         Component currentFocusOwner = thisManager.getGlobalFocusOwner();
         Component nativeFocusOwner = thisManager.getNativeFocusOwner();
         Window nativeFocusedWindow = thisManager.getNativeFocusedWindow();
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer("SNFH for {0} in {1}",
                        String.valueOf(descendant), String.valueOf(heavyweight));
         }
-        if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
             focusLog.finest("0. Current focus owner {0}",
                             String.valueOf(currentFocusOwner));
             focusLog.finest("0. Native focus owner {0}",
@@ -2422,7 +2422,7 @@
         }
         synchronized (heavyweightRequests) {
             HeavyweightFocusRequest hwFocusRequest = getLastHWRequest();
-            if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 focusLog.finest("Request {0}", String.valueOf(hwFocusRequest));
             }
             if (hwFocusRequest == null &&
@@ -2430,7 +2430,7 @@
             {
                 if (descendant == currentFocusOwner) {
                     // Redundant request.
-                    if (focusLog.isLoggable(PlatformLogger.FINEST))
+                    if (focusLog.isLoggable(PlatformLogger.Level.FINEST))
                         focusLog.finest("1. SNFH_FAILURE for {0}",
                                         String.valueOf(descendant));
                     return SNFH_FAILURE;
@@ -2464,7 +2464,7 @@
                 // SunToolkit.postPriorityEvent(newFocusOwnerEvent);
                 SunToolkit.postEvent(descendant.appContext, newFocusOwnerEvent);
 
-                if (focusLog.isLoggable(PlatformLogger.FINEST))
+                if (focusLog.isLoggable(PlatformLogger.Level.FINEST))
                     focusLog.finest("2. SNFH_HANDLED for {0}", String.valueOf(descendant));
                 return SNFH_SUCCESS_HANDLED;
             } else if (hwFocusRequest != null &&
@@ -2478,7 +2478,7 @@
                     manager.enqueueKeyEvents(time, descendant);
                 }
 
-                if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+                if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                     focusLog.finest("3. SNFH_HANDLED for lightweight" +
                                     descendant + " in " + heavyweight);
                 }
@@ -2502,7 +2502,7 @@
                                              (hwFocusRequest != null)
                                              ? hwFocusRequest.heavyweight
                                              : nativeFocusedWindow)) {
-                        if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+                        if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                             focusLog.finest("4. SNFH_FAILURE for " + descendant);
                         }
                         return SNFH_FAILURE;
@@ -2513,7 +2513,7 @@
                 heavyweightRequests.add
                     (new HeavyweightFocusRequest(heavyweight, descendant,
                                                  temporary, cause));
-                if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+                if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                     focusLog.finest("5. SNFH_PROCEED for " + descendant);
                 }
                 return SNFH_SUCCESS_PROCEED;
@@ -2905,11 +2905,11 @@
         }
 
         KeyboardFocusManager manager = getCurrentKeyboardFocusManager();
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             if (event instanceof FocusEvent || event instanceof WindowEvent) {
                 focusLog.finer(">>> {0}", String.valueOf(event));
             }
-            if (focusLog.isLoggable(PlatformLogger.FINER) && event instanceof KeyEvent) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINER) && event instanceof KeyEvent) {
                 focusLog.finer("    focus owner is {0}",
                                String.valueOf(manager.getGlobalFocusOwner()));
                 focusLog.finer(">>> {0}", String.valueOf(event));
@@ -2996,7 +2996,7 @@
         }
     }
     static void removeLastFocusRequest(Component heavyweight) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             if (heavyweight == null) {
                 log.fine("Assertion (heavyweight != null) failed");
             }
--- a/jdk/src/share/classes/java/awt/SplashScreen.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/SplashScreen.java	Wed Jul 05 19:00:49 2017 +0200
@@ -219,7 +219,7 @@
                     }
                 }
                 catch(java.net.MalformedURLException e) {
-                    if (log.isLoggable(PlatformLogger.FINE)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("MalformedURLException caught in the getImageURL() method", e);
                     }
                 }
--- a/jdk/src/share/classes/java/awt/Toolkit.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/Toolkit.java	Wed Jul 05 19:00:49 2017 +0200
@@ -48,8 +48,6 @@
 import java.io.FileInputStream;
 
 import java.util.*;
-import sun.util.logging.PlatformLogger;
-
 import java.beans.PropertyChangeListener;
 import java.beans.PropertyChangeSupport;
 import sun.awt.AppContext;
@@ -1983,7 +1981,7 @@
      */
     public abstract boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType modalExclusionType);
 
-    private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.Toolkit");
+    // 8014718: logging has been removed from SunToolkit
 
     private static final int LONG_BITS = 64;
     private int[] calls = new int[LONG_BITS];
@@ -2150,12 +2148,6 @@
         }
 
     synchronized int countAWTEventListeners(long eventMask) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
-            if (eventMask == 0) {
-                log.fine("Assertion (eventMask != 0) failed");
-            }
-        }
-
         int ci = 0;
         for (; eventMask != 0; eventMask >>>= 1, ci++) {
         }
--- a/jdk/src/share/classes/java/awt/WaitDispatchSupport.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/WaitDispatchSupport.java	Wed Jul 05 19:00:49 2017 +0200
@@ -108,7 +108,7 @@
         this.condition = new Conditional() {
             @Override
             public boolean evaluate() {
-                if (log.isLoggable(PlatformLogger.FINEST)) {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                     log.finest("evaluate(): blockingEDT=" + keepBlockingEDT.get() +
                                ", blockingCT=" + keepBlockingCT.get());
                 }
@@ -165,7 +165,7 @@
      */
     @Override
     public boolean enter() {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("enter(): blockingEDT=" + keepBlockingEDT.get() +
                      ", blockingCT=" + keepBlockingCT.get());
         }
@@ -192,11 +192,11 @@
 
         Thread currentThread = Thread.currentThread();
         if (currentThread == dispatchThread) {
-            if (log.isLoggable(PlatformLogger.FINEST)) {
+            if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                 log.finest("On dispatch thread: " + dispatchThread);
             }
             if (interval != 0) {
-                if (log.isLoggable(PlatformLogger.FINEST)) {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                     log.finest("scheduling the timer for " + interval + " ms");
                 }
                 timer.schedule(timerTask = new TimerTask() {
@@ -213,7 +213,7 @@
             SequencedEvent currentSE = KeyboardFocusManager.
                 getCurrentKeyboardFocusManager().getCurrentSequencedEvent();
             if (currentSE != null) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("Dispose current SequencedEvent: " + currentSE);
                 }
                 currentSE.dispose();
@@ -231,7 +231,7 @@
                 }
             });
         } else {
-            if (log.isLoggable(PlatformLogger.FINEST)) {
+            if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                 log.finest("On non-dispatch thread: " + currentThread);
             }
             synchronized (getTreeLock()) {
@@ -257,11 +257,11 @@
                             getTreeLock().wait();
                         }
                     }
-                    if (log.isLoggable(PlatformLogger.FINE)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("waitDone " + keepBlockingEDT.get() + " " + keepBlockingCT.get());
                     }
                 } catch (InterruptedException e) {
-                    if (log.isLoggable(PlatformLogger.FINE)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("Exception caught while waiting: " + e);
                     }
                 } finally {
@@ -284,7 +284,7 @@
      * @inheritDoc
      */
     public boolean exit() {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("exit(): blockingEDT=" + keepBlockingEDT.get() +
                      ", blockingCT=" + keepBlockingCT.get());
         }
@@ -311,7 +311,7 @@
     };
 
     private void wakeupEDT() {
-        if (log.isLoggable(PlatformLogger.FINEST)) {
+        if (log.isLoggable(PlatformLogger.Level.FINEST)) {
             log.finest("wakeupEDT(): EDT == " + dispatchThread);
         }
         EventQueue eq = dispatchThread.getEventQueue();
--- a/jdk/src/share/classes/java/awt/Window.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/Window.java	Wed Jul 05 19:00:49 2017 +0200
@@ -3149,7 +3149,7 @@
         }
         synchronized (getTreeLock()) {
             super.setGraphicsConfiguration(gc);
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("+ Window.setGraphicsConfiguration(): new GC is \n+ " + getGraphicsConfiguration_NoClientCode() + "\n+ this is " + this);
             }
         }
--- a/jdk/src/share/classes/java/awt/color/ICC_Profile.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/color/ICC_Profile.java	Wed Jul 05 19:00:49 2017 +0200
@@ -37,6 +37,7 @@
 
 import sun.java2d.cmm.PCMM;
 import sun.java2d.cmm.CMSManager;
+import sun.java2d.cmm.ProfileDataVerifier;
 import sun.java2d.cmm.ProfileDeferralMgr;
 import sun.java2d.cmm.ProfileDeferralInfo;
 import sun.java2d.cmm.ProfileActivator;
@@ -775,6 +776,8 @@
             ProfileDeferralMgr.activateProfiles();
         }
 
+        ProfileDataVerifier.verify(data);
+
         try {
             theID = CMSManager.getModule().loadProfile(data);
         } catch (CMMException c) {
--- a/jdk/src/share/classes/java/awt/event/InputEvent.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/event/InputEvent.java	Wed Jul 05 19:00:49 2017 +0200
@@ -353,7 +353,7 @@
                     sm.checkSystemClipboardAccess();
                     b = true;
                 } catch (SecurityException se) {
-                    if (logger.isLoggable(PlatformLogger.FINE)) {
+                    if (logger.isLoggable(PlatformLogger.Level.FINE)) {
                         logger.fine("InputEvent.canAccessSystemClipboard() got SecurityException ", se);
                     }
                 }
--- a/jdk/src/share/classes/java/awt/image/BufferedImage.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/image/BufferedImage.java	Wed Jul 05 19:00:49 2017 +0200
@@ -35,6 +35,8 @@
 import java.awt.geom.Point2D;
 import java.awt.Point;
 import java.awt.Rectangle;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.Hashtable;
 import java.util.Vector;
 
@@ -643,6 +645,7 @@
         this.properties = properties;
         int numBands = raster.getNumBands();
         boolean isAlphaPre = cm.isAlphaPremultiplied();
+        final boolean isStandard = isStandard(cm, raster);
         ColorSpace cs;
 
         // Force the raster data alpha state to match the premultiplied
@@ -653,8 +656,9 @@
         cs = cm.getColorSpace();
         int csType = cs.getType();
         if (csType != ColorSpace.TYPE_RGB) {
-            if (csType == ColorSpace.TYPE_GRAY
-                && cm instanceof ComponentColorModel) {
+            if (csType == ColorSpace.TYPE_GRAY &&
+                isStandard &&
+                cm instanceof ComponentColorModel) {
                 // Check if this might be a child raster (fix for bug 4240596)
                 if (sm instanceof ComponentSampleModel &&
                     ((ComponentSampleModel)sm).getPixelStride() != numBands) {
@@ -684,6 +688,7 @@
             // are correct
             int pixSize = cm.getPixelSize();
             if (iraster.getPixelStride() == 1 &&
+                isStandard &&
                 cm instanceof DirectColorModel  &&
                 (pixSize == 32 || pixSize == 24))
             {
@@ -716,6 +721,7 @@
             }   // if (iraster.getPixelStride() == 1
         }   // ((raster instanceof IntegerComponentRaster) &&
         else if ((cm instanceof IndexColorModel) && (numBands == 1) &&
+                 isStandard &&
                  (!cm.hasAlpha() || !isAlphaPre))
         {
             IndexColorModel icm = (IndexColorModel) cm;
@@ -733,6 +739,7 @@
         }   // else if (cm instanceof IndexColorModel) && (numBands == 1))
         else if ((raster instanceof ShortComponentRaster)
                  && (cm instanceof DirectColorModel)
+                 && isStandard
                  && (numBands == 3)
                  && !cm.hasAlpha())
         {
@@ -752,6 +759,7 @@
         }   // else if ((cm instanceof IndexColorModel) && (numBands == 1))
         else if ((raster instanceof ByteComponentRaster)
                  && (cm instanceof ComponentColorModel)
+                 && isStandard
                  && (raster.getSampleModel() instanceof PixelInterleavedSampleModel)
                  && (numBands == 3 || numBands == 4))
         {
@@ -776,14 +784,15 @@
                 }
             }
             if (is8bit &&
+                braster.getPixelStride() == numBands &&
                 offs[0] == numBands-1 &&
                 offs[1] == numBands-2 &&
                 offs[2] == numBands-3)
             {
-                if (numBands == 3) {
+                if (numBands == 3 && !ccm.hasAlpha()) {
                     imageType = TYPE_3BYTE_BGR;
                 }
-                else if (offs[3] == 0) {
+                else if (offs[3] == 0 && ccm.hasAlpha()) {
                     imageType = (isAlphaPre
                                  ? TYPE_4BYTE_ABGR_PRE
                                  : TYPE_4BYTE_ABGR);
@@ -792,6 +801,27 @@
         }   // else if ((raster instanceof ByteComponentRaster) &&
     }
 
+    private static boolean isStandard(ColorModel cm, WritableRaster wr) {
+        final Class<? extends ColorModel> cmClass = cm.getClass();
+        final Class<? extends WritableRaster> wrClass = wr.getClass();
+        final Class<? extends SampleModel> smClass = wr.getSampleModel().getClass();
+
+        final PrivilegedAction<Boolean> checkClassLoadersAction =
+                new PrivilegedAction<Boolean>()
+        {
+
+            @Override
+            public Boolean run() {
+                final ClassLoader std = System.class.getClassLoader();
+
+                return (cmClass.getClassLoader() == std) &&
+                        (smClass.getClassLoader() == std) &&
+                        (wrClass.getClassLoader() == std);
+            }
+        };
+        return AccessController.doPrivileged(checkClassLoadersAction);
+    }
+
     /**
      * Returns the image type.  If it is not one of the known types,
      * TYPE_CUSTOM is returned.
--- a/jdk/src/share/classes/java/awt/image/ComponentSampleModel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/image/ComponentSampleModel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -148,7 +148,7 @@
         this.pixelStride = pixelStride;
         this.scanlineStride  = scanlineStride;
         this.bandOffsets = (int[])bandOffsets.clone();
-        numBands = bandOffsets.length;
+        numBands = this.bandOffsets.length;
         if (pixelStride < 0) {
             throw new IllegalArgumentException("Pixel stride must be >= 0");
         }
@@ -223,24 +223,24 @@
             (dataType > DataBuffer.TYPE_DOUBLE)) {
             throw new IllegalArgumentException("Unsupported dataType.");
         }
-        int maxBank = bankIndices[0];
+        int maxBank = this.bankIndices[0];
         if (maxBank < 0) {
             throw new IllegalArgumentException("Index of bank 0 is less than "+
                                                "0 ("+maxBank+")");
         }
-        for (int i=1; i < bankIndices.length; i++) {
-            if (bankIndices[i] > maxBank) {
-                maxBank = bankIndices[i];
+        for (int i=1; i < this.bankIndices.length; i++) {
+            if (this.bankIndices[i] > maxBank) {
+                maxBank = this.bankIndices[i];
             }
-            else if (bankIndices[i] < 0) {
+            else if (this.bankIndices[i] < 0) {
                 throw new IllegalArgumentException("Index of bank "+i+
                                                    " is less than 0 ("+
                                                    maxBank+")");
             }
         }
         numBanks         = maxBank+1;
-        numBands         = bandOffsets.length;
-        if (bandOffsets.length != bankIndices.length) {
+        numBands         = this.bandOffsets.length;
+        if (this.bandOffsets.length != this.bankIndices.length) {
             throw new IllegalArgumentException("Length of bandOffsets must "+
                                                "equal length of bankIndices.");
         }
--- a/jdk/src/share/classes/java/awt/image/PixelInterleavedSampleModel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/image/PixelInterleavedSampleModel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -85,11 +85,11 @@
                                        int scanlineStride,
                                        int bandOffsets[]) {
         super(dataType, w, h, pixelStride, scanlineStride, bandOffsets);
-        int minBandOff=bandOffsets[0];
-        int maxBandOff=bandOffsets[0];
-        for (int i=1; i<bandOffsets.length; i++) {
-            minBandOff = Math.min(minBandOff,bandOffsets[i]);
-            maxBandOff = Math.max(maxBandOff,bandOffsets[i]);
+        int minBandOff=this.bandOffsets[0];
+        int maxBandOff=this.bandOffsets[0];
+        for (int i=1; i<this.bandOffsets.length; i++) {
+            minBandOff = Math.min(minBandOff,this.bandOffsets[i]);
+            maxBandOff = Math.max(maxBandOff,this.bandOffsets[i]);
         }
         maxBandOff -= minBandOff;
         if (maxBandOff > scanlineStride) {
--- a/jdk/src/share/classes/java/awt/image/Raster.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/awt/image/Raster.java	Wed Jul 05 19:00:49 2017 +0200
@@ -257,15 +257,10 @@
                                                          int bandOffsets[],
                                                          Point location) {
         DataBuffer d;
-        int bands = bandOffsets.length;
 
-        int maxBandOff = bandOffsets[0];
-        for (int i=1; i < bands; i++) {
-            if (bandOffsets[i] > maxBandOff) {
-                maxBandOff = bandOffsets[i];
-            }
-        }
-        int size = maxBandOff + scanlineStride*(h-1) + pixelStride*(w-1) + 1;
+        int size = scanlineStride * (h - 1) + // fisrt (h - 1) scans
+            pixelStride * w; // last scan
+
         switch(dataType) {
         case DataBuffer.TYPE_BYTE:
             d = new DataBufferByte(size);
@@ -397,7 +392,9 @@
             }
         }
         int banks = maxBank + 1;
-        int size = maxBandOff + scanlineStride*(h-1) + (w-1) + 1;
+        int size = maxBandOff +
+            scanlineStride * (h - 1) + // fisrt (h - 1) scans
+            w; // last scan
 
         switch(dataType) {
         case DataBuffer.TYPE_BYTE:
--- a/jdk/src/share/classes/java/io/BufferedInputStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/BufferedInputStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -185,7 +185,7 @@
      *
      * @param   in     the underlying input stream.
      * @param   size   the buffer size.
-     * @exception IllegalArgumentException if size <= 0.
+     * @exception IllegalArgumentException if {@code size <= 0}.
      */
     public BufferedInputStream(InputStream in, int size) {
         super(in);
--- a/jdk/src/share/classes/java/io/BufferedReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/BufferedReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -95,7 +95,7 @@
      * @param  in   A Reader
      * @param  sz   Input-buffer size
      *
-     * @exception  IllegalArgumentException  If sz is <= 0
+     * @exception  IllegalArgumentException  If {@code sz <= 0}
      */
     public BufferedReader(Reader in, int sz) {
         super(in);
@@ -484,7 +484,7 @@
      *                         whose size is no smaller than limit.
      *                         Therefore large values should be used with care.
      *
-     * @exception  IllegalArgumentException  If readAheadLimit is < 0
+     * @exception  IllegalArgumentException  If {@code readAheadLimit < 0}
      * @exception  IOException  If an I/O error occurs
      */
     public void mark(int readAheadLimit) throws IOException {
--- a/jdk/src/share/classes/java/io/BufferedWriter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/BufferedWriter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -95,7 +95,7 @@
      * @param  out  A Writer
      * @param  sz   Output-buffer size, a positive integer
      *
-     * @exception  IllegalArgumentException  If sz is <= 0
+     * @exception  IllegalArgumentException  If {@code sz <= 0}
      */
     public BufferedWriter(Writer out, int sz) {
         super(out);
--- a/jdk/src/share/classes/java/io/Console.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/Console.java	Wed Jul 05 19:00:49 2017 +0200
@@ -75,7 +75,7 @@
  * manually zero the returned character array after processing to minimize the
  * lifetime of sensitive data in memory.
  *
- * <blockquote><pre>
+ * <blockquote><pre>{@code
  * Console cons;
  * char[] passwd;
  * if ((cons = System.console()) != null &&
@@ -83,7 +83,7 @@
  *     ...
  *     java.util.Arrays.fill(passwd, ' ');
  * }
- * </pre></blockquote>
+ * }</pre></blockquote>
  *
  * @author  Xueming Shen
  * @since   1.6
--- a/jdk/src/share/classes/java/io/File.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/File.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1899,14 +1899,20 @@
 
         // file name generation
         private static final SecureRandom random = new SecureRandom();
-        static File generateFile(String prefix, String suffix, File dir) {
+        static File generateFile(String prefix, String suffix, File dir)
+            throws IOException
+        {
             long n = random.nextLong();
             if (n == Long.MIN_VALUE) {
                 n = 0;      // corner case
             } else {
                 n = Math.abs(n);
             }
-            return new File(dir, prefix + Long.toString(n) + suffix);
+            String name = prefix + Long.toString(n) + suffix;
+            File f = new File(dir, name);
+            if (!name.equals(f.getName()))
+                throw new IOException("Unable to create temporary file");
+            return f;
         }
     }
 
@@ -1988,25 +1994,21 @@
         if (suffix == null)
             suffix = ".tmp";
 
-        File tmpdir = (directory != null) ? directory : TempDirectory.location();
-        SecurityManager sm = System.getSecurityManager();
+        File tmpdir = (directory != null) ? directory
+                                          : TempDirectory.location();
         File f;
-        do {
-            f = TempDirectory.generateFile(prefix, suffix, tmpdir);
-            if (sm != null) {
-                try {
-                    sm.checkWrite(f.getPath());
-                } catch (SecurityException se) {
-                    // don't reveal temporary directory location
-                    if (directory == null)
-                        throw new SecurityException("Unable to create temporary file");
-                    throw se;
-                }
-            }
-            if (f.isInvalid()) {
+        try {
+            do {
+                f = TempDirectory.generateFile(prefix, suffix, tmpdir);
+            } while (f.exists());
+            if (!f.createNewFile())
                 throw new IOException("Unable to create temporary file");
-            }
-        } while (!fs.createFileExclusively(f.getPath()));
+        } catch (SecurityException se) {
+            // don't reveal temporary directory location
+            if (directory == null)
+                throw new SecurityException("Unable to create temporary file");
+            throw se;
+        }
         return f;
     }
 
--- a/jdk/src/share/classes/java/io/ObjectOutputStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/ObjectOutputStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -36,6 +36,7 @@
 import java.util.concurrent.ConcurrentMap;
 import static java.io.ObjectStreamClass.processQueue;
 import java.io.SerialCallbackContext;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * An ObjectOutputStream writes primitive data types and graphs of Java objects
@@ -1228,6 +1229,12 @@
         }
     }
 
+    private boolean isCustomSubclass() {
+        // Return true if this class is a custom subclass of ObjectOutputStream
+        return getClass().getClassLoader()
+                   != ObjectOutputStream.class.getClassLoader();
+    }
+
     /**
      * Writes class descriptor representing a dynamic proxy class to stream.
      */
@@ -1245,6 +1252,9 @@
         }
 
         bout.setBlockDataMode(true);
+        if (isCustomSubclass()) {
+            ReflectUtil.checkPackageAccess(cl);
+        }
         annotateProxyClass(cl);
         bout.setBlockDataMode(false);
         bout.writeByte(TC_ENDBLOCKDATA);
@@ -1271,6 +1281,9 @@
 
         Class<?> cl = desc.forClass();
         bout.setBlockDataMode(true);
+        if (isCustomSubclass()) {
+            ReflectUtil.checkPackageAccess(cl);
+        }
         annotateClass(cl);
         bout.setBlockDataMode(false);
         bout.writeByte(TC_ENDBLOCKDATA);
--- a/jdk/src/share/classes/java/io/ObjectStreamClass.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/ObjectStreamClass.java	Wed Jul 05 19:00:49 2017 +0200
@@ -49,7 +49,10 @@
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 import sun.misc.Unsafe;
+import sun.reflect.CallerSensitive;
+import sun.reflect.Reflection;
 import sun.reflect.ReflectionFactory;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * Serialization's descriptor for classes.  It contains the name and
@@ -258,7 +261,17 @@
      *
      * @return  the <code>Class</code> instance that this descriptor represents
      */
+    @CallerSensitive
     public Class<?> forClass() {
+        if (cl == null) {
+            return null;
+        }
+        if (System.getSecurityManager() != null) {
+            Class<?> caller = Reflection.getCallerClass();
+            if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(), cl.getClassLoader())) {
+                ReflectUtil.checkPackageAccess(cl);
+            }
+        }
         return cl;
     }
 
@@ -1151,7 +1164,14 @@
             end = end.getSuperclass();
         }
 
+        HashSet<String> oscNames = new HashSet<>(3);
+
         for (ObjectStreamClass d = this; d != null; d = d.superDesc) {
+            if (oscNames.contains(d.name)) {
+                throw new InvalidClassException("Circular reference.");
+            } else {
+                oscNames.add(d.name);
+            }
 
             // search up inheritance hierarchy for class with matching name
             String searchName = (d.cl != null) ? d.cl.getName() : d.name;
--- a/jdk/src/share/classes/java/io/ObjectStreamField.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/ObjectStreamField.java	Wed Jul 05 19:00:49 2017 +0200
@@ -26,6 +26,9 @@
 package java.io;
 
 import java.lang.reflect.Field;
+import sun.reflect.CallerSensitive;
+import sun.reflect.Reflection;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * A description of a Serializable field from a Serializable class.  An array
@@ -157,7 +160,14 @@
      * @return  a <code>Class</code> object representing the type of the
      *          serializable field
      */
+    @CallerSensitive
     public Class<?> getType() {
+        if (System.getSecurityManager() != null) {
+            Class<?> caller = Reflection.getCallerClass();
+            if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(), type.getClassLoader())) {
+                ReflectUtil.checkPackageAccess(type);
+            }
+        }
         return type;
     }
 
--- a/jdk/src/share/classes/java/io/PipedInputStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/PipedInputStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -117,7 +117,7 @@
      * @param      src   the stream to connect to.
      * @param      pipeSize the size of the pipe's buffer.
      * @exception  IOException  if an I/O error occurs.
-     * @exception  IllegalArgumentException if <code>pipeSize <= 0</code>.
+     * @exception  IllegalArgumentException if {@code pipeSize <= 0}.
      * @since      1.6
      */
     public PipedInputStream(PipedOutputStream src, int pipeSize)
@@ -147,7 +147,7 @@
      * connected} to a <code>PipedOutputStream</code> before being used.
      *
      * @param      pipeSize the size of the pipe's buffer.
-     * @exception  IllegalArgumentException if <code>pipeSize <= 0</code>.
+     * @exception  IllegalArgumentException if {@code pipeSize <= 0}.
      * @since      1.6
      */
     public PipedInputStream(int pipeSize) {
--- a/jdk/src/share/classes/java/io/PipedReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/PipedReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -91,7 +91,7 @@
      * @param      src       the stream to connect to.
      * @param      pipeSize  the size of the pipe's buffer.
      * @exception  IOException  if an I/O error occurs.
-     * @exception  IllegalArgumentException if <code>pipeSize <= 0</code>.
+     * @exception  IllegalArgumentException if {@code pipeSize <= 0}.
      * @since      1.6
      */
     public PipedReader(PipedWriter src, int pipeSize) throws IOException {
@@ -120,7 +120,7 @@
      * before being used.
      *
      * @param   pipeSize the size of the pipe's buffer.
-     * @exception  IllegalArgumentException if <code>pipeSize <= 0</code>.
+     * @exception  IllegalArgumentException if {@code pipeSize <= 0}.
      * @since      1.6
      */
     public PipedReader(int pipeSize) {
--- a/jdk/src/share/classes/java/io/PrintStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/PrintStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -851,7 +851,7 @@
      *         <tt>null</tt> argument depends on the <a
      *         href="../util/Formatter.html#syntax">conversion</a>.
      *
-     * @throws  IllegalFormatException
+     * @throws  java.util.IllegalFormatException
      *          If a format string contains an illegal syntax, a format
      *          specifier that is incompatible with the given arguments,
      *          insufficient arguments given the format string, or other
@@ -901,7 +901,7 @@
      *         <tt>null</tt> argument depends on the <a
      *         href="../util/Formatter.html#syntax">conversion</a>.
      *
-     * @throws  IllegalFormatException
+     * @throws  java.util.IllegalFormatException
      *          If a format string contains an illegal syntax, a format
      *          specifier that is incompatible with the given arguments,
      *          insufficient arguments given the format string, or other
@@ -944,7 +944,7 @@
      *         <tt>null</tt> argument depends on the <a
      *         href="../util/Formatter.html#syntax">conversion</a>.
      *
-     * @throws  IllegalFormatException
+     * @throws  java.util.IllegalFormatException
      *          If a format string contains an illegal syntax, a format
      *          specifier that is incompatible with the given arguments,
      *          insufficient arguments given the format string, or other
@@ -1001,7 +1001,7 @@
      *         <tt>null</tt> argument depends on the <a
      *         href="../util/Formatter.html#syntax">conversion</a>.
      *
-     * @throws  IllegalFormatException
+     * @throws  java.util.IllegalFormatException
      *          If a format string contains an illegal syntax, a format
      *          specifier that is incompatible with the given arguments,
      *          insufficient arguments given the format string, or other
--- a/jdk/src/share/classes/java/io/PushbackInputStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/PushbackInputStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -85,7 +85,7 @@
      *
      * @param  in    the input stream from which bytes will be read.
      * @param  size  the size of the pushback buffer.
-     * @exception IllegalArgumentException if size is <= 0
+     * @exception IllegalArgumentException if {@code size <= 0}
      * @since  JDK1.1
      */
     public PushbackInputStream(InputStream in, int size) {
--- a/jdk/src/share/classes/java/io/PushbackReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/PushbackReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -47,7 +47,7 @@
      *
      * @param   in   The reader from which characters will be read
      * @param   size The size of the pushback buffer
-     * @exception IllegalArgumentException if size is <= 0
+     * @exception IllegalArgumentException if {@code size <= 0}
      */
     public PushbackReader(Reader in, int size) {
         super(in);
--- a/jdk/src/share/classes/java/io/StringReader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/io/StringReader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -163,7 +163,7 @@
      *                         is no actual limit, so this argument must not
      *                         be negative, but is otherwise ignored.
      *
-     * @exception  IllegalArgumentException  If readAheadLimit is < 0
+     * @exception  IllegalArgumentException  If {@code readAheadLimit < 0}
      * @exception  IOException  If an I/O error occurs
      */
     public void mark(int readAheadLimit) throws IOException {
--- a/jdk/src/share/classes/java/lang/AbstractStringBuilder.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/AbstractStringBuilder.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -689,7 +689,7 @@
      * @return  a reference to this object.
      */
     public AbstractStringBuilder append(float f) {
-        new FloatingDecimal(f).appendTo(this);
+        FloatingDecimal.appendTo(f,this);
         return this;
     }
 
@@ -706,7 +706,7 @@
      * @return  a reference to this object.
      */
     public AbstractStringBuilder append(double d) {
-        new FloatingDecimal(d).appendTo(this);
+        FloatingDecimal.appendTo(d,this);
         return this;
     }
 
--- a/jdk/src/share/classes/java/lang/CharSequence.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/CharSequence.java	Wed Jul 05 19:00:49 2017 +0200
@@ -179,10 +179,25 @@
 
             @Override
             public void forEachRemaining(IntConsumer block) {
-                while (cur < length()) {
-                    int cp = Character.codePointAt(CharSequence.this, cur);
-                    cur += Character.charCount(cp);
-                    block.accept(cp);
+                final int length = length();
+                int i = cur;
+                try {
+                    while (i < length) {
+                        char c1 = charAt(i++);
+                        if (!Character.isHighSurrogate(c1) || i >= length) {
+                            block.accept(c1);
+                        } else {
+                            char c2 = charAt(i);
+                            if (Character.isLowSurrogate(c2)) {
+                                i++;
+                                block.accept(Character.toCodePoint(c1, c2));
+                            } else {
+                                block.accept(c1);
+                            }
+                        }
+                    }
+                } finally {
+                    cur = i;
                 }
             }
 
@@ -191,12 +206,20 @@
             }
 
             public int nextInt() {
-                if (!hasNext()) {
+                final int length = length();
+
+                if (cur >= length) {
                     throw new NoSuchElementException();
                 }
-                int cp = Character.codePointAt(CharSequence.this, cur);
-                cur += Character.charCount(cp);
-                return cp;
+                char c1 = charAt(cur++);
+                if (Character.isHighSurrogate(c1) && cur < length) {
+                    char c2 = charAt(cur);
+                    if (Character.isLowSurrogate(c2)) {
+                        cur++;
+                        return Character.toCodePoint(c1, c2);
+                    }
+                }
+                return c1;
             }
         }
 
--- a/jdk/src/share/classes/java/lang/Character.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Character.java	Wed Jul 05 19:00:49 2017 +0200
@@ -4782,9 +4782,9 @@
      * Unicode surrogate pair</a>.
 
      * <p>This method is equivalent to the expression:
-     * <blockquote><pre>
+     * <blockquote><pre>{@code
      * isHighSurrogate(high) && isLowSurrogate(low)
-     * </pre></blockquote>
+     * }</pre></blockquote>
      *
      * @param  high the high-surrogate code value to be tested
      * @param  low the low-surrogate code value to be tested
--- a/jdk/src/share/classes/java/lang/Class.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Class.java	Wed Jul 05 19:00:49 2017 +0200
@@ -708,8 +708,9 @@
      */
     @SuppressWarnings("unchecked")
     public TypeVariable<Class<T>>[] getTypeParameters() {
-        if (getGenericSignature() != null)
-            return (TypeVariable<Class<T>>[])getGenericInfo().getTypeParameters();
+        ClassRepository info = getGenericInfo();
+        if (info != null)
+            return (TypeVariable<Class<T>>[])info.getTypeParameters();
         else
             return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
     }
@@ -759,15 +760,19 @@
      * @since 1.5
      */
     public Type getGenericSuperclass() {
-        if (getGenericSignature() != null) {
-            // Historical irregularity:
-            // Generic signature marks interfaces with superclass = Object
-            // but this API returns null for interfaces
-            if (isInterface())
-                return null;
-            return getGenericInfo().getSuperclass();
-        } else
+        ClassRepository info = getGenericInfo();
+        if (info == null) {
             return getSuperclass();
+        }
+
+        // Historical irregularity:
+        // Generic signature marks interfaces with superclass = Object
+        // but this API returns null for interfaces
+        if (isInterface()) {
+            return null;
+        }
+
+        return info.getSuperclass();
     }
 
     /**
@@ -830,7 +835,23 @@
      *
      * @return an array of interfaces implemented by this class.
      */
-    public native Class<?>[] getInterfaces();
+    public Class<?>[] getInterfaces() {
+        ReflectionData<T> rd = reflectionData();
+        if (rd == null) {
+            // no cloning required
+            return getInterfaces0();
+        } else {
+            Class<?>[] interfaces = rd.interfaces;
+            if (interfaces == null) {
+                interfaces = getInterfaces0();
+                rd.interfaces = interfaces;
+            }
+            // defensively copy before handing over to user code
+            return interfaces.clone();
+        }
+    }
+
+    private native Class<?>[] getInterfaces0();
 
     /**
      * Returns the {@code Type}s representing the interfaces
@@ -882,10 +903,8 @@
      * @since 1.5
      */
     public Type[] getGenericInterfaces() {
-        if (getGenericSignature() != null)
-            return getGenericInfo().getSuperInterfaces();
-        else
-            return getInterfaces();
+        ClassRepository info = getGenericInfo();
+        return (info == null) ?  getInterfaces() : info.getSuperInterfaces();
     }
 
 
@@ -962,9 +981,28 @@
      *
      * @return the immediately enclosing method of the underlying class, if
      *     that class is a local or anonymous class; otherwise {@code null}.
+     * @exception  SecurityException
+     *             If a security manager, <i>s</i>, is present and any of the
+     *             following conditions is met:
+     *
+     *             <ul>
+     *
+     *             <li> invocation of
+     *             {@link SecurityManager#checkMemberAccess
+     *             s.checkMemberAccess(enclosingClass, Member.DECLARED)} denies
+     *             access to the methods within the enclosing class
+     *
+     *             <li> the caller's class loader is not the same as or an
+     *             ancestor of the class loader for the enclosing class and
+     *             invocation of {@link SecurityManager#checkPackageAccess
+     *             s.checkPackageAccess()} denies access to the package
+     *             of the enclosing class
+     *
+     *             </ul>
      * @since 1.5
      */
-    public Method getEnclosingMethod() {
+    @CallerSensitive
+    public Method getEnclosingMethod() throws SecurityException {
         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
 
         if (enclosingInfo == null)
@@ -985,13 +1023,22 @@
             for(int i = 0; i < parameterClasses.length; i++)
                 parameterClasses[i] = toClass(parameterTypes[i]);
 
+            // Perform access check
+            Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
+            // be very careful not to change the stack depth of this
+            // checkMemberAccess call for security reasons
+            // see java.lang.SecurityManager.checkMemberAccess
+            //
+            // Note that we need to do this on the enclosing class
+            enclosingCandidate.checkMemberAccess(Member.DECLARED,
+                                                 Reflection.getCallerClass(), true);
             /*
              * Loop over all declared methods; match method name,
              * number of and type of parameters, *and* return
              * type.  Matching return type is also necessary
              * because of covariant returns, etc.
              */
-            for(Method m: enclosingInfo.getEnclosingClass().getDeclaredMethods()) {
+            for(Method m: enclosingCandidate.getDeclaredMethods()) {
                 if (m.getName().equals(enclosingInfo.getName()) ) {
                     Class<?>[] candidateParamClasses = m.getParameterTypes();
                     if (candidateParamClasses.length == parameterClasses.length) {
@@ -1090,9 +1137,28 @@
      *
      * @return the immediately enclosing constructor of the underlying class, if
      *     that class is a local or anonymous class; otherwise {@code null}.
+     * @exception  SecurityException
+     *             If a security manager, <i>s</i>, is present and any of the
+     *             following conditions is met:
+     *
+     *             <ul>
+     *
+     *             <li> invocation of
+     *             {@link SecurityManager#checkMemberAccess
+     *             s.checkMemberAccess(enclosingClass, Member.DECLARED)} denies
+     *             access to the constructors within the enclosing class
+     *
+     *             <li> the caller's class loader is not the same as or an
+     *             ancestor of the class loader for the enclosing class and
+     *             invocation of {@link SecurityManager#checkPackageAccess
+     *             s.checkPackageAccess()} denies access to the package
+     *             of the enclosing class
+     *
+     *             </ul>
      * @since 1.5
      */
-    public Constructor<?> getEnclosingConstructor() {
+    @CallerSensitive
+    public Constructor<?> getEnclosingConstructor() throws SecurityException {
         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
 
         if (enclosingInfo == null)
@@ -1112,11 +1178,20 @@
             for(int i = 0; i < parameterClasses.length; i++)
                 parameterClasses[i] = toClass(parameterTypes[i]);
 
+            // Perform access check
+            Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
+            // be very careful not to change the stack depth of this
+            // checkMemberAccess call for security reasons
+            // see java.lang.SecurityManager.checkMemberAccess
+            //
+            // Note that we need to do this on the enclosing class
+            enclosingCandidate.checkMemberAccess(Member.DECLARED,
+                                                 Reflection.getCallerClass(), true);
             /*
              * Loop over all declared constructors; match number
              * of and type of parameters.
              */
-            for(Constructor<?> c: enclosingInfo.getEnclosingClass().getDeclaredConstructors()) {
+            for(Constructor<?> c: enclosingCandidate.getDeclaredConstructors()) {
                 Class<?>[] candidateParamClasses = c.getParameterTypes();
                 if (candidateParamClasses.length == parameterClasses.length) {
                     boolean matches = true;
@@ -1156,9 +1231,16 @@
      * class.  If the underlying class is a top level class this
      * method returns {@code null}.
      * @return the immediately enclosing class of the underlying class
+     * @exception  SecurityException
+     *             If a security manager, <i>s</i>, is present and the caller's
+     *             class loader is not the same as or an ancestor of the class
+     *             loader for the enclosing class and invocation of {@link
+     *             SecurityManager#checkPackageAccess s.checkPackageAccess()}
+     *             denies access to the package of the enclosing class
      * @since 1.5
      */
-    public Class<?> getEnclosingClass() {
+    @CallerSensitive
+    public Class<?> getEnclosingClass() throws SecurityException {
         // There are five kinds of classes (or interfaces):
         // a) Top level classes
         // b) Nested classes (static member classes)
@@ -1171,18 +1253,24 @@
         // attribute if and only if it is a local class or an
         // anonymous class.
         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
+        Class<?> enclosingCandidate;
 
         if (enclosingInfo == null) {
             // This is a top level or a nested class or an inner class (a, b, or c)
-            return getDeclaringClass();
+            enclosingCandidate = getDeclaringClass();
         } else {
             Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
             // This is a local class or an anonymous class (d or e)
             if (enclosingClass == this || enclosingClass == null)
                 throw new InternalError("Malformed enclosing method information");
             else
-                return enclosingClass;
+                enclosingCandidate = enclosingClass;
         }
+
+        if (enclosingCandidate != null)
+            enclosingCandidate.checkPackageAccess(
+                    ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
+        return enclosingCandidate;
     }
 
     /**
@@ -2212,14 +2300,6 @@
      */
     private native java.security.ProtectionDomain getProtectionDomain0();
 
-
-    /**
-     * Set the ProtectionDomain for this class. Called by
-     * ClassLoader.defineClass.
-     */
-    native void setProtectionDomain0(java.security.ProtectionDomain pd);
-
-
     /*
      * Return the Virtual Machine's Class object for the named
      * primitive type.
@@ -2238,6 +2318,8 @@
      * Check if client is allowed to access members.  If access is denied,
      * throw a SecurityException.
      *
+     * This method also enforces package access.
+     *
      * <p> Default policy: allow all clients access with normal Java access
      * control.
      */
@@ -2258,7 +2340,19 @@
                 // checkMemberAccess of subclasses of SecurityManager as specified.
                 s.checkMemberAccess(this, which);
             }
+            this.checkPackageAccess(ccl, checkProxyInterfaces);
+        }
+    }
 
+    /*
+     * Checks if a client loaded in ClassLoader ccl is allowed to access this
+     * class under the current package access policy. If access is denied,
+     * throw a SecurityException.
+     */
+    private void checkPackageAccess(final ClassLoader ccl, boolean checkProxyInterfaces) {
+        final SecurityManager s = System.getSecurityManager();
+        if (s != null) {
+            final ClassLoader cl = getClassLoader0();
 
             if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
                 String name = this.getName();
@@ -2266,7 +2360,7 @@
                 if (i != -1) {
                     // skip the package access check on a proxy class in default proxy package
                     String pkg = name.substring(0, i);
-                    if (!Proxy.isProxyClass(this) || !pkg.equals(ReflectUtil.PROXY_PACKAGE)) {
+                    if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
                         s.checkPackageAccess(pkg);
                     }
                 }
@@ -2321,6 +2415,8 @@
         // Intermediate results for getFields and getMethods
         volatile Field[] declaredPublicFields;
         volatile Method[] declaredPublicMethods;
+        volatile Class<?>[] interfaces;
+
         // Value of classRedefinedCount when we created this ReflectionData instance
         final int redefinedCount;
 
@@ -2396,10 +2492,10 @@
     }
 
     // Generic signature handling
-    private native String getGenericSignature();
+    private native String getGenericSignature0();
 
     // Generic info repository; lazily initialized
-    private transient ClassRepository genericInfo;
+    private volatile transient ClassRepository genericInfo;
 
     // accessor for factory
     private GenericsFactory getFactory() {
@@ -2407,15 +2503,20 @@
         return CoreReflectionFactory.make(this, ClassScope.make(this));
     }
 
-    // accessor for generic info repository
+    // accessor for generic info repository;
+    // generic info is lazily initialized
     private ClassRepository getGenericInfo() {
-        // lazily initialize repository if necessary
+        ClassRepository genericInfo = this.genericInfo;
         if (genericInfo == null) {
-            // create and cache generic info repository
-            genericInfo = ClassRepository.make(getGenericSignature(),
-                                               getFactory());
+            String signature = getGenericSignature0();
+            if (signature == null) {
+                genericInfo = ClassRepository.NONE;
+            } else {
+                genericInfo = ClassRepository.make(signature, getFactory());
+            }
+            this.genericInfo = genericInfo;
         }
-        return genericInfo; //return cached repository
+        return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
     }
 
     // Annotations handling
--- a/jdk/src/share/classes/java/lang/ClassLoader.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/ClassLoader.java	Wed Jul 05 19:00:49 2017 +0200
@@ -702,7 +702,7 @@
      * bootstrap class loader.  If <tt>name</tt> is not <tt>null</tt>, it
      * must be equal to the <a href="#name">binary name</a> of the class
      * specified by the byte array "<tt>b</tt>", otherwise a {@link
-     * <tt>NoClassDefFoundError</tt>} will be thrown.  </p>
+     * NoClassDefFoundError <tt>NoClassDefFoundError</tt>} will be thrown. </p>
      *
      * @param  name
      *         The expected <a href="#name">binary name</a> of the class, or
--- a/jdk/src/share/classes/java/lang/Comparable.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Comparable.java	Wed Jul 05 19:00:49 2017 +0200
@@ -56,7 +56,7 @@
  * method.<p>
  *
  * For example, if one adds two keys <tt>a</tt> and <tt>b</tt> such that
- * <tt>(!a.equals(b) && a.compareTo(b) == 0)</tt> to a sorted
+ * {@code (!a.equals(b) && a.compareTo(b) == 0)} to a sorted
  * set that does not use an explicit comparator, the second <tt>add</tt>
  * operation returns false (and the size of the sorted set does not increase)
  * because <tt>a</tt> and <tt>b</tt> are equivalent from the sorted set's
--- a/jdk/src/share/classes/java/lang/Double.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Double.java	Wed Jul 05 19:00:49 2017 +0200
@@ -201,7 +201,7 @@
      * @return a string representation of the argument.
      */
     public static String toString(double d) {
-        return new FloatingDecimal(d).toJavaFormatString();
+        return FloatingDecimal.toJavaFormatString(d);
     }
 
     /**
@@ -509,7 +509,7 @@
      *             parsable number.
      */
     public static Double valueOf(String s) throws NumberFormatException {
-        return new Double(FloatingDecimal.readJavaFormatString(s).doubleValue());
+        return new Double(parseDouble(s));
     }
 
     /**
@@ -545,7 +545,7 @@
      * @since 1.2
      */
     public static double parseDouble(String s) throws NumberFormatException {
-        return FloatingDecimal.readJavaFormatString(s).doubleValue();
+        return FloatingDecimal.parseDouble(s);
     }
 
     /**
@@ -917,13 +917,13 @@
      * <p>In all other cases, let <i>s</i>, <i>e</i>, and <i>m</i> be three
      * values that can be computed from the argument:
      *
-     * <blockquote><pre>
-     * int s = ((bits &gt;&gt; 63) == 0) ? 1 : -1;
-     * int e = (int)((bits &gt;&gt; 52) & 0x7ffL);
+     * <blockquote><pre>{@code
+     * int s = ((bits >> 63) == 0) ? 1 : -1;
+     * int e = (int)((bits >> 52) & 0x7ffL);
      * long m = (e == 0) ?
-     *                 (bits & 0xfffffffffffffL) &lt;&lt; 1 :
+     *                 (bits & 0xfffffffffffffL) << 1 :
      *                 (bits & 0xfffffffffffffL) | 0x10000000000000L;
-     * </pre></blockquote>
+     * }</pre></blockquote>
      *
      * Then the floating-point result equals the value of the mathematical
      * expression <i>s</i>&middot;<i>m</i>&middot;2<sup><i>e</i>-1075</sup>.
--- a/jdk/src/share/classes/java/lang/Float.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Float.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -203,7 +203,7 @@
      * @return a string representation of the argument.
      */
     public static String toString(float f) {
-        return new FloatingDecimal(f).toJavaFormatString();
+        return FloatingDecimal.toJavaFormatString(f);
     }
 
     /**
@@ -421,7 +421,7 @@
      *          parsable number.
      */
     public static Float valueOf(String s) throws NumberFormatException {
-        return new Float(FloatingDecimal.readJavaFormatString(s).floatValue());
+        return new Float(parseFloat(s));
     }
 
     /**
@@ -456,7 +456,7 @@
      * @since 1.2
      */
     public static float parseFloat(String s) throws NumberFormatException {
-        return FloatingDecimal.readJavaFormatString(s).floatValue();
+        return FloatingDecimal.parseFloat(s);
     }
 
     /**
@@ -821,13 +821,13 @@
      * <p>In all other cases, let <i>s</i>, <i>e</i>, and <i>m</i> be three
      * values that can be computed from the argument:
      *
-     * <blockquote><pre>
-     * int s = ((bits &gt;&gt; 31) == 0) ? 1 : -1;
-     * int e = ((bits &gt;&gt; 23) & 0xff);
+     * <blockquote><pre>{@code
+     * int s = ((bits >> 31) == 0) ? 1 : -1;
+     * int e = ((bits >> 23) & 0xff);
      * int m = (e == 0) ?
-     *                 (bits & 0x7fffff) &lt;&lt; 1 :
+     *                 (bits & 0x7fffff) << 1 :
      *                 (bits & 0x7fffff) | 0x800000;
-     * </pre></blockquote>
+     * }</pre></blockquote>
      *
      * Then the floating-point result equals the value of the mathematical
      * expression <i>s</i>&middot;<i>m</i>&middot;2<sup><i>e</i>-150</sup>.
--- a/jdk/src/share/classes/java/lang/Integer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Integer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -788,10 +788,14 @@
             String integerCacheHighPropValue =
                 sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
             if (integerCacheHighPropValue != null) {
-                int i = parseInt(integerCacheHighPropValue);
-                i = Math.max(i, 127);
-                // Maximum array size is Integer.MAX_VALUE
-                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
+                try {
+                    int i = parseInt(integerCacheHighPropValue);
+                    i = Math.max(i, 127);
+                    // Maximum array size is Integer.MAX_VALUE
+                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
+                } catch( NumberFormatException nfe) {
+                    // If the property cannot be parsed into an int, ignore it.
+                }
             }
             high = h;
 
--- a/jdk/src/share/classes/java/lang/StackTraceElement.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/StackTraceElement.java	Wed Jul 05 19:00:49 2017 +0200
@@ -181,12 +181,12 @@
      * {@code StackTraceElement} instance representing the same execution
      * point as this instance.  Two stack trace elements {@code a} and
      * {@code b} are equal if and only if:
-     * <pre>
+     * <pre>{@code
      *     equals(a.getFileName(), b.getFileName()) &&
      *     a.getLineNumber() == b.getLineNumber()) &&
      *     equals(a.getClassName(), b.getClassName()) &&
      *     equals(a.getMethodName(), b.getMethodName())
-     * </pre>
+     * }</pre>
      * where {@code equals} has the semantics of {@link
      * java.util.Objects#equals(Object, Object) Objects.equals}.
      *
--- a/jdk/src/share/classes/java/lang/String.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/String.java	Wed Jul 05 19:00:49 2017 +0200
@@ -3156,101 +3156,4 @@
      *          guaranteed to be from a pool of unique strings.
      */
     public native String intern();
-
-    /**
-     * Seed value used for each alternative hash calculated.
-     */
-    private static final int HASHING_SEED;
-
-    static {
-        long nanos = System.nanoTime();
-        long now = System.currentTimeMillis();
-        int SEED_MATERIAL[] = {
-                System.identityHashCode(String.class),
-                System.identityHashCode(System.class),
-                (int) (nanos >>> 32),
-                (int) nanos,
-                (int) (now >>> 32),
-                (int) now,
-                (int) (System.nanoTime() >>> 2)
-        };
-
-        // Use murmur3 to scramble the seeding material.
-        // Inline implementation to avoid loading classes
-        int h1 = 0;
-
-        // body
-        for(int k1 : SEED_MATERIAL) {
-            k1 *= 0xcc9e2d51;
-            k1 = (k1 << 15) | (k1 >>> 17);
-            k1 *= 0x1b873593;
-
-            h1 ^= k1;
-            h1 = (h1 << 13) | (h1 >>> 19);
-            h1 = h1 * 5 + 0xe6546b64;
-        }
-
-        // tail (always empty, as body is always 32-bit chunks)
-
-        // finalization
-
-        h1 ^= SEED_MATERIAL.length * 4;
-
-        // finalization mix force all bits of a hash block to avalanche
-        h1 ^= h1 >>> 16;
-        h1 *= 0x85ebca6b;
-        h1 ^= h1 >>> 13;
-        h1 *= 0xc2b2ae35;
-        h1 ^= h1 >>> 16;
-
-        HASHING_SEED = h1;
-    }
-
-    /**
-     * Cached value of the hashing algorithm result
-     */
-    private transient int hash32 = 0;
-
-    /**
-    * Return a 32-bit hash code value for this object.
-    * <p>
-    * The general contract of {@code hash32} is:
-    * <ul>
-    * <li>Whenever it is invoked on the same object more than once during
-    *     an execution of a Java application, the {@code hash32} method
-    *     must consistently return the same integer, provided no information
-    *     used in {@code equals} comparisons on the object is modified.
-    *     This integer need not remain consistent from one execution of an
-    *     application to another execution of the same application.
-    * <li>If two objects are equal according to the {@code equals(Object)}
-    *     method, then calling the {@code hash32} method on each of
-    *     the two objects must produce the same integer result.
-    * <li>It is <em>not</em> required that if two objects are unequal
-    *     according to the {@link java.lang.Object#equals(java.lang.Object)}
-    *     method, then calling the {@code hash32} method on each of the
-    *     two objects must produce distinct integer results.  However, the
-    *     programmer should be aware that producing distinct integer results
-    *     for unequal objects may improve the performance of hash tables.
-    * </ul>
-    *
-    * The hash value will never be zero.
-    *
-    * @return  a hash code value for this object.
-    * @see     java.lang.Object#equals(java.lang.Object)
-    */
-    public int hash32() {
-        int h = hash32;
-        if (0 == h) {
-           // harmless data race on hash32 here.
-           h = sun.misc.Hashing.murmur3_32(HASHING_SEED, value, 0, value.length);
-
-           // ensure result is not zero to avoid recalcing
-           h = (0 != h) ? h : 1;
-
-           hash32 = h;
-        }
-
-        return h;
-    }
-
 }
--- a/jdk/src/share/classes/java/lang/Thread.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Thread.java	Wed Jul 05 19:00:49 2017 +0200
@@ -812,68 +812,10 @@
      */
     @Deprecated
     public final void stop() {
-        stop(new ThreadDeath());
-    }
-
-    /**
-     * Forces the thread to stop executing.
-     * <p>
-     * If there is a security manager installed, the <code>checkAccess</code>
-     * method of this thread is called, which may result in a
-     * <code>SecurityException</code> being raised (in the current thread).
-     * <p>
-     * If this thread is different from the current thread (that is, the current
-     * thread is trying to stop a thread other than itself) or
-     * <code>obj</code> is not an instance of <code>ThreadDeath</code>, the
-     * security manager's <code>checkPermission</code> method (with the
-     * <code>RuntimePermission("stopThread")</code> argument) is called in
-     * addition.
-     * Again, this may result in throwing a
-     * <code>SecurityException</code> (in the current thread).
-     * <p>
-     * If the argument <code>obj</code> is null, a
-     * <code>NullPointerException</code> is thrown (in the current thread).
-     * <p>
-     * The thread represented by this thread is forced to stop
-     * whatever it is doing abnormally and to throw the
-     * <code>Throwable</code> object <code>obj</code> as an exception. This
-     * is an unusual action to take; normally, the <code>stop</code> method
-     * that takes no arguments should be used.
-     * <p>
-     * It is permitted to stop a thread that has not yet been started.
-     * If the thread is eventually started, it immediately terminates.
-     *
-     * @param      obj   the Throwable object to be thrown.
-     * @exception  SecurityException  if the current thread cannot modify
-     *               this thread.
-     * @throws     NullPointerException if obj is <tt>null</tt>.
-     * @see        #interrupt()
-     * @see        #checkAccess()
-     * @see        #run()
-     * @see        #start()
-     * @see        #stop()
-     * @see        SecurityManager#checkAccess(Thread)
-     * @see        SecurityManager#checkPermission
-     * @deprecated This method is inherently unsafe.  See {@link #stop()}
-     *        for details.  An additional danger of this
-     *        method is that it may be used to generate exceptions that the
-     *        target thread is unprepared to handle (including checked
-     *        exceptions that the thread could not possibly throw, were it
-     *        not for this method).
-     *        For more information, see
-     *        <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
-     *        are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
-     */
-    @Deprecated
-    public final synchronized void stop(Throwable obj) {
-        if (obj == null)
-            throw new NullPointerException();
-
         SecurityManager security = System.getSecurityManager();
         if (security != null) {
             checkAccess();
-            if ((this != Thread.currentThread()) ||
-                (!(obj instanceof ThreadDeath))) {
+            if (this != Thread.currentThread()) {
                 security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
             }
         }
@@ -884,7 +826,26 @@
         }
 
         // The VM can handle all thread states
-        stop0(obj);
+        stop0(new ThreadDeath());
+    }
+
+    /**
+     * Throws {@code UnsupportedOperationException}.
+     *
+     * @param obj ignored
+     *
+     * @deprecated This method was originally designed to force a thread to stop
+     *        and throw a given {@code Throwable} as an exception. It was
+     *        inherently unsafe (see {@link #stop()} for details), and furthermore
+     *        could be used to generate exceptions that the target thread was
+     *        not prepared to handle.
+     *        For more information, see
+     *        <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why
+     *        are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.
+     */
+    @Deprecated
+    public final synchronized void stop(Throwable obj) {
+        throw new UnsupportedOperationException();
     }
 
     /**
--- a/jdk/src/share/classes/java/lang/annotation/IncompleteAnnotationException.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/annotation/IncompleteAnnotationException.java	Wed Jul 05 19:00:49 2017 +0200
@@ -55,8 +55,7 @@
     public IncompleteAnnotationException(
             Class<? extends Annotation> annotationType,
             String elementName) {
-        super(annotationType.getName().toString() +
-              " missing element " +
+        super(annotationType.getName() + " missing element " +
               elementName.toString());
 
         this.annotationType = annotationType;
--- a/jdk/src/share/classes/java/lang/instrument/Instrumentation.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/instrument/Instrumentation.java	Wed Jul 05 19:00:49 2017 +0200
@@ -593,24 +593,28 @@
      * and the normal automatic resolution.  For
      * <code>RegisterNatives</code>, the JVM will attempt this
      * association:
-     * <pre>
-     *   method(foo) -> nativeImplementation(foo)</pre>
+     * <pre>{@code
+     *   method(foo) -> nativeImplementation(foo)
+     * }</pre>
      * <p/>
      * When this fails, the resolution will be retried with
      * the specified prefix prepended to the method name,
      * yielding the correct resolution:
-     * <pre>
-     *   method(wrapped_foo) -> nativeImplementation(foo)</pre>
+     * <pre>{@code
+     *   method(wrapped_foo) -> nativeImplementation(foo)
+     * }</pre>
      * <p/>
      * For automatic resolution, the JVM will attempt:
-     * <pre>
-     *   method(wrapped_foo) -> nativeImplementation(wrapped_foo)</pre>
+     * <pre>{@code
+     *   method(wrapped_foo) -> nativeImplementation(wrapped_foo)
+     * }</pre>
      * <p/>
      * When this fails, the resolution will be retried with
      * the specified prefix deleted from the implementation name,
      * yielding the correct resolution:
-     * <pre>
-     *   method(wrapped_foo) -> nativeImplementation(foo)</pre>
+     * <pre>{@code
+     *   method(wrapped_foo) -> nativeImplementation(foo)
+     * }</pre>
      * <p/>
      * Note that since the prefix is only used when standard
      * resolution fails, native methods can be wrapped selectively.
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandle.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandle.java	Wed Jul 05 19:00:49 2017 +0200
@@ -251,7 +251,7 @@
  *
  * <h3>Usage examples</h3>
  * Here are some examples of usage:
- * <p><blockquote><pre>
+ * <p><blockquote><pre>{@code
 Object x, y; String s; int i;
 MethodType mt; MethodHandle mh;
 MethodHandles.Lookup lookup = MethodHandles.lookup();
@@ -287,7 +287,7 @@
 mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
 mh.invokeExact(System.out, "Hello, world.");
 // invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
- * </pre></blockquote>
+ * }</pre></blockquote>
  * Each of the above calls to {@code invokeExact} or plain {@code invoke}
  * generates a single invokevirtual instruction with
  * the symbolic type descriptor indicated in the following comment.
@@ -754,7 +754,7 @@
      * (The array may also be null when zero elements are required.)
      * <p>
      * Here are some simple examples of array-spreading method handles:
-     * <blockquote><pre>
+     * <blockquote><pre>{@code
 MethodHandle equals = publicLookup()
   .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
 assert( (boolean) equals.invokeExact("me", (Object)"me"));
@@ -790,7 +790,7 @@
 assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
 MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
 assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
-     * </pre></blockquote>
+     * }</pre></blockquote>
      * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments
      * @param arrayLength the number of arguments to spread from an incoming array argument
      * @return a new method handle which spreads its final array argument,
@@ -878,7 +878,7 @@
      * number of collected arguments, use {@link #asVarargsCollector asVarargsCollector} instead.
      * <p>
      * Here are some examples of array-collecting method handles:
-     * <blockquote><pre>
+     * <blockquote><pre>{@code
 MethodHandle deepToString = publicLookup()
   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
 assertEquals("[won]",   (String) deepToString.invokeExact(new Object[]{"won"}));
@@ -904,7 +904,7 @@
   .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
   .asCollector(long[].class, 1);
 assertEquals("[123]", (String) longsToString.invokeExact((long)123));
-     * </pre></blockquote>
+     * }</pre></blockquote>
      * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
      * @param arrayLength the number of arguments to collect into a new array argument
      * @return a new method handle which collects some trailing argument
@@ -1041,7 +1041,7 @@
      * It may (or may not) return the original variable arity method handle.
      * <p>
      * Here is an example, of a list-making variable arity method handle:
-     * <blockquote><pre>
+     * <blockquote><pre>{@code
 MethodHandle deepToString = publicLookup()
   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
 MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
@@ -1063,7 +1063,7 @@
 List ls = (List) asList.invoke((Object)argv);
 assertEquals(1, ls.size());
 assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
-     * </pre></blockquote>
+     * }</pre></blockquote>
      * <p style="font-size:smaller;">
      * <em>Discussion:</em>
      * These rules are designed as a dynamically-typed variation
@@ -1134,7 +1134,7 @@
      * a previous argument to {@code asVarargsCollector}.
      * <p>
      * Here is an example, of a list-making variable arity method handle:
-     * <blockquote><pre>
+     * <blockquote><pre>{@code
 MethodHandle asListVar = publicLookup()
   .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
   .asVarargsCollector(Object[].class);
@@ -1153,7 +1153,7 @@
 assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
 assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
 assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
-     * </pre></blockquote>
+     * }</pre></blockquote>
      *
      * @return a new method handle which accepts only a fixed number of arguments
      * @see #asVarargsCollector
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java	Wed Jul 05 19:00:49 2017 +0200
@@ -31,11 +31,13 @@
 import java.util.List;
 import java.util.ArrayList;
 import java.util.Arrays;
+
 import sun.invoke.util.ValueConversions;
 import sun.invoke.util.VerifyAccess;
 import sun.invoke.util.Wrapper;
 import sun.reflect.CallerSensitive;
 import sun.reflect.Reflection;
+import sun.reflect.misc.ReflectUtil;
 import sun.security.util.SecurityConstants;
 import static java.lang.invoke.MethodHandleStatics.*;
 import static java.lang.invoke.MethodHandleNatives.Constants.*;
@@ -578,14 +580,11 @@
          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
          * @throws NullPointerException if any argument is null
          */
-        @CallerSensitive
         public
         MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
-            Class<?> callerClass = Reflection.getCallerClass();
-            checkSecurityManager(refc, method, callerClass);
-            return getDirectMethod(REF_invokeStatic, refc, method,
-                                   findBoundCallerClass(method, callerClass));
+            checkSecurityManager(refc, method);
+            return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method));
         }
 
         /**
@@ -631,7 +630,6 @@
          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
          * @throws NullPointerException if any argument is null
          */
-        @CallerSensitive
         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
             if (refc == MethodHandle.class) {
                 MethodHandle mh = findVirtualForMH(name, type);
@@ -639,10 +637,8 @@
             }
             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
             MemberName method = resolveOrFail(refKind, refc, name, type);
-            Class<?> callerClass = Reflection.getCallerClass();
-            checkSecurityManager(refc, method, callerClass);
-            return getDirectMethod(refKind, refc, method,
-                                   findBoundCallerClass(method, callerClass));
+            checkSecurityManager(refc, method);
+            return getDirectMethod(refKind, refc, method, findBoundCallerClass(method));
         }
         private MethodHandle findVirtualForMH(String name, MethodType type) {
             // these names require special lookups because of the implicit MethodType argument
@@ -679,11 +675,10 @@
          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
          * @throws NullPointerException if any argument is null
          */
-        @CallerSensitive
         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
             String name = "<init>";
             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
-            checkSecurityManager(refc, ctor, Reflection.getCallerClass());
+            checkSecurityManager(refc, ctor);
             return getDirectConstructor(refc, ctor);
         }
 
@@ -721,16 +716,13 @@
          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
          * @throws NullPointerException if any argument is null
          */
-        @CallerSensitive
         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
             checkSpecialCaller(specialCaller);
             Lookup specialLookup = this.in(specialCaller);
             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
-            Class<?> callerClass = Reflection.getCallerClass();
-            checkSecurityManager(refc, method, callerClass);
-            return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method,
-                                                 findBoundCallerClass(method, callerClass));
+            checkSecurityManager(refc, method);
+            return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
         }
 
         /**
@@ -750,10 +742,9 @@
          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
          * @throws NullPointerException if any argument is null
          */
-        @CallerSensitive
         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
             MemberName field = resolveOrFail(REF_getField, refc, name, type);
-            checkSecurityManager(refc, field, Reflection.getCallerClass());
+            checkSecurityManager(refc, field);
             return getDirectField(REF_getField, refc, field);
         }
 
@@ -774,10 +765,9 @@
          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
          * @throws NullPointerException if any argument is null
          */
-        @CallerSensitive
         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
             MemberName field = resolveOrFail(REF_putField, refc, name, type);
-            checkSecurityManager(refc, field, Reflection.getCallerClass());
+            checkSecurityManager(refc, field);
             return getDirectField(REF_putField, refc, field);
         }
 
@@ -797,10 +787,9 @@
          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
          * @throws NullPointerException if any argument is null
          */
-        @CallerSensitive
         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
-            checkSecurityManager(refc, field, Reflection.getCallerClass());
+            checkSecurityManager(refc, field);
             return getDirectField(REF_getStatic, refc, field);
         }
 
@@ -820,10 +809,9 @@
          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
          * @throws NullPointerException if any argument is null
          */
-        @CallerSensitive
         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
-            checkSecurityManager(refc, field, Reflection.getCallerClass());
+            checkSecurityManager(refc, field);
             return getDirectField(REF_putStatic, refc, field);
         }
 
@@ -873,14 +861,11 @@
          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
          * @throws NullPointerException if any argument is null
          */
-        @CallerSensitive
         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
             Class<? extends Object> refc = receiver.getClass(); // may get NPE
             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
-            Class<?> callerClass = Reflection.getCallerClass();
-            checkSecurityManager(refc, method, callerClass);
-            MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method,
-                                                        findBoundCallerClass(method, callerClass));
+            checkSecurityManager(refc, method);
+            MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method));
             return mh.bindReceiver(receiver).setVarargs(method);
         }
 
@@ -905,16 +890,14 @@
          *                                is set and {@code asVarargsCollector} fails
          * @throws NullPointerException if the argument is null
          */
-        @CallerSensitive
         public MethodHandle unreflect(Method m) throws IllegalAccessException {
             MemberName method = new MemberName(m);
             byte refKind = method.getReferenceKind();
             if (refKind == REF_invokeSpecial)
                 refKind = REF_invokeVirtual;
             assert(method.isMethod());
-            Class<?> callerClass = findBoundCallerClass(method, Reflection.getCallerClass());
             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
-            return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method, callerClass);
+            return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
         }
 
         /**
@@ -938,15 +921,13 @@
          *                                is set and {@code asVarargsCollector} fails
          * @throws NullPointerException if any argument is null
          */
-        @CallerSensitive
         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
             checkSpecialCaller(specialCaller);
             Lookup specialLookup = this.in(specialCaller);
             MemberName method = new MemberName(m, true);
             assert(method.isMethod());
-            Class<?> callerClass = findBoundCallerClass(method, Reflection.getCallerClass());
             // ignore m.isAccessible:  this is a new kind of access
-            return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method, callerClass);
+            return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method));
         }
 
         /**
@@ -1047,21 +1028,25 @@
         /**
          * Find my trustable caller class if m is a caller sensitive method.
          * If this lookup object has private access, then the caller class is the lookupClass.
-         * Otherwise, it is the caller of the currently executing public API method (e.g., findVirtual).
-         * This is the same caller class as is used by checkSecurityManager.
+         * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
          */
-        Class<?> findBoundCallerClass(MemberName m, Class<?> callerAtEntryPoint) {
+        Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
             Class<?> callerClass = null;
             if (MethodHandleNatives.isCallerSensitive(m)) {
-                // Do not refactor this to a more "logical" place, since it is stack walk magic.
-                // Note that this is the same expression as in Step 2 below in checkSecurityManager.
-                callerClass = ((allowedModes & PRIVATE) != 0
-                               ? lookupClass  // for strong access modes, no extra check
-                               : callerAtEntryPoint);
+                // Only full-power lookup is allowed to resolve caller-sensitive methods
+                if (isFullPowerLookup()) {
+                    callerClass = lookupClass;
+                } else {
+                    throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
+                }
             }
             return callerClass;
         }
 
+        private boolean isFullPowerLookup() {
+            return (allowedModes & PRIVATE) != 0;
+        }
+
         /**
          * Determine whether a security manager has an overridden
          * SecurityManager.checkMemberAccess method.
@@ -1082,10 +1067,8 @@
          * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
          * Determines a trustable caller class to compare with refc, the symbolic reference class.
          * If this lookup object has private access, then the caller class is the lookupClass.
-         * Otherwise, it is the caller of the currently executing public API method (e.g., findVirtual).
-         * This function performs stack walk magic: do not refactor it.
          */
-        void checkSecurityManager(Class<?> refc, MemberName m, Class<?> caller) {
+        void checkSecurityManager(Class<?> refc, MemberName m) {
             SecurityManager smgr = System.getSecurityManager();
             if (smgr == null)  return;
             if (allowedModes == TRUSTED)  return;
@@ -1105,13 +1088,10 @@
             }
 
             // Step 2:
-            Class<?> callerClass = ((allowedModes & PRIVATE) != 0
-                                    ? lookupClass  // for strong access modes, no extra check
-                                    : caller);
-            if (!VerifyAccess.classLoaderIsAncestor(lookupClass, refc) ||
-                (callerClass != lookupClass &&
-                 !VerifyAccess.classLoaderIsAncestor(callerClass, refc)))
-                smgr.checkPackageAccess(VerifyAccess.getPackageName(refc));
+            if (!isFullPowerLookup() ||
+                !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
+                ReflectUtil.checkPackageAccess(refc);
+            }
 
             // Step 3:
             if (m.isPublic()) return;
@@ -1121,7 +1101,7 @@
                 final int which = Member.DECLARED;
                 final Class<?> clazz = defc;
                 if (!overridden) {
-                    if (caller.getClassLoader() != clazz.getClassLoader()) {
+                    if (!isFullPowerLookup()) {
                         smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
                     }
                 } else {
@@ -1132,8 +1112,9 @@
             }
 
             // Step 4:
-            if (defc != refc)
-                smgr.checkPackageAccess(VerifyAccess.getPackageName(defc));
+            if (defc != refc) {
+                ReflectUtil.checkPackageAccess(defc);
+            }
         }
 
         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
@@ -1593,7 +1574,7 @@
      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
      * incoming arguments which are not mentioned in the reordering array
      * are may be any type, as determined only by {@code newType}.
-     * <blockquote><pre>
+     * <blockquote><pre>{@code
 import static java.lang.invoke.MethodHandles.*;
 import static java.lang.invoke.MethodType.*;
 ...
@@ -1609,7 +1590,7 @@
 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
 assert(twice.type().equals(intfn1));
 assert((int)twice.invokeExact(21) == 42);
-     * </pre></blockquote>
+     * }</pre></blockquote>
      * @param target the method handle to invoke after arguments are reordered
      * @param newType the expected type of the new method handle
      * @param reorder an index array which controls the reordering
--- a/jdk/src/share/classes/java/lang/invoke/MethodType.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/invoke/MethodType.java	Wed Jul 05 19:00:49 2017 +0200
@@ -27,10 +27,13 @@
 
 import sun.invoke.util.Wrapper;
 import java.lang.ref.WeakReference;
+import java.lang.ref.Reference;
 import java.lang.ref.ReferenceQueue;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ConcurrentHashMap;
 import sun.invoke.util.BytecodeDescriptor;
 import static java.lang.invoke.MethodHandleStatics.*;
 import sun.invoke.util.VerifyType;
@@ -171,7 +174,7 @@
         return new IndexOutOfBoundsException(num.toString());
     }
 
-    static final WeakInternSet internTable = new WeakInternSet();
+    static final ConcurrentWeakInternSet<MethodType> internTable = new ConcurrentWeakInternSet<>();
 
     static final Class<?>[] NO_PTYPES = {};
 
@@ -1013,267 +1016,104 @@
     }
 
     /**
-     * Weak intern set based on implementation of the <tt>HashSet</tt> and
-     * <tt>WeakHashMap</tt>, with <em>weak values</em>.  Note: <tt>null</tt>
-     * values will yield <tt>NullPointerException</tt>
-     * Refer to implementation of WeakInternSet for details.
+     * Simple implementation of weak concurrent intern set.
      *
-     * @see         java.util.HashMap
-     * @see         java.util.HashSet
-     * @see         java.util.WeakHashMap
-     * @see         java.lang.ref.WeakReference
+     * @param <T> interned type
      */
-    private static class WeakInternSet {
-        // The default initial capacity -- MUST be a power of two.
-        private static final int DEFAULT_INITIAL_CAPACITY = 16;
-
-        // The maximum capacity, used if a higher value is implicitly specified
-        // by either of the constructors with arguments.
-        // MUST be a power of two <= 1<<30.
-        private static final int MAXIMUM_CAPACITY = 1 << 30;
-
-        // The load factor used when none specified in constructor.
-        private static final float DEFAULT_LOAD_FACTOR = 0.75f;
-
-        // The table, resized as necessary. Length MUST Always be a power of two.
-        private Entry[] table;
-
-        // The number of entries contained in this set.
-        private int size;
-
-        // The next size value at which to resize (capacity * load factor).
-        private int threshold;
+    private static class ConcurrentWeakInternSet<T> {
 
-        // The load factor for the hash table.
-        private final float loadFactor;
-
-        // Reference queue for cleared WeakEntries
-        private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
-
-        private Entry[] newTable(int n) {
-            return new Entry[n];
-        }
+        private final ConcurrentMap<WeakEntry<T>, WeakEntry<T>> map;
+        private final ReferenceQueue<T> stale;
 
-        /**
-         * Constructs a new, empty <tt>WeakInternSet</tt> with the default initial
-         * capacity (16) and load factor (0.75).
-         */
-        WeakInternSet() {
-            this.loadFactor = DEFAULT_LOAD_FACTOR;
-            threshold = DEFAULT_INITIAL_CAPACITY;
-            table = newTable(DEFAULT_INITIAL_CAPACITY);
-        }
-
-        /**
-         * Applies a supplemental hash function to a given hashCode, which
-         * defends against poor quality hash functions.  This is critical
-         * because hashing uses power-of-two length hash tables, that
-         * otherwise encounter collisions for hashCodes that do not differ
-         * in lower bits.
-         * @param h preliminary hash code value
-         * @return supplemental hash code value
-         */
-        private static int hash(int h) {
-            // This function ensures that hashCodes that differ only by
-            // constant multiples at each bit position have a bounded
-            // number of collisions (approximately 8 at default load factor).
-            h ^= (h >>> 20) ^ (h >>> 12);
-            return h ^ (h >>> 7) ^ (h >>> 4);
+        public ConcurrentWeakInternSet() {
+            this.map = new ConcurrentHashMap<>();
+            this.stale = new ReferenceQueue<>();
         }
 
         /**
-         * Checks for equality of non-null reference x and possibly-null y.  By
-         * default uses Object.equals.
-         * @param x first object to compare
-         * @param y second object to compare
-         * @return <tt>true</tt> if objects are equal
-         */
-        private static boolean eq(Object x, Object y) {
-            return x == y || x.equals(y);
-        }
-
-        /**
-         * Returns index for hash code h.
-         * @param h      raw hash code
-         * @param length length of table (power of 2)
-         * @return index in table
-         */
-        private static int indexFor(int h, int length) {
-            return h & (length-1);
-        }
-
-        /**
-         * Expunges stale entries from the table.
+         * Get the existing interned element.
+         * This method returns null if no element is interned.
+         *
+         * @param elem element to look up
+         * @return the interned element
          */
-        private void expungeStaleEntries() {
-            for (Object x; (x = queue.poll()) != null; ) {
-                synchronized (queue) {
-                    Entry entry = (Entry) x;
-                    int i = indexFor(entry.hash, table.length);
-                    Entry prev = table[i];
-                    Entry p = prev;
-                    while (p != null) {
-                        Entry next = p.next;
-                        if (p == entry) {
-                            if (prev == entry)
-                                table[i] = next;
-                            else
-                                prev.next = next;
-                            entry.next = null;
-                            size--;
-                            break;
-                        }
-                        prev = p;
-                        p = next;
-                    }
-                }
-            }
-        }
+        public T get(T elem) {
+            if (elem == null) throw new NullPointerException();
+            expungeStaleElements();
 
-        /**
-         * Returns the table after first expunging stale entries.
-         * @return an expunged hash table
-         */
-        private Entry[] getTable() {
-            expungeStaleEntries();
-            return table;
-        }
-
-        /**
-         * Returns the entry to which the specified value is mapped,
-         * or {@code null} if this set contains no entry for the value.
-         *
-         * <p>More formally, if this set contains an entry for value
-         * {@code entry} to a value {@code value} such that
-         * {@code entry.equals(value)}, then this method returns {@code entry};
-         * otherwise it returns {@code null}.
-         *
-         * @param value value to search for in set
-         * @return interned value if in set, otherwise <tt>null</tt>
-         */
-        synchronized MethodType get(MethodType value) {
-            int h = hash(value.hashCode());
-            Entry[] tab = getTable();
-            int index = indexFor(h, tab.length);
-            Entry e = tab[index];
-            MethodType g;
-            while (e != null) {
-                if (e.hash == h && eq(value, g = e.get()))
-                    return g;
-                e = e.next;
+            WeakEntry<T> value = map.get(new WeakEntry<>(elem));
+            if (value != null) {
+                T res = value.get();
+                if (res != null) {
+                    return res;
+                }
             }
             return null;
         }
 
         /**
-         * Attempts to add the specified value to the set and returns same value.
-         * If the set previously contained an entry for this value, the old
-         * value is left untouched and returned as the result.
+         * Interns the element.
+         * Always returns non-null element, matching the one in the intern set.
+         * Under the race against another add(), it can return <i>different</i>
+         * element, if another thread beats us to interning it.
          *
-         * @param value value to be added
-         * @return the previous entry associated with <tt>value</tt>, or
-         *         <tt>value</tt> if there was no previous entry found
+         * @param elem element to add
+         * @return element that was actually added
          */
-        synchronized MethodType add(MethodType value) {
-            int h = hash(value.hashCode());
-            Entry[] tab = getTable();
-            int i = indexFor(h, tab.length);
-            MethodType g;
-            for (Entry e = tab[i]; e != null; e = e.next) {
-                if (h == e.hash && eq(value, g = e.get())) {
-                    return g;
-                }
-            }
-            Entry e = tab[i];
-            tab[i] = new Entry(value, queue, h, e);
-            if (++size >= threshold)
-                resize(tab.length * 2);
-            return value;
+        public T add(T elem) {
+            if (elem == null) throw new NullPointerException();
+
+            // Playing double race here, and so spinloop is required.
+            // First race is with two concurrent updaters.
+            // Second race is with GC purging weak ref under our feet.
+            // Hopefully, we almost always end up with a single pass.
+            T interned;
+            WeakEntry<T> e = new WeakEntry<>(elem, stale);
+            do {
+                expungeStaleElements();
+                WeakEntry<T> exist = map.putIfAbsent(e, e);
+                interned = (exist == null) ? elem : exist.get();
+            } while (interned == null);
+            return interned;
         }
 
-        /**
-         * Rehashes the contents of this set into a new array with a
-         * larger capacity.  This method is called automatically when the
-         * number of keys in this set reaches its threshold.
-         *
-         * If current capacity is MAXIMUM_CAPACITY, this method does not
-         * resize the set, but sets threshold to Integer.MAX_VALUE.
-         * This has the effect of preventing future calls.
-         *
-         * @param newCapacity the new capacity, MUST be a power of two;
-         *        must be greater than current capacity unless current
-         *        capacity is MAXIMUM_CAPACITY (in which case value
-         *        is irrelevant)
-         */
-        private void resize(int newCapacity) {
-            Entry[] oldTable = getTable();
-            int oldCapacity = oldTable.length;
-            if (oldCapacity == MAXIMUM_CAPACITY) {
-                threshold = Integer.MAX_VALUE;
-                return;
-            }
-
-            Entry[] newTable = newTable(newCapacity);
-            transfer(oldTable, newTable);
-            table = newTable;
-
-            /*
-             * If ignoring null elements and processing ref queue caused massive
-             * shrinkage, then restore old table.  This should be rare, but avoids
-             * unbounded expansion of garbage-filled tables.
-             */
-            if (size >= threshold / 2) {
-                threshold = (int)(newCapacity * loadFactor);
-            } else {
-                expungeStaleEntries();
-                transfer(newTable, oldTable);
-                table = oldTable;
+        private void expungeStaleElements() {
+            Reference<? extends T> reference;
+            while ((reference = stale.poll()) != null) {
+                map.remove(reference);
             }
         }
 
-        /**
-         * Transfers all entries from src to dest tables
-         * @param src  original table
-         * @param dest new table
-         */
-        private void transfer(Entry[] src, Entry[] dest) {
-            for (int j = 0; j < src.length; ++j) {
-                Entry e = src[j];
-                src[j] = null;
-                while (e != null) {
-                    Entry next = e.next;
-                    MethodType key = e.get();
-                    if (key == null) {
-                        e.next = null;  // Help GC
-                        size--;
-                    } else {
-                        int i = indexFor(e.hash, dest.length);
-                        e.next = dest[i];
-                        dest[i] = e;
-                    }
-                    e = next;
+        private static class WeakEntry<T> extends WeakReference<T> {
+
+            public final int hashcode;
+
+            public WeakEntry(T key, ReferenceQueue<T> queue) {
+                super(key, queue);
+                hashcode = key.hashCode();
+            }
+
+            public WeakEntry(T key) {
+                super(key);
+                hashcode = key.hashCode();
+            }
+
+            @Override
+            public boolean equals(Object obj) {
+                if (obj instanceof WeakEntry) {
+                    Object that = ((WeakEntry) obj).get();
+                    Object mine = get();
+                    return (that == null || mine == null) ? (this == obj) : mine.equals(that);
                 }
+                return false;
             }
-        }
-
-        /**
-         * The entries in this hash table extend WeakReference, using its main ref
-         * field as the key.
-         */
-        private static class Entry extends WeakReference<MethodType> {
-            final int hash;
-            Entry next;
 
-            /**
-             * Creates new entry.
-             */
-            Entry(MethodType key,
-                  ReferenceQueue<Object> queue,
-                  int hash, Entry next) {
-                super(key, queue);
-                this.hash  = hash;
-                this.next  = next;
+            @Override
+            public int hashCode() {
+                return hashcode;
             }
+
         }
     }
+
 }
--- a/jdk/src/share/classes/java/lang/management/MemoryUsage.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/management/MemoryUsage.java	Wed Jul 05 19:00:49 2017 +0200
@@ -72,8 +72,8 @@
  *      The amount of used and committed memory will always be less than
  *      or equal to <tt>max</tt> if <tt>max</tt> is defined.
  *      A memory allocation may fail if it attempts to increase the
- *      used memory such that <tt>used &gt committed</tt> even
- *      if <tt>used &lt= max</tt> would still be true (for example,
+ *      used memory such that <tt>used &gt; committed</tt> even
+ *      if <tt>used &lt;= max</tt> would still be true (for example,
  *      when the system is low on virtual memory).
  * </td>
  * </tr>
--- a/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java	Wed Jul 05 19:00:49 2017 +0200
@@ -308,7 +308,7 @@
      *
      * <p>
      * <b>MBeanServer access</b>:<br>
-     * The mapped type of <tt>Map<String,String></tt> is
+     * The mapped type of {@code Map<String,String>} is
      * {@link javax.management.openmbean.TabularData TabularData}
      * with two items in each row as follows:
      * <blockquote>
--- a/jdk/src/share/classes/java/lang/management/ThreadMXBean.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/management/ThreadMXBean.java	Wed Jul 05 19:00:49 2017 +0200
@@ -198,7 +198,7 @@
      * <tt>null</tt> if the thread of the given ID is not alive or
      * it does not exist.
      *
-     * @throws IllegalArgumentException if <tt>id &lt= 0</tt>.
+     * @throws IllegalArgumentException if {@code id <= 0}.
      * @throws java.lang.SecurityException if a security manager
      *         exists and the caller does not have
      *         ManagementPermission("monitor").
@@ -236,7 +236,7 @@
      * with no stack trace, no locked monitor and no synchronizer info.
      *
      * @throws IllegalArgumentException if any element in the input array
-     *      <tt>ids</tt> is <tt>&lt= 0</tt>.
+     *         <tt>ids</tt> is {@code <= 0}.
      * @throws java.lang.SecurityException if a security manager
      *         exists and the caller does not have
      *         ManagementPermission("monitor").
@@ -282,7 +282,7 @@
      * <tt>null</tt> if the thread of the given ID is not alive or
      * it does not exist.
      *
-     * @throws IllegalArgumentException if <tt>id &lt= 0</tt>.
+     * @throws IllegalArgumentException if {@code id <= 0}.
      * @throws IllegalArgumentException if <tt>maxDepth is negative</tt>.
      * @throws java.lang.SecurityException if a security manager
      *         exists and the caller does not have
@@ -336,7 +336,7 @@
      *
      * @throws IllegalArgumentException if <tt>maxDepth is negative</tt>.
      * @throws IllegalArgumentException if any element in the input array
-     *      <tt>ids</tt> is <tt>&lt= 0</tt>.
+     *      <tt>ids</tt> is {@code <= 0}.
      * @throws java.lang.SecurityException if a security manager
      *         exists and the caller does not have
      *         ManagementPermission("monitor").
@@ -466,7 +466,7 @@
      * and CPU time measurement is enabled;
      * <tt>-1</tt> otherwise.
      *
-     * @throws IllegalArgumentException if <tt>id &lt= 0 </tt>.
+     * @throws IllegalArgumentException if {@code id <= 0}.
      * @throws java.lang.UnsupportedOperationException if the Java
      * virtual machine does not support CPU time measurement for
      * other threads.
@@ -501,7 +501,7 @@
      * and CPU time measurement is enabled;
      * <tt>-1</tt> otherwise.
      *
-     * @throws IllegalArgumentException if <tt>id &lt= 0 </tt>.
+     * @throws IllegalArgumentException if {@code id <= 0}.
      * @throws java.lang.UnsupportedOperationException if the Java
      * virtual machine does not support CPU time measurement for
      * other threads.
--- a/jdk/src/share/classes/java/lang/reflect/Proxy.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/Proxy.java	Wed Jul 05 19:00:49 2017 +0200
@@ -751,25 +751,21 @@
     private static void checkNewProxyPermission(Class<?> caller, Class<?> proxyClass) {
         SecurityManager sm = System.getSecurityManager();
         if (sm != null) {
-            String pcn = proxyClass.getName();
-            if (pcn.startsWith(ReflectUtil.PROXY_PACKAGE + ".")) {
-                // all proxy interfaces are public
-                return;
-            }
-
-            ClassLoader ccl = caller.getClassLoader();
-            ClassLoader pcl = proxyClass.getClassLoader();
+            if (ReflectUtil.isNonPublicProxyClass(proxyClass)) {
+                ClassLoader ccl = caller.getClassLoader();
+                ClassLoader pcl = proxyClass.getClassLoader();
 
-            // do permission check if the caller is in a different runtime package
-            // of the proxy class
-            int n = pcn.lastIndexOf('.');
-            String pkg = (n == -1) ? "" : pcn.substring(0, n);
+                // do permission check if the caller is in a different runtime package
+                // of the proxy class
+                int n = proxyClass.getName().lastIndexOf('.');
+                String pkg = (n == -1) ? "" : proxyClass.getName().substring(0, n);
 
-            n = caller.getName().lastIndexOf('.');
-            String callerPkg = (n == -1) ? "" : caller.getName().substring(0, n);
+                n = caller.getName().lastIndexOf('.');
+                String callerPkg = (n == -1) ? "" : caller.getName().substring(0, n);
 
-            if (pcl != ccl || !pkg.equals(callerPkg)) {
-                sm.checkPermission(new ReflectPermission("newProxyInPackage." + pkg));
+                if (pcl != ccl || !pkg.equals(callerPkg)) {
+                    sm.checkPermission(new ReflectPermission("newProxyInPackage." + pkg));
+                }
             }
         }
     }
--- a/jdk/src/share/classes/java/math/BigDecimal.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/math/BigDecimal.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -3538,24 +3538,7 @@
                 return expandBigIntegerTenPowers(n);
         }
 
-        if (n < 1024*524288) {
-            // BigInteger.pow is slow, so make 10**n by constructing a
-            // BigInteger from a character string (still not very fast)
-            // which occupies no more than 1GB (!) of memory.
-            char tenpow[] = new char[n + 1];
-            tenpow[0] = '1';
-            for (int i = 1; i <= n; i++) {
-                tenpow[i] = '0';
-            }
-            return new BigInteger(tenpow, 1, tenpow.length);
-        }
-
-        if ((n & 0x1) == 0x1) {
-            return BigInteger.TEN.multiply(bigTenToThe(n - 1));
-        } else {
-            BigInteger tmp = bigTenToThe(n/2);
-            return tmp.multiply(tmp);
-        }
+        return BigInteger.TEN.pow(n);
     }
 
     /**
--- a/jdk/src/share/classes/java/math/BigInteger.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/math/BigInteger.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,9 +29,12 @@
 
 package java.math;
 
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamField;
+import java.util.Arrays;
 import java.util.Random;
-import java.io.*;
-import java.util.Arrays;
 
 /**
  * Immutable arbitrary-precision integers.  All operations behave as if
@@ -94,6 +97,7 @@
  * @see     BigDecimal
  * @author  Josh Bloch
  * @author  Michael McCloskey
+ * @author  Alan Eliasen
  * @since JDK1.1
  */
 
@@ -174,6 +178,39 @@
      */
     final static long LONG_MASK = 0xffffffffL;
 
+    /**
+     * The threshold value for using Karatsuba multiplication.  If the number
+     * of ints in both mag arrays are greater than this number, then
+     * Karatsuba multiplication will be used.   This value is found
+     * experimentally to work well.
+     */
+    private static final int KARATSUBA_THRESHOLD = 50;
+
+    /**
+     * The threshold value for using 3-way Toom-Cook multiplication.
+     * If the number of ints in each mag array is greater than the
+     * Karatsuba threshold, and the number of ints in at least one of
+     * the mag arrays is greater than this threshold, then Toom-Cook
+     * multiplication will be used.
+     */
+    private static final int TOOM_COOK_THRESHOLD = 75;
+
+    /**
+     * The threshold value for using Karatsuba squaring.  If the number
+     * of ints in the number are larger than this value,
+     * Karatsuba squaring will be used.   This value is found
+     * experimentally to work well.
+     */
+    private static final int KARATSUBA_SQUARE_THRESHOLD = 90;
+
+    /**
+     * The threshold value for using Toom-Cook squaring.  If the number
+     * of ints in the number are larger than this value,
+     * Toom-Cook squaring will be used.   This value is found
+     * experimentally to work well.
+     */
+    private static final int TOOM_COOK_SQUARE_THRESHOLD = 140;
+
     //Constructors
 
     /**
@@ -522,15 +559,16 @@
 
         if (bitLength < 2)
             throw new ArithmeticException("bitLength < 2");
-        // The cutoff of 95 was chosen empirically for best performance
-        prime = (bitLength < 95 ? smallPrime(bitLength, certainty, rnd)
+        prime = (bitLength < SMALL_PRIME_THRESHOLD
+                                ? smallPrime(bitLength, certainty, rnd)
                                 : largePrime(bitLength, certainty, rnd));
         signum = 1;
         mag = prime.mag;
     }
 
     // Minimum size in bits that the requested prime number has
-    // before we use the large prime number generating algorithms
+    // before we use the large prime number generating algorithms.
+    // The cutoff of 95 was chosen empirically for best performance.
     private static final int SMALL_PRIME_THRESHOLD = 95;
 
     // Certainty required to meet the spec of probablePrime
@@ -553,7 +591,6 @@
         if (bitLength < 2)
             throw new ArithmeticException("bitLength < 2");
 
-        // The cutoff of 95 was chosen empirically for best performance
         return (bitLength < SMALL_PRIME_THRESHOLD ?
                 smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
                 largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
@@ -986,6 +1023,7 @@
     private final static int MAX_CONSTANT = 16;
     private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
     private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
+
     static {
         for (int i = 1; i <= MAX_CONSTANT; i++) {
             int[] magnitude = new int[1];
@@ -1015,6 +1053,11 @@
     private static final BigInteger TWO = valueOf(2);
 
     /**
+     * The BigInteger constant -1.  (Not exported.)
+     */
+    private static final BigInteger NEGATIVE_ONE = valueOf(-1);
+
+    /**
      * The BigInteger constant ten.
      *
      * @since   1.5
@@ -1290,17 +1333,29 @@
     public BigInteger multiply(BigInteger val) {
         if (val.signum == 0 || signum == 0)
             return ZERO;
-        int resultSign = signum == val.signum ? 1 : -1;
-        if (val.mag.length == 1) {
-            return  multiplyByInt(mag,val.mag[0], resultSign);
+
+        int xlen = mag.length;
+        int ylen = val.mag.length;
+
+        if ((xlen < KARATSUBA_THRESHOLD) || (ylen < KARATSUBA_THRESHOLD))
+        {
+            int resultSign = signum == val.signum ? 1 : -1;
+            if (val.mag.length == 1) {
+                return multiplyByInt(mag,val.mag[0], resultSign);
+            }
+            if(mag.length == 1) {
+                return multiplyByInt(val.mag,mag[0], resultSign);
+            }
+            int[] result = multiplyToLen(mag, xlen,
+                                         val.mag, ylen, null);
+            result = trustedStripLeadingZeroInts(result);
+            return new BigInteger(result, resultSign);
         }
-        if(mag.length == 1) {
-            return multiplyByInt(val.mag,mag[0], resultSign);
-        }
-        int[] result = multiplyToLen(mag, mag.length,
-                                     val.mag, val.mag.length, null);
-        result = trustedStripLeadingZeroInts(result);
-        return new BigInteger(result, resultSign);
+        else
+            if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD))
+                return multiplyKaratsuba(this, val);
+            else
+               return multiplyToomCook3(this, val);
     }
 
     private static BigInteger multiplyByInt(int[] x, int y, int sign) {
@@ -1402,6 +1457,272 @@
     }
 
     /**
+     * Multiplies two BigIntegers using the Karatsuba multiplication
+     * algorithm.  This is a recursive divide-and-conquer algorithm which is
+     * more efficient for large numbers than what is commonly called the
+     * "grade-school" algorithm used in multiplyToLen.  If the numbers to be
+     * multiplied have length n, the "grade-school" algorithm has an
+     * asymptotic complexity of O(n^2).  In contrast, the Karatsuba algorithm
+     * has complexity of O(n^(log2(3))), or O(n^1.585).  It achieves this
+     * increased performance by doing 3 multiplies instead of 4 when
+     * evaluating the product.  As it has some overhead, should be used when
+     * both numbers are larger than a certain threshold (found
+     * experimentally).
+     *
+     * See:  http://en.wikipedia.org/wiki/Karatsuba_algorithm
+     */
+    private static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y)
+    {
+        int xlen = x.mag.length;
+        int ylen = y.mag.length;
+
+        // The number of ints in each half of the number.
+        int half = (Math.max(xlen, ylen)+1) / 2;
+
+        // xl and yl are the lower halves of x and y respectively,
+        // xh and yh are the upper halves.
+        BigInteger xl = x.getLower(half);
+        BigInteger xh = x.getUpper(half);
+        BigInteger yl = y.getLower(half);
+        BigInteger yh = y.getUpper(half);
+
+        BigInteger p1 = xh.multiply(yh);  // p1 = xh*yh
+        BigInteger p2 = xl.multiply(yl);  // p2 = xl*yl
+
+        // p3=(xh+xl)*(yh+yl)
+        BigInteger p3 = xh.add(xl).multiply(yh.add(yl));
+
+        // result = p1 * 2^(32*2*half) + (p3 - p1 - p2) * 2^(32*half) + p2
+        BigInteger result = p1.shiftLeft(32*half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32*half).add(p2);
+
+        if (x.signum != y.signum)
+            return result.negate();
+        else
+            return result;
+    }
+
+    /**
+     * Multiplies two BigIntegers using a 3-way Toom-Cook multiplication
+     * algorithm.  This is a recursive divide-and-conquer algorithm which is
+     * more efficient for large numbers than what is commonly called the
+     * "grade-school" algorithm used in multiplyToLen.  If the numbers to be
+     * multiplied have length n, the "grade-school" algorithm has an
+     * asymptotic complexity of O(n^2).  In contrast, 3-way Toom-Cook has a
+     * complexity of about O(n^1.465).  It achieves this increased asymptotic
+     * performance by breaking each number into three parts and by doing 5
+     * multiplies instead of 9 when evaluating the product.  Due to overhead
+     * (additions, shifts, and one division) in the Toom-Cook algorithm, it
+     * should only be used when both numbers are larger than a certain
+     * threshold (found experimentally).  This threshold is generally larger
+     * than that for Karatsuba multiplication, so this algorithm is generally
+     * only used when numbers become significantly larger.
+     *
+     * The algorithm used is the "optimal" 3-way Toom-Cook algorithm outlined
+     * by Marco Bodrato.
+     *
+     *  See: http://bodrato.it/toom-cook/
+     *       http://bodrato.it/papers/#WAIFI2007
+     *
+     * "Towards Optimal Toom-Cook Multiplication for Univariate and
+     * Multivariate Polynomials in Characteristic 2 and 0." by Marco BODRATO;
+     * In C.Carlet and B.Sunar, Eds., "WAIFI'07 proceedings", p. 116-133,
+     * LNCS #4547. Springer, Madrid, Spain, June 21-22, 2007.
+     *
+     */
+    private static BigInteger multiplyToomCook3(BigInteger a, BigInteger b)
+    {
+        int alen = a.mag.length;
+        int blen = b.mag.length;
+
+        int largest = Math.max(alen, blen);
+
+        // k is the size (in ints) of the lower-order slices.
+        int k = (largest+2)/3;   // Equal to ceil(largest/3)
+
+        // r is the size (in ints) of the highest-order slice.
+        int r = largest - 2*k;
+
+        // Obtain slices of the numbers. a2 and b2 are the most significant
+        // bits of the numbers a and b, and a0 and b0 the least significant.
+        BigInteger a0, a1, a2, b0, b1, b2;
+        a2 = a.getToomSlice(k, r, 0, largest);
+        a1 = a.getToomSlice(k, r, 1, largest);
+        a0 = a.getToomSlice(k, r, 2, largest);
+        b2 = b.getToomSlice(k, r, 0, largest);
+        b1 = b.getToomSlice(k, r, 1, largest);
+        b0 = b.getToomSlice(k, r, 2, largest);
+
+        BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1;
+
+        v0 = a0.multiply(b0);
+        da1 = a2.add(a0);
+        db1 = b2.add(b0);
+        vm1 = da1.subtract(a1).multiply(db1.subtract(b1));
+        da1 = da1.add(a1);
+        db1 = db1.add(b1);
+        v1 = da1.multiply(db1);
+        v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(
+             db1.add(b2).shiftLeft(1).subtract(b0));
+        vinf = a2.multiply(b2);
+
+        /* The algorithm requires two divisions by 2 and one by 3.
+           All divisions are known to be exact, that is, they do not produce
+           remainders, and all results are positive.  The divisions by 2 are
+           implemented as right shifts which are relatively efficient, leaving
+           only an exact division by 3, which is done by a specialized
+           linear-time algorithm. */
+        t2 = v2.subtract(vm1).exactDivideBy3();
+        tm1 = v1.subtract(vm1).shiftRight(1);
+        t1 = v1.subtract(v0);
+        t2 = t2.subtract(t1).shiftRight(1);
+        t1 = t1.subtract(tm1).subtract(vinf);
+        t2 = t2.subtract(vinf.shiftLeft(1));
+        tm1 = tm1.subtract(t2);
+
+        // Number of bits to shift left.
+        int ss = k*32;
+
+        BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
+
+        if (a.signum != b.signum)
+            return result.negate();
+        else
+            return result;
+    }
+
+
+    /**
+     * Returns a slice of a BigInteger for use in Toom-Cook multiplication.
+     *
+     * @param lowerSize The size of the lower-order bit slices.
+     * @param upperSize The size of the higher-order bit slices.
+     * @param slice The index of which slice is requested, which must be a
+     * number from 0 to size-1. Slice 0 is the highest-order bits, and slice
+     * size-1 are the lowest-order bits. Slice 0 may be of different size than
+     * the other slices.
+     * @param fullsize The size of the larger integer array, used to align
+     * slices to the appropriate position when multiplying different-sized
+     * numbers.
+     */
+    private BigInteger getToomSlice(int lowerSize, int upperSize, int slice,
+                                    int fullsize)
+    {
+        int start, end, sliceSize, len, offset;
+
+        len = mag.length;
+        offset = fullsize - len;
+
+        if (slice == 0)
+        {
+            start = 0 - offset;
+            end = upperSize - 1 - offset;
+        }
+        else
+        {
+            start = upperSize + (slice-1)*lowerSize - offset;
+            end = start + lowerSize - 1;
+        }
+
+        if (start < 0)
+            start = 0;
+        if (end < 0)
+           return ZERO;
+
+        sliceSize = (end-start) + 1;
+
+        if (sliceSize <= 0)
+            return ZERO;
+
+        // While performing Toom-Cook, all slices are positive and
+        // the sign is adjusted when the final number is composed.
+        if (start==0 && sliceSize >= len)
+            return this.abs();
+
+        int intSlice[] = new int[sliceSize];
+        System.arraycopy(mag, start, intSlice, 0, sliceSize);
+
+        return new BigInteger(trustedStripLeadingZeroInts(intSlice), 1);
+    }
+
+    /**
+     * Does an exact division (that is, the remainder is known to be zero)
+     * of the specified number by 3.  This is used in Toom-Cook
+     * multiplication.  This is an efficient algorithm that runs in linear
+     * time.  If the argument is not exactly divisible by 3, results are
+     * undefined.  Note that this is expected to be called with positive
+     * arguments only.
+     */
+    private BigInteger exactDivideBy3()
+    {
+        int len = mag.length;
+        int[] result = new int[len];
+        long x, w, q, borrow;
+        borrow = 0L;
+        for (int i=len-1; i>=0; i--)
+        {
+            x = (mag[i] & LONG_MASK);
+            w = x - borrow;
+            if (borrow > x)       // Did we make the number go negative?
+                borrow = 1L;
+            else
+                borrow = 0L;
+
+            // 0xAAAAAAAB is the modular inverse of 3 (mod 2^32).  Thus,
+            // the effect of this is to divide by 3 (mod 2^32).
+            // This is much faster than division on most architectures.
+            q = (w * 0xAAAAAAABL) & LONG_MASK;
+            result[i] = (int) q;
+
+            // Now check the borrow. The second check can of course be
+            // eliminated if the first fails.
+            if (q >= 0x55555556L)
+            {
+                borrow++;
+                if (q >= 0xAAAAAAABL)
+                    borrow++;
+            }
+        }
+        result = trustedStripLeadingZeroInts(result);
+        return new BigInteger(result, signum);
+    }
+
+    /**
+     * Returns a new BigInteger representing n lower ints of the number.
+     * This is used by Karatsuba multiplication and Karatsuba squaring.
+     */
+    private BigInteger getLower(int n) {
+        int len = mag.length;
+
+        if (len <= n)
+            return this;
+
+        int lowerInts[] = new int[n];
+        System.arraycopy(mag, len-n, lowerInts, 0, n);
+
+        return new BigInteger(trustedStripLeadingZeroInts(lowerInts), 1);
+    }
+
+    /**
+     * Returns a new BigInteger representing mag.length-n upper
+     * ints of the number.  This is used by Karatsuba multiplication and
+     * Karatsuba squaring.
+     */
+    private BigInteger getUpper(int n) {
+        int len = mag.length;
+
+        if (len <= n)
+            return ZERO;
+
+        int upperLen = len - n;
+        int upperInts[] = new int[upperLen];
+        System.arraycopy(mag, 0, upperInts, 0, upperLen);
+
+        return new BigInteger(trustedStripLeadingZeroInts(upperInts), 1);
+    }
+
+    // Squaring
+
+    /**
      * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}.
      *
      * @return {@code this<sup>2</sup>}
@@ -1409,8 +1730,18 @@
     private BigInteger square() {
         if (signum == 0)
             return ZERO;
-        int[] z = squareToLen(mag, mag.length, null);
-        return new BigInteger(trustedStripLeadingZeroInts(z), 1);
+        int len = mag.length;
+
+        if (len < KARATSUBA_SQUARE_THRESHOLD)
+        {
+            int[] z = squareToLen(mag, len, null);
+            return new BigInteger(trustedStripLeadingZeroInts(z), 1);
+        }
+        else
+            if (len < TOOM_COOK_SQUARE_THRESHOLD)
+                return squareKaratsuba();
+            else
+               return squareToomCook3();
     }
 
     /**
@@ -1481,6 +1812,83 @@
     }
 
     /**
+     * Squares a BigInteger using the Karatsuba squaring algorithm.  It should
+     * be used when both numbers are larger than a certain threshold (found
+     * experimentally).  It is a recursive divide-and-conquer algorithm that
+     * has better asymptotic performance than the algorithm used in
+     * squareToLen.
+     */
+    private BigInteger squareKaratsuba()
+    {
+        int half = (mag.length+1) / 2;
+
+        BigInteger xl = getLower(half);
+        BigInteger xh = getUpper(half);
+
+        BigInteger xhs = xh.square();  // xhs = xh^2
+        BigInteger xls = xl.square();  // xls = xl^2
+
+        // xh^2 << 64  +  (((xl+xh)^2 - (xh^2 + xl^2)) << 32) + xl^2
+        return xhs.shiftLeft(half*32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half*32).add(xls);
+    }
+
+    /**
+     * Squares a BigInteger using the 3-way Toom-Cook squaring algorithm.  It
+     * should be used when both numbers are larger than a certain threshold
+     * (found experimentally).  It is a recursive divide-and-conquer algorithm
+     * that has better asymptotic performance than the algorithm used in
+     * squareToLen or squareKaratsuba.
+     */
+    private BigInteger squareToomCook3()
+    {
+        int len = mag.length;
+
+        // k is the size (in ints) of the lower-order slices.
+        int k = (len+2)/3;   // Equal to ceil(largest/3)
+
+        // r is the size (in ints) of the highest-order slice.
+        int r = len - 2*k;
+
+        // Obtain slices of the numbers. a2 is the most significant
+        // bits of the number, and a0 the least significant.
+        BigInteger a0, a1, a2;
+        a2 = getToomSlice(k, r, 0, len);
+        a1 = getToomSlice(k, r, 1, len);
+        a0 = getToomSlice(k, r, 2, len);
+        BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1;
+
+        v0 = a0.square();
+        da1 = a2.add(a0);
+        vm1 = da1.subtract(a1).square();
+        da1 = da1.add(a1);
+        v1 = da1.square();
+        vinf = a2.square();
+        v2 = da1.add(a2).shiftLeft(1).subtract(a0).square();
+
+        /* The algorithm requires two divisions by 2 and one by 3.
+           All divisions are known to be exact, that is, they do not produce
+           remainders, and all results are positive.  The divisions by 2 are
+           implemented as right shifts which are relatively efficient, leaving
+           only a division by 3.
+           The division by 3 is done by an optimized algorithm for this case.
+        */
+        t2 = v2.subtract(vm1).exactDivideBy3();
+        tm1 = v1.subtract(vm1).shiftRight(1);
+        t1 = v1.subtract(v0);
+        t2 = t2.subtract(t1).shiftRight(1);
+        t1 = t1.subtract(tm1).subtract(vinf);
+        t2 = t2.subtract(vinf.shiftLeft(1));
+        tm1 = tm1.subtract(t2);
+
+        // Number of bits to shift left.
+        int ss = k*32;
+
+        return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
+    }
+
+    // Division
+
+    /**
      * Returns a BigInteger whose value is {@code (this / val)}.
      *
      * @param  val value by which this BigInteger is to be divided.
@@ -1549,23 +1957,100 @@
         if (signum==0)
             return (exponent==0 ? ONE : this);
 
-        // Perform exponentiation using repeated squaring trick
-        int newSign = (signum<0 && (exponent&1)==1 ? -1 : 1);
-        int[] baseToPow2 = this.mag;
-        int[] result = {1};
-
-        while (exponent != 0) {
-            if ((exponent & 1)==1) {
-                result = multiplyToLen(result, result.length,
-                                       baseToPow2, baseToPow2.length, null);
-                result = trustedStripLeadingZeroInts(result);
+        BigInteger partToSquare = this.abs();
+
+        // Factor out powers of two from the base, as the exponentiation of
+        // these can be done by left shifts only.
+        // The remaining part can then be exponentiated faster.  The
+        // powers of two will be multiplied back at the end.
+        int powersOfTwo = partToSquare.getLowestSetBit();
+
+        int remainingBits;
+
+        // Factor the powers of two out quickly by shifting right, if needed.
+        if (powersOfTwo > 0)
+        {
+            partToSquare = partToSquare.shiftRight(powersOfTwo);
+            remainingBits = partToSquare.bitLength();
+            if (remainingBits == 1)  // Nothing left but +/- 1?
+                if (signum<0 && (exponent&1)==1)
+                    return NEGATIVE_ONE.shiftLeft(powersOfTwo*exponent);
+                else
+                    return ONE.shiftLeft(powersOfTwo*exponent);
+        }
+        else
+        {
+            remainingBits = partToSquare.bitLength();
+            if (remainingBits == 1)  // Nothing left but +/- 1?
+                if (signum<0 && (exponent&1)==1)
+                    return NEGATIVE_ONE;
+                else
+                    return ONE;
+        }
+
+        // This is a quick way to approximate the size of the result,
+        // similar to doing log2[n] * exponent.  This will give an upper bound
+        // of how big the result can be, and which algorithm to use.
+        int scaleFactor = remainingBits * exponent;
+
+        // Use slightly different algorithms for small and large operands.
+        // See if the result will safely fit into a long. (Largest 2^63-1)
+        if (partToSquare.mag.length==1 && scaleFactor <= 62)
+        {
+            // Small number algorithm.  Everything fits into a long.
+            int newSign = (signum<0 && (exponent&1)==1 ? -1 : 1);
+            long result = 1;
+            long baseToPow2 = partToSquare.mag[0] & LONG_MASK;
+
+            int workingExponent = exponent;
+
+            // Perform exponentiation using repeated squaring trick
+            while (workingExponent != 0) {
+                if ((workingExponent & 1)==1)
+                    result = result * baseToPow2;
+
+                if ((workingExponent >>>= 1) != 0)
+                    baseToPow2 = baseToPow2 * baseToPow2;
             }
-            if ((exponent >>>= 1) != 0) {
-                baseToPow2 = squareToLen(baseToPow2, baseToPow2.length, null);
-                baseToPow2 = trustedStripLeadingZeroInts(baseToPow2);
+
+            // Multiply back the powers of two (quickly, by shifting left)
+            if (powersOfTwo > 0)
+            {
+                int bitsToShift = powersOfTwo*exponent;
+                if (bitsToShift + scaleFactor <= 62) // Fits in long?
+                    return valueOf((result << bitsToShift) * newSign);
+                else
+                    return valueOf(result*newSign).shiftLeft(bitsToShift);
             }
+            else
+                return valueOf(result*newSign);
         }
-        return new BigInteger(result, newSign);
+        else
+        {
+            // Large number algorithm.  This is basically identical to
+            // the algorithm above, but calls multiply() and square()
+            // which may use more efficient algorithms for large numbers.
+            BigInteger answer = ONE;
+
+            int workingExponent = exponent;
+            // Perform exponentiation using repeated squaring trick
+            while (workingExponent != 0) {
+                if ((workingExponent & 1)==1)
+                    answer = answer.multiply(partToSquare);
+
+                if ((workingExponent >>>= 1) != 0)
+                    partToSquare = partToSquare.square();
+            }
+            // Multiply back the (exponentiated) powers of two (quickly,
+            // by shifting left)
+            if (powersOfTwo > 0)
+                answer = answer.shiftLeft(powersOfTwo*exponent);
+
+            if (signum<0 && (exponent&1)==1)
+                return answer.negate();
+            else
+                return answer;
+        }
     }
 
     /**
@@ -2117,7 +2602,7 @@
          * Perform exponentiation using repeated squaring trick, chopping off
          * high order bits as indicated by modulus.
          */
-        BigInteger result = valueOf(1);
+        BigInteger result = ONE;
         BigInteger baseToPow2 = this.mod2(p);
         int expOffset = 0;
 
@@ -2850,6 +3335,7 @@
         return buf.toString();
     }
 
+
     /* zero[i] is a string of i consecutive zeros. */
     private static String zeros[] = new String[64];
     static {
@@ -3218,21 +3704,21 @@
      * little-endian binary representation of the magnitude (int 0 is the
      * least significant). If the magnitude is zero, return value is undefined.
      */
-     private int firstNonzeroIntNum() {
-         int fn = firstNonzeroIntNum - 2;
-         if (fn == -2) { // firstNonzeroIntNum not initialized yet
-             fn = 0;
-
-             // Search for the first nonzero int
-             int i;
-             int mlen = mag.length;
-             for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
-                 ;
-             fn = mlen - i - 1;
-             firstNonzeroIntNum = fn + 2; // offset by two to initialize
-         }
-         return fn;
-     }
+    private int firstNonzeroIntNum() {
+        int fn = firstNonzeroIntNum - 2;
+        if (fn == -2) { // firstNonzeroIntNum not initialized yet
+            fn = 0;
+
+            // Search for the first nonzero int
+            int i;
+            int mlen = mag.length;
+            for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
+                ;
+            fn = mlen - i - 1;
+            firstNonzeroIntNum = fn + 2; // offset by two to initialize
+        }
+        return fn;
+    }
 
     /** use serialVersionUID from JDK 1.1. for interoperability */
     private static final long serialVersionUID = -8287574255936472291L;
--- a/jdk/src/share/classes/java/net/CookieManager.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/net/CookieManager.java	Wed Jul 05 19:00:49 2017 +0200
@@ -41,7 +41,7 @@
  *
  * <p> The HTTP cookie management in java.net package looks like:
  * <blockquote>
- * <pre>
+ * <pre>{@code
  *                  use
  * CookieHandler <------- HttpURLConnection
  *       ^
@@ -58,7 +58,7 @@
  *                            | impl
  *                            |
  *                  Internal in-memory implementation
- * </pre>
+ * }</pre>
  * <ul>
  *   <li>
  *     CookieHandler is at the core of cookie management. User can call
@@ -284,7 +284,7 @@
                     } catch (IllegalArgumentException e) {
                         // Bogus header, make an empty list and log the error
                         cookies = java.util.Collections.emptyList();
-                        if (logger.isLoggable(PlatformLogger.SEVERE)) {
+                        if (logger.isLoggable(PlatformLogger.Level.SEVERE)) {
                             logger.severe("Invalid cookie for " + uri + ": " + headerValue);
                         }
                     }
@@ -309,7 +309,10 @@
                         // there is no dot at the beginning of effective request-host,
                         // the default Domain can only domain-match itself.)
                         if (cookie.getDomain() == null) {
-                            cookie.setDomain(uri.getHost());
+                            String host = uri.getHost();
+                            if (host != null && !host.contains("."))
+                                host += ".local";
+                            cookie.setDomain(host);
                         }
                         String ports = cookie.getPortlist();
                         if (ports != null) {
--- a/jdk/src/share/classes/java/net/CookiePolicy.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/net/CookiePolicy.java	Wed Jul 05 19:00:49 2017 +0200
@@ -30,7 +30,7 @@
  * and which should be rejected. Three pre-defined policy implementations
  * are provided, namely ACCEPT_ALL, ACCEPT_NONE and ACCEPT_ORIGINAL_SERVER.
  *
- * <p>See RFC 2965 sec. 3.3 & 7 for more detail.
+ * <p>See RFC 2965 sec. 3.3 and 7 for more detail.
  *
  * @author Edward Wang
  * @since 1.6
@@ -59,6 +59,8 @@
      */
     public static final CookiePolicy ACCEPT_ORIGINAL_SERVER  = new CookiePolicy(){
         public boolean shouldAccept(URI uri, HttpCookie cookie) {
+            if (uri == null || cookie == null)
+                return false;
             return HttpCookie.domainMatches(cookie.getDomain(), uri.getHost());
         }
     };
--- a/jdk/src/share/classes/java/net/DatagramSocket.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/net/DatagramSocket.java	Wed Jul 05 19:00:49 2017 +0200
@@ -334,12 +334,12 @@
     }
 
     /**
-     * Binds this DatagramSocket to a specific address & port.
+     * Binds this DatagramSocket to a specific address and port.
      * <p>
      * If the address is <code>null</code>, then the system will pick up
      * an ephemeral port and a valid local address to bind the socket.
      *<p>
-     * @param   addr The address & port to bind to.
+     * @param   addr The address and port to bind to.
      * @throws  SocketException if any error happens during the bind, or if the
      *          socket is already bound.
      * @throws  SecurityException  if a security manager exists and its
@@ -844,7 +844,7 @@
      *  a <B>java.net.SocketTimeoutException</B> is raised, though the
      *  DatagramSocket is still valid.  The option <B>must</B> be enabled
      *  prior to entering the blocking operation to have effect.  The
-     *  timeout must be > 0.
+     *  timeout must be {@code > 0}.
      *  A timeout of zero is interpreted as an infinite timeout.
      *
      * @param timeout the specified timeout in milliseconds.
@@ -1101,8 +1101,8 @@
      * As the underlying network implementation may ignore this
      * value applications should consider it a hint.
      *
-     * <P> The tc <B>must</B> be in the range <code> 0 <= tc <=
-     * 255</code> or an IllegalArgumentException will be thrown.
+     * <P> The tc <B>must</B> be in the range {@code 0 <= tc <=
+     * 255} or an IllegalArgumentException will be thrown.
      * <p>Notes:
      * <p>For Internet Protocol v4 the value consists of an
      * <code>integer</code>, the least significant 8 bits of which
--- a/jdk/src/share/classes/java/net/HttpURLConnection.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/net/HttpURLConnection.java	Wed Jul 05 19:00:49 2017 +0200
@@ -109,7 +109,7 @@
      * server. In this case, {@link #getHeaderField(int) getHeaderField(0)} returns the status
      * line, but <code>getHeaderFieldKey(0)</code> returns null.
      *
-     * @param   n   an index, where n >=0.
+     * @param   n   an index, where {@code n >=0}.
      * @return  the key for the <code>n</code><sup>th</sup> header field,
      *          or <code>null</code> if the key does not exist.
      */
@@ -260,7 +260,7 @@
      * {@link #getHeaderFieldKey getHeaderFieldKey} method to iterate through all
      * the headers in the message.
      *
-     * @param   n   an index, where n>=0.
+     * @param   n   an index, where {@code n>=0}.
      * @return  the value of the <code>n</code><sup>th</sup> header field,
      *          or <code>null</code> if the value does not exist.
      * @see     java.net.HttpURLConnection#getHeaderFieldKey(int)
--- a/jdk/src/share/classes/java/net/InetSocketAddress.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/net/InetSocketAddress.java	Wed Jul 05 19:00:49 2017 +0200
@@ -389,7 +389,7 @@
      * Two instances of <code>InetSocketAddress</code> represent the same
      * address if both the InetAddresses (or hostnames if it is unresolved) and port
      * numbers are equal.
-     * If both addresses are unresolved, then the hostname & the port number
+     * If both addresses are unresolved, then the hostname and the port number
      * are compared.
      *
      * Note: Hostnames are case insensitive. e.g. "FooBar" and "foobar" are
--- a/jdk/src/share/classes/java/net/MulticastSocket.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/net/MulticastSocket.java	Wed Jul 05 19:00:49 2017 +0200
@@ -201,7 +201,7 @@
      * scope of the multicasts.
      *
      * <p>The ttl is an <b>unsigned</b> 8-bit quantity, and so <B>must</B> be
-     * in the range <code> 0 <= ttl <= 0xFF </code>.
+     * in the range {@code 0 <= ttl <= 0xFF }.
      *
      * @param ttl the time-to-live
      * @exception IOException if an I/O exception occurs
--- a/jdk/src/share/classes/java/net/ServerSocket.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/net/ServerSocket.java	Wed Jul 05 19:00:49 2017 +0200
@@ -316,7 +316,7 @@
      * If the address is <code>null</code>, then the system will pick up
      * an ephemeral port and a valid local address to bind the socket.
      * <p>
-     * @param   endpoint        The IP address & port number to bind to.
+     * @param   endpoint        The IP address and port number to bind to.
      * @throws  IOException if the bind operation fails, or if the socket
      *                     is already bound.
      * @throws  SecurityException       if a <code>SecurityManager</code> is present and
@@ -343,7 +343,7 @@
      * or may choose to ignore the parameter altogther. The value provided
      * should be greater than <code>0</code>. If it is less than or equal to
      * <code>0</code>, then an implementation specific default will be used.
-     * @param   endpoint        The IP address & port number to bind to.
+     * @param   endpoint        The IP address and port number to bind to.
      * @param   backlog         requested maximum length of the queue of
      *                          incoming connections.
      * @throws  IOException if the bind operation fails, or if the socket
@@ -390,15 +390,29 @@
      * If the socket was bound prior to being {@link #close closed},
      * then this method will continue to return the local address
      * after the socket is closed.
+     * <p>
+     * If there is a security manager set, its {@code checkConnect} method is
+     * called with the local address and {@code -1} as its arguments to see
+     * if the operation is allowed. If the operation is not allowed,
+     * the {@link InetAddress#getLoopbackAddress loopback} address is returned.
      *
      * @return  the address to which this socket is bound,
-     *          or <code>null</code> if the socket is unbound.
+     *          or the loopback address if denied by the security manager,
+     *          or {@code null} if the socket is unbound.
+     *
+     * @see SecurityManager#checkConnect
      */
     public InetAddress getInetAddress() {
         if (!isBound())
             return null;
         try {
-            return getImpl().getInetAddress();
+            InetAddress in = getImpl().getInetAddress();
+            SecurityManager sm = System.getSecurityManager();
+            if (sm != null)
+                sm.checkConnect(in.getHostAddress(), -1);
+            return in;
+        } catch (SecurityException e) {
+            return InetAddress.getLoopbackAddress();
         } catch (SocketException e) {
             // nothing
             // If we're bound, the impl has been created
@@ -431,18 +445,28 @@
     }
 
     /**
-     * Returns the address of the endpoint this socket is bound to, or
-     * <code>null</code> if it is not bound yet.
+     * Returns the address of the endpoint this socket is bound to.
      * <p>
      * If the socket was bound prior to being {@link #close closed},
      * then this method will continue to return the address of the endpoint
      * after the socket is closed.
+     * <p>
+     * If there is a security manager set, its {@code checkConnect} method is
+     * called with the local address and {@code -1} as its arguments to see
+     * if the operation is allowed. If the operation is not allowed,
+     * a {@code SocketAddress} representing the
+     * {@link InetAddress#getLoopbackAddress loopback} address and the local
+     * port to which the socket is bound is returned.
      *
-     * @return a <code>SocketAddress</code> representing the local endpoint of this
-     *         socket, or <code>null</code> if it is not bound yet.
+     * @return a {@code SocketAddress} representing the local endpoint of
+     *         this socket, or a {@code SocketAddress} representing the
+     *         loopback address if denied by the security manager,
+     *         or {@code null} if the socket is not bound yet.
+     *
      * @see #getInetAddress()
      * @see #getLocalPort()
      * @see #bind(SocketAddress)
+     * @see SecurityManager#checkConnect
      * @since 1.4
      */
 
@@ -614,7 +638,7 @@
      * a <B>java.net.SocketTimeoutException</B> is raised, though the
      * ServerSocket is still valid.  The option <B>must</B> be enabled
      * prior to entering the blocking operation to have effect.  The
-     * timeout must be > 0.
+     * timeout must be {@code > 0}.
      * A timeout of zero is interpreted as an infinite timeout.
      * @param timeout the specified timeout, in milliseconds
      * @exception SocketException if there is an error in
@@ -709,13 +733,25 @@
     /**
      * Returns the implementation address and implementation port of
      * this socket as a <code>String</code>.
+     * <p>
+     * If there is a security manager set, its {@code checkConnect} method is
+     * called with the local address and {@code -1} as its arguments to see
+     * if the operation is allowed. If the operation is not allowed,
+     * an {@code InetAddress} representing the
+     * {@link InetAddress#getLoopbackAddress loopback} address is returned as
+     * the implementation address.
      *
      * @return  a string representation of this socket.
      */
     public String toString() {
         if (!isBound())
             return "ServerSocket[unbound]";
-        return "ServerSocket[addr=" + impl.getInetAddress() +
+        InetAddress in;
+        if (System.getSecurityManager() != null)
+            in = InetAddress.getLoopbackAddress();
+        else
+            in = impl.getInetAddress();
+        return "ServerSocket[addr=" + in +
                 ",localport=" + impl.getLocalPort()  + "]";
     }
 
--- a/jdk/src/share/classes/java/net/Socket.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/net/Socket.java	Wed Jul 05 19:00:49 2017 +0200
@@ -682,11 +682,18 @@
 
     /**
      * Gets the local address to which the socket is bound.
+     * <p>
+     * If there is a security manager set, its {@code checkConnect} method is
+     * called with the local address and {@code -1} as its arguments to see
+     * if the operation is allowed. If the operation is not allowed,
+     * the {@link InetAddress#getLoopbackAddress loopback} address is returned.
      *
-     * @return the local address to which the socket is bound, or
-     *         the {@link InetAddress#isAnyLocalAddress wildcard} address
-     *         if the socket is closed or not bound yet.
+     * @return the local address to which the socket is bound,
+     *         the loopback address if denied by the security manager, or
+     *         the wildcard address if the socket is closed or not bound yet.
      * @since   JDK1.1
+     *
+     * @see SecurityManager#checkConnect
      */
     public InetAddress getLocalAddress() {
         // This is for backward compatibility
@@ -695,9 +702,14 @@
         InetAddress in = null;
         try {
             in = (InetAddress) getImpl().getOption(SocketOptions.SO_BINDADDR);
+            SecurityManager sm = System.getSecurityManager();
+            if (sm != null)
+                sm.checkConnect(in.getHostAddress(), -1);
             if (in.isAnyLocalAddress()) {
                 in = InetAddress.anyLocalAddress();
             }
+        } catch (SecurityException e) {
+            in = InetAddress.getLoopbackAddress();
         } catch (Exception e) {
             in = InetAddress.anyLocalAddress(); // "0.0.0.0"
         }
@@ -770,8 +782,7 @@
     }
 
     /**
-     * Returns the address of the endpoint this socket is bound to, or
-     * <code>null</code> if it is not bound yet.
+     * Returns the address of the endpoint this socket is bound to.
      * <p>
      * If a socket bound to an endpoint represented by an
      * <code>InetSocketAddress </code> is {@link #close closed},
@@ -780,12 +791,23 @@
      * <code>InetSocketAddress</code>'s address is the
      * {@link InetAddress#isAnyLocalAddress wildcard} address
      * and its port is the local port that it was bound to.
+     * <p>
+     * If there is a security manager set, its {@code checkConnect} method is
+     * called with the local address and {@code -1} as its arguments to see
+     * if the operation is allowed. If the operation is not allowed,
+     * a {@code SocketAddress} representing the
+     * {@link InetAddress#getLoopbackAddress loopback} address and the local
+     * port to which this socket is bound is returned.
      *
-     * @return a <code>SocketAddress</code> representing the local endpoint of this
-     *         socket, or <code>null</code> if it is not bound yet.
+     * @return a {@code SocketAddress} representing the local endpoint of
+     *         this socket, or a {@code SocketAddress} representing the
+     *         loopback address if denied by the security manager, or
+     *         {@code null} if the socket is not bound yet.
+     *
      * @see #getLocalAddress()
      * @see #getLocalPort()
      * @see #bind(SocketAddress)
+     * @see SecurityManager#checkConnect
      * @since 1.4
      */
 
@@ -1086,7 +1108,7 @@
      *  expires, a <B>java.net.SocketTimeoutException</B> is raised, though the
      *  Socket is still valid. The option <B>must</B> be enabled
      *  prior to entering the blocking operation to have effect. The
-     *  timeout must be > 0.
+     *  timeout must be {@code > 0}.
      *  A timeout of zero is interpreted as an infinite timeout.
      *
      * @param timeout the specified timeout, in milliseconds.
@@ -1295,8 +1317,8 @@
      * As the underlying network implementation may ignore this
      * value applications should consider it a hint.
      *
-     * <P> The tc <B>must</B> be in the range <code> 0 <= tc <=
-     * 255</code> or an IllegalArgumentException will be thrown.
+     * <P> The tc <B>must</B> be in the range {@code 0 <= tc <=
+     * 255} or an IllegalArgumentException will be thrown.
      * <p>Notes:
      * <p>For Internet Protocol v4 the value consists of an
      * <code>integer</code>, the least significant 8 bits of which
--- a/jdk/src/share/classes/java/net/SocksSocketImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/net/SocksSocketImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -28,6 +28,7 @@
 import java.io.OutputStream;
 import java.io.BufferedOutputStream;
 import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.security.PrivilegedExceptionAction;
 import sun.net.SocksProxy;
 import sun.net.www.ParseUtil;
@@ -590,7 +591,13 @@
         /* Test for AnyLocal */
         InetAddress naddr = baddr;
         if (naddr.isAnyLocalAddress()) {
-            naddr = cmdsock.getLocalAddress();
+            naddr = AccessController.doPrivileged(
+                        new PrivilegedAction<InetAddress>() {
+                            public InetAddress run() {
+                                return cmdsock.getLocalAddress();
+
+                            }
+                        });
             addr1 = naddr.getAddress();
         }
         out.write(PROTO_VERS4);
--- a/jdk/src/share/classes/java/net/StandardSocketOptions.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/net/StandardSocketOptions.java	Wed Jul 05 19:00:49 2017 +0200
@@ -277,8 +277,8 @@
      * The <em>time-to-live</em> for Internet Protocol (IP) multicast datagrams.
      *
      * <p> The value of this socket option is an {@code Integer} in the range
-     * <tt>0&nbsp;<=&nbsp;value&nbsp;<=&nbsp;255</tt>. It is used to control
-     * the scope of multicast datagrams sent by the datagram-oriented socket.
+     * {@code 0 <= value <= 255}. It is used to control the scope of multicast
+     * datagrams sent by the datagram-oriented socket.
      * In the case of an {@link StandardProtocolFamily#INET IPv4} socket
      * the option is the time-to-live (TTL) on multicast datagrams sent by the
      * socket. Datagrams with a TTL of zero are not transmitted on the network
--- a/jdk/src/share/classes/java/net/URI.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/net/URI.java	Wed Jul 05 19:00:49 2017 +0200
@@ -258,7 +258,7 @@
  *       <td>All <i>alphanum</i> characters together with those in the string
  *        <tt>"_-!.~'()*"</tt></td></tr>
  *   <tr><th valign=top><i>punct</i></th>
- *       <td>The characters in the string <tt>",;:$&+="</tt></td></tr>
+ *       <td>The characters in the string <tt>",;:$&amp;+="</tt></td></tr>
  *   <tr><th valign=top><i>reserved</i></th>
  *       <td>All <i>punct</i> characters together with those in the string
  *        <tt>"?/[]@"</tt></td></tr>
--- a/jdk/src/share/classes/java/net/URLConnection.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/net/URLConnection.java	Wed Jul 05 19:00:49 2017 +0200
@@ -662,7 +662,7 @@
      * Returns the key for the <code>n</code><sup>th</sup> header field.
      * It returns <code>null</code> if there are fewer than <code>n+1</code> fields.
      *
-     * @param   n   an index, where n>=0
+     * @param   n   an index, where {@code n>=0}
      * @return  the key for the <code>n</code><sup>th</sup> header field,
      *          or <code>null</code> if there are fewer than <code>n+1</code>
      *          fields.
@@ -680,7 +680,7 @@
      * {@link #getHeaderFieldKey(int) getHeaderFieldKey} method to iterate through all
      * the headers in the message.
      *
-     * @param   n   an index, where n>=0
+     * @param   n   an index, where {@code n>=0}
      * @return  the value of the <code>n</code><sup>th</sup> header field
      *          or <code>null</code> if there are fewer than <code>n+1</code> fields
      * @see     java.net.URLConnection#getHeaderFieldKey(int)
--- a/jdk/src/share/classes/java/nio/Buffer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/Buffer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -209,7 +209,7 @@
     }
 
     /**
-     * Returns this buffer's capacity. </p>
+     * Returns this buffer's capacity.
      *
      * @return  The capacity of this buffer
      */
@@ -218,7 +218,7 @@
     }
 
     /**
-     * Returns this buffer's position. </p>
+     * Returns this buffer's position.
      *
      * @return  The position of this buffer
      */
@@ -228,7 +228,7 @@
 
     /**
      * Sets this buffer's position.  If the mark is defined and larger than the
-     * new position then it is discarded. </p>
+     * new position then it is discarded.
      *
      * @param  newPosition
      *         The new position value; must be non-negative
@@ -248,7 +248,7 @@
     }
 
     /**
-     * Returns this buffer's limit. </p>
+     * Returns this buffer's limit.
      *
      * @return  The limit of this buffer
      */
@@ -259,7 +259,7 @@
     /**
      * Sets this buffer's limit.  If the position is larger than the new limit
      * then it is set to the new limit.  If the mark is defined and larger than
-     * the new limit then it is discarded. </p>
+     * the new limit then it is discarded.
      *
      * @param  newLimit
      *         The new limit value; must be non-negative
@@ -280,7 +280,7 @@
     }
 
     /**
-     * Sets this buffer's mark at its position. </p>
+     * Sets this buffer's mark at its position.
      *
      * @return  This buffer
      */
@@ -383,7 +383,7 @@
 
     /**
      * Returns the number of elements between the current position and the
-     * limit. </p>
+     * limit.
      *
      * @return  The number of elements remaining in this buffer
      */
@@ -393,7 +393,7 @@
 
     /**
      * Tells whether there are any elements between the current position and
-     * the limit. </p>
+     * the limit.
      *
      * @return  <tt>true</tt> if, and only if, there is at least one element
      *          remaining in this buffer
@@ -403,7 +403,7 @@
     }
 
     /**
-     * Tells whether or not this buffer is read-only. </p>
+     * Tells whether or not this buffer is read-only.
      *
      * @return  <tt>true</tt> if, and only if, this buffer is read-only
      */
@@ -477,7 +477,7 @@
 
     /**
      * Tells whether or not this buffer is
-     * <a href="ByteBuffer.html#direct"><i>direct</i></a>. </p>
+     * <a href="ByteBuffer.html#direct"><i>direct</i></a>.
      *
      * @return  <tt>true</tt> if, and only if, this buffer is direct
      *
@@ -491,7 +491,7 @@
     /**
      * Checks the current position against the limit, throwing a {@link
      * BufferUnderflowException} if it is not smaller than the limit, and then
-     * increments the position. </p>
+     * increments the position.
      *
      * @return  The current position value, before it is incremented
      */
@@ -512,7 +512,7 @@
     /**
      * Checks the current position against the limit, throwing a {@link
      * BufferOverflowException} if it is not smaller than the limit, and then
-     * increments the position. </p>
+     * increments the position.
      *
      * @return  The current position value, before it is incremented
      */
--- a/jdk/src/share/classes/java/nio/ByteOrder.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/ByteOrder.java	Wed Jul 05 19:00:49 2017 +0200
@@ -45,7 +45,6 @@
     /**
      * Constant denoting big-endian byte order.  In this order, the bytes of a
      * multibyte value are ordered from most significant to least significant.
-     * </p>
      */
     public static final ByteOrder BIG_ENDIAN
         = new ByteOrder("BIG_ENDIAN");
@@ -53,7 +52,7 @@
     /**
      * Constant denoting little-endian byte order.  In this order, the bytes of
      * a multibyte value are ordered from least significant to most
-     * significant.  </p>
+     * significant.
      */
     public static final ByteOrder LITTLE_ENDIAN
         = new ByteOrder("LITTLE_ENDIAN");
--- a/jdk/src/share/classes/java/nio/CharBufferSpliterator.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/CharBufferSpliterator.java	Wed Jul 05 19:00:49 2017 +0200
@@ -5,7 +5,7 @@
  * This code is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License version 2 only, as
  * published by the Free Software Foundation.  Oracle designates this
-* particular file as subject to the "Classpath" exception as provided
+ * particular file as subject to the "Classpath" exception as provided
  * by Oracle in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
--- a/jdk/src/share/classes/java/nio/X-Buffer.java.template	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/X-Buffer.java.template	Wed Jul 05 19:00:49 2017 +0200
@@ -551,7 +551,7 @@
 
     /**
      * Relative <i>get</i> method.  Reads the $type$ at this buffer's
-     * current position, and then increments the position. </p>
+     * current position, and then increments the position.
      *
      * @return  The $type$ at the buffer's current position
      *
@@ -581,7 +581,7 @@
 
     /**
      * Absolute <i>get</i> method.  Reads the $type$ at the given
-     * index. </p>
+     * index.
      *
      * @param  index
      *         The index from which the $type$ will be read
@@ -652,12 +652,13 @@
      * <tt>src.get(dst,&nbsp;off,&nbsp;len)</tt> has exactly the same effect as
      * the loop
      *
-     * <pre>
+     * <pre>{@code
      *     for (int i = off; i < off + len; i++)
-     *         dst[i] = src.get(); </pre>
+     *         dst[i] = src.get():
+     * }</pre>
      *
      * except that it first checks that there are sufficient $type$s in
-     * this buffer and it is potentially much more efficient. </p>
+     * this buffer and it is potentially much more efficient.
      *
      * @param  dst
      *         The array into which $type$s are to be written
@@ -738,7 +739,7 @@
      *         dst.put(src.get()); </pre>
      *
      * except that it first checks that there is sufficient space in this
-     * buffer and it is potentially much more efficient. </p>
+     * buffer and it is potentially much more efficient.
      *
      * @param  src
      *         The source buffer from which $type$s are to be read;
@@ -788,12 +789,13 @@
      * <tt>dst.put(src,&nbsp;off,&nbsp;len)</tt> has exactly the same effect as
      * the loop
      *
-     * <pre>
+     * <pre>{@code
      *     for (int i = off; i < off + len; i++)
-     *         dst.put(a[i]); </pre>
+     *         dst.put(a[i]);
+     * }</pre>
      *
      * except that it first checks that there is sufficient space in this
-     * buffer and it is potentially much more efficient. </p>
+     * buffer and it is potentially much more efficient.
      *
      * @param  src
      *         The array from which $type$s are to be read
@@ -874,12 +876,13 @@
      * <tt>dst.put(src,&nbsp;start,&nbsp;end)</tt> has exactly the same effect
      * as the loop
      *
-     * <pre>
+     * <pre>{@code
      *     for (int i = start; i < end; i++)
-     *         dst.put(src.charAt(i)); </pre>
+     *         dst.put(src.charAt(i));
+     * }</pre>
      *
      * except that it first checks that there is sufficient space in this
-     * buffer and it is potentially much more efficient. </p>
+     * buffer and it is potentially much more efficient.
      *
      * @param  src
      *         The string from which $type$s are to be read
@@ -1038,12 +1041,13 @@
      * write was incomplete.  The following loop, for example, copies bytes
      * from one channel to another via the buffer <tt>buf</tt>:
      *
-     * <blockquote><pre>
-     * buf.clear();          // Prepare buffer for use
-     * while (in.read(buf) >= 0 || buf.position != 0) {
-     *     buf.flip();
-     *     out.write(buf);
-     *     buf.compact();    // In case of partial write
+     * <blockquote><pre>{@code
+     *   buf.clear();          // Prepare buffer for use
+     *   while (in.read(buf) >= 0 || buf.position != 0) {
+     *       buf.flip();
+     *       out.write(buf);
+     *       buf.compact();    // In case of partial write
+     *   }
      * }</pre></blockquote>
      *
 #end[byte]
@@ -1056,7 +1060,7 @@
     public abstract $Type$Buffer compact();
 
     /**
-     * Tells whether or not this $type$ buffer is direct. </p>
+     * Tells whether or not this $type$ buffer is direct.
      *
      * @return  <tt>true</tt> if, and only if, this buffer is direct
      */
@@ -1065,7 +1069,7 @@
 #if[!char]
 
     /**
-     * Returns a string summarizing the state of this buffer.  </p>
+     * Returns a string summarizing the state of this buffer.
      *
      * @return  A summary string
      */
@@ -1250,7 +1254,7 @@
 
     /**
      * Reads the character at the given index relative to the current
-     * position. </p>
+     * position.
      *
      * @param  index
      *         The index of the character to be read, relative to the position;
@@ -1448,7 +1452,7 @@
     }
 
     /**
-     * Modifies this buffer's byte order.  </p>
+     * Modifies this buffer's byte order.
      *
      * @param  bo
      *         The new byte order,
--- a/jdk/src/share/classes/java/nio/channels/AsynchronousServerSocketChannel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/AsynchronousServerSocketChannel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -253,7 +253,7 @@
      * <p> To allow for concurrent handling of new connections, the completion
      * handler is not invoked directly by the initiating thread when a new
      * connection is accepted immediately (see <a
-     * href="AsynchronousChannelGroup.html#threading">Threading<a>).
+     * href="AsynchronousChannelGroup.html#threading">Threading</a>).
      *
      * <p> If a security manager has been installed then it verifies that the
      * address and port number of the connection's remote endpoint are permitted
@@ -297,4 +297,25 @@
      *          If this channel's socket has not yet been bound
      */
     public abstract Future<AsynchronousSocketChannel> accept();
+
+    /**
+     * {@inheritDoc}
+     * <p>
+     * If there is a security manager set, its {@code checkConnect} method is
+     * called with the local address and {@code -1} as its arguments to see
+     * if the operation is allowed. If the operation is not allowed,
+     * a {@code SocketAddress} representing the
+     * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
+     * local port of the channel's socket is returned.
+     *
+     * @return  The {@code SocketAddress} that the socket is bound to, or the
+     *          {@code SocketAddress} representing the loopback address if
+     *          denied by the security manager, or {@code null} if the
+     *          channel's socket is not bound
+     *
+     * @throws  ClosedChannelException     {@inheritDoc}
+     * @throws  IOException                {@inheritDoc}
+     */
+    @Override
+    public abstract SocketAddress getLocalAddress() throws IOException;
 }
--- a/jdk/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/AsynchronousSocketChannel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -645,4 +645,24 @@
                                    TimeUnit unit,
                                    A attachment,
                                    CompletionHandler<Long,? super A> handler);
+
+    /**
+     * {@inheritDoc}
+     * <p>
+     * If there is a security manager set, its {@code checkConnect} method is
+     * called with the local address and {@code -1} as its arguments to see
+     * if the operation is allowed. If the operation is not allowed,
+     * a {@code SocketAddress} representing the
+     * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
+     * local port of the channel's socket is returned.
+     *
+     * @return  The {@code SocketAddress} that the socket is bound to, or the
+     *          {@code SocketAddress} representing the loopback address if
+     *          denied by the security manager, or {@code null} if the
+     *          channel's socket is not bound
+     *
+     * @throws  ClosedChannelException     {@inheritDoc}
+     * @throws  IOException                {@inheritDoc}
+     */
+    public abstract SocketAddress getLocalAddress() throws IOException;
 }
--- a/jdk/src/share/classes/java/nio/channels/Channel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/Channel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -56,7 +56,7 @@
 public interface Channel extends Closeable {
 
     /**
-     * Tells whether or not this channel is open.  </p>
+     * Tells whether or not this channel is open.
      *
      * @return <tt>true</tt> if, and only if, this channel is open
      */
--- a/jdk/src/share/classes/java/nio/channels/DatagramChannel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/DatagramChannel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -565,4 +565,25 @@
         return write(srcs, 0, srcs.length);
     }
 
+    /**
+     * {@inheritDoc}
+     * <p>
+     * If there is a security manager set, its {@code checkConnect} method is
+     * called with the local address and {@code -1} as its arguments to see
+     * if the operation is allowed. If the operation is not allowed,
+     * a {@code SocketAddress} representing the
+     * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
+     * local port of the channel's socket is returned.
+     *
+     * @return  The {@code SocketAddress} that the socket is bound to, or the
+     *          {@code SocketAddress} representing the loopback address if
+     *          denied by the security manager, or {@code null} if the
+     *          channel's socket is not bound
+     *
+     * @throws  ClosedChannelException     {@inheritDoc}
+     * @throws  IOException                {@inheritDoc}
+     */
+    @Override
+    public abstract SocketAddress getLocalAddress() throws IOException;
+
 }
--- a/jdk/src/share/classes/java/nio/channels/FileChannel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/FileChannel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -418,7 +418,7 @@
     // -- Other operations --
 
     /**
-     * Returns this channel's file position.  </p>
+     * Returns this channel's file position.
      *
      * @return  This channel's file position,
      *          a non-negative integer counting the number of bytes
@@ -461,7 +461,7 @@
     public abstract FileChannel position(long newPosition) throws IOException;
 
     /**
-     * Returns the current size of this channel's file.  </p>
+     * Returns the current size of this channel's file.
      *
      * @return  The current size of this channel's file,
      *          measured in bytes
--- a/jdk/src/share/classes/java/nio/channels/FileLock.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/FileLock.java	Wed Jul 05 19:00:49 2017 +0200
@@ -124,7 +124,7 @@
     private final boolean shared;
 
     /**
-     * Initializes a new instance of this class.  </p>
+     * Initializes a new instance of this class.
      *
      * @param  channel
      *         The file channel upon whose file this lock is held
@@ -249,7 +249,7 @@
     }
 
     /**
-     * Tells whether this lock is shared.  </p>
+     * Tells whether this lock is shared.
      *
      * @return <tt>true</tt> if lock is shared,
      *         <tt>false</tt> if it is exclusive
@@ -259,7 +259,7 @@
     }
 
     /**
-     * Tells whether or not this lock overlaps the given lock range.  </p>
+     * Tells whether or not this lock overlaps the given lock range.
      *
      * @return  <tt>true</tt> if, and only if, this lock and the given lock
      *          range overlap by at least one byte
--- a/jdk/src/share/classes/java/nio/channels/NetworkChannel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/NetworkChannel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -87,8 +87,7 @@
     NetworkChannel bind(SocketAddress local) throws IOException;
 
     /**
-     * Returns the socket address that this channel's socket is bound to, or
-     * {@code null} if the socket is not bound.
+     * Returns the socket address that this channel's socket is bound to.
      *
      * <p> Where the channel is {@link #bind bound} to an Internet Protocol
      * socket address then the return value from this method is of type {@link
--- a/jdk/src/share/classes/java/nio/channels/Pipe.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/Pipe.java	Wed Jul 05 19:00:49 2017 +0200
@@ -53,7 +53,7 @@
 public abstract class Pipe {
 
     /**
-     * A channel representing the readable end of a {@link Pipe}.  </p>
+     * A channel representing the readable end of a {@link Pipe}.
      *
      * @since 1.4
      */
@@ -84,7 +84,7 @@
     }
 
     /**
-     * A channel representing the writable end of a {@link Pipe}.  </p>
+     * A channel representing the writable end of a {@link Pipe}.
      *
      * @since 1.4
      */
@@ -120,14 +120,14 @@
     protected Pipe() { }
 
     /**
-     * Returns this pipe's source channel.  </p>
+     * Returns this pipe's source channel.
      *
      * @return  This pipe's source channel
      */
     public abstract SourceChannel source();
 
     /**
-     * Returns this pipe's sink channel.  </p>
+     * Returns this pipe's sink channel.
      *
      * @return  This pipe's sink channel
      */
--- a/jdk/src/share/classes/java/nio/channels/SelectableChannel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/SelectableChannel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -111,7 +111,7 @@
      * identifying this channel's supported operations.  The bits that are set
      * in this integer value denote exactly the operations that are valid for
      * this channel.  This method always returns the same value for a given
-     * concrete channel class. </p>
+     * concrete channel class.
      *
      * @return  The valid-operation set
      */
@@ -140,7 +140,7 @@
 
     /**
      * Retrieves the key representing the channel's registration with the given
-     * selector.  </p>
+     * selector.
      *
      * @return  The key returned when this channel was last registered with the
      *          given selector, or <tt>null</tt> if this channel is not
@@ -208,7 +208,7 @@
      * @throws  IllegalArgumentException
      *          If a bit in the <tt>ops</tt> set does not correspond to an
      *          operation that is supported by this channel, that is, if
-     *          <tt>set & ~validOps() != 0</tt>
+     *          {@code set & ~validOps() != 0}
      *
      * @return  A key representing the registration of this channel with
      *          the given selector
@@ -265,8 +265,8 @@
      *
      * @throws  IllegalArgumentException
      *          If a bit in <tt>ops</tt> does not correspond to an operation
-     *          that is supported by this channel, that is, if <tt>set &
-     *          ~validOps() != 0</tt>
+     *          that is supported by this channel, that is, if {@code set &
+     *          ~validOps() != 0}
      *
      * @return  A key representing the registration of this channel with
      *          the given selector
@@ -333,7 +333,6 @@
      * configureBlocking} and {@link #register register} methods synchronize.
      * This is often useful in the implementation of adaptors that require a
      * specific blocking mode to be maintained for a short period of time.
-     * </p>
      *
      * @return  The blocking-mode lock object
      */
--- a/jdk/src/share/classes/java/nio/channels/SelectionKey.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/SelectionKey.java	Wed Jul 05 19:00:49 2017 +0200
@@ -119,7 +119,7 @@
 
     /**
      * Returns the channel for which this key was created.  This method will
-     * continue to return the channel even after the key is cancelled.  </p>
+     * continue to return the channel even after the key is cancelled.
      *
      * @return  This key's channel
      */
@@ -127,7 +127,7 @@
 
     /**
      * Returns the selector for which this key was created.  This method will
-     * continue to return the selector even after the key is cancelled.  </p>
+     * continue to return the selector even after the key is cancelled.
      *
      * @return  This key's selector
      */
@@ -191,7 +191,7 @@
      * @throws  IllegalArgumentException
      *          If a bit in the set does not correspond to an operation that
      *          is supported by this key's channel, that is, if
-     *          <tt>(ops & ~channel().validOps()) != 0</tt>
+     *          {@code (ops & ~channel().validOps()) != 0}
      *
      * @throws  CancelledKeyException
      *          If this key has been cancelled
@@ -228,7 +228,7 @@
     public static final int OP_READ = 1 << 0;
 
     /**
-     * Operation-set bit for write operations.  </p>
+     * Operation-set bit for write operations.
      *
      * <p> Suppose that a selection key's interest set contains
      * <tt>OP_WRITE</tt> at the start of a <a
@@ -241,7 +241,7 @@
     public static final int OP_WRITE = 1 << 2;
 
     /**
-     * Operation-set bit for socket-connect operations.  </p>
+     * Operation-set bit for socket-connect operations.
      *
      * <p> Suppose that a selection key's interest set contains
      * <tt>OP_CONNECT</tt> at the start of a <a
@@ -254,7 +254,7 @@
     public static final int OP_CONNECT = 1 << 3;
 
     /**
-     * Operation-set bit for socket-accept operations.  </p>
+     * Operation-set bit for socket-accept operations.
      *
      * <p> Suppose that a selection key's interest set contains
      * <tt>OP_ACCEPT</tt> at the start of a <a
@@ -272,15 +272,15 @@
      * <p> An invocation of this method of the form <tt>k.isReadable()</tt>
      * behaves in exactly the same way as the expression
      *
-     * <blockquote><pre>
-     * k.readyOps()&nbsp;&amp;&nbsp;OP_READ&nbsp;!=&nbsp;0</pre></blockquote>
+     * <blockquote><pre>{@code
+     * k.readyOps() & OP_READ != 0
+     * }</pre></blockquote>
      *
      * <p> If this key's channel does not support read operations then this
      * method always returns <tt>false</tt>.  </p>
      *
      * @return  <tt>true</tt> if, and only if,
-     *          <tt>readyOps()</tt>&nbsp;<tt>&</tt>&nbsp;<tt>OP_READ</tt> is
-     *          nonzero
+                {@code readyOps() & OP_READ} is nonzero
      *
      * @throws  CancelledKeyException
      *          If this key has been cancelled
@@ -295,15 +295,15 @@
      * <p> An invocation of this method of the form <tt>k.isWritable()</tt>
      * behaves in exactly the same way as the expression
      *
-     * <blockquote><pre>
-     * k.readyOps()&nbsp;&amp;&nbsp;OP_WRITE&nbsp;!=&nbsp;0</pre></blockquote>
+     * <blockquote><pre>{@code
+     * k.readyOps() & OP_WRITE != 0
+     * }</pre></blockquote>
      *
      * <p> If this key's channel does not support write operations then this
      * method always returns <tt>false</tt>.  </p>
      *
      * @return  <tt>true</tt> if, and only if,
-     *          <tt>readyOps()</tt>&nbsp;<tt>&</tt>&nbsp;<tt>OP_WRITE</tt>
-     *          is nonzero
+     *          {@code readyOps() & OP_WRITE} is nonzero
      *
      * @throws  CancelledKeyException
      *          If this key has been cancelled
@@ -319,15 +319,15 @@
      * <p> An invocation of this method of the form <tt>k.isConnectable()</tt>
      * behaves in exactly the same way as the expression
      *
-     * <blockquote><pre>
-     * k.readyOps()&nbsp;&amp;&nbsp;OP_CONNECT&nbsp;!=&nbsp;0</pre></blockquote>
+     * <blockquote><pre>{@code
+     * k.readyOps() & OP_CONNECT != 0
+     * }</pre></blockquote>
      *
      * <p> If this key's channel does not support socket-connect operations
      * then this method always returns <tt>false</tt>.  </p>
      *
      * @return  <tt>true</tt> if, and only if,
-     *          <tt>readyOps()</tt>&nbsp;<tt>&</tt>&nbsp;<tt>OP_CONNECT</tt>
-     *          is nonzero
+     *          {@code readyOps() & OP_CONNECT} is nonzero
      *
      * @throws  CancelledKeyException
      *          If this key has been cancelled
@@ -343,15 +343,15 @@
      * <p> An invocation of this method of the form <tt>k.isAcceptable()</tt>
      * behaves in exactly the same way as the expression
      *
-     * <blockquote><pre>
-     * k.readyOps()&nbsp;&amp;&nbsp;OP_ACCEPT&nbsp;!=&nbsp;0</pre></blockquote>
+     * <blockquote><pre>{@code
+     * k.readyOps() & OP_ACCEPT != 0
+     * }</pre></blockquote>
      *
      * <p> If this key's channel does not support socket-accept operations then
      * this method always returns <tt>false</tt>.  </p>
      *
      * @return  <tt>true</tt> if, and only if,
-     *          <tt>readyOps()</tt>&nbsp;<tt>&</tt>&nbsp;<tt>OP_ACCEPT</tt>
-     *          is nonzero
+     *          {@code readyOps() & OP_ACCEPT} is nonzero
      *
      * @throws  CancelledKeyException
      *          If this key has been cancelled
@@ -389,7 +389,7 @@
     }
 
     /**
-     * Retrieves the current attachment.  </p>
+     * Retrieves the current attachment.
      *
      * @return  The object currently attached to this key,
      *          or <tt>null</tt> if there is no attachment
--- a/jdk/src/share/classes/java/nio/channels/Selector.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/Selector.java	Wed Jul 05 19:00:49 2017 +0200
@@ -228,14 +228,14 @@
     }
 
     /**
-     * Tells whether or not this selector is open.  </p>
+     * Tells whether or not this selector is open.
      *
      * @return <tt>true</tt> if, and only if, this selector is open
      */
     public abstract boolean isOpen();
 
     /**
-     * Returns the provider that created this channel.  </p>
+     * Returns the provider that created this channel.
      *
      * @return  The provider that created this channel
      */
--- a/jdk/src/share/classes/java/nio/channels/ServerSocketChannel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/ServerSocketChannel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -265,4 +265,25 @@
      */
     public abstract SocketChannel accept() throws IOException;
 
+    /**
+     * {@inheritDoc}
+     * <p>
+     * If there is a security manager set, its {@code checkConnect} method is
+     * called with the local address and {@code -1} as its arguments to see
+     * if the operation is allowed. If the operation is not allowed,
+     * a {@code SocketAddress} representing the
+     * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
+     * local port of the channel's socket is returned.
+     *
+     * @return  The {@code SocketAddress} that the socket is bound to, or the
+     *          {@code SocketAddress} representing the loopback address if
+     *          denied by the security manager, or {@code null} if the
+     *          channel's socket is not bound
+     *
+     * @throws  ClosedChannelException     {@inheritDoc}
+     * @throws  IOException                {@inheritDoc}
+     */
+    @Override
+    public abstract SocketAddress getLocalAddress() throws IOException;
+
 }
--- a/jdk/src/share/classes/java/nio/channels/SocketChannel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/SocketChannel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -302,7 +302,7 @@
 
     /**
      * Tells whether or not a connection operation is in progress on this
-     * channel.  </p>
+     * channel.
      *
      * @return  <tt>true</tt> if, and only if, a connection operation has been
      *          initiated on this channel but not yet completed by invoking the
@@ -493,4 +493,25 @@
         return write(srcs, 0, srcs.length);
     }
 
+    /**
+     * {@inheritDoc}
+     * <p>
+     * If there is a security manager set, its {@code checkConnect} method is
+     * called with the local address and {@code -1} as its arguments to see
+     * if the operation is allowed. If the operation is not allowed,
+     * a {@code SocketAddress} representing the
+     * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
+     * local port of the channel's socket is returned.
+     *
+     * @return  The {@code SocketAddress} that the socket is bound to, or the
+     *          {@code SocketAddress} representing the loopback address if
+     *          denied by the security manager, or {@code null} if the
+     *          channel's socket is not bound
+     *
+     * @throws  ClosedChannelException     {@inheritDoc}
+     * @throws  IOException                {@inheritDoc}
+     */
+    @Override
+    public abstract SocketAddress getLocalAddress() throws IOException;
+
 }
--- a/jdk/src/share/classes/java/nio/channels/spi/AbstractSelectionKey.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/spi/AbstractSelectionKey.java	Wed Jul 05 19:00:49 2017 +0200
@@ -43,7 +43,7 @@
 {
 
     /**
-     * Initializes a new instance of this class.  </p>
+     * Initializes a new instance of this class.
      */
     protected AbstractSelectionKey() { }
 
--- a/jdk/src/share/classes/java/nio/channels/spi/AbstractSelector.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/spi/AbstractSelector.java	Wed Jul 05 19:00:49 2017 +0200
@@ -76,7 +76,7 @@
     private final SelectorProvider provider;
 
     /**
-     * Initializes a new instance of this class.  </p>
+     * Initializes a new instance of this class.
      */
     protected AbstractSelector(SelectorProvider provider) {
         this.provider = provider;
--- a/jdk/src/share/classes/java/nio/channels/spi/SelectorProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/channels/spi/SelectorProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -72,7 +72,7 @@
     private static SelectorProvider provider = null;
 
     /**
-     * Initializes a new instance of this class.  </p>
+     * Initializes a new instance of this class.
      *
      * @throws  SecurityException
      *          If a security manager has been installed and it denies
@@ -180,7 +180,7 @@
     }
 
     /**
-     * Opens a datagram channel.  </p>
+     * Opens a datagram channel.
      *
      * @return  The new channel
      */
@@ -206,7 +206,7 @@
         throws IOException;
 
     /**
-     * Opens a pipe. </p>
+     * Opens a pipe.
      *
      * @return  The new pipe
      */
@@ -214,7 +214,7 @@
         throws IOException;
 
     /**
-     * Opens a selector.  </p>
+     * Opens a selector.
      *
      * @return  The new selector
      */
@@ -222,7 +222,7 @@
         throws IOException;
 
     /**
-     * Opens a server-socket channel.  </p>
+     * Opens a server-socket channel.
      *
      * @return  The new channel
      */
@@ -230,7 +230,7 @@
         throws IOException;
 
     /**
-     * Opens a socket channel. </p>
+     * Opens a socket channel.
      *
      * @return  The new channel
      */
--- a/jdk/src/share/classes/java/nio/charset/Charset-X-Coder.java.template	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/charset/Charset-X-Coder.java.template	Wed Jul 05 19:00:49 2017 +0200
@@ -161,7 +161,7 @@
 
     /**
      * Initializes a new $coder$.  The new $coder$ will have the given
-     * $otypes-per-itype$ and replacement values. </p>
+     * $otypes-per-itype$ and replacement values.
      *
      * @param  average$ItypesPerOtype$
      *         A positive float value indicating the expected number of
@@ -207,7 +207,7 @@
     /**
      * Initializes a new $coder$.  The new $coder$ will have the given
      * $otypes-per-itype$ values and its replacement will be the
-     * $replTypeName$ $defaultReplName$. </p>
+     * $replTypeName$ $defaultReplName$.
      *
      * @param  average$ItypesPerOtype$
      *         A positive float value indicating the expected number of
@@ -230,7 +230,7 @@
     }
 
     /**
-     * Returns the charset that created this $coder$.  </p>
+     * Returns the charset that created this $coder$.
      *
      * @return  This $coder$'s charset
      */
@@ -239,7 +239,7 @@
     }
 
     /**
-     * Returns this $coder$'s replacement value. </p>
+     * Returns this $coder$'s replacement value.
      *
      * @return  This $coder$'s current replacement,
      *          which is never <tt>null</tt> and is never empty
@@ -260,7 +260,7 @@
      * method, passing the new replacement, after checking that the new
      * replacement is acceptable.  </p>
      *
-     * @param  newReplacement
+     * @param  newReplacement  The replacement value
      *
 #if[decoder]
      *         The new replacement; must not be <tt>null</tt>
@@ -305,7 +305,7 @@
      * should be overridden by $coder$s that require notification of changes to
      * the replacement.  </p>
      *
-     * @param  newReplacement
+     * @param  newReplacement    The replacement value
      */
     protected void implReplaceWith($replType$ newReplacement) {
     }
@@ -351,7 +351,7 @@
 #end[encoder]
 
     /**
-     * Returns this $coder$'s current action for malformed-input errors.  </p>
+     * Returns this $coder$'s current action for malformed-input errors.
      *
      * @return The current malformed-input action, which is never <tt>null</tt>
      */
@@ -360,7 +360,7 @@
     }
 
     /**
-     * Changes this $coder$'s action for malformed-input errors.  </p>
+     * Changes this $coder$'s action for malformed-input errors.
      *
      * <p> This method invokes the {@link #implOnMalformedInput
      * implOnMalformedInput} method, passing the new action.  </p>
@@ -391,7 +391,6 @@
 
     /**
      * Returns this $coder$'s current action for unmappable-character errors.
-     * </p>
      *
      * @return The current unmappable-character action, which is never
      *         <tt>null</tt>
@@ -435,7 +434,7 @@
     /**
      * Returns the average number of $otype$s that will be produced for each
      * $itype$ of input.  This heuristic value may be used to estimate the size
-     * of the output buffer required for a given input sequence. </p>
+     * of the output buffer required for a given input sequence.
      *
      * @return  The average number of $otype$s produced
      *          per $itype$ of input
@@ -447,7 +446,7 @@
     /**
      * Returns the maximum number of $otype$s that will be produced for each
      * $itype$ of input.  This value may be used to compute the worst-case size
-     * of the output buffer required for a given input sequence. </p>
+     * of the output buffer required for a given input sequence.
      *
      * @return  The maximum number of $otype$s that will be produced per
      *          $itype$ of input
--- a/jdk/src/share/classes/java/nio/charset/Charset.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/charset/Charset.java	Wed Jul 05 19:00:49 2017 +0200
@@ -490,7 +490,7 @@
     }
 
     /**
-     * Tells whether the named charset is supported. </p>
+     * Tells whether the named charset is supported.
      *
      * @param  charsetName
      *         The name of the requested charset; may be either
@@ -510,7 +510,7 @@
     }
 
     /**
-     * Returns a charset object for the named charset. </p>
+     * Returns a charset object for the named charset.
      *
      * @param  charsetName
      *         The name of the requested charset; may be either
@@ -629,7 +629,7 @@
 
     /**
      * Initializes a new charset with the given canonical name and alias
-     * set. </p>
+     * set.
      *
      * @param  canonicalName
      *         The canonical name of this charset
@@ -650,7 +650,7 @@
     }
 
     /**
-     * Returns this charset's canonical name. </p>
+     * Returns this charset's canonical name.
      *
      * @return  The canonical name of this charset
      */
@@ -659,7 +659,7 @@
     }
 
     /**
-     * Returns a set containing this charset's aliases. </p>
+     * Returns a set containing this charset's aliases.
      *
      * @return  An immutable set of this charset's aliases
      */
@@ -690,7 +690,7 @@
     /**
      * Tells whether or not this charset is registered in the <a
      * href="http://www.iana.org/assignments/character-sets">IANA Charset
-     * Registry</a>.  </p>
+     * Registry</a>.
      *
      * @return  <tt>true</tt> if, and only if, this charset is known by its
      *          implementor to be registered with the IANA
@@ -742,14 +742,14 @@
     public abstract boolean contains(Charset cs);
 
     /**
-     * Constructs a new decoder for this charset. </p>
+     * Constructs a new decoder for this charset.
      *
      * @return  A new decoder for this charset
      */
     public abstract CharsetDecoder newDecoder();
 
     /**
-     * Constructs a new encoder for this charset. </p>
+     * Constructs a new encoder for this charset.
      *
      * @return  A new encoder for this charset
      *
@@ -881,7 +881,7 @@
     }
 
     /**
-     * Computes a hashcode for this charset. </p>
+     * Computes a hashcode for this charset.
      *
      * @return  An integer hashcode
      */
@@ -907,7 +907,7 @@
     }
 
     /**
-     * Returns a string describing this charset. </p>
+     * Returns a string describing this charset.
      *
      * @return  A string describing this charset
      */
--- a/jdk/src/share/classes/java/nio/charset/CoderResult.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/charset/CoderResult.java	Wed Jul 05 19:00:49 2017 +0200
@@ -71,7 +71,7 @@
  *
  * </ul>
  *
- * For convenience, the {@link #isError() isError} method returns <tt>true</tt>
+ * <p> For convenience, the {@link #isError() isError} method returns <tt>true</tt>
  * for result objects that describe malformed-input and unmappable-character
  * errors but <tt>false</tt> for those that describe underflow or overflow
  * conditions.  </p>
@@ -112,7 +112,7 @@
     }
 
     /**
-     * Tells whether or not this object describes an underflow condition.  </p>
+     * Tells whether or not this object describes an underflow condition.
      *
      * @return  <tt>true</tt> if, and only if, this object denotes underflow
      */
@@ -121,7 +121,7 @@
     }
 
     /**
-     * Tells whether or not this object describes an overflow condition.  </p>
+     * Tells whether or not this object describes an overflow condition.
      *
      * @return  <tt>true</tt> if, and only if, this object denotes overflow
      */
@@ -130,7 +130,7 @@
     }
 
     /**
-     * Tells whether or not this object describes an error condition.  </p>
+     * Tells whether or not this object describes an error condition.
      *
      * @return  <tt>true</tt> if, and only if, this object denotes either a
      *          malformed-input error or an unmappable-character error
@@ -141,7 +141,6 @@
 
     /**
      * Tells whether or not this object describes a malformed-input error.
-     * </p>
      *
      * @return  <tt>true</tt> if, and only if, this object denotes a
      *          malformed-input error
@@ -152,7 +151,7 @@
 
     /**
      * Tells whether or not this object describes an unmappable-character
-     * error.  </p>
+     * error.
      *
      * @return  <tt>true</tt> if, and only if, this object denotes an
      *          unmappable-character error
@@ -163,7 +162,7 @@
 
     /**
      * Returns the length of the erroneous input described by this
-     * object&nbsp;&nbsp;<i>(optional operation)</i>.  </p>
+     * object&nbsp;&nbsp;<i>(optional operation)</i>.
      *
      * @return  The length of the erroneous input, a positive integer
      *
@@ -180,14 +179,14 @@
     /**
      * Result object indicating underflow, meaning that either the input buffer
      * has been completely consumed or, if the input buffer is not yet empty,
-     * that additional input is required.  </p>
+     * that additional input is required.
      */
     public static final CoderResult UNDERFLOW
         = new CoderResult(CR_UNDERFLOW, 0);
 
     /**
      * Result object indicating overflow, meaning that there is insufficient
-     * room in the output buffer.  </p>
+     * room in the output buffer.
      */
     public static final CoderResult OVERFLOW
         = new CoderResult(CR_OVERFLOW, 0);
@@ -226,7 +225,7 @@
 
     /**
      * Static factory method that returns the unique object describing a
-     * malformed-input error of the given length.  </p>
+     * malformed-input error of the given length.
      *
      * @return  The requested coder-result object
      */
@@ -242,7 +241,7 @@
 
     /**
      * Static factory method that returns the unique result object describing
-     * an unmappable-character error of the given length.  </p>
+     * an unmappable-character error of the given length.
      *
      * @return  The requested coder-result object
      */
@@ -252,7 +251,6 @@
 
     /**
      * Throws an exception appropriate to the result described by this object.
-     * </p>
      *
      * @throws  BufferUnderflowException
      *          If this object is {@link #UNDERFLOW}
--- a/jdk/src/share/classes/java/nio/charset/CodingErrorAction.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/charset/CodingErrorAction.java	Wed Jul 05 19:00:49 2017 +0200
@@ -50,7 +50,7 @@
 
     /**
      * Action indicating that a coding error is to be handled by dropping the
-     * erroneous input and resuming the coding operation.  </p>
+     * erroneous input and resuming the coding operation.
      */
     public static final CodingErrorAction IGNORE
         = new CodingErrorAction("IGNORE");
@@ -58,7 +58,7 @@
     /**
      * Action indicating that a coding error is to be handled by dropping the
      * erroneous input, appending the coder's replacement value to the output
-     * buffer, and resuming the coding operation.  </p>
+     * buffer, and resuming the coding operation.
      */
     public static final CodingErrorAction REPLACE
         = new CodingErrorAction("REPLACE");
@@ -73,7 +73,7 @@
         = new CodingErrorAction("REPORT");
 
     /**
-     * Returns a string describing this action.  </p>
+     * Returns a string describing this action.
      *
      * @return  A descriptive string
      */
--- a/jdk/src/share/classes/java/nio/charset/UnmappableCharacterException.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/charset/UnmappableCharacterException.java	Wed Jul 05 19:00:49 2017 +0200
@@ -29,7 +29,7 @@
 /**
  * Checked exception thrown when an input character (or byte) sequence
  * is valid but cannot be mapped to an output byte (or character)
- * sequence.  </p>
+ * sequence.
  *
  * @since 1.4
  */
--- a/jdk/src/share/classes/java/nio/charset/spi/CharsetProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/charset/spi/CharsetProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -72,7 +72,7 @@
 public abstract class CharsetProvider {
 
     /**
-     * Initializes a new charset provider. </p>
+     * Initializes a new charset provider.
      *
      * @throws  SecurityException
      *          If a security manager has been installed and it denies
@@ -88,14 +88,14 @@
      * Creates an iterator that iterates over the charsets supported by this
      * provider.  This method is used in the implementation of the {@link
      * java.nio.charset.Charset#availableCharsets Charset.availableCharsets}
-     * method. </p>
+     * method.
      *
      * @return  The new iterator
      */
     public abstract Iterator<Charset> charsets();
 
     /**
-     * Retrieves a charset for the given charset name. </p>
+     * Retrieves a charset for the given charset name.
      *
      * @param  charsetName
      *         The name of the requested charset; may be either
--- a/jdk/src/share/classes/java/nio/file/Files.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/file/Files.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1494,10 +1494,19 @@
     // lazy loading of default and installed file type detectors
     private static class FileTypeDetectors{
         static final FileTypeDetector defaultFileTypeDetector =
-            sun.nio.fs.DefaultFileTypeDetector.create();
+            createDefaultFileTypeDetector();
         static final List<FileTypeDetector> installeDetectors =
             loadInstalledDetectors();
 
+        // creates the default file type detector
+        private static FileTypeDetector createDefaultFileTypeDetector() {
+            return AccessController
+                .doPrivileged(new PrivilegedAction<FileTypeDetector>() {
+                    @Override public FileTypeDetector run() {
+                        return sun.nio.fs.DefaultFileTypeDetector.create();
+                }});
+        }
+
         // loads all installed file type detectors
         private static List<FileTypeDetector> loadInstalledDetectors() {
             return AccessController
--- a/jdk/src/share/classes/java/nio/file/Path.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/nio/file/Path.java	Wed Jul 05 19:00:49 2017 +0200
@@ -64,7 +64,7 @@
  * those developing custom file system implementations. Methods may be added to
  * this interface in future releases. </p>
  *
- * <a name="interop"><h4>Accessing Files</h4></a>
+ * <h4>Accessing Files</h4>
  * <p> Paths may be used with the {@link Files} class to operate on files,
  * directories, and other types of files. For example, suppose we want a {@link
  * java.io.BufferedReader} to read text from a file "{@code access.log}". The
@@ -87,7 +87,7 @@
  * addition, the {@link #toFile toFile} method is useful to construct a {@code
  * File} from the {@code String} representation of a {@code Path}.
  *
- * <h4>Concurrency</h4></a>
+ * <h4>Concurrency</h4>
  * <p> Implementations of this interface are immutable and safe for use by
  * multiple concurrent threads.
  *
--- a/jdk/src/share/classes/java/rmi/dgc/VMID.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/rmi/dgc/VMID.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,10 +25,8 @@
 
 package java.rmi.dgc;
 
-import java.io.*;
-import java.net.*;
 import java.rmi.server.UID;
-import java.security.*;
+import java.security.SecureRandom;
 
 /**
  * A VMID is a identifier that is unique across all Java virtual
@@ -39,9 +37,8 @@
  * @author      Peter Jones
  */
 public final class VMID implements java.io.Serializable {
-
-    /** array of bytes uniquely identifying this host */
-    private static byte[] localAddr = computeAddressHash();
+    /** Array of bytes uniquely identifying this host */
+    private static final byte[] randomBytes;
 
     /**
      * @serial array of bytes uniquely identifying host created on
@@ -56,6 +53,14 @@
     /** indicate compatibility with JDK 1.1.x version of class */
     private static final long serialVersionUID = -538642295484486218L;
 
+    static {
+        // Generate 8 bytes of random data.
+        SecureRandom secureRandom = new SecureRandom();
+        byte bytes[] = new byte[8];
+        secureRandom.nextBytes(bytes);
+        randomBytes = bytes;
+    }
+
     /**
      * Create a new VMID.  Each new VMID returned from this constructor
      * is unique for all Java virtual machines under the following
@@ -65,7 +70,7 @@
      * for the lifetime of this object.  <p>
      */
     public VMID() {
-        addr = localAddr;
+        addr = randomBytes;
         uid = new UID();
     }
 
@@ -126,52 +131,4 @@
         result.append(uid.toString());
         return result.toString();
     }
-
-    /**
-     * Compute the hash an IP address.  The hash is the first 8 bytes
-     * of the SHA digest of the IP address.
-     */
-    private static byte[] computeAddressHash() {
-
-        /*
-         * Get the local host's IP address.
-         */
-        byte[] addr = java.security.AccessController.doPrivileged(
-            new PrivilegedAction<byte[]>() {
-            public byte[] run() {
-                try {
-                    return InetAddress.getLocalHost().getAddress();
-                } catch (Exception e) {
-                }
-                return new byte[] { 0, 0, 0, 0 };
-            }
-        });
-
-        byte[] addrHash;
-        final int ADDR_HASH_LENGTH = 8;
-
-        try {
-            /*
-             * Calculate message digest of IP address using SHA.
-             */
-            MessageDigest md = MessageDigest.getInstance("SHA");
-            ByteArrayOutputStream sink = new ByteArrayOutputStream(64);
-            DataOutputStream out = new DataOutputStream(
-                new DigestOutputStream(sink, md));
-            out.write(addr, 0, addr.length);
-            out.flush();
-
-            byte digest[] = md.digest();
-            int hashlength = Math.min(ADDR_HASH_LENGTH, digest.length);
-            addrHash = new byte[hashlength];
-            System.arraycopy(digest, 0, addrHash, 0, hashlength);
-
-        } catch (IOException ignore) {
-            /* can't happen, but be deterministic anyway. */
-            addrHash = new byte[0];
-        } catch (NoSuchAlgorithmException complain) {
-            throw new InternalError(complain.toString(), complain);
-        }
-        return addrHash;
-    }
 }
--- a/jdk/src/share/classes/java/security/AccessControlContext.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/security/AccessControlContext.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -77,7 +77,10 @@
 public final class AccessControlContext {
 
     private ProtectionDomain context[];
+    // isPrivileged and isAuthorized are referenced by the VM - do not remove
+    // or change their names
     private boolean isPrivileged;
+    private boolean isAuthorized = false;
 
     // Note: This field is directly used by the virtual machine
     // native codes. Don't touch it.
@@ -172,6 +175,7 @@
         SecurityManager sm = System.getSecurityManager();
         if (sm != null) {
             sm.checkPermission(SecurityConstants.CREATE_ACC_PERMISSION);
+            this.isAuthorized = true;
         }
 
         this.context = acc.context;
@@ -257,6 +261,7 @@
             this.parent = parent;
             this.privilegedContext = context; // used in checkPermission2()
         }
+        this.isAuthorized = true;
     }
 
 
@@ -265,10 +270,11 @@
      */
 
     AccessControlContext(ProtectionDomain context[],
-                                 boolean isPrivileged)
+                         boolean isPrivileged)
     {
         this.context = context;
         this.isPrivileged = isPrivileged;
+        this.isAuthorized = true;
     }
 
     /**
--- a/jdk/src/share/classes/java/security/AccessController.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/security/AccessController.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -329,28 +329,31 @@
 
 
     /**
-     * Performs the specified <code>PrivilegedAction</code> with privileges
-     * enabled and restricted by the specified
-     * <code>AccessControlContext</code>.
+     * Performs the specified {@code PrivilegedAction} with privileges
+     * enabled and restricted by the specified {@code AccessControlContext}.
      * The action is performed with the intersection of the permissions
      * possessed by the caller's protection domain, and those possessed
-     * by the domains represented by the specified
-     * <code>AccessControlContext</code>.
+     * by the domains represented by the specified {@code AccessControlContext}.
+     * <p>
+     * If the action's {@code run} method throws an (unchecked) exception,
+     * it will propagate through this method.
      * <p>
-     * If the action's <code>run</code> method throws an (unchecked) exception,
-     * it will propagate through this method.
+     * If a security manager is installed and the {@code AccessControlContext}
+     * was not created by system code and the caller's {@code ProtectionDomain}
+     * has not been granted the {@literal "createAccessControlContext"}
+     * {@link java.security.SecurityPermission}, then the action is performed
+     * with no permissions.
      *
      * @param action the action to be performed.
      * @param context an <i>access control context</i>
      *                representing the restriction to be applied to the
      *                caller's domain's privileges before performing
      *                the specified action.  If the context is
-     *                <code>null</code>,
-     *                then no additional restriction is applied.
+     *                {@code null}, then no additional restriction is applied.
      *
-     * @return the value returned by the action's <code>run</code> method.
+     * @return the value returned by the action's {@code run} method.
      *
-     * @exception NullPointerException if the action is <code>null</code>
+     * @exception NullPointerException if the action is {@code null}
      *
      * @see #doPrivileged(PrivilegedAction)
      * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext)
@@ -566,30 +569,34 @@
     }
 
     /**
-     * Performs the specified <code>PrivilegedExceptionAction</code> with
+     * Performs the specified {@code PrivilegedExceptionAction} with
      * privileges enabled and restricted by the specified
-     * <code>AccessControlContext</code>.  The action is performed with the
+     * {@code AccessControlContext}.  The action is performed with the
      * intersection of the permissions possessed by the caller's
      * protection domain, and those possessed by the domains represented by the
-     * specified <code>AccessControlContext</code>.
+     * specified {@code AccessControlContext}.
+     * <p>
+     * If the action's {@code run} method throws an <i>unchecked</i>
+     * exception, it will propagate through this method.
      * <p>
-     * If the action's <code>run</code> method throws an <i>unchecked</i>
-     * exception, it will propagate through this method.
+     * If a security manager is installed and the {@code AccessControlContext}
+     * was not created by system code and the caller's {@code ProtectionDomain}
+     * has not been granted the {@literal "createAccessControlContext"}
+     * {@link java.security.SecurityPermission}, then the action is performed
+     * with no permissions.
      *
      * @param action the action to be performed
      * @param context an <i>access control context</i>
      *                representing the restriction to be applied to the
      *                caller's domain's privileges before performing
      *                the specified action.  If the context is
-     *                <code>null</code>,
-     *                then no additional restriction is applied.
+     *                {@code null}, then no additional restriction is applied.
      *
-     * @return the value returned by the action's <code>run</code> method
+     * @return the value returned by the action's {@code run} method
      *
      * @exception PrivilegedActionException if the specified action's
-     *         <code>run</code> method
-     *         threw a <i>checked</i> exception
-     * @exception NullPointerException if the action is <code>null</code>
+     *         {@code run} method threw a <i>checked</i> exception
+     * @exception NullPointerException if the action is {@code null}
      *
      * @see #doPrivileged(PrivilegedAction)
      * @see #doPrivileged(PrivilegedAction,AccessControlContext)
--- a/jdk/src/share/classes/java/security/KeyStore.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/security/KeyStore.java	Wed Jul 05 19:00:49 2017 +0200
@@ -317,7 +317,7 @@
          *     been specified by properties in the domain configuration data.
          *     It is cloned to prevent subsequent modification.
          *
-         * @exception NullPointerExcetion if {@code configuration} or
+         * @exception NullPointerException if {@code configuration} or
          *     {@code protectionParams} is {@code null}
          */
         public DomainLoadStoreParameter(URI configuration,
@@ -2093,7 +2093,7 @@
                              oldException);
                     }
                     try {
-                        return AccessController.doPrivileged(action);
+                        return AccessController.doPrivileged(action, context);
                     } catch (PrivilegedActionException e) {
                         Throwable cause = e.getCause();
                         throw new KeyStoreException
--- a/jdk/src/share/classes/java/security/ProtectionDomain.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/security/ProtectionDomain.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -277,6 +277,11 @@
         return false;
     }
 
+    // called by the VM -- do not remove
+    boolean impliesCreateAccessControlContext() {
+        return implies(SecurityConstants.CREATE_ACC_PERMISSION);
+    }
+
     /**
      * Convert a ProtectionDomain to a String.
      */
--- a/jdk/src/share/classes/java/security/SecureRandom.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/security/SecureRandom.java	Wed Jul 05 19:00:49 2017 +0200
@@ -466,7 +466,7 @@
      * <code>nextLong</code>, and <code>nextFloat</code>).
      *
      * @param numBits number of pseudo-random bits to be generated, where
-     * 0 <= <code>numBits</code> <= 32.
+     * {@code 0 <= numBits <= 32}.
      *
      * @return an <code>int</code> containing the user-specified number
      * of pseudo-random bits (right justified, with leading zeros).
--- a/jdk/src/share/classes/java/security/Signature.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/security/Signature.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -248,6 +248,7 @@
         Signature sig;
         if (instance.impl instanceof Signature) {
             sig = (Signature)instance.impl;
+            sig.algorithm = algorithm;
         } else {
             SignatureSpi spi = (SignatureSpi)instance.impl;
             sig = new Delegate(spi, algorithm);
--- a/jdk/src/share/classes/java/security/cert/CertPathValidatorException.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/security/cert/CertPathValidatorException.java	Wed Jul 05 19:00:49 2017 +0200
@@ -141,8 +141,8 @@
      * that caused the error (or -1 if not applicable). Note that
      * the list of certificates in a <code>CertPath</code> is zero based.
      * @throws IndexOutOfBoundsException if the index is out of range
-     * <code>(index < -1 || (certPath != null && index >=
-     * certPath.getCertificates().size())</code>
+     * {@code (index < -1 || (certPath != null && index >=
+     * certPath.getCertificates().size()) }
      * @throws IllegalArgumentException if <code>certPath</code> is
      * <code>null</code> and <code>index</code> is not -1
      */
@@ -164,8 +164,8 @@
      * the list of certificates in a <code>CertPath</code> is zero based.
      * @param reason the reason the validation failed
      * @throws IndexOutOfBoundsException if the index is out of range
-     * <code>(index < -1 || (certPath != null && index >=
-     * certPath.getCertificates().size())</code>
+     * {@code (index < -1 || (certPath != null && index >=
+     * certPath.getCertificates().size()) }
      * @throws IllegalArgumentException if <code>certPath</code> is
      * <code>null</code> and <code>index</code> is not -1
      * @throws NullPointerException if <code>reason</code> is <code>null</code>
--- a/jdk/src/share/classes/java/security/cert/CertificateFactory.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/security/cert/CertificateFactory.java	Wed Jul 05 19:00:49 2017 +0200
@@ -65,7 +65,7 @@
  * read position of the input stream is positioned to the next certificate in
  * the file:<p>
  *
- * <pre>
+ * <pre>{@code
  * FileInputStream fis = new FileInputStream(filename);
  * BufferedInputStream bis = new BufferedInputStream(fis);
  *
@@ -75,7 +75,7 @@
  *    Certificate cert = cf.generateCertificate(bis);
  *    System.out.println(cert.toString());
  * }
- * </pre>
+ * }</pre>
  *
  * <p>The following example parses a PKCS#7-formatted certificate reply stored
  * in a file and extracts all the certificates from it:<p>
--- a/jdk/src/share/classes/java/security/cert/X509Extension.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/security/cert/X509Extension.java	Wed Jul 05 19:00:49 2017 +0200
@@ -84,12 +84,12 @@
      *
      * Here is sample code to get a Set of critical extensions from an
      * X509Certificate and print the OIDs:
-     * <pre><code>
+     * <pre>{@code
      * X509Certificate cert = null;
      * try (InputStream inStrm = new FileInputStream("DER-encoded-Cert")) {
      *     CertificateFactory cf = CertificateFactory.getInstance("X.509");
      *     cert = (X509Certificate)cf.generateCertificate(inStrm);
-     * }<p>
+     * }
      *
      * Set<String> critSet = cert.getCriticalExtensionOIDs();
      * if (critSet != null && !critSet.isEmpty()) {
@@ -98,7 +98,7 @@
      *         System.out.println(oid);
      *     }
      * }
-     * </code></pre>
+     * }</pre>
      * @return a Set (or an empty Set if none are marked critical) of
      * the extension OID strings for extensions that are marked critical.
      * If there are no extensions present at all, then this method returns
--- a/jdk/src/share/classes/java/security/spec/EllipticCurve.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/security/spec/EllipticCurve.java	Wed Jul 05 19:00:49 2017 +0200
@@ -184,9 +184,9 @@
      * Returns a hash code value for this elliptic curve.
      * @return a hash code value computed from the hash codes of the field, A,
      * and B, as follows:
-     * <code>
+     * <pre>{@code
      *     (field.hashCode() << 6) + (a.hashCode() << 4) + (b.hashCode() << 2)
-     * </code>
+     * }</pre>
      */
     public int hashCode() {
         return (field.hashCode() << 6 +
--- a/jdk/src/share/classes/java/sql/DatabaseMetaData.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/sql/DatabaseMetaData.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1218,21 +1218,21 @@
      *
      * <P>Each procedure description has the the following columns:
      *  <OL>
-     *  <LI><B>PROCEDURE_CAT</B> String => procedure catalog (may be <code>null</code>)
-     *  <LI><B>PROCEDURE_SCHEM</B> String => procedure schema (may be <code>null</code>)
-     *  <LI><B>PROCEDURE_NAME</B> String => procedure name
+     *  <LI><B>PROCEDURE_CAT</B> String {@code =>} procedure catalog (may be <code>null</code>)
+     *  <LI><B>PROCEDURE_SCHEM</B> String {@code =>} procedure schema (may be <code>null</code>)
+     *  <LI><B>PROCEDURE_NAME</B> String {@code =>} procedure name
      *  <LI> reserved for future use
      *  <LI> reserved for future use
      *  <LI> reserved for future use
-     *  <LI><B>REMARKS</B> String => explanatory comment on the procedure
-     *  <LI><B>PROCEDURE_TYPE</B> short => kind of procedure:
+     *  <LI><B>REMARKS</B> String {@code =>} explanatory comment on the procedure
+     *  <LI><B>PROCEDURE_TYPE</B> short {@code =>} kind of procedure:
      *      <UL>
      *      <LI> procedureResultUnknown - Cannot determine if  a return value
      *       will be returned
      *      <LI> procedureNoResult - Does not return a return value
      *      <LI> procedureReturnsResult - Returns a return value
      *      </UL>
-     *  <LI><B>SPECIFIC_NAME</B> String  => The name which uniquely identifies this
+     *  <LI><B>SPECIFIC_NAME</B> String  {@code =>} The name which uniquely identifies this
      * procedure within its schema.
      *  </OL>
      * <p>
@@ -1297,11 +1297,11 @@
      * <P>Each row in the <code>ResultSet</code> is a parameter description or
      * column description with the following fields:
      *  <OL>
-     *  <LI><B>PROCEDURE_CAT</B> String => procedure catalog (may be <code>null</code>)
-     *  <LI><B>PROCEDURE_SCHEM</B> String => procedure schema (may be <code>null</code>)
-     *  <LI><B>PROCEDURE_NAME</B> String => procedure name
-     *  <LI><B>COLUMN_NAME</B> String => column/parameter name
-     *  <LI><B>COLUMN_TYPE</B> Short => kind of column/parameter:
+     *  <LI><B>PROCEDURE_CAT</B> String {@code =>} procedure catalog (may be <code>null</code>)
+     *  <LI><B>PROCEDURE_SCHEM</B> String {@code =>} procedure schema (may be <code>null</code>)
+     *  <LI><B>PROCEDURE_NAME</B> String {@code =>} procedure name
+     *  <LI><B>COLUMN_NAME</B> String {@code =>} column/parameter name
+     *  <LI><B>COLUMN_TYPE</B> Short {@code =>} kind of column/parameter:
      *      <UL>
      *      <LI> procedureColumnUnknown - nobody knows
      *      <LI> procedureColumnIn - IN parameter
@@ -1310,44 +1310,44 @@
      *      <LI> procedureColumnReturn - procedure return value
      *      <LI> procedureColumnResult - result column in <code>ResultSet</code>
      *      </UL>
-     *  <LI><B>DATA_TYPE</B> int => SQL type from java.sql.Types
-     *  <LI><B>TYPE_NAME</B> String => SQL type name, for a UDT type the
+     *  <LI><B>DATA_TYPE</B> int {@code =>} SQL type from java.sql.Types
+     *  <LI><B>TYPE_NAME</B> String {@code =>} SQL type name, for a UDT type the
      *  type name is fully qualified
-     *  <LI><B>PRECISION</B> int => precision
-     *  <LI><B>LENGTH</B> int => length in bytes of data
-     *  <LI><B>SCALE</B> short => scale -  null is returned for data types where
+     *  <LI><B>PRECISION</B> int {@code =>} precision
+     *  <LI><B>LENGTH</B> int {@code =>} length in bytes of data
+     *  <LI><B>SCALE</B> short {@code =>} scale -  null is returned for data types where
      * SCALE is not applicable.
-     *  <LI><B>RADIX</B> short => radix
-     *  <LI><B>NULLABLE</B> short => can it contain NULL.
+     *  <LI><B>RADIX</B> short {@code =>} radix
+     *  <LI><B>NULLABLE</B> short {@code =>} can it contain NULL.
      *      <UL>
      *      <LI> procedureNoNulls - does not allow NULL values
      *      <LI> procedureNullable - allows NULL values
      *      <LI> procedureNullableUnknown - nullability unknown
      *      </UL>
-     *  <LI><B>REMARKS</B> String => comment describing parameter/column
-     *  <LI><B>COLUMN_DEF</B> String => default value for the column, which should be interpreted as a string when the value is enclosed in single quotes (may be <code>null</code>)
+     *  <LI><B>REMARKS</B> String {@code =>} comment describing parameter/column
+     *  <LI><B>COLUMN_DEF</B> String {@code =>} default value for the column, which should be interpreted as a string when the value is enclosed in single quotes (may be <code>null</code>)
      *      <UL>
      *      <LI> The string NULL (not enclosed in quotes) - if NULL was specified as the default value
      *      <LI> TRUNCATE (not enclosed in quotes)        - if the specified default value cannot be represented without truncation
      *      <LI> NULL                                     - if a default value was not specified
      *      </UL>
-     *  <LI><B>SQL_DATA_TYPE</B> int  => reserved for future use
-     *  <LI><B>SQL_DATETIME_SUB</B> int  => reserved for future use
-     *  <LI><B>CHAR_OCTET_LENGTH</B> int  => the maximum length of binary and character based columns.  For any other datatype the returned value is a
+     *  <LI><B>SQL_DATA_TYPE</B> int  {@code =>} reserved for future use
+     *  <LI><B>SQL_DATETIME_SUB</B> int  {@code =>} reserved for future use
+     *  <LI><B>CHAR_OCTET_LENGTH</B> int  {@code =>} the maximum length of binary and character based columns.  For any other datatype the returned value is a
      * NULL
-     *  <LI><B>ORDINAL_POSITION</B> int  => the ordinal position, starting from 1, for the input and output parameters for a procedure. A value of 0
+     *  <LI><B>ORDINAL_POSITION</B> int  {@code =>} the ordinal position, starting from 1, for the input and output parameters for a procedure. A value of 0
      *is returned if this row describes the procedure's return value.  For result set columns, it is the
      *ordinal position of the column in the result set starting from 1.  If there are
      *multiple result sets, the column ordinal positions are implementation
      * defined.
-     *  <LI><B>IS_NULLABLE</B> String  => ISO rules are used to determine the nullability for a column.
+     *  <LI><B>IS_NULLABLE</B> String  {@code =>} ISO rules are used to determine the nullability for a column.
      *       <UL>
      *       <LI> YES           --- if the column can include NULLs
      *       <LI> NO            --- if the column cannot include NULLs
      *       <LI> empty string  --- if the nullability for the
      * column is unknown
      *       </UL>
-     *  <LI><B>SPECIFIC_NAME</B> String  => the name which uniquely identifies this procedure within its schema.
+     *  <LI><B>SPECIFIC_NAME</B> String  {@code =>} the name which uniquely identifies this procedure within its schema.
      *  </OL>
      *
      * <P><B>Note:</B> Some databases may not return the column
@@ -1481,19 +1481,19 @@
      * <P>
      * Each table description has the following columns:
      *  <OL>
-     *  <LI><B>TABLE_CAT</B> String => table catalog (may be <code>null</code>)
-     *  <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>)
-     *  <LI><B>TABLE_NAME</B> String => table name
-     *  <LI><B>TABLE_TYPE</B> String => table type.  Typical types are "TABLE",
+     *  <LI><B>TABLE_CAT</B> String {@code =>} table catalog (may be <code>null</code>)
+     *  <LI><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)
+     *  <LI><B>TABLE_NAME</B> String {@code =>} table name
+     *  <LI><B>TABLE_TYPE</B> String {@code =>} table type.  Typical types are "TABLE",
      *                  "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY",
      *                  "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
-     *  <LI><B>REMARKS</B> String => explanatory comment on the table
-     *  <LI><B>TYPE_CAT</B> String => the types catalog (may be <code>null</code>)
-     *  <LI><B>TYPE_SCHEM</B> String => the types schema (may be <code>null</code>)
-     *  <LI><B>TYPE_NAME</B> String => type name (may be <code>null</code>)
-     *  <LI><B>SELF_REFERENCING_COL_NAME</B> String => name of the designated
+     *  <LI><B>REMARKS</B> String {@code =>} explanatory comment on the table
+     *  <LI><B>TYPE_CAT</B> String {@code =>} the types catalog (may be <code>null</code>)
+     *  <LI><B>TYPE_SCHEM</B> String {@code =>} the types schema (may be <code>null</code>)
+     *  <LI><B>TYPE_NAME</B> String {@code =>} type name (may be <code>null</code>)
+     *  <LI><B>SELF_REFERENCING_COL_NAME</B> String {@code =>} name of the designated
      *                  "identifier" column of a typed table (may be <code>null</code>)
-     *  <LI><B>REF_GENERATION</B> String => specifies how values in
+     *  <LI><B>REF_GENERATION</B> String {@code =>} specifies how values in
      *                  SELF_REFERENCING_COL_NAME are created. Values are
      *                  "SYSTEM", "USER", "DERIVED". (may be <code>null</code>)
      *  </OL>
@@ -1528,8 +1528,8 @@
      *
      * <P>The schema columns are:
      *  <OL>
-     *  <LI><B>TABLE_SCHEM</B> String => schema name
-     *  <LI><B>TABLE_CATALOG</B> String => catalog name (may be <code>null</code>)
+     *  <LI><B>TABLE_SCHEM</B> String {@code =>} schema name
+     *  <LI><B>TABLE_CATALOG</B> String {@code =>} catalog name (may be <code>null</code>)
      *  </OL>
      *
      * @return a <code>ResultSet</code> object in which each row is a
@@ -1545,7 +1545,7 @@
      *
      * <P>The catalog column is:
      *  <OL>
-     *  <LI><B>TABLE_CAT</B> String => catalog name
+     *  <LI><B>TABLE_CAT</B> String {@code =>} catalog name
      *  </OL>
      *
      * @return a <code>ResultSet</code> object in which each row has a
@@ -1560,7 +1560,7 @@
      *
      * <P>The table type is:
      *  <OL>
-     *  <LI><B>TABLE_TYPE</B> String => table type.  Typical types are "TABLE",
+     *  <LI><B>TABLE_TYPE</B> String {@code =>} table type.  Typical types are "TABLE",
      *                  "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY",
      *                  "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
      *  </OL>
@@ -1582,55 +1582,55 @@
      *
      * <P>Each column description has the following columns:
      *  <OL>
-     *  <LI><B>TABLE_CAT</B> String => table catalog (may be <code>null</code>)
-     *  <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>)
-     *  <LI><B>TABLE_NAME</B> String => table name
-     *  <LI><B>COLUMN_NAME</B> String => column name
-     *  <LI><B>DATA_TYPE</B> int => SQL type from java.sql.Types
-     *  <LI><B>TYPE_NAME</B> String => Data source dependent type name,
+     *  <LI><B>TABLE_CAT</B> String {@code =>} table catalog (may be <code>null</code>)
+     *  <LI><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)
+     *  <LI><B>TABLE_NAME</B> String {@code =>} table name
+     *  <LI><B>COLUMN_NAME</B> String {@code =>} column name
+     *  <LI><B>DATA_TYPE</B> int {@code =>} SQL type from java.sql.Types
+     *  <LI><B>TYPE_NAME</B> String {@code =>} Data source dependent type name,
      *  for a UDT the type name is fully qualified
-     *  <LI><B>COLUMN_SIZE</B> int => column size.
+     *  <LI><B>COLUMN_SIZE</B> int {@code =>} column size.
      *  <LI><B>BUFFER_LENGTH</B> is not used.
-     *  <LI><B>DECIMAL_DIGITS</B> int => the number of fractional digits. Null is returned for data types where
+     *  <LI><B>DECIMAL_DIGITS</B> int {@code =>} the number of fractional digits. Null is returned for data types where
      * DECIMAL_DIGITS is not applicable.
-     *  <LI><B>NUM_PREC_RADIX</B> int => Radix (typically either 10 or 2)
-     *  <LI><B>NULLABLE</B> int => is NULL allowed.
+     *  <LI><B>NUM_PREC_RADIX</B> int {@code =>} Radix (typically either 10 or 2)
+     *  <LI><B>NULLABLE</B> int {@code =>} is NULL allowed.
      *      <UL>
      *      <LI> columnNoNulls - might not allow <code>NULL</code> values
      *      <LI> columnNullable - definitely allows <code>NULL</code> values
      *      <LI> columnNullableUnknown - nullability unknown
      *      </UL>
-     *  <LI><B>REMARKS</B> String => comment describing column (may be <code>null</code>)
-     *  <LI><B>COLUMN_DEF</B> String => default value for the column, which should be interpreted as a string when the value is enclosed in single quotes (may be <code>null</code>)
-     *  <LI><B>SQL_DATA_TYPE</B> int => unused
-     *  <LI><B>SQL_DATETIME_SUB</B> int => unused
-     *  <LI><B>CHAR_OCTET_LENGTH</B> int => for char types the
+     *  <LI><B>REMARKS</B> String {@code =>} comment describing column (may be <code>null</code>)
+     *  <LI><B>COLUMN_DEF</B> String {@code =>} default value for the column, which should be interpreted as a string when the value is enclosed in single quotes (may be <code>null</code>)
+     *  <LI><B>SQL_DATA_TYPE</B> int {@code =>} unused
+     *  <LI><B>SQL_DATETIME_SUB</B> int {@code =>} unused
+     *  <LI><B>CHAR_OCTET_LENGTH</B> int {@code =>} for char types the
      *       maximum number of bytes in the column
-     *  <LI><B>ORDINAL_POSITION</B> int => index of column in table
+     *  <LI><B>ORDINAL_POSITION</B> int {@code =>} index of column in table
      *      (starting at 1)
-     *  <LI><B>IS_NULLABLE</B> String  => ISO rules are used to determine the nullability for a column.
+     *  <LI><B>IS_NULLABLE</B> String  {@code =>} ISO rules are used to determine the nullability for a column.
      *       <UL>
      *       <LI> YES           --- if the column can include NULLs
      *       <LI> NO            --- if the column cannot include NULLs
      *       <LI> empty string  --- if the nullability for the
      * column is unknown
      *       </UL>
-     *  <LI><B>SCOPE_CATALOG</B> String => catalog of table that is the scope
+     *  <LI><B>SCOPE_CATALOG</B> String {@code =>} catalog of table that is the scope
      *      of a reference attribute (<code>null</code> if DATA_TYPE isn't REF)
-     *  <LI><B>SCOPE_SCHEMA</B> String => schema of table that is the scope
+     *  <LI><B>SCOPE_SCHEMA</B> String {@code =>} schema of table that is the scope
      *      of a reference attribute (<code>null</code> if the DATA_TYPE isn't REF)
-     *  <LI><B>SCOPE_TABLE</B> String => table name that this the scope
+     *  <LI><B>SCOPE_TABLE</B> String {@code =>} table name that this the scope
      *      of a reference attribute (<code>null</code> if the DATA_TYPE isn't REF)
-     *  <LI><B>SOURCE_DATA_TYPE</B> short => source type of a distinct type or user-generated
+     *  <LI><B>SOURCE_DATA_TYPE</B> short {@code =>} source type of a distinct type or user-generated
      *      Ref type, SQL type from java.sql.Types (<code>null</code> if DATA_TYPE
      *      isn't DISTINCT or user-generated REF)
-     *   <LI><B>IS_AUTOINCREMENT</B> String  => Indicates whether this column is auto incremented
+     *   <LI><B>IS_AUTOINCREMENT</B> String  {@code =>} Indicates whether this column is auto incremented
      *       <UL>
      *       <LI> YES           --- if the column is auto incremented
      *       <LI> NO            --- if the column is not auto incremented
      *       <LI> empty string  --- if it cannot be determined whether the column is auto incremented
      *       </UL>
-     *   <LI><B>IS_GENERATEDCOLUMN</B> String  => Indicates whether this is a generated column
+     *   <LI><B>IS_GENERATEDCOLUMN</B> String  {@code =>} Indicates whether this is a generated column
      *       <UL>
      *       <LI> YES           --- if this a generated column
      *       <LI> NO            --- if this not a generated column
@@ -1703,15 +1703,15 @@
      *
      * <P>Each privilige description has the following columns:
      *  <OL>
-     *  <LI><B>TABLE_CAT</B> String => table catalog (may be <code>null</code>)
-     *  <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>)
-     *  <LI><B>TABLE_NAME</B> String => table name
-     *  <LI><B>COLUMN_NAME</B> String => column name
-     *  <LI><B>GRANTOR</B> String => grantor of access (may be <code>null</code>)
-     *  <LI><B>GRANTEE</B> String => grantee of access
-     *  <LI><B>PRIVILEGE</B> String => name of access (SELECT,
+     *  <LI><B>TABLE_CAT</B> String {@code =>} table catalog (may be <code>null</code>)
+     *  <LI><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)
+     *  <LI><B>TABLE_NAME</B> String {@code =>} table name
+     *  <LI><B>COLUMN_NAME</B> String {@code =>} column name
+     *  <LI><B>GRANTOR</B> String {@code =>} grantor of access (may be <code>null</code>)
+     *  <LI><B>GRANTEE</B> String {@code =>} grantee of access
+     *  <LI><B>PRIVILEGE</B> String {@code =>} name of access (SELECT,
      *      INSERT, UPDATE, REFRENCES, ...)
-     *  <LI><B>IS_GRANTABLE</B> String => "YES" if grantee is permitted
+     *  <LI><B>IS_GRANTABLE</B> String {@code =>} "YES" if grantee is permitted
      *      to grant to others; "NO" if not; <code>null</code> if unknown
      *  </OL>
      *
@@ -1749,14 +1749,14 @@
      *
      * <P>Each privilige description has the following columns:
      *  <OL>
-     *  <LI><B>TABLE_CAT</B> String => table catalog (may be <code>null</code>)
-     *  <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>)
-     *  <LI><B>TABLE_NAME</B> String => table name
-     *  <LI><B>GRANTOR</B> String => grantor of access (may be <code>null</code>)
-     *  <LI><B>GRANTEE</B> String => grantee of access
-     *  <LI><B>PRIVILEGE</B> String => name of access (SELECT,
+     *  <LI><B>TABLE_CAT</B> String {@code =>} table catalog (may be <code>null</code>)
+     *  <LI><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)
+     *  <LI><B>TABLE_NAME</B> String {@code =>} table name
+     *  <LI><B>GRANTOR</B> String {@code =>} grantor of access (may be <code>null</code>)
+     *  <LI><B>GRANTEE</B> String {@code =>} grantee of access
+     *  <LI><B>PRIVILEGE</B> String {@code =>} name of access (SELECT,
      *      INSERT, UPDATE, REFRENCES, ...)
-     *  <LI><B>IS_GRANTABLE</B> String => "YES" if grantee is permitted
+     *  <LI><B>IS_GRANTABLE</B> String {@code =>} "YES" if grantee is permitted
      *      to grant to others; "NO" if not; <code>null</code> if unknown
      *  </OL>
      *
@@ -1783,21 +1783,21 @@
      *
      * <P>Each column description has the following columns:
      *  <OL>
-     *  <LI><B>SCOPE</B> short => actual scope of result
+     *  <LI><B>SCOPE</B> short {@code =>} actual scope of result
      *      <UL>
      *      <LI> bestRowTemporary - very temporary, while using row
      *      <LI> bestRowTransaction - valid for remainder of current transaction
      *      <LI> bestRowSession - valid for remainder of current session
      *      </UL>
-     *  <LI><B>COLUMN_NAME</B> String => column name
-     *  <LI><B>DATA_TYPE</B> int => SQL data type from java.sql.Types
-     *  <LI><B>TYPE_NAME</B> String => Data source dependent type name,
+     *  <LI><B>COLUMN_NAME</B> String {@code =>} column name
+     *  <LI><B>DATA_TYPE</B> int {@code =>} SQL data type from java.sql.Types
+     *  <LI><B>TYPE_NAME</B> String {@code =>} Data source dependent type name,
      *  for a UDT the type name is fully qualified
-     *  <LI><B>COLUMN_SIZE</B> int => precision
-     *  <LI><B>BUFFER_LENGTH</B> int => not used
-     *  <LI><B>DECIMAL_DIGITS</B> short  => scale - Null is returned for data types where
+     *  <LI><B>COLUMN_SIZE</B> int {@code =>} precision
+     *  <LI><B>BUFFER_LENGTH</B> int {@code =>} not used
+     *  <LI><B>DECIMAL_DIGITS</B> short  {@code =>} scale - Null is returned for data types where
      * DECIMAL_DIGITS is not applicable.
-     *  <LI><B>PSEUDO_COLUMN</B> short => is this a pseudo column
+     *  <LI><B>PSEUDO_COLUMN</B> short {@code =>} is this a pseudo column
      *      like an Oracle ROWID
      *      <UL>
      *      <LI> bestRowUnknown - may or may not be pseudo column
@@ -1902,15 +1902,15 @@
      *
      * <P>Each column description has the following columns:
      *  <OL>
-     *  <LI><B>SCOPE</B> short => is not used
-     *  <LI><B>COLUMN_NAME</B> String => column name
-     *  <LI><B>DATA_TYPE</B> int => SQL data type from <code>java.sql.Types</code>
-     *  <LI><B>TYPE_NAME</B> String => Data source-dependent type name
-     *  <LI><B>COLUMN_SIZE</B> int => precision
-     *  <LI><B>BUFFER_LENGTH</B> int => length of column value in bytes
-     *  <LI><B>DECIMAL_DIGITS</B> short  => scale - Null is returned for data types where
+     *  <LI><B>SCOPE</B> short {@code =>} is not used
+     *  <LI><B>COLUMN_NAME</B> String {@code =>} column name
+     *  <LI><B>DATA_TYPE</B> int {@code =>} SQL data type from <code>java.sql.Types</code>
+     *  <LI><B>TYPE_NAME</B> String {@code =>} Data source-dependent type name
+     *  <LI><B>COLUMN_SIZE</B> int {@code =>} precision
+     *  <LI><B>BUFFER_LENGTH</B> int {@code =>} length of column value in bytes
+     *  <LI><B>DECIMAL_DIGITS</B> short  {@code =>} scale - Null is returned for data types where
      * DECIMAL_DIGITS is not applicable.
-     *  <LI><B>PSEUDO_COLUMN</B> short => whether this is pseudo column
+     *  <LI><B>PSEUDO_COLUMN</B> short {@code =>} whether this is pseudo column
      *      like an Oracle ROWID
      *      <UL>
      *      <LI> versionColumnUnknown - may or may not be pseudo column
@@ -1978,14 +1978,14 @@
      *
      * <P>Each primary key column description has the following columns:
      *  <OL>
-     *  <LI><B>TABLE_CAT</B> String => table catalog (may be <code>null</code>)
-     *  <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>)
-     *  <LI><B>TABLE_NAME</B> String => table name
-     *  <LI><B>COLUMN_NAME</B> String => column name
-     *  <LI><B>KEY_SEQ</B> short => sequence number within primary key( a value
+     *  <LI><B>TABLE_CAT</B> String {@code =>} table catalog (may be <code>null</code>)
+     *  <LI><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)
+     *  <LI><B>TABLE_NAME</B> String {@code =>} table name
+     *  <LI><B>COLUMN_NAME</B> String {@code =>} column name
+     *  <LI><B>KEY_SEQ</B> short {@code =>} sequence number within primary key( a value
      *  of 1 represents the first column of the primary key, a value of 2 would
      *  represent the second column within the primary key).
-     *  <LI><B>PK_NAME</B> String => primary key name (may be <code>null</code>)
+     *  <LI><B>PK_NAME</B> String {@code =>} primary key name (may be <code>null</code>)
      *  </OL>
      *
      * @param catalog a catalog name; must match the catalog name as it
@@ -2012,22 +2012,22 @@
      *
      * <P>Each primary key column description has the following columns:
      *  <OL>
-     *  <LI><B>PKTABLE_CAT</B> String => primary key table catalog
+     *  <LI><B>PKTABLE_CAT</B> String {@code =>} primary key table catalog
      *      being imported (may be <code>null</code>)
-     *  <LI><B>PKTABLE_SCHEM</B> String => primary key table schema
+     *  <LI><B>PKTABLE_SCHEM</B> String {@code =>} primary key table schema
      *      being imported (may be <code>null</code>)
-     *  <LI><B>PKTABLE_NAME</B> String => primary key table name
+     *  <LI><B>PKTABLE_NAME</B> String {@code =>} primary key table name
      *      being imported
-     *  <LI><B>PKCOLUMN_NAME</B> String => primary key column name
+     *  <LI><B>PKCOLUMN_NAME</B> String {@code =>} primary key column name
      *      being imported
-     *  <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be <code>null</code>)
-     *  <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be <code>null</code>)
-     *  <LI><B>FKTABLE_NAME</B> String => foreign key table name
-     *  <LI><B>FKCOLUMN_NAME</B> String => foreign key column name
-     *  <LI><B>KEY_SEQ</B> short => sequence number within a foreign key( a value
+     *  <LI><B>FKTABLE_CAT</B> String {@code =>} foreign key table catalog (may be <code>null</code>)
+     *  <LI><B>FKTABLE_SCHEM</B> String {@code =>} foreign key table schema (may be <code>null</code>)
+     *  <LI><B>FKTABLE_NAME</B> String {@code =>} foreign key table name
+     *  <LI><B>FKCOLUMN_NAME</B> String {@code =>} foreign key column name
+     *  <LI><B>KEY_SEQ</B> short {@code =>} sequence number within a foreign key( a value
      *  of 1 represents the first column of the foreign key, a value of 2 would
      *  represent the second column within the foreign key).
-     *  <LI><B>UPDATE_RULE</B> short => What happens to a
+     *  <LI><B>UPDATE_RULE</B> short {@code =>} What happens to a
      *       foreign key when the primary key is updated:
      *      <UL>
      *      <LI> importedNoAction - do not allow update of primary
@@ -2041,7 +2041,7 @@
      *      <LI> importedKeyRestrict - same as importedKeyNoAction
      *                                 (for ODBC 2.x compatibility)
      *      </UL>
-     *  <LI><B>DELETE_RULE</B> short => What happens to
+     *  <LI><B>DELETE_RULE</B> short {@code =>} What happens to
      *      the foreign key when primary is deleted.
      *      <UL>
      *      <LI> importedKeyNoAction - do not allow delete of primary
@@ -2054,9 +2054,9 @@
      *      <LI> importedKeySetDefault - change imported key to default if
      *               its primary key has been deleted
      *      </UL>
-     *  <LI><B>FK_NAME</B> String => foreign key name (may be <code>null</code>)
-     *  <LI><B>PK_NAME</B> String => primary key name (may be <code>null</code>)
-     *  <LI><B>DEFERRABILITY</B> short => can the evaluation of foreign key
+     *  <LI><B>FK_NAME</B> String {@code =>} foreign key name (may be <code>null</code>)
+     *  <LI><B>PK_NAME</B> String {@code =>} primary key name (may be <code>null</code>)
+     *  <LI><B>DEFERRABILITY</B> short {@code =>} can the evaluation of foreign key
      *      constraints be deferred until commit
      *      <UL>
      *      <LI> importedKeyInitiallyDeferred - see SQL92 for definition
@@ -2195,22 +2195,22 @@
      *
      * <P>Each foreign key column description has the following columns:
      *  <OL>
-     *  <LI><B>PKTABLE_CAT</B> String => primary key table catalog (may be <code>null</code>)
-     *  <LI><B>PKTABLE_SCHEM</B> String => primary key table schema (may be <code>null</code>)
-     *  <LI><B>PKTABLE_NAME</B> String => primary key table name
-     *  <LI><B>PKCOLUMN_NAME</B> String => primary key column name
-     *  <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be <code>null</code>)
+     *  <LI><B>PKTABLE_CAT</B> String {@code =>} primary key table catalog (may be <code>null</code>)
+     *  <LI><B>PKTABLE_SCHEM</B> String {@code =>} primary key table schema (may be <code>null</code>)
+     *  <LI><B>PKTABLE_NAME</B> String {@code =>} primary key table name
+     *  <LI><B>PKCOLUMN_NAME</B> String {@code =>} primary key column name
+     *  <LI><B>FKTABLE_CAT</B> String {@code =>} foreign key table catalog (may be <code>null</code>)
      *      being exported (may be <code>null</code>)
-     *  <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be <code>null</code>)
+     *  <LI><B>FKTABLE_SCHEM</B> String {@code =>} foreign key table schema (may be <code>null</code>)
      *      being exported (may be <code>null</code>)
-     *  <LI><B>FKTABLE_NAME</B> String => foreign key table name
+     *  <LI><B>FKTABLE_NAME</B> String {@code =>} foreign key table name
      *      being exported
-     *  <LI><B>FKCOLUMN_NAME</B> String => foreign key column name
+     *  <LI><B>FKCOLUMN_NAME</B> String {@code =>} foreign key column name
      *      being exported
-     *  <LI><B>KEY_SEQ</B> short => sequence number within foreign key( a value
+     *  <LI><B>KEY_SEQ</B> short {@code =>} sequence number within foreign key( a value
      *  of 1 represents the first column of the foreign key, a value of 2 would
      *  represent the second column within the foreign key).
-     *  <LI><B>UPDATE_RULE</B> short => What happens to
+     *  <LI><B>UPDATE_RULE</B> short {@code =>} What happens to
      *       foreign key when primary is updated:
      *      <UL>
      *      <LI> importedNoAction - do not allow update of primary
@@ -2224,7 +2224,7 @@
      *      <LI> importedKeyRestrict - same as importedKeyNoAction
      *                                 (for ODBC 2.x compatibility)
      *      </UL>
-     *  <LI><B>DELETE_RULE</B> short => What happens to
+     *  <LI><B>DELETE_RULE</B> short {@code =>} What happens to
      *      the foreign key when primary is deleted.
      *      <UL>
      *      <LI> importedKeyNoAction - do not allow delete of primary
@@ -2237,9 +2237,9 @@
      *      <LI> importedKeySetDefault - change imported key to default if
      *               its primary key has been deleted
      *      </UL>
-     *  <LI><B>FK_NAME</B> String => foreign key name (may be <code>null</code>)
-     *  <LI><B>PK_NAME</B> String => primary key name (may be <code>null</code>)
-     *  <LI><B>DEFERRABILITY</B> short => can the evaluation of foreign key
+     *  <LI><B>FK_NAME</B> String {@code =>} foreign key name (may be <code>null</code>)
+     *  <LI><B>PK_NAME</B> String {@code =>} primary key name (may be <code>null</code>)
+     *  <LI><B>DEFERRABILITY</B> short {@code =>} can the evaluation of foreign key
      *      constraints be deferred until commit
      *      <UL>
      *      <LI> importedKeyInitiallyDeferred - see SQL92 for definition
@@ -2276,22 +2276,22 @@
      *
      * <P>Each foreign key column description has the following columns:
      *  <OL>
-     *  <LI><B>PKTABLE_CAT</B> String => parent key table catalog (may be <code>null</code>)
-     *  <LI><B>PKTABLE_SCHEM</B> String => parent key table schema (may be <code>null</code>)
-     *  <LI><B>PKTABLE_NAME</B> String => parent key table name
-     *  <LI><B>PKCOLUMN_NAME</B> String => parent key column name
-     *  <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be <code>null</code>)
+     *  <LI><B>PKTABLE_CAT</B> String {@code =>} parent key table catalog (may be <code>null</code>)
+     *  <LI><B>PKTABLE_SCHEM</B> String {@code =>} parent key table schema (may be <code>null</code>)
+     *  <LI><B>PKTABLE_NAME</B> String {@code =>} parent key table name
+     *  <LI><B>PKCOLUMN_NAME</B> String {@code =>} parent key column name
+     *  <LI><B>FKTABLE_CAT</B> String {@code =>} foreign key table catalog (may be <code>null</code>)
      *      being exported (may be <code>null</code>)
-     *  <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be <code>null</code>)
+     *  <LI><B>FKTABLE_SCHEM</B> String {@code =>} foreign key table schema (may be <code>null</code>)
      *      being exported (may be <code>null</code>)
-     *  <LI><B>FKTABLE_NAME</B> String => foreign key table name
+     *  <LI><B>FKTABLE_NAME</B> String {@code =>} foreign key table name
      *      being exported
-     *  <LI><B>FKCOLUMN_NAME</B> String => foreign key column name
+     *  <LI><B>FKCOLUMN_NAME</B> String {@code =>} foreign key column name
      *      being exported
-     *  <LI><B>KEY_SEQ</B> short => sequence number within foreign key( a value
+     *  <LI><B>KEY_SEQ</B> short {@code =>} sequence number within foreign key( a value
      *  of 1 represents the first column of the foreign key, a value of 2 would
      *  represent the second column within the foreign key).
-     *  <LI><B>UPDATE_RULE</B> short => What happens to
+     *  <LI><B>UPDATE_RULE</B> short {@code =>} What happens to
      *       foreign key when parent key is updated:
      *      <UL>
      *      <LI> importedNoAction - do not allow update of parent
@@ -2305,7 +2305,7 @@
      *      <LI> importedKeyRestrict - same as importedKeyNoAction
      *                                 (for ODBC 2.x compatibility)
      *      </UL>
-     *  <LI><B>DELETE_RULE</B> short => What happens to
+     *  <LI><B>DELETE_RULE</B> short {@code =>} What happens to
      *      the foreign key when parent key is deleted.
      *      <UL>
      *      <LI> importedKeyNoAction - do not allow delete of parent
@@ -2318,9 +2318,9 @@
      *      <LI> importedKeySetDefault - change imported key to default if
      *               its parent key has been deleted
      *      </UL>
-     *  <LI><B>FK_NAME</B> String => foreign key name (may be <code>null</code>)
-     *  <LI><B>PK_NAME</B> String => parent key name (may be <code>null</code>)
-     *  <LI><B>DEFERRABILITY</B> short => can the evaluation of foreign key
+     *  <LI><B>FK_NAME</B> String {@code =>} foreign key name (may be <code>null</code>)
+     *  <LI><B>PK_NAME</B> String {@code =>} parent key name (may be <code>null</code>)
+     *  <LI><B>DEFERRABILITY</B> short {@code =>} can the evaluation of foreign key
      *      constraints be deferred until commit
      *      <UL>
      *      <LI> importedKeyInitiallyDeferred - see SQL92 for definition
@@ -2371,40 +2371,40 @@
      *
      * <P>Each type description has the following columns:
      *  <OL>
-     *  <LI><B>TYPE_NAME</B> String => Type name
-     *  <LI><B>DATA_TYPE</B> int => SQL data type from java.sql.Types
-     *  <LI><B>PRECISION</B> int => maximum precision
-     *  <LI><B>LITERAL_PREFIX</B> String => prefix used to quote a literal
+     *  <LI><B>TYPE_NAME</B> String {@code =>} Type name
+     *  <LI><B>DATA_TYPE</B> int {@code =>} SQL data type from java.sql.Types
+     *  <LI><B>PRECISION</B> int {@code =>} maximum precision
+     *  <LI><B>LITERAL_PREFIX</B> String {@code =>} prefix used to quote a literal
      *      (may be <code>null</code>)
-     *  <LI><B>LITERAL_SUFFIX</B> String => suffix used to quote a literal
+     *  <LI><B>LITERAL_SUFFIX</B> String {@code =>} suffix used to quote a literal
      (may be <code>null</code>)
-     *  <LI><B>CREATE_PARAMS</B> String => parameters used in creating
+     *  <LI><B>CREATE_PARAMS</B> String {@code =>} parameters used in creating
      *      the type (may be <code>null</code>)
-     *  <LI><B>NULLABLE</B> short => can you use NULL for this type.
+     *  <LI><B>NULLABLE</B> short {@code =>} can you use NULL for this type.
      *      <UL>
      *      <LI> typeNoNulls - does not allow NULL values
      *      <LI> typeNullable - allows NULL values
      *      <LI> typeNullableUnknown - nullability unknown
      *      </UL>
-     *  <LI><B>CASE_SENSITIVE</B> boolean=> is it case sensitive.
-     *  <LI><B>SEARCHABLE</B> short => can you use "WHERE" based on this type:
+     *  <LI><B>CASE_SENSITIVE</B> boolean{@code =>} is it case sensitive.
+     *  <LI><B>SEARCHABLE</B> short {@code =>} can you use "WHERE" based on this type:
      *      <UL>
      *      <LI> typePredNone - No support
      *      <LI> typePredChar - Only supported with WHERE .. LIKE
      *      <LI> typePredBasic - Supported except for WHERE .. LIKE
      *      <LI> typeSearchable - Supported for all WHERE ..
      *      </UL>
-     *  <LI><B>UNSIGNED_ATTRIBUTE</B> boolean => is it unsigned.
-     *  <LI><B>FIXED_PREC_SCALE</B> boolean => can it be a money value.
-     *  <LI><B>AUTO_INCREMENT</B> boolean => can it be used for an
+     *  <LI><B>UNSIGNED_ATTRIBUTE</B> boolean {@code =>} is it unsigned.
+     *  <LI><B>FIXED_PREC_SCALE</B> boolean {@code =>} can it be a money value.
+     *  <LI><B>AUTO_INCREMENT</B> boolean {@code =>} can it be used for an
      *      auto-increment value.
-     *  <LI><B>LOCAL_TYPE_NAME</B> String => localized version of type name
+     *  <LI><B>LOCAL_TYPE_NAME</B> String {@code =>} localized version of type name
      *      (may be <code>null</code>)
-     *  <LI><B>MINIMUM_SCALE</B> short => minimum scale supported
-     *  <LI><B>MAXIMUM_SCALE</B> short => maximum scale supported
-     *  <LI><B>SQL_DATA_TYPE</B> int => unused
-     *  <LI><B>SQL_DATETIME_SUB</B> int => unused
-     *  <LI><B>NUM_PREC_RADIX</B> int => usually 2 or 10
+     *  <LI><B>MINIMUM_SCALE</B> short {@code =>} minimum scale supported
+     *  <LI><B>MAXIMUM_SCALE</B> short {@code =>} maximum scale supported
+     *  <LI><B>SQL_DATA_TYPE</B> int {@code =>} unused
+     *  <LI><B>SQL_DATETIME_SUB</B> int {@code =>} unused
+     *  <LI><B>NUM_PREC_RADIX</B> int {@code =>} usually 2 or 10
      *  </OL>
      *
      * <p>The PRECISION column represents the maximum column size that the server supports for the given datatype.
@@ -2498,16 +2498,16 @@
      *
      * <P>Each index column description has the following columns:
      *  <OL>
-     *  <LI><B>TABLE_CAT</B> String => table catalog (may be <code>null</code>)
-     *  <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>)
-     *  <LI><B>TABLE_NAME</B> String => table name
-     *  <LI><B>NON_UNIQUE</B> boolean => Can index values be non-unique.
+     *  <LI><B>TABLE_CAT</B> String {@code =>} table catalog (may be <code>null</code>)
+     *  <LI><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)
+     *  <LI><B>TABLE_NAME</B> String {@code =>} table name
+     *  <LI><B>NON_UNIQUE</B> boolean {@code =>} Can index values be non-unique.
      *      false when TYPE is tableIndexStatistic
-     *  <LI><B>INDEX_QUALIFIER</B> String => index catalog (may be <code>null</code>);
+     *  <LI><B>INDEX_QUALIFIER</B> String {@code =>} index catalog (may be <code>null</code>);
      *      <code>null</code> when TYPE is tableIndexStatistic
-     *  <LI><B>INDEX_NAME</B> String => index name; <code>null</code> when TYPE is
+     *  <LI><B>INDEX_NAME</B> String {@code =>} index name; <code>null</code> when TYPE is
      *      tableIndexStatistic
-     *  <LI><B>TYPE</B> short => index type:
+     *  <LI><B>TYPE</B> short {@code =>} index type:
      *      <UL>
      *      <LI> tableIndexStatistic - this identifies table statistics that are
      *           returned in conjuction with a table's index descriptions
@@ -2515,20 +2515,20 @@
      *      <LI> tableIndexHashed - this is a hashed index
      *      <LI> tableIndexOther - this is some other style of index
      *      </UL>
-     *  <LI><B>ORDINAL_POSITION</B> short => column sequence number
+     *  <LI><B>ORDINAL_POSITION</B> short {@code =>} column sequence number
      *      within index; zero when TYPE is tableIndexStatistic
-     *  <LI><B>COLUMN_NAME</B> String => column name; <code>null</code> when TYPE is
+     *  <LI><B>COLUMN_NAME</B> String {@code =>} column name; <code>null</code> when TYPE is
      *      tableIndexStatistic
-     *  <LI><B>ASC_OR_DESC</B> String => column sort sequence, "A" => ascending,
-     *      "D" => descending, may be <code>null</code> if sort sequence is not supported;
+     *  <LI><B>ASC_OR_DESC</B> String {@code =>} column sort sequence, "A" {@code =>} ascending,
+     *      "D" {@code =>} descending, may be <code>null</code> if sort sequence is not supported;
      *      <code>null</code> when TYPE is tableIndexStatistic
-     *  <LI><B>CARDINALITY</B> long => When TYPE is tableIndexStatistic, then
+     *  <LI><B>CARDINALITY</B> long {@code =>} When TYPE is tableIndexStatistic, then
      *      this is the number of rows in the table; otherwise, it is the
      *      number of unique values in the index.
-     *  <LI><B>PAGES</B> long => When TYPE is  tableIndexStatisic then
+     *  <LI><B>PAGES</B> long {@code =>} When TYPE is  tableIndexStatisic then
      *      this is the number of pages used for the table, otherwise it
      *      is the number of pages used for the current index.
-     *  <LI><B>FILTER_CONDITION</B> String => Filter condition, if any.
+     *  <LI><B>FILTER_CONDITION</B> String {@code =>} Filter condition, if any.
      *      (may be <code>null</code>)
      *  </OL>
      *
@@ -2781,14 +2781,14 @@
      *
      * <P>Each type description has the following columns:
      *  <OL>
-     *  <LI><B>TYPE_CAT</B> String => the type's catalog (may be <code>null</code>)
-     *  <LI><B>TYPE_SCHEM</B> String => type's schema (may be <code>null</code>)
-     *  <LI><B>TYPE_NAME</B> String => type name
-     *  <LI><B>CLASS_NAME</B> String => Java class name
-     *  <LI><B>DATA_TYPE</B> int => type value defined in java.sql.Types.
+     *  <LI><B>TYPE_CAT</B> String {@code =>} the type's catalog (may be <code>null</code>)
+     *  <LI><B>TYPE_SCHEM</B> String {@code =>} type's schema (may be <code>null</code>)
+     *  <LI><B>TYPE_NAME</B> String {@code =>} type name
+     *  <LI><B>CLASS_NAME</B> String {@code =>} Java class name
+     *  <LI><B>DATA_TYPE</B> int {@code =>} type value defined in java.sql.Types.
      *     One of JAVA_OBJECT, STRUCT, or DISTINCT
-     *  <LI><B>REMARKS</B> String => explanatory comment on the type
-     *  <LI><B>BASE_TYPE</B> short => type code of the source type of a
+     *  <LI><B>REMARKS</B> String {@code =>} explanatory comment on the type
+     *  <LI><B>BASE_TYPE</B> short {@code =>} type code of the source type of a
      *     DISTINCT type or the type that implements the user-generated
      *     reference type of the SELF_REFERENCING_COLUMN of a structured
      *     type as defined in java.sql.Types (<code>null</code> if DATA_TYPE is not
@@ -2894,14 +2894,14 @@
      * describes the designated UDT and a direct supertype. A row has the following
      * columns:
      *  <OL>
-     *  <LI><B>TYPE_CAT</B> String => the UDT's catalog (may be <code>null</code>)
-     *  <LI><B>TYPE_SCHEM</B> String => UDT's schema (may be <code>null</code>)
-     *  <LI><B>TYPE_NAME</B> String => type name of the UDT
-     *  <LI><B>SUPERTYPE_CAT</B> String => the direct super type's catalog
+     *  <LI><B>TYPE_CAT</B> String {@code =>} the UDT's catalog (may be <code>null</code>)
+     *  <LI><B>TYPE_SCHEM</B> String {@code =>} UDT's schema (may be <code>null</code>)
+     *  <LI><B>TYPE_NAME</B> String {@code =>} type name of the UDT
+     *  <LI><B>SUPERTYPE_CAT</B> String {@code =>} the direct super type's catalog
      *                           (may be <code>null</code>)
-     *  <LI><B>SUPERTYPE_SCHEM</B> String => the direct super type's schema
+     *  <LI><B>SUPERTYPE_SCHEM</B> String {@code =>} the direct super type's schema
      *                             (may be <code>null</code>)
-     *  <LI><B>SUPERTYPE_NAME</B> String => the direct super type's name
+     *  <LI><B>SUPERTYPE_NAME</B> String {@code =>} the direct super type's name
      *  </OL>
      *
      * <P><B>Note:</B> If the driver does not support type hierarchies, an
@@ -2936,10 +2936,10 @@
      *
      * <P>Each type description has the following columns:
      *  <OL>
-     *  <LI><B>TABLE_CAT</B> String => the type's catalog (may be <code>null</code>)
-     *  <LI><B>TABLE_SCHEM</B> String => type's schema (may be <code>null</code>)
-     *  <LI><B>TABLE_NAME</B> String => type name
-     *  <LI><B>SUPERTABLE_NAME</B> String => the direct super type's name
+     *  <LI><B>TABLE_CAT</B> String {@code =>} the type's catalog (may be <code>null</code>)
+     *  <LI><B>TABLE_SCHEM</B> String {@code =>} type's schema (may be <code>null</code>)
+     *  <LI><B>TABLE_NAME</B> String {@code =>} type name
+     *  <LI><B>SUPERTABLE_NAME</B> String {@code =>} the direct super type's name
      *  </OL>
      *
      * <P><B>Note:</B> If the driver does not support type hierarchies, an
@@ -3001,35 +3001,35 @@
      * The <code>ResultSet</code> object that is returned has the following
      * columns:
      * <OL>
-     *  <LI><B>TYPE_CAT</B> String => type catalog (may be <code>null</code>)
-     *  <LI><B>TYPE_SCHEM</B> String => type schema (may be <code>null</code>)
-     *  <LI><B>TYPE_NAME</B> String => type name
-     *  <LI><B>ATTR_NAME</B> String => attribute name
-     *  <LI><B>DATA_TYPE</B> int => attribute type SQL type from java.sql.Types
-     *  <LI><B>ATTR_TYPE_NAME</B> String => Data source dependent type name.
+     *  <LI><B>TYPE_CAT</B> String {@code =>} type catalog (may be <code>null</code>)
+     *  <LI><B>TYPE_SCHEM</B> String {@code =>} type schema (may be <code>null</code>)
+     *  <LI><B>TYPE_NAME</B> String {@code =>} type name
+     *  <LI><B>ATTR_NAME</B> String {@code =>} attribute name
+     *  <LI><B>DATA_TYPE</B> int {@code =>} attribute type SQL type from java.sql.Types
+     *  <LI><B>ATTR_TYPE_NAME</B> String {@code =>} Data source dependent type name.
      *  For a UDT, the type name is fully qualified. For a REF, the type name is
      *  fully qualified and represents the target type of the reference type.
-     *  <LI><B>ATTR_SIZE</B> int => column size.  For char or date
+     *  <LI><B>ATTR_SIZE</B> int {@code =>} column size.  For char or date
      *      types this is the maximum number of characters; for numeric or
      *      decimal types this is precision.
-     *  <LI><B>DECIMAL_DIGITS</B> int => the number of fractional digits. Null is returned for data types where
+     *  <LI><B>DECIMAL_DIGITS</B> int {@code =>} the number of fractional digits. Null is returned for data types where
      * DECIMAL_DIGITS is not applicable.
-     *  <LI><B>NUM_PREC_RADIX</B> int => Radix (typically either 10 or 2)
-     *  <LI><B>NULLABLE</B> int => whether NULL is allowed
+     *  <LI><B>NUM_PREC_RADIX</B> int {@code =>} Radix (typically either 10 or 2)
+     *  <LI><B>NULLABLE</B> int {@code =>} whether NULL is allowed
      *      <UL>
      *      <LI> attributeNoNulls - might not allow NULL values
      *      <LI> attributeNullable - definitely allows NULL values
      *      <LI> attributeNullableUnknown - nullability unknown
      *      </UL>
-     *  <LI><B>REMARKS</B> String => comment describing column (may be <code>null</code>)
-     *  <LI><B>ATTR_DEF</B> String => default value (may be <code>null</code>)
-     *  <LI><B>SQL_DATA_TYPE</B> int => unused
-     *  <LI><B>SQL_DATETIME_SUB</B> int => unused
-     *  <LI><B>CHAR_OCTET_LENGTH</B> int => for char types the
+     *  <LI><B>REMARKS</B> String {@code =>} comment describing column (may be <code>null</code>)
+     *  <LI><B>ATTR_DEF</B> String {@code =>} default value (may be <code>null</code>)
+     *  <LI><B>SQL_DATA_TYPE</B> int {@code =>} unused
+     *  <LI><B>SQL_DATETIME_SUB</B> int {@code =>} unused
+     *  <LI><B>CHAR_OCTET_LENGTH</B> int {@code =>} for char types the
      *       maximum number of bytes in the column
-     *  <LI><B>ORDINAL_POSITION</B> int => index of the attribute in the UDT
+     *  <LI><B>ORDINAL_POSITION</B> int {@code =>} index of the attribute in the UDT
      *      (starting at 1)
-     *  <LI><B>IS_NULLABLE</B> String  => ISO rules are used to determine
+     *  <LI><B>IS_NULLABLE</B> String  {@code =>} ISO rules are used to determine
      * the nullability for a attribute.
      *       <UL>
      *       <LI> YES           --- if the attribute can include NULLs
@@ -3037,13 +3037,13 @@
      *       <LI> empty string  --- if the nullability for the
      * attribute is unknown
      *       </UL>
-     *  <LI><B>SCOPE_CATALOG</B> String => catalog of table that is the
+     *  <LI><B>SCOPE_CATALOG</B> String {@code =>} catalog of table that is the
      *      scope of a reference attribute (<code>null</code> if DATA_TYPE isn't REF)
-     *  <LI><B>SCOPE_SCHEMA</B> String => schema of table that is the
+     *  <LI><B>SCOPE_SCHEMA</B> String {@code =>} schema of table that is the
      *      scope of a reference attribute (<code>null</code> if DATA_TYPE isn't REF)
-     *  <LI><B>SCOPE_TABLE</B> String => table name that is the scope of a
+     *  <LI><B>SCOPE_TABLE</B> String {@code =>} table name that is the scope of a
      *      reference attribute (<code>null</code> if the DATA_TYPE isn't REF)
-     * <LI><B>SOURCE_DATA_TYPE</B> short => source type of a distinct type or user-generated
+     * <LI><B>SOURCE_DATA_TYPE</B> short {@code =>} source type of a distinct type or user-generated
      *      Ref type,SQL type from java.sql.Types (<code>null</code> if DATA_TYPE
      *      isn't DISTINCT or user-generated REF)
      *  </OL>
@@ -3203,14 +3203,14 @@
      * and if so  the lifetime for which a <code>RowId</code> object remains valid.
      * <p>
      * The returned int values have the following relationship:
-     * <pre>
+     * <pre>{@code
      *     ROWID_UNSUPPORTED < ROWID_VALID_OTHER < ROWID_VALID_TRANSACTION
      *         < ROWID_VALID_SESSION < ROWID_VALID_FOREVER
-     * </pre>
+     * }</pre>
      * so conditional logic such as
-     * <pre>
+     * <pre>{@code
      *     if (metadata.getRowIdLifetime() > DatabaseMetaData.ROWID_VALID_TRANSACTION)
-     * </pre>
+     * }</pre>
      * can be used. Valid Forever means valid across all Sessions, and valid for
      * a Session means valid across all its contained Transactions.
      *
@@ -3227,8 +3227,8 @@
      *
      * <P>The schema columns are:
      *  <OL>
-     *  <LI><B>TABLE_SCHEM</B> String => schema name
-     *  <LI><B>TABLE_CATALOG</B> String => catalog name (may be <code>null</code>)
+     *  <LI><B>TABLE_SCHEM</B> String {@code =>} schema name
+     *  <LI><B>TABLE_CATALOG</B> String {@code =>} catalog name (may be <code>null</code>)
      *  </OL>
      *
      *
@@ -3273,10 +3273,10 @@
          * that the driver supports.  The result set contains the following columns
          * <p>
          * <ol>
-         * <li><b>NAME</b> String=> The name of the client info property<br>
-         * <li><b>MAX_LEN</b> int=> The maximum length of the value for the property<br>
-         * <li><b>DEFAULT_VALUE</b> String=> The default value of the property<br>
-         * <li><b>DESCRIPTION</b> String=> A description of the property.  This will typically
+         * <li><b>NAME</b> String{@code =>} The name of the client info property<br>
+         * <li><b>MAX_LEN</b> int{@code =>} The maximum length of the value for the property<br>
+         * <li><b>DEFAULT_VALUE</b> String{@code =>} The default value of the property<br>
+         * <li><b>DESCRIPTION</b> String{@code =>} A description of the property.  This will typically
          *                                              contain information as to where this property is
          *                                              stored in the database.
          * </ol>
@@ -3305,19 +3305,19 @@
      *
      * <P>Each function description has the the following columns:
      *  <OL>
-     *  <LI><B>FUNCTION_CAT</B> String => function catalog (may be <code>null</code>)
-     *  <LI><B>FUNCTION_SCHEM</B> String => function schema (may be <code>null</code>)
-     *  <LI><B>FUNCTION_NAME</B> String => function name.  This is the name
+     *  <LI><B>FUNCTION_CAT</B> String {@code =>} function catalog (may be <code>null</code>)
+     *  <LI><B>FUNCTION_SCHEM</B> String {@code =>} function schema (may be <code>null</code>)
+     *  <LI><B>FUNCTION_NAME</B> String {@code =>} function name.  This is the name
      * used to invoke the function
-     *  <LI><B>REMARKS</B> String => explanatory comment on the function
-     * <LI><B>FUNCTION_TYPE</B> short => kind of function:
+     *  <LI><B>REMARKS</B> String {@code =>} explanatory comment on the function
+     * <LI><B>FUNCTION_TYPE</B> short {@code =>} kind of function:
      *      <UL>
      *      <LI>functionResultUnknown - Cannot determine if a return value
      *       or table will be returned
      *      <LI> functionNoTable- Does not return a table
      *      <LI> functionReturnsTable - Returns a table
      *      </UL>
-     *  <LI><B>SPECIFIC_NAME</B> String  => the name which uniquely identifies
+     *  <LI><B>SPECIFIC_NAME</B> String  {@code =>} the name which uniquely identifies
      *  this function within its schema.  This is a user specified, or DBMS
      * generated, name that may be different then the <code>FUNCTION_NAME</code>
      * for example with overload functions
@@ -3359,12 +3359,12 @@
      * is a parameter description, column description or
      * return type description with the following fields:
      *  <OL>
-     *  <LI><B>FUNCTION_CAT</B> String => function catalog (may be <code>null</code>)
-     *  <LI><B>FUNCTION_SCHEM</B> String => function schema (may be <code>null</code>)
-     *  <LI><B>FUNCTION_NAME</B> String => function name.  This is the name
+     *  <LI><B>FUNCTION_CAT</B> String {@code =>} function catalog (may be <code>null</code>)
+     *  <LI><B>FUNCTION_SCHEM</B> String {@code =>} function schema (may be <code>null</code>)
+     *  <LI><B>FUNCTION_NAME</B> String {@code =>} function name.  This is the name
      * used to invoke the function
-     *  <LI><B>COLUMN_NAME</B> String => column/parameter name
-     *  <LI><B>COLUMN_TYPE</B> Short => kind of column/parameter:
+     *  <LI><B>COLUMN_NAME</B> String {@code =>} column/parameter name
+     *  <LI><B>COLUMN_TYPE</B> Short {@code =>} kind of column/parameter:
      *      <UL>
      *      <LI> functionColumnUnknown - nobody knows
      *      <LI> functionColumnIn - IN parameter
@@ -3374,30 +3374,30 @@
      *      <LI> functionColumnResult - Indicates that the parameter or column
      *  is a column in the <code>ResultSet</code>
      *      </UL>
-     *  <LI><B>DATA_TYPE</B> int => SQL type from java.sql.Types
-     *  <LI><B>TYPE_NAME</B> String => SQL type name, for a UDT type the
+     *  <LI><B>DATA_TYPE</B> int {@code =>} SQL type from java.sql.Types
+     *  <LI><B>TYPE_NAME</B> String {@code =>} SQL type name, for a UDT type the
      *  type name is fully qualified
-     *  <LI><B>PRECISION</B> int => precision
-     *  <LI><B>LENGTH</B> int => length in bytes of data
-     *  <LI><B>SCALE</B> short => scale -  null is returned for data types where
+     *  <LI><B>PRECISION</B> int {@code =>} precision
+     *  <LI><B>LENGTH</B> int {@code =>} length in bytes of data
+     *  <LI><B>SCALE</B> short {@code =>} scale -  null is returned for data types where
      * SCALE is not applicable.
-     *  <LI><B>RADIX</B> short => radix
-     *  <LI><B>NULLABLE</B> short => can it contain NULL.
+     *  <LI><B>RADIX</B> short {@code =>} radix
+     *  <LI><B>NULLABLE</B> short {@code =>} can it contain NULL.
      *      <UL>
      *      <LI> functionNoNulls - does not allow NULL values
      *      <LI> functionNullable - allows NULL values
      *      <LI> functionNullableUnknown - nullability unknown
      *      </UL>
-     *  <LI><B>REMARKS</B> String => comment describing column/parameter
-     *  <LI><B>CHAR_OCTET_LENGTH</B> int  => the maximum length of binary
+     *  <LI><B>REMARKS</B> String {@code =>} comment describing column/parameter
+     *  <LI><B>CHAR_OCTET_LENGTH</B> int  {@code =>} the maximum length of binary
      * and character based parameters or columns.  For any other datatype the returned value
      * is a NULL
-     *  <LI><B>ORDINAL_POSITION</B> int  => the ordinal position, starting
+     *  <LI><B>ORDINAL_POSITION</B> int  {@code =>} the ordinal position, starting
      * from 1, for the input and output parameters. A value of 0
      * is returned if this row describes the function's return value.
      * For result set columns, it is the
      * ordinal position of the column in the result set starting from 1.
-     *  <LI><B>IS_NULLABLE</B> String  => ISO rules are used to determine
+     *  <LI><B>IS_NULLABLE</B> String  {@code =>} ISO rules are used to determine
      * the nullability for a parameter or column.
      *       <UL>
      *       <LI> YES           --- if the parameter or column can include NULLs
@@ -3405,7 +3405,7 @@
      *       <LI> empty string  --- if the nullability for the
      * parameter  or column is unknown
      *       </UL>
-     *  <LI><B>SPECIFIC_NAME</B> String  => the name which uniquely identifies
+     *  <LI><B>SPECIFIC_NAME</B> String  {@code =>} the name which uniquely identifies
      * this function within its schema.  This is a user specified, or DBMS
      * generated, name that may be different then the <code>FUNCTION_NAME</code>
      * for example with overload functions
@@ -3591,21 +3591,21 @@
      *
      * <P>Each column description has the following columns:
      *  <OL>
-     *  <LI><B>TABLE_CAT</B> String => table catalog (may be <code>null</code>)
-     *  <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>)
-     *  <LI><B>TABLE_NAME</B> String => table name
-     *  <LI><B>COLUMN_NAME</B> String => column name
-     *  <LI><B>DATA_TYPE</B> int => SQL type from java.sql.Types
-     *  <LI><B>COLUMN_SIZE</B> int => column size.
-     *  <LI><B>DECIMAL_DIGITS</B> int => the number of fractional digits. Null is returned for data types where
+     *  <LI><B>TABLE_CAT</B> String {@code =>} table catalog (may be <code>null</code>)
+     *  <LI><B>TABLE_SCHEM</B> String {@code =>} table schema (may be <code>null</code>)
+     *  <LI><B>TABLE_NAME</B> String {@code =>} table name
+     *  <LI><B>COLUMN_NAME</B> String {@code =>} column name
+     *  <LI><B>DATA_TYPE</B> int {@code =>} SQL type from java.sql.Types
+     *  <LI><B>COLUMN_SIZE</B> int {@code =>} column size.
+     *  <LI><B>DECIMAL_DIGITS</B> int {@code =>} the number of fractional digits. Null is returned for data types where
      * DECIMAL_DIGITS is not applicable.
-     *  <LI><B>NUM_PREC_RADIX</B> int => Radix (typically either 10 or 2)
-     *  <LI><B>COLUMN_USAGE</B> String => The allowed usage for the column.  The
+     *  <LI><B>NUM_PREC_RADIX</B> int {@code =>} Radix (typically either 10 or 2)
+     *  <LI><B>COLUMN_USAGE</B> String {@code =>} The allowed usage for the column.  The
      *  value returned will correspond to the enum name returned by {@link PseudoColumnUsage#name PseudoColumnUsage.name()}
-     *  <LI><B>REMARKS</B> String => comment describing column (may be <code>null</code>)
-     *  <LI><B>CHAR_OCTET_LENGTH</B> int => for char types the
+     *  <LI><B>REMARKS</B> String {@code =>} comment describing column (may be <code>null</code>)
+     *  <LI><B>CHAR_OCTET_LENGTH</B> int {@code =>} for char types the
      *       maximum number of bytes in the column
-     *  <LI><B>IS_NULLABLE</B> String  => ISO rules are used to determine the nullability for a column.
+     *  <LI><B>IS_NULLABLE</B> String  {@code =>} ISO rules are used to determine the nullability for a column.
      *       <UL>
      *       <LI> YES           --- if the column can include NULLs
      *       <LI> NO            --- if the column cannot include NULLs
--- a/jdk/src/share/classes/java/sql/DriverManager.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/sql/DriverManager.java	Wed Jul 05 19:00:49 2017 +0200
@@ -36,7 +36,7 @@
 
 /**
  * <P>The basic service for managing a set of JDBC drivers.<br>
- * <B>NOTE:</B> The {@link <code>DataSource</code>} interface, new in the
+ * <B>NOTE:</B> The {@link javax.sql.DataSource} interface, new in the
  * JDBC 2.0 API, provides another way to connect to a data source.
  * The use of a <code>DataSource</code> object is the preferred means of
  * connecting to a data source.
--- a/jdk/src/share/classes/java/sql/ResultSet.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/sql/ResultSet.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1350,7 +1350,7 @@
      * @param rows the number of rows to fetch
      * @exception SQLException if a database access error occurs; this method
      * is called on a closed result set or the
-     * condition <code>rows >= 0 </code> is not satisfied
+     * condition {@code rows >= 0} is not satisfied
      * @since 1.2
      * @see #getFetchSize
      */
--- a/jdk/src/share/classes/java/sql/Statement.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/sql/Statement.java	Wed Jul 05 19:00:49 2017 +0200
@@ -144,7 +144,7 @@
      * @param max the new column size limit in bytes; zero means there is no limit
      * @exception SQLException if a database access error occurs,
      * this method is called on a closed <code>Statement</code>
-     *            or the condition max >= 0 is not satisfied
+     *            or the condition {@code max >= 0} is not satisfied
      * @see #getMaxFieldSize
      */
     void setMaxFieldSize(int max) throws SQLException;
@@ -174,7 +174,7 @@
      * @param max the new max rows limit; zero means there is no limit
      * @exception SQLException if a database access error occurs,
      * this method is called on a closed <code>Statement</code>
-     *            or the condition max >= 0 is not satisfied
+     *            or the condition {@code max >= 0} is not satisfied
      * @see #getMaxRows
      */
     void setMaxRows(int max) throws SQLException;
@@ -240,7 +240,7 @@
      *        there is no limit
      * @exception SQLException if a database access error occurs,
      * this method is called on a closed <code>Statement</code>
-     *            or the condition seconds >= 0 is not satisfied
+     *            or the condition {@code seconds >= 0} is not satisfied
      * @see #getQueryTimeout
      */
     void setQueryTimeout(int seconds) throws SQLException;
@@ -385,10 +385,10 @@
      * object(s) obtained with the method <code>getResultSet</code>.
      *
      * <P>There are no more results when the following is true:
-     * <PRE>
+     * <PRE>{@code
      *     // stmt is a Statement object
      *     ((stmt.getMoreResults() == false) && (stmt.getUpdateCount() == -1))
-     * </PRE>
+     * }</PRE>
      *
      * @return <code>true</code> if the next result is a <code>ResultSet</code>
      *         object; <code>false</code> if it is an update count or there are
@@ -452,7 +452,7 @@
      * @param rows the number of rows to fetch
      * @exception SQLException if a database access error occurs,
      * this method is called on a closed <code>Statement</code> or the
-     *        condition  <code>rows >= 0</code> is not satisfied.
+     *        condition {@code rows >= 0} is not satisfied.
      * @since 1.2
      * @see #getFetchSize
      */
@@ -665,10 +665,10 @@
      * <code>true</code> if the next result is a <code>ResultSet</code> object.
      *
      * <P>There are no more results when the following is true:
-     * <PRE>
+     * <PRE>{@code
      *     // stmt is a Statement object
      *     ((stmt.getMoreResults(current) == false) && (stmt.getUpdateCount() == -1))
-     * </PRE>
+     * }</PRE>
      *
      * @param current one of the following <code>Statement</code>
      *        constants indicating what should happen to current
@@ -1107,7 +1107,7 @@
      * @param max the new max rows limit; zero means there is no limit
      * @exception SQLException if a database access error occurs,
      * this method is called on a closed <code>Statement</code>
-     *            or the condition max >= 0 is not satisfied
+     *            or the condition {@code max >= 0} is not satisfied
      * @see #getMaxRows
      * @since 1.8
      */
--- a/jdk/src/share/classes/java/text/CharacterIterator.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/text/CharacterIterator.java	Wed Jul 05 19:00:49 2017 +0200
@@ -62,27 +62,27 @@
  * <P>Examples:<P>
  *
  * Traverse the text from start to finish
- * <pre>
+ * <pre>{@code
  * public void traverseForward(CharacterIterator iter) {
  *     for(char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
  *         processChar(c);
  *     }
  * }
- * </pre>
+ * }</pre>
  *
  * Traverse the text backwards, from end to start
- * <pre>
+ * <pre>{@code
  * public void traverseBackward(CharacterIterator iter) {
  *     for(char c = iter.last(); c != CharacterIterator.DONE; c = iter.previous()) {
  *         processChar(c);
  *     }
  * }
- * </pre>
+ * }</pre>
  *
  * Traverse both forward and backward from a given position in the text.
  * Calls to notBoundary() in this example represents some
  * additional stopping criteria.
- * <pre>
+ * <pre>{@code
  * public void traverseOut(CharacterIterator iter, int pos) {
  *     for (char c = iter.setIndex(pos);
  *              c != CharacterIterator.DONE && notBoundary(c);
@@ -96,7 +96,7 @@
  *     int start = iter.getIndex();
  *     processSection(start, end);
  * }
- * </pre>
+ * }</pre>
  *
  * @see StringCharacterIterator
  * @see AttributedCharacterIterator
--- a/jdk/src/share/classes/java/text/ChoiceFormat.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/text/ChoiceFormat.java	Wed Jul 05 19:00:49 2017 +0200
@@ -376,7 +376,7 @@
 
     /**
      * Returns pattern with formatted double.
-     * @param number number to be formatted & substituted.
+     * @param number number to be formatted and substituted.
      * @param toAppendTo where text is appended.
      * @param status ignore no useful status is returned.
      */
--- a/jdk/src/share/classes/java/text/Collator.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/text/Collator.java	Wed Jul 05 19:00:49 2017 +0200
@@ -72,14 +72,14 @@
  * The following example shows how to compare two strings using
  * the <code>Collator</code> for the default locale.
  * <blockquote>
- * <pre>
+ * <pre>{@code
  * // Compare two strings in the default locale
  * Collator myCollator = Collator.getInstance();
  * if( myCollator.compare("abc", "ABC") < 0 )
  *     System.out.println("abc is less than ABC");
  * else
  *     System.out.println("abc is greater than or equal to ABC");
- * </pre>
+ * }</pre>
  * </blockquote>
  *
  * <p>
--- a/jdk/src/share/classes/java/text/DigitList.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/text/DigitList.java	Wed Jul 05 19:00:49 2017 +0200
@@ -271,7 +271,7 @@
      * @param maximumFractionDigits The most fractional digits which should
      * be converted.
      */
-    public final void set(boolean isNegative, double source, int maximumFractionDigits) {
+    final void set(boolean isNegative, double source, int maximumFractionDigits) {
         set(isNegative, source, maximumFractionDigits, true);
     }
 
@@ -288,10 +288,11 @@
      */
     final void set(boolean isNegative, double source, int maximumDigits, boolean fixedPoint) {
 
-        FloatingDecimal fd = new FloatingDecimal(source);
-        boolean hasBeenRoundedUp = fd.digitsRoundedUp();
-        boolean allDecimalDigits = fd.decimalDigitsExact();
-        String digitsString = fd.toJavaFormatString();
+        FloatingDecimal.BinaryToASCIIConverter fdConverter  = FloatingDecimal.getBinaryToASCIIConverter(source);
+        boolean hasBeenRoundedUp = fdConverter.digitsRoundedUp();
+        boolean allDecimalDigits = fdConverter.decimalDigitsExact();
+        assert !fdConverter.isExceptional();
+        String digitsString = fdConverter.toJavaFormatString();
 
         set(isNegative, digitsString,
             hasBeenRoundedUp, allDecimalDigits,
@@ -305,9 +306,9 @@
      * @param allDecimalDigits Boolean value indicating if the digits in s are
      * an exact decimal representation of the double that was passed.
      */
-    final void set(boolean isNegative, String s,
-                   boolean roundedUp, boolean allDecimalDigits,
-                   int maximumDigits, boolean fixedPoint) {
+    private void set(boolean isNegative, String s,
+                     boolean roundedUp, boolean allDecimalDigits,
+                     int maximumDigits, boolean fixedPoint) {
         this.isNegative = isNegative;
         int len = s.length();
         char[] source = getDataChars(len);
@@ -607,7 +608,7 @@
     /**
      * Utility routine to set the value of the digit list from a long
      */
-    public final void set(boolean isNegative, long source) {
+    final void set(boolean isNegative, long source) {
         set(isNegative, source, 0);
     }
 
@@ -620,7 +621,7 @@
      * If maximumDigits is lower than the number of significant digits
      * in source, the representation will be rounded.  Ignored if <= 0.
      */
-    public final void set(boolean isNegative, long source, int maximumDigits) {
+    final void set(boolean isNegative, long source, int maximumDigits) {
         this.isNegative = isNegative;
 
         // This method does not expect a negative number. However,
--- a/jdk/src/share/classes/java/text/SimpleDateFormat.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/text/SimpleDateFormat.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1845,6 +1845,8 @@
             }
             ++pos.index;
         }
+        // Remember the actual start index
+        int actualStart = pos.index;
 
       parsing:
         {
@@ -1924,9 +1926,9 @@
                 // we made adjustments to place the 2-digit year in the proper
                 // century, for parsed strings from "00" to "99".  Any other string
                 // is treated literally:  "2250", "-1", "1", "002".
-                if (count <= 2 && (pos.index - start) == 2
-                    && Character.isDigit(text.charAt(start))
-                    && Character.isDigit(text.charAt(start+1))) {
+                if (count <= 2 && (pos.index - actualStart) == 2
+                    && Character.isDigit(text.charAt(actualStart))
+                    && Character.isDigit(text.charAt(actualStart + 1))) {
                     // Assume for example that the defaultCenturyStart is 6/18/1903.
                     // This means that two-digit years will be forced into the range
                     // 6/18/1903 to 6/17/2003.  As a result, years 00, 01, and 02
--- a/jdk/src/share/classes/java/util/Calendar.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/Calendar.java	Wed Jul 05 19:00:49 2017 +0200
@@ -2681,9 +2681,9 @@
      * Returns whether this <code>Calendar</code> represents a time
      * before the time represented by the specified
      * <code>Object</code>. This method is equivalent to:
-     * <pre><blockquote>
+     * <pre>{@code
      *         compareTo(when) < 0
-     * </blockquote></pre>
+     * }</pre>
      * if and only if <code>when</code> is a <code>Calendar</code>
      * instance. Otherwise, the method returns <code>false</code>.
      *
@@ -2702,9 +2702,9 @@
      * Returns whether this <code>Calendar</code> represents a time
      * after the time represented by the specified
      * <code>Object</code>. This method is equivalent to:
-     * <pre><blockquote>
+     * <pre>{@code
      *         compareTo(when) > 0
-     * </blockquote></pre>
+     * }</pre>
      * if and only if <code>when</code> is a <code>Calendar</code>
      * instance. Otherwise, the method returns <code>false</code>.
      *
--- a/jdk/src/share/classes/java/util/Collections.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/Collections.java	Wed Jul 05 19:00:49 2017 +0200
@@ -924,9 +924,9 @@
      * Returns the starting position of the first occurrence of the specified
      * target list within the specified source list, or -1 if there is no
      * such occurrence.  More formally, returns the lowest index <tt>i</tt>
-     * such that <tt>source.subList(i, i+target.size()).equals(target)</tt>,
+     * such that {@code source.subList(i, i+target.size()).equals(target)},
      * or -1 if there is no such index.  (Returns -1 if
-     * <tt>target.size() > source.size()</tt>.)
+     * {@code target.size() > source.size()})
      *
      * <p>This implementation uses the "brute force" technique of scanning
      * over the source list, looking for a match with the target at each
@@ -977,9 +977,9 @@
      * Returns the starting position of the last occurrence of the specified
      * target list within the specified source list, or -1 if there is no such
      * occurrence.  More formally, returns the highest index <tt>i</tt>
-     * such that <tt>source.subList(i, i+target.size()).equals(target)</tt>,
+     * such that {@code source.subList(i, i+target.size()).equals(target)},
      * or -1 if there is no such index.  (Returns -1 if
-     * <tt>target.size() > source.size()</tt>.)
+     * {@code target.size() > source.size()})
      *
      * <p>This implementation uses the "brute force" technique of iterating
      * over the source list, looking for a match with the target at each
--- a/jdk/src/share/classes/java/util/Currency.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/Currency.java	Wed Jul 05 19:00:49 2017 +0200
@@ -764,7 +764,7 @@
 
     private static void info(String message, Throwable t) {
         PlatformLogger logger = PlatformLogger.getLogger("java.util.Currency");
-        if (logger.isLoggable(PlatformLogger.INFO)) {
+        if (logger.isLoggable(PlatformLogger.Level.INFO)) {
             if (t != null) {
                 logger.info(message, t);
             } else {
--- a/jdk/src/share/classes/java/util/Date.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/Date.java	Wed Jul 05 19:00:49 2017 +0200
@@ -984,8 +984,9 @@
      * exclusive OR of the two halves of the primitive <tt>long</tt>
      * value returned by the {@link Date#getTime}
      * method. That is, the hash code is the value of the expression:
-     * <blockquote><pre>
-     * (int)(this.getTime()^(this.getTime() >>> 32))</pre></blockquote>
+     * <blockquote><pre>{@code
+     * (int)(this.getTime()^(this.getTime() >>> 32))
+     * }</pre></blockquote>
      *
      * @return  a hash code value for this object.
      */
@@ -1085,7 +1086,7 @@
     /**
      * Creates a string representation of this <tt>Date</tt> object of
      * the form:
-     * <blockquote<pre>
+     * <blockquote><pre>
      * d mon yyyy hh:mm:ss GMT</pre></blockquote>
      * where:<ul>
      * <li><i>d</i> is the day of the month (<tt>1</tt> through <tt>31</tt>),
--- a/jdk/src/share/classes/java/util/Formatter.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/Formatter.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2807,10 +2807,10 @@
                 cal = Calendar.getInstance(l == null ? Locale.US : l);
                 cal.setTime((Date)arg);
             } else if (arg instanceof Calendar) {
-                cal = (Calendar) ((Calendar)arg).clone();
+                cal = (Calendar) ((Calendar) arg).clone();
                 cal.setLenient(true);
             } else if (arg instanceof TemporalAccessor) {
-                print((TemporalAccessor)arg, c, l);
+                print((TemporalAccessor) arg, c, l);
                 return;
             } else {
                 failConversion(c, arg);
@@ -3242,13 +3242,10 @@
                 int prec = (precision == -1 ? 6 : precision);
 
                 FormattedFloatingDecimal fd
-                    = new FormattedFloatingDecimal(value, prec,
-                        FormattedFloatingDecimal.Form.SCIENTIFIC);
-
-                char[] v = new char[MAX_FD_CHARS];
-                int len = fd.getChars(v);
-
-                char[] mant = addZeros(mantissa(v, len), prec);
+                        = FormattedFloatingDecimal.valueOf(value, prec,
+                          FormattedFloatingDecimal.Form.SCIENTIFIC);
+
+                char[] mant = addZeros(fd.getMantissa(), prec);
 
                 // If the precision is zero and the '#' flag is set, add the
                 // requested decimal point.
@@ -3256,7 +3253,7 @@
                     mant = addDot(mant);
 
                 char[] exp = (value == 0.0)
-                    ? new char[] {'+','0','0'} : exponent(v, len);
+                    ? new char[] {'+','0','0'} : fd.getExponent();
 
                 int newW = width;
                 if (width != -1)
@@ -3279,15 +3276,10 @@
                 int prec = (precision == -1 ? 6 : precision);
 
                 FormattedFloatingDecimal fd
-                    = new FormattedFloatingDecimal(value, prec,
-                        FormattedFloatingDecimal.Form.DECIMAL_FLOAT);
-
-                // MAX_FD_CHARS + 1 (round?)
-                char[] v = new char[MAX_FD_CHARS + 1
-                                   + Math.abs(fd.getExponent())];
-                int len = fd.getChars(v);
-
-                char[] mant = addZeros(mantissa(v, len), prec);
+                        = FormattedFloatingDecimal.valueOf(value, prec,
+                          FormattedFloatingDecimal.Form.DECIMAL_FLOAT);
+
+                char[] mant = addZeros(fd.getMantissa(), prec);
 
                 // If the precision is zero and the '#' flag is set, add the
                 // requested decimal point.
@@ -3306,22 +3298,17 @@
                     prec = 1;
 
                 FormattedFloatingDecimal fd
-                    = new FormattedFloatingDecimal(value, prec,
-                        FormattedFloatingDecimal.Form.GENERAL);
-
-                // MAX_FD_CHARS + 1 (round?)
-                char[] v = new char[MAX_FD_CHARS + 1
-                                   + Math.abs(fd.getExponent())];
-                int len = fd.getChars(v);
-
-                char[] exp = exponent(v, len);
+                        = FormattedFloatingDecimal.valueOf(value, prec,
+                          FormattedFloatingDecimal.Form.GENERAL);
+
+                char[] exp = fd.getExponent();
                 if (exp != null) {
                     prec -= 1;
                 } else {
                     prec = prec - (value == 0 ? 0 : fd.getExponentRounded()) - 1;
                 }
 
-                char[] mant = addZeros(mantissa(v, len), prec);
+                char[] mant = addZeros(fd.getMantissa(), prec);
                 // If the precision is zero and the '#' flag is set, add the
                 // requested decimal point.
                 if (f.contains(Flags.ALTERNATE) && (prec == 0))
@@ -3380,30 +3367,6 @@
             }
         }
 
-        private char[] mantissa(char[] v, int len) {
-            int i;
-            for (i = 0; i < len; i++) {
-                if (v[i] == 'e')
-                    break;
-            }
-            char[] tmp = new char[i];
-            System.arraycopy(v, 0, tmp, 0, i);
-            return tmp;
-        }
-
-        private char[] exponent(char[] v, int len) {
-            int i;
-            for (i = len - 1; i >= 0; i--) {
-                if (v[i] == 'e')
-                    break;
-            }
-            if (i == -1)
-                return null;
-            char[] tmp = new char[len - i - 1];
-            System.arraycopy(v, i + 1, tmp, 0, len - i - 1);
-            return tmp;
-        }
-
         // Add zeros to the requested precision.
         private char[] addZeros(char[] v, int prec) {
             // Look for the dot.  If we don't find one, the we'll need to add
--- a/jdk/src/share/classes/java/util/HashMap.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/HashMap.java	Wed Jul 05 19:00:49 2017 +0200
@@ -28,6 +28,8 @@
 import java.io.*;
 import java.lang.reflect.ParameterizedType;
 import java.lang.reflect.Type;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.BiConsumer;
 import java.util.function.Consumer;
 import java.util.function.BiFunction;
 import java.util.function.Function;
@@ -912,7 +914,8 @@
      */
     final int initHashSeed() {
         if (sun.misc.VM.isBooted() && Holder.USE_HASHSEED) {
-            return sun.misc.Hashing.randomHashSeed(this);
+            int seed = ThreadLocalRandom.current().nextInt();
+            return (seed != 0) ? seed : 1;
         }
         return 0;
     }
@@ -1297,10 +1300,112 @@
      */
     public V remove(Object key) {
         Entry<K,V> e = removeEntryForKey(key);
-        return (e == null ? null : e.value);
+       return (e == null ? null : e.value);
+   }
+
+   // optimized implementations of default methods in Map
+
+    @Override
+    public void forEach(BiConsumer<? super K, ? super V> action) {
+        Objects.requireNonNull(action);
+        final int expectedModCount = modCount;
+        if (nullKeyEntry != null) {
+            forEachNullKey(expectedModCount, action);
+        }
+        Object[] tab = this.table;
+        for (int index = 0; index < tab.length; index++) {
+            Object item = tab[index];
+            if (item == null) {
+                continue;
+            }
+            if (item instanceof HashMap.TreeBin) {
+                eachTreeNode(expectedModCount, ((TreeBin)item).first, action);
+                continue;
+            }
+            @SuppressWarnings("unchecked")
+            Entry<K, V> entry = (Entry<K, V>)item;
+            while (entry != null) {
+                action.accept(entry.key, entry.value);
+                entry = (Entry<K, V>)entry.next;
+
+                if (expectedModCount != modCount) {
+                    throw new ConcurrentModificationException();
+                }
+            }
+        }
+    }
+
+    private void eachTreeNode(int expectedModCount, TreeNode<K, V> node, BiConsumer<? super K, ? super V> action) {
+        while (node != null) {
+            @SuppressWarnings("unchecked")
+            Entry<K, V> entry = (Entry<K, V>)node.entry;
+            action.accept(entry.key, entry.value);
+            node = (TreeNode<K, V>)entry.next;
+
+            if (expectedModCount != modCount) {
+                throw new ConcurrentModificationException();
+            }
+        }
     }
 
-    // optimized implementations of default methods in Map
+    private void forEachNullKey(int expectedModCount, BiConsumer<? super K, ? super V> action) {
+        action.accept(null, nullKeyEntry.value);
+
+        if (expectedModCount != modCount) {
+            throw new ConcurrentModificationException();
+        }
+    }
+
+    @Override
+    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
+        Objects.requireNonNull(function);
+        final int expectedModCount = modCount;
+        if (nullKeyEntry != null) {
+            replaceforNullKey(expectedModCount, function);
+        }
+        Object[] tab = this.table;
+        for (int index = 0; index < tab.length; index++) {
+            Object item = tab[index];
+            if (item == null) {
+                continue;
+            }
+            if (item instanceof HashMap.TreeBin) {
+                replaceEachTreeNode(expectedModCount, ((TreeBin)item).first, function);
+                continue;
+            }
+            @SuppressWarnings("unchecked")
+            Entry<K, V> entry = (Entry<K, V>)item;
+            while (entry != null) {
+                entry.value = function.apply(entry.key, entry.value);
+                entry = (Entry<K, V>)entry.next;
+
+                if (expectedModCount != modCount) {
+                    throw new ConcurrentModificationException();
+                }
+            }
+        }
+    }
+
+    private void replaceEachTreeNode(int expectedModCount, TreeNode<K, V> node, BiFunction<? super K, ? super V, ? extends V> function) {
+        while (node != null) {
+            @SuppressWarnings("unchecked")
+            Entry<K, V> entry = (Entry<K, V>)node.entry;
+            entry.value = function.apply(entry.key, entry.value);
+            node = (TreeNode<K, V>)entry.next;
+
+            if (expectedModCount != modCount) {
+                throw new ConcurrentModificationException();
+            }
+        }
+    }
+
+    private void replaceforNullKey(int expectedModCount, BiFunction<? super K, ? super V, ? extends V> function) {
+        nullKeyEntry.value = function.apply(null, nullKeyEntry.value);
+
+        if (expectedModCount != modCount) {
+            throw new ConcurrentModificationException();
+        }
+    }
 
     @Override
     public V putIfAbsent(K key, V value) {
@@ -2295,12 +2400,12 @@
             if (e == null)
                 throw new NoSuchElementException();
 
-            if (e instanceof Entry) {
+            if (e instanceof TreeNode) { // TreeBin
+                retVal = (Entry<K,V>)((TreeNode)e).entry;
+                next = retVal.next;
+            } else {
                 retVal = (Entry<K,V>)e;
                 next = ((Entry<K,V>)e).next;
-            } else { // TreeBin
-                retVal = (Entry<K,V>)((TreeNode)e).entry;
-                next = retVal.next;
             }
 
             if (next == null) { // Move to next bin
@@ -2572,8 +2677,9 @@
 
         // set other fields that need values
         if (Holder.USE_HASHSEED) {
+            int seed = ThreadLocalRandom.current().nextInt();
             Holder.UNSAFE.putIntVolatile(this, Holder.HASHSEED_OFFSET,
-                    sun.misc.Hashing.randomHashSeed(this));
+                                         (seed != 0) ? seed : 1);
         }
         table = EMPTY_TABLE;
 
--- a/jdk/src/share/classes/java/util/Hashtable.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/Hashtable.java	Wed Jul 05 19:00:49 2017 +0200
@@ -26,6 +26,7 @@
 package java.util;
 
 import java.io.*;
+import java.util.concurrent.ThreadLocalRandom;
 import java.util.function.BiConsumer;
 import java.util.function.Function;
 import java.util.function.BiFunction;
@@ -219,7 +220,8 @@
      */
     final int initHashSeed() {
         if (sun.misc.VM.isBooted() && Holder.USE_HASHSEED) {
-            return sun.misc.Hashing.randomHashSeed(this);
+            int seed = ThreadLocalRandom.current().nextInt();
+            return (seed != 0) ? seed : 1;
         }
         return 0;
     }
@@ -930,19 +932,39 @@
     public synchronized void forEach(BiConsumer<? super K, ? super V> action) {
         Objects.requireNonNull(action);     // explicit check required in case
                                             // table is empty.
-        Entry<?,?>[] tab = table;
-        for (Entry<?,?> entry : tab) {
+        final int expectedModCount = modCount;
+
+        Entry<?, ?>[] tab = table;
+        for (Entry<?, ?> entry : tab) {
             while (entry != null) {
                 action.accept((K)entry.key, (V)entry.value);
                 entry = entry.next;
+
+                if (expectedModCount != modCount) {
+                    throw new ConcurrentModificationException();
+                }
             }
         }
     }
 
     @Override
-    public synchronized void replaceAll(
-            BiFunction<? super K, ? super V, ? extends V> function) {
-        Map.super.replaceAll(function);
+    public synchronized void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
+        Objects.requireNonNull(function);     // explicit check required in case
+                                              // table is empty.
+        final int expectedModCount = modCount;
+
+        Entry<K, V>[] tab = (Entry<K, V>[])table;
+        for (Entry<K, V> entry : tab) {
+            while (entry != null) {
+                entry.value = Objects.requireNonNull(
+                    function.apply(entry.key, entry.value));
+                entry = entry.next;
+
+                if (expectedModCount != modCount) {
+                    throw new ConcurrentModificationException();
+                }
+            }
+        }
     }
 
     @Override
@@ -1056,7 +1078,7 @@
     }
 
     @Override
-    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
+    public synchronized V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
         Objects.requireNonNull(remappingFunction);
 
         Entry<?,?> tab[] = table;
@@ -1085,7 +1107,7 @@
     }
 
     @Override
-    public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
+    public synchronized V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
         Objects.requireNonNull(remappingFunction);
 
         Entry<?,?> tab[] = table;
@@ -1120,7 +1142,7 @@
     }
 
     @Override
-    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
+    public synchronized V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
         Objects.requireNonNull(remappingFunction);
 
         Entry<?,?> tab[] = table;
@@ -1206,8 +1228,9 @@
 
         // set hashMask
         if (Holder.USE_HASHSEED) {
+            int seed = ThreadLocalRandom.current().nextInt();
             Holder.UNSAFE.putIntVolatile(this, Holder.HASHSEED_OFFSET,
-                    sun.misc.Hashing.randomHashSeed(this));
+                                         (seed != 0) ? seed : 1);
         }
 
         // Read the original length of the array and number of elements
--- a/jdk/src/share/classes/java/util/IdentityHashMap.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/IdentityHashMap.java	Wed Jul 05 19:00:49 2017 +0200
@@ -27,6 +27,8 @@
 
 import java.io.*;
 import java.lang.reflect.Array;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
 import java.util.function.Consumer;
 
 /**
@@ -1337,6 +1339,42 @@
         tab[i + 1] = value;
     }
 
+    @Override
+    public void forEach(BiConsumer<? super K, ? super V> action) {
+        Objects.requireNonNull(action);
+        int expectedModCount = modCount;
+
+        Object[] t = table;
+        for (int index = 0; index < t.length; index += 2) {
+            Object k = t[index];
+            if (k != null) {
+                action.accept((K) unmaskNull(k), (V) t[index + 1]);
+            }
+
+            if (modCount != expectedModCount) {
+                throw new ConcurrentModificationException();
+            }
+        }
+    }
+
+    @Override
+    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
+        Objects.requireNonNull(function);
+        int expectedModCount = modCount;
+
+        Object[] t = table;
+        for (int index = 0; index < t.length; index += 2) {
+            Object k = t[index];
+            if (k != null) {
+                t[index + 1] = function.apply((K) unmaskNull(k), (V) t[index + 1]);
+            }
+
+            if (modCount != expectedModCount) {
+                throw new ConcurrentModificationException();
+            }
+        }
+    }
+
     /**
      * Similar form as array-based Spliterators, but skips blank elements,
      * and guestimates size as decreasing by half per split.
--- a/jdk/src/share/classes/java/util/LinkedHashMap.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/LinkedHashMap.java	Wed Jul 05 19:00:49 2017 +0200
@@ -25,6 +25,8 @@
 
 package java.util;
 import java.io.*;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
 
 /**
  * <p>Hash table and linked list implementation of the <tt>Map</tt> interface,
@@ -296,6 +298,32 @@
         header.before = header.after = header;
     }
 
+    @Override
+    public void forEach(BiConsumer<? super K, ? super V> action) {
+        Objects.requireNonNull(action);
+        int expectedModCount = modCount;
+        for (Entry<K, V> entry = header.after; entry != header; entry = entry.after) {
+            action.accept(entry.key, entry.value);
+
+            if (expectedModCount != modCount) {
+                throw new ConcurrentModificationException();
+            }
+        }
+    }
+
+    @Override
+    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
+        Objects.requireNonNull(function);
+        int expectedModCount = modCount;
+        for (Entry<K, V> entry = header.after; entry != header; entry = entry.after) {
+            entry.value = function.apply(entry.key, entry.value);
+
+            if (expectedModCount != modCount) {
+                throw new ConcurrentModificationException();
+            }
+        }
+    }
+
     /**
      * LinkedHashMap entry.
      */
@@ -437,13 +465,13 @@
      * <p>Sample use: this override will allow the map to grow up to 100
      * entries and then delete the eldest entry each time a new entry is
      * added, maintaining a steady state of 100 entries.
-     * <pre>
+     * <pre>{@code
      *     private static final int MAX_ENTRIES = 100;
      *
      *     protected boolean removeEldestEntry(Map.Entry eldest) {
      *        return size() > MAX_ENTRIES;
      *     }
-     * </pre>
+     * }</pre>
      *
      * <p>This method typically does not modify the map in any way,
      * instead allowing the map to modify itself as directed by its
--- a/jdk/src/share/classes/java/util/Map.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/Map.java	Wed Jul 05 19:00:49 2017 +0200
@@ -545,6 +545,7 @@
                 k = entry.getKey();
                 v = entry.getValue();
             } catch(IllegalStateException ise) {
+                // this usually means the entry is no longer in the map.
                 throw new ConcurrentModificationException(ise);
             }
             action.accept(k, v);
@@ -599,9 +600,19 @@
                 k = entry.getKey();
                 v = entry.getValue();
             } catch(IllegalStateException ise) {
+                // this usually means the entry is no longer in the map.
                 throw new ConcurrentModificationException(ise);
             }
-            entry.setValue(function.apply(k, v));
+
+            // ise thrown from function is not a cme.
+            v = function.apply(k, v);
+
+            try {
+                entry.setValue(v);
+            } catch(IllegalStateException ise) {
+                // this usually means the entry is no longer in the map.
+                throw new ConcurrentModificationException(ise);
+            }
         }
     }
 
--- a/jdk/src/share/classes/java/util/Random.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/Random.java	Wed Jul 05 19:00:49 2017 +0200
@@ -372,7 +372,7 @@
      * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
      * pseudorandomly generated and returned. All 2<font
      * size="-1"><sup>24</sup></font> possible {@code float} values
-     * of the form <i>m&nbsp;x&nbsp</i>2<font
+     * of the form <i>m&nbsp;x&nbsp;</i>2<font
      * size="-1"><sup>-24</sup></font>, where <i>m</i> is a positive
      * integer less than 2<font size="-1"><sup>24</sup> </font>, are
      * produced with (approximately) equal probability.
--- a/jdk/src/share/classes/java/util/ResourceBundle.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/ResourceBundle.java	Wed Jul 05 19:00:49 2017 +0200
@@ -2323,9 +2323,9 @@
          * is returned. And if the resource bundles for the "ja" and
          * "" <code>Locale</code>s are found, then the runtime resource
          * lookup path (parent chain) is:
-         * <pre>
+         * <pre>{@code
          *     Messages_ja -> Messages
-         * </pre>
+         * }</pre>
          *
          * @param baseName
          *        the base name of the resource bundle, a fully
--- a/jdk/src/share/classes/java/util/Scanner.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/Scanner.java	Wed Jul 05 19:00:49 2017 +0200
@@ -49,47 +49,51 @@
  *
  * <p>For example, this code allows a user to read a number from
  * <tt>System.in</tt>:
- * <blockquote><pre>
+ * <blockquote><pre>{@code
  *     Scanner sc = new Scanner(System.in);
  *     int i = sc.nextInt();
- * </pre></blockquote>
+ * }</pre></blockquote>
  *
  * <p>As another example, this code allows <code>long</code> types to be
  * assigned from entries in a file <code>myNumbers</code>:
- * <blockquote><pre>
+ * <blockquote><pre>{@code
  *      Scanner sc = new Scanner(new File("myNumbers"));
  *      while (sc.hasNextLong()) {
  *          long aLong = sc.nextLong();
- *      }</pre></blockquote>
+ *      }
+ * }</pre></blockquote>
  *
  * <p>The scanner can also use delimiters other than whitespace. This
  * example reads several items in from a string:
- *<blockquote><pre>
+ * <blockquote><pre>{@code
  *     String input = "1 fish 2 fish red fish blue fish";
  *     Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
  *     System.out.println(s.nextInt());
  *     System.out.println(s.nextInt());
  *     System.out.println(s.next());
  *     System.out.println(s.next());
- *     s.close(); </pre></blockquote>
+ *     s.close();
+ * }</pre></blockquote>
  * <p>
  * prints the following output:
- * <blockquote><pre>
+ * <blockqjote><pre>{@code
  *     1
  *     2
  *     red
- *     blue </pre></blockquote>
+ *     blue
+ * }</pre></blockquote>
  *
  * <p>The same output can be generated with this code, which uses a regular
  * expression to parse all four tokens at once:
- *<blockquote><pre>
+ * <blockquote><pre>{@code
  *     String input = "1 fish 2 fish red fish blue fish";
  *     Scanner s = new Scanner(input);
  *     s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
  *     MatchResult result = s.match();
  *     for (int i=1; i<=result.groupCount(); i++)
  *         System.out.println(result.group(i));
- *     s.close(); </pre></blockquote>
+ *     s.close();
+ * }</pre></blockquote>
  *
  * <p>The <a name="default-delimiter">default whitespace delimiter</a> used
  * by a scanner is as recognized by {@link java.lang.Character}.{@link
@@ -2640,11 +2644,11 @@
      * <tt>scanner.reset()</tt> behaves in exactly the same way as the
      * invocation
      *
-     * <blockquote><pre>
+     * <blockquote><pre>{@code
      *   scanner.useDelimiter("\\p{javaWhitespace}+")
      *          .useLocale(Locale.getDefault(Locale.Category.FORMAT))
      *          .useRadix(10);
-     * </pre></blockquote>
+     * }</pre></blockquote>
      *
      * @return this scanner
      *
--- a/jdk/src/share/classes/java/util/Spliterators.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/Spliterators.java	Wed Jul 05 19:00:49 2017 +0200
@@ -663,7 +663,7 @@
      * @return An iterator
      * @throws NullPointerException if the given spliterator is {@code null}
      */
-    public static<T> Iterator<T> iteratorFromSpliterator(Spliterator<? extends T> spliterator) {
+    public static<T> Iterator<T> iterator(Spliterator<? extends T> spliterator) {
         Objects.requireNonNull(spliterator);
         class Adapter implements Iterator<T>, Consumer<T> {
             boolean valueReady = false;
@@ -708,7 +708,7 @@
      * @return An iterator
      * @throws NullPointerException if the given spliterator is {@code null}
      */
-    public static PrimitiveIterator.OfInt iteratorFromSpliterator(Spliterator.OfInt spliterator) {
+    public static PrimitiveIterator.OfInt iterator(Spliterator.OfInt spliterator) {
         Objects.requireNonNull(spliterator);
         class Adapter implements PrimitiveIterator.OfInt, IntConsumer {
             boolean valueReady = false;
@@ -753,7 +753,7 @@
      * @return An iterator
      * @throws NullPointerException if the given spliterator is {@code null}
      */
-    public static PrimitiveIterator.OfLong iteratorFromSpliterator(Spliterator.OfLong spliterator) {
+    public static PrimitiveIterator.OfLong iterator(Spliterator.OfLong spliterator) {
         Objects.requireNonNull(spliterator);
         class Adapter implements PrimitiveIterator.OfLong, LongConsumer {
             boolean valueReady = false;
@@ -798,7 +798,7 @@
      * @return An iterator
      * @throws NullPointerException if the given spliterator is {@code null}
      */
-    public static PrimitiveIterator.OfDouble iteratorFromSpliterator(Spliterator.OfDouble spliterator) {
+    public static PrimitiveIterator.OfDouble iterator(Spliterator.OfDouble spliterator) {
         Objects.requireNonNull(spliterator);
         class Adapter implements PrimitiveIterator.OfDouble, DoubleConsumer {
             boolean valueReady = false;
--- a/jdk/src/share/classes/java/util/TimerTask.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/TimerTask.java	Wed Jul 05 19:00:49 2017 +0200
@@ -130,14 +130,14 @@
      * <p>This method is typically invoked from within a task's run method, to
      * determine whether the current execution of the task is sufficiently
      * timely to warrant performing the scheduled activity:
-     * <pre>
+     * <pre>{@code
      *   public void run() {
      *       if (System.currentTimeMillis() - scheduledExecutionTime() >=
      *           MAX_TARDINESS)
      *               return;  // Too late; skip this execution.
      *       // Perform the task
      *   }
-     * </pre>
+     * }</pre>
      * This method is typically <i>not</i> used in conjunction with
      * <i>fixed-delay execution</i> repeating tasks, as their scheduled
      * execution times are allowed to drift over time, and so are not terribly
--- a/jdk/src/share/classes/java/util/TreeMap.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/TreeMap.java	Wed Jul 05 19:00:49 2017 +0200
@@ -25,6 +25,8 @@
 
 package java.util;
 
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
 import java.util.function.Consumer;
 
 /**
@@ -945,6 +947,33 @@
         return tailMap(fromKey, true);
     }
 
+    @Override
+    public void forEach(BiConsumer<? super K, ? super V> action) {
+        Objects.requireNonNull(action);
+        int expectedModCount = modCount;
+        for (Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
+            action.accept(e.key, e.value);
+
+            if (expectedModCount != modCount) {
+                throw new ConcurrentModificationException();
+            }
+        }
+    }
+
+    @Override
+    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
+        Objects.requireNonNull(function);
+        int expectedModCount = modCount;
+
+        for (Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
+            e.value = Objects.requireNonNull(function.apply(e.key, e.value));
+
+            if (expectedModCount != modCount) {
+                throw new ConcurrentModificationException();
+            }
+        }
+    }
+
     // View class support
 
     class Values extends AbstractCollection<V> {
--- a/jdk/src/share/classes/java/util/WeakHashMap.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/WeakHashMap.java	Wed Jul 05 19:00:49 2017 +0200
@@ -27,6 +27,9 @@
 
 import java.lang.ref.WeakReference;
 import java.lang.ref.ReferenceQueue;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
 import java.util.function.Consumer;
 
 
@@ -215,7 +218,8 @@
         if (sun.misc.VM.isBooted() && Holder.USE_HASHSEED) {
             // Do not set hashSeed more than once!
             // assert hashSeed == 0;
-            hashSeed = sun.misc.Hashing.randomHashSeed(this);
+            int seed = ThreadLocalRandom.current().nextInt();
+            hashSeed = (seed != 0) ? seed : 1;
         }
     }
 
@@ -1034,6 +1038,48 @@
         }
     }
 
+    @Override
+    public void forEach(BiConsumer<? super K, ? super V> action) {
+        Objects.requireNonNull(action);
+        int expectedModCount = modCount;
+
+        Entry<K, V>[] tab = getTable();
+        for (Entry<K, V> entry : tab) {
+            while (entry != null) {
+                Object key = entry.get();
+                if (key != null) {
+                    action.accept((K)WeakHashMap.unmaskNull(key), entry.value);
+                }
+                entry = entry.next;
+
+                if (expectedModCount != modCount) {
+                    throw new ConcurrentModificationException();
+                }
+            }
+        }
+    }
+
+    @Override
+    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
+        Objects.requireNonNull(function);
+        int expectedModCount = modCount;
+
+        Entry<K, V>[] tab = getTable();;
+        for (Entry<K, V> entry : tab) {
+            while (entry != null) {
+                Object key = entry.get();
+                if (key != null) {
+                    entry.value = function.apply((K)WeakHashMap.unmaskNull(key), entry.value);
+                }
+                entry = entry.next;
+
+                if (expectedModCount != modCount) {
+                    throw new ConcurrentModificationException();
+                }
+            }
+        }
+    }
+
     /**
      * Similar form as other hash Spliterators, but skips dead
      * elements.
--- a/jdk/src/share/classes/java/util/concurrent/ConcurrentMap.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/concurrent/ConcurrentMap.java	Wed Jul 05 19:00:49 2017 +0200
@@ -35,6 +35,8 @@
 
 package java.util.concurrent;
 import java.util.Map;
+import java.util.Objects;
+import java.util.function.BiFunction;
 
 /**
  * A {@link java.util.Map} providing additional atomic
@@ -183,4 +185,26 @@
      *         or value prevents it from being stored in this map
      */
     V replace(K key, V value);
+
+    /**
+     * {@inheritDoc}
+     *
+     * @implNote This implementation assumes that the ConcurrentMap cannot
+     * contain null values and get() returning null unambiguously means the key
+     * is absent. Implementations which support null values
+     * <strong>must</strong> override this default implementation.
+     */
+    @Override
+    default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
+        Objects.requireNonNull(function);
+        forEach((k,v) -> {
+            while(!replace(k, v, function.apply(k, v))) {
+                // v changed or k is gone
+                if( (v = get(k)) == null) {
+                    // k is no longer in the map.
+                    break;
+                }
+            }
+        });
+    }
 }
--- a/jdk/src/share/classes/java/util/jar/Pack200.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/jar/Pack200.java	Wed Jul 05 19:00:49 2017 +0200
@@ -45,7 +45,7 @@
  * transform the byte-stream back to JAR format.
  * <p>
  * Here is an example using  packer and unpacker:<p>
- * <blockquote><pre>
+ * <pre>{@code
  *    import java.util.jar.Pack200;
  *    import java.util.jar.Pack200.*;
  *    ...
@@ -90,7 +90,7 @@
  *    } catch (IOException ioe) {
  *        ioe.printStackTrace();
  *    }
- * </pre></blockquote>
+ * }</pre>
  * <p>
  * A Pack200 file compressed with gzip can be hosted on HTTP/1.1 web servers.
  * The deployment applications can use "Accept-Encoding=pack200-gzip". This
--- a/jdk/src/share/classes/java/util/logging/ConsoleHandler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/logging/ConsoleHandler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -35,7 +35,7 @@
  * <p>
  * <b>Configuration:</b>
  * By default each <tt>ConsoleHandler</tt> is initialized using the following
- * <tt>LogManager</tt> configuration properties where <tt><handler-name></tt>
+ * <tt>LogManager</tt> configuration properties where {@code <handler-name>}
  * refers to the fully-qualified class name of the handler.
  * If properties are not defined
  * (or have invalid values) then the specified default values are used.
--- a/jdk/src/share/classes/java/util/logging/FileHandler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/logging/FileHandler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -333,7 +333,7 @@
      * @exception  IOException if there are IO problems opening the files.
      * @exception  SecurityException  if a security manager exists and if
      *             the caller does not have <tt>LoggingPermission("control")</tt>.
-     * @exception IllegalArgumentException if limit < 0, or count < 1.
+     * @exception  IllegalArgumentException if {@code limit < 0}, or {@code count < 1}.
      * @exception  IllegalArgumentException if pattern is an empty string
      */
     public FileHandler(String pattern, int limit, int count)
@@ -371,7 +371,7 @@
      * @exception  IOException if there are IO problems opening the files.
      * @exception  SecurityException  if a security manager exists and if
      *             the caller does not have <tt>LoggingPermission("control")</tt>.
-     * @exception IllegalArgumentException if limit < 0, or count < 1.
+     * @exception  IllegalArgumentException if {@code limit < 0}, or {@code count < 1}.
      * @exception  IllegalArgumentException if pattern is an empty string
      *
      */
--- a/jdk/src/share/classes/java/util/logging/LogManager.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/logging/LogManager.java	Wed Jul 05 19:00:49 2017 +0200
@@ -391,27 +391,23 @@
                 // from the execution stack.
                 Object ecx = javaAwtAccess.getExecutionContext();
                 if (ecx == null) {
-                    // fall back to AppContext.getAppContext()
+                    // fall back to thread group seach of AppContext
                     ecx = javaAwtAccess.getContext();
                 }
-                context = (LoggerContext)javaAwtAccess.get(ecx, LoggerContext.class);
-                if (context == null) {
-                    if (javaAwtAccess.isMainAppContext()) {
-                        context = userContext;
-                    } else {
-                        context = new LoggerContext();
-                        // during initialization, rootLogger is null when
-                        // instantiating itself RootLogger
-                        if (manager.rootLogger != null)
-                            context.addLocalLogger(manager.rootLogger);
+                if (ecx != null) {
+                    context = (LoggerContext)javaAwtAccess.get(ecx, LoggerContext.class);
+                    if (context == null) {
+                        if (javaAwtAccess.isMainAppContext()) {
+                            context = userContext;
+                        } else {
+                            context = new LoggerContext();
+                        }
+                        javaAwtAccess.put(ecx, LoggerContext.class, context);
                     }
-                    javaAwtAccess.put(ecx, LoggerContext.class, context);
                 }
             }
-        } else {
-            context = userContext;
         }
-        return context;
+        return context != null ? context : userContext;
     }
 
     private List<LoggerContext> contexts() {
@@ -536,14 +532,26 @@
             return logger;
         }
 
+        synchronized void ensureRootLogger(Logger logger) {
+            if (logger.getName().isEmpty())
+                return;
+
+            // during initialization, rootLogger is null when
+            // instantiating itself RootLogger
+            if (findLogger("") == null && manager.rootLogger != null) {
+                addLocalLogger(manager.rootLogger);
+            }
+        }
+
         // Add a logger to this context.  This method will only set its level
         // and process parent loggers.  It doesn't set its handlers.
         synchronized boolean addLocalLogger(Logger logger) {
+            ensureRootLogger(logger);
+
             final String name = logger.getName();
             if (name == null) {
                 throw new NullPointerException();
             }
-
             LoggerWeakRef ref = namedLoggers.get(name);
             if (ref != null) {
                 if (ref.get() == null) {
--- a/jdk/src/share/classes/java/util/logging/MemoryHandler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/logging/MemoryHandler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -64,7 +64,7 @@
  *        (defaults to no <tt>Filter</tt>). </li>
  * <li>   &lt;handler-name&gt;.size
  *        defines the buffer size (defaults to 1000). </li>
- * <li>   &lt;handler-name>.push
+ * <li>   &lt;handler-name&gt;.push
  *        defines the <tt>pushLevel</tt> (defaults to <tt>level.SEVERE</tt>). </li>
  * <li>   &lt;handler-name&gt;.target
  *        specifies the name of the target <tt>Handler </tt> class.
@@ -155,7 +155,7 @@
      * @param size    the number of log records to buffer (must be greater than zero)
      * @param pushLevel  message level to push on
      *
-     * @throws IllegalArgumentException if size is <= 0
+     * @throws IllegalArgumentException if {@code size is <= 0}
      */
     public MemoryHandler(Handler target, int size, Level pushLevel) {
         if (target == null || pushLevel == null) {
--- a/jdk/src/share/classes/java/util/prefs/Preferences.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/prefs/Preferences.java	Wed Jul 05 19:00:49 2017 +0200
@@ -134,52 +134,52 @@
  * subsequently restore from the backup.
  *
  * <p>The XML document has the following DOCTYPE declaration:
- * <pre>
- * &lt;!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd"&gt;
- * </pre>
+ * <pre>{@code
+ * <!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd">
+ * }</pre>
  * Note that the system URI (http://java.sun.com/dtd/preferences.dtd) is
  * <i>not</i> accessed when exporting or importing preferences; it merely
  * serves as a string to uniquely identify the DTD, which is:
- * <pre>
- *    &lt;?xml version="1.0" encoding="UTF-8"?&gt;
+ * <pre>{@code
+ *    <?xml version="1.0" encoding="UTF-8"?>
  *
- *    &lt;!-- DTD for a Preferences tree. --&gt;
+ *    <!-- DTD for a Preferences tree. -->
  *
- *    &lt;!-- The preferences element is at the root of an XML document
- *         representing a Preferences tree. --&gt;
- *    &lt;!ELEMENT preferences (root)&gt;
+ *    <!-- The preferences element is at the root of an XML document
+ *         representing a Preferences tree. -->
+ *    <!ELEMENT preferences (root)>
  *
- *    &lt;!-- The preferences element contains an optional version attribute,
- *          which specifies version of DTD. --&gt;
- *    &lt;!ATTLIST preferences EXTERNAL_XML_VERSION CDATA "0.0" &gt
+ *    <!-- The preferences element contains an optional version attribute,
+ *          which specifies version of DTD. -->
+ *    <!ATTLIST preferences EXTERNAL_XML_VERSION CDATA "0.0" >
  *
- *    &lt;!-- The root element has a map representing the root's preferences
- *         (if any), and one node for each child of the root (if any). --&gt;
- *    &lt;!ELEMENT root (map, node*) &gt;
+ *    <!-- The root element has a map representing the root's preferences
+ *         (if any), and one node for each child of the root (if any). -->
+ *    <!ELEMENT root (map, node*) >
  *
- *    &lt;!-- Additionally, the root contains a type attribute, which
- *         specifies whether it's the system or user root. --&gt;
- *    &lt;!ATTLIST root
- *              type (system|user) #REQUIRED &gt;
+ *    <!-- Additionally, the root contains a type attribute, which
+ *         specifies whether it's the system or user root. -->
+ *    <!ATTLIST root
+ *              type (system|user) #REQUIRED >
  *
- *    &lt;!-- Each node has a map representing its preferences (if any),
- *         and one node for each child (if any). --&gt;
- *    &lt;!ELEMENT node (map, node*) &gt;
+ *    <!-- Each node has a map representing its preferences (if any),
+ *         and one node for each child (if any). -->
+ *    <!ELEMENT node (map, node*) >
  *
- *    &lt;!-- Additionally, each node has a name attribute --&gt;
- *    &lt;!ATTLIST node
- *              name CDATA #REQUIRED &gt;
+ *    <!-- Additionally, each node has a name attribute -->
+ *    <!ATTLIST node
+ *              name CDATA #REQUIRED >
  *
- *    &lt;!-- A map represents the preferences stored at a node (if any). --&gt;
- *    &lt;!ELEMENT map (entry*) &gt;
+ *    <!-- A map represents the preferences stored at a node (if any). -->
+ *    <!ELEMENT map (entry*) >
  *
- *    &lt;!-- An entry represents a single preference, which is simply
- *          a key-value pair. --&gt;
- *    &lt;!ELEMENT entry EMPTY &gt;
- *    &lt;!ATTLIST entry
+ *    <!-- An entry represents a single preference, which is simply
+ *          a key-value pair. -->
+ *    <!ELEMENT entry EMPTY >
+ *    <!ATTLIST entry
  *              key   CDATA #REQUIRED
- *              value CDATA #REQUIRED &gt;
- * </pre>
+ *              value CDATA #REQUIRED >
+ * }</pre>
  *
  * Every <tt>Preferences</tt> implementation must have an associated {@link
  * PreferencesFactory} implementation.  Every Java(TM) SE implementation must provide
@@ -1161,9 +1161,9 @@
      * This XML document is, in effect, an offline backup of the node.
      *
      * <p>The XML document will have the following DOCTYPE declaration:
-     * <pre>
-     * &lt;!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd"&gt;
-     * </pre>
+     * <pre>{@code
+     * <!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd">
+     * }</pre>
      * The UTF-8 character encoding will be used.
      *
      * <p>This method is an exception to the general rule that the results of
@@ -1192,9 +1192,9 @@
      * effect, an offline backup of the subtree rooted at the node.
      *
      * <p>The XML document will have the following DOCTYPE declaration:
-     * <pre>
-     * &lt;!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd"&gt;
-     * </pre>
+     * <pre>{@code
+     * <!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd">
+     * }</pre>
      * The UTF-8 character encoding will be used.
      *
      * <p>This method is an exception to the general rule that the results of
@@ -1228,9 +1228,9 @@
      * do not exist, the nodes will be created.
      *
      * <p>The XML document must have the following DOCTYPE declaration:
-     * <pre>
-     * &lt;!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd"&gt;
-     * </pre>
+     * <pre>{@code
+     * <!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd">
+     * }</pre>
      * (This method is designed for use in conjunction with
      * {@link #exportNode(OutputStream)} and
      * {@link #exportSubtree(OutputStream)}.
--- a/jdk/src/share/classes/java/util/regex/MatchResult.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/regex/MatchResult.java	Wed Jul 05 19:00:49 2017 +0200
@@ -79,7 +79,7 @@
     /**
      * Returns the offset after the last character matched.  </p>
      *
-     * @return  @return  The offset after the last character matched
+     * @return  The offset after the last character matched
      *
      * @throws  IllegalStateException
      *          If no match has yet been attempted,
--- a/jdk/src/share/classes/java/util/regex/Pattern.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/regex/Pattern.java	Wed Jul 05 19:00:49 2017 +0200
@@ -108,7 +108,7 @@
  * <tr><td valign="top" headers="construct characters"><tt>&#92;x</tt><i>{h...h}</i></td>
  *     <td headers="matches">The character with hexadecimal&nbsp;value&nbsp;<tt>0x</tt><i>h...h</i>
  *         ({@link java.lang.Character#MIN_CODE_POINT Character.MIN_CODE_POINT}
- *         &nbsp;&lt;=&nbsp;<tt>0x</tt><i>h...h</i>&nbsp;&lt;=&nbsp
+ *         &nbsp;&lt;=&nbsp;<tt>0x</tt><i>h...h</i>&nbsp;&lt;=&nbsp;
  *          {@link java.lang.Character#MAX_CODE_POINT Character.MAX_CODE_POINT})</td></tr>
  * <tr><td valign="top" headers="matches"><tt>\t</tt></td>
  *     <td headers="matches">The tab character (<tt>'&#92;u0009'</tt>)</td></tr>
--- a/jdk/src/share/classes/java/util/stream/DoublePipeline.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/stream/DoublePipeline.java	Wed Jul 05 19:00:49 2017 +0200
@@ -168,7 +168,7 @@
 
     @Override
     public final PrimitiveIterator.OfDouble iterator() {
-        return Spliterators.iteratorFromSpliterator(spliterator());
+        return Spliterators.iterator(spliterator());
     }
 
     @Override
@@ -461,7 +461,7 @@
     @Override
     public final double[] toArray() {
         return Nodes.flattenDouble((Node.OfDouble) evaluateToArrayNode(Double[]::new))
-                        .asDoubleArray();
+                        .asPrimitiveArray();
     }
 
     //
--- a/jdk/src/share/classes/java/util/stream/DoubleStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/stream/DoubleStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -753,75 +753,4 @@
                 },
                 Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL));
     }
-
-    /**
-     * Returns a sequential {@code DoubleStream} from {@code startInclusive} (inclusive)
-     * to {@code endExclusive} (exclusive) by an incremental step of 1.0.
-     *
-     * @implSpec
-     * The implementation behaves as if:
-     * <pre>{@code
-     *     doubleRange(startInclusive, endExclusive, 1.0);
-     * }</pre>
-     *
-     * @param startInclusive the (inclusive) initial value
-     * @param endExclusive the exclusive upper bound
-     * @return a sequential {@code DoubleStream} for the range of {@code double}
-     *         elements
-     */
-    public static DoubleStream range(double startInclusive, double endExclusive) {
-        return range(startInclusive, endExclusive, 1.0);
-    }
-
-    /**
-     * Returns a sequential {@code DoubleStream} from {@code startInclusive}
-     * (inclusive) to {@code endExclusive} (exclusive) by {@code step}. If
-     * {@code startInclusive} is greater than or equal to {@code
-     * endExclusive}, an empty stream is returned.
-     *
-     * An equivalent sequence of increasing values can be produced
-     * sequentially using a {@code for} loop as follows:
-     * <pre>{@code
-     *     long size = (long) Math.ceil((startInclusive - endExclusive) / step);
-     *     long i = 0
-     *     for (double v = startInclusive; i < size; i++, v = startInclusive + step * i) {
-     *         ...
-     *     }
-     * }</pre>
-     *
-     * @param startInclusive the (inclusive) initial value
-     * @param endExclusive the exclusive upper bound
-     * @param step the difference between consecutive values
-     * @return a sequential {@code DoubleStream} for tne range of {@code double}
-     *         elements
-     * @throws IllegalArgumentException if {@code step} is less than or equal to
-     *         0. is {@code NaN}, or the count of elements in the range would be
-     *         greater than {@code Long.MAX_VALUE}
-     */
-    public static DoubleStream range(double startInclusive, double endExclusive, double step) {
-        // @@@ Need to check for ranges that may not produce distinct values
-        //     such as when the step is very small
-        //     Also clarify the size of the range which may produce more or less
-        //     than expected
-        if (step <= 0 || Double.isNaN(step)) {
-            throw new IllegalArgumentException(String.format("Illegal step: %f", step));
-        } else {
-            double range = endExclusive - startInclusive;
-            if (range <= 0) {
-                return empty();
-            }
-            double size = Math.ceil((endExclusive - startInclusive) / step);
-            if (Double.isNaN(size)) {
-                throw new IllegalArgumentException(
-                        String.format("Illegal range: %f size is NaN", size));
-            } else if (size > Long.MAX_VALUE) {
-                throw new IllegalArgumentException(
-                        String.format("Illegal range: size %f > Long.MAX_VALUE", size));
-            } else {
-                return StreamSupport.doubleStream(
-                        new Streams.RangeDoubleSpliterator(
-                                startInclusive, endExclusive, step, 0, (long) size));
-            }
-        }
-    }
 }
--- a/jdk/src/share/classes/java/util/stream/IntPipeline.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/stream/IntPipeline.java	Wed Jul 05 19:00:49 2017 +0200
@@ -172,7 +172,7 @@
 
     @Override
     public final PrimitiveIterator.OfInt iterator() {
-        return Spliterators.iteratorFromSpliterator(spliterator());
+        return Spliterators.iterator(spliterator());
     }
 
     @Override
@@ -183,7 +183,7 @@
     // Stateless intermediate ops from IntStream
 
     @Override
-    public final LongStream longs() {
+    public final LongStream asLongStream() {
         return new LongPipeline.StatelessOp<Integer>(this, StreamShape.INT_VALUE,
                                                      StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
             @Override
@@ -199,7 +199,7 @@
     }
 
     @Override
-    public final DoubleStream doubles() {
+    public final DoubleStream asDoubleStream() {
         return new DoublePipeline.StatelessOp<Integer>(this, StreamShape.INT_VALUE,
                                                        StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
             @Override
@@ -424,7 +424,7 @@
 
     @Override
     public final long count() {
-        return longs().map(e -> 1L).sum();
+        return asLongStream().map(e -> 1L).sum();
     }
 
     @Override
@@ -498,7 +498,7 @@
     @Override
     public final int[] toArray() {
         return Nodes.flattenInt((Node.OfInt) evaluateToArrayNode(Integer[]::new))
-                        .asIntArray();
+                        .asPrimitiveArray();
     }
 
     //
--- a/jdk/src/share/classes/java/util/stream/IntStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/stream/IntStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -625,7 +625,7 @@
      * @return a {@code LongStream} consisting of the elements of this stream,
      * converted to {@code long}
      */
-    LongStream longs();
+    LongStream asLongStream();
 
     /**
      * Returns a {@code DoubleStream} consisting of the elements of this stream,
@@ -634,7 +634,7 @@
      * @return a {@code DoubleStream} consisting of the elements of this stream,
      * converted to {@code double}
      */
-    DoubleStream doubles();
+    DoubleStream asDoubleStream();
 
     /**
      * Returns a {@code Stream} consisting of the elements of this stream,
@@ -759,12 +759,13 @@
     /**
      * Returns a sequential {@code IntStream} from {@code startInclusive}
      * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of
-     * 1.
+     * {@code 1}.
      *
-     * @implSpec
-     * The implementation behaves as if:
+     * @apiNote
+     * <p>An equivalent sequence of increasing values can be produced
+     * sequentially using a {@code for} loop as follows:
      * <pre>{@code
-     *     intRange(startInclusive, endExclusive, 1);
+     *     for (int i = startInclusive; i < endExclusive ; i++) { ... }
      * }</pre>
      *
      * @param startInclusive the (inclusive) initial value
@@ -773,36 +774,37 @@
      *         elements
      */
     public static IntStream range(int startInclusive, int endExclusive) {
-        return range(startInclusive, endExclusive, 1);
+        if (startInclusive >= endExclusive) {
+            return empty();
+        } else {
+            return StreamSupport.intStream(
+                    new Streams.RangeIntSpliterator(startInclusive, endExclusive, false));
+        }
     }
 
     /**
      * Returns a sequential {@code IntStream} from {@code startInclusive}
-     * (inclusive) to {@code endExclusive} (exclusive) by a positive {@code
-     * step}.  If {@code startInclusive} is greater than or equal to {@code
-     * endExclusive}, an empty stream is returned.
+     * (inclusive) to {@code endInclusive} (inclusive) by an incremental step of
+     * {@code 1}.
      *
+     * @apiNote
      * <p>An equivalent sequence of increasing values can be produced
      * sequentially using a {@code for} loop as follows:
      * <pre>{@code
-     *     for (int i = startInclusive; i < endExclusive ; i += step) { ... }
+     *     for (int i = startInclusive; i <= endInclusive ; i++) { ... }
      * }</pre>
      *
      * @param startInclusive the (inclusive) initial value
-     * @param endExclusive the exclusive upper bound
-     * @param step the positive difference between consecutive values
+     * @param endInclusive the inclusive upper bound
      * @return a sequential {@code IntStream} for the range of {@code int}
      *         elements
-     * @throws IllegalArgumentException if {@code step} is less than or equal to
-     *                                  0
      */
-    public static IntStream range(int startInclusive, int endExclusive, int step) {
-        if (step <= 0) {
-            throw new IllegalArgumentException(String.format("Illegal step: %d", step));
-        } else if (startInclusive >= endExclusive) {
+    public static IntStream rangeClosed(int startInclusive, int endInclusive) {
+        if (startInclusive > endInclusive) {
             return empty();
         } else {
-            return StreamSupport.intStream(new Streams.RangeIntSpliterator(startInclusive, endExclusive, step));
+            return StreamSupport.intStream(
+                    new Streams.RangeIntSpliterator(startInclusive, endInclusive, true));
         }
     }
 }
--- a/jdk/src/share/classes/java/util/stream/LongPipeline.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/stream/LongPipeline.java	Wed Jul 05 19:00:49 2017 +0200
@@ -169,7 +169,7 @@
 
     @Override
     public final PrimitiveIterator.OfLong iterator() {
-        return Spliterators.iteratorFromSpliterator(spliterator());
+        return Spliterators.iterator(spliterator());
     }
 
     @Override
@@ -180,7 +180,7 @@
     // Stateless intermediate ops from LongStream
 
     @Override
-    public final DoubleStream doubles() {
+    public final DoubleStream asDoubleStream() {
         return new DoublePipeline.StatelessOp<Long>(this, StreamShape.LONG_VALUE,
                                                     StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
             @Override
@@ -479,7 +479,8 @@
 
     @Override
     public final long[] toArray() {
-        return Nodes.flattenLong((Node.OfLong) evaluateToArrayNode(Long[]::new)).asLongArray();
+        return Nodes.flattenLong((Node.OfLong) evaluateToArrayNode(Long[]::new))
+                .asPrimitiveArray();
     }
 
 
--- a/jdk/src/share/classes/java/util/stream/LongStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/stream/LongStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -625,7 +625,7 @@
      * @return a {@code DoubleStream} consisting of the elements of this stream,
      * converted to {@code double}
      */
-    DoubleStream doubles();
+    DoubleStream asDoubleStream();
 
     /**
      * Returns a {@code Stream} consisting of the elements of this stream,
@@ -750,12 +750,13 @@
     /**
      * Returns a sequential {@code LongStream} from {@code startInclusive}
      * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of
-     * 1.
+     * {@code 1}.
      *
-     * @implSpec
-     * The implementation behaves as if:
+     * @apiNote
+     * <p>An equivalent sequence of increasing values can be produced
+     * sequentially using a {@code for} loop as follows:
      * <pre>{@code
-     *     longRange(startInclusive, endExclusive, 1);
+     *     for (long i = startInclusive; i < endExclusive ; i++) { ... }
      * }</pre>
      *
      * @param startInclusive the (inclusive) initial value
@@ -764,36 +765,56 @@
      *         elements
      */
     public static LongStream range(long startInclusive, final long endExclusive) {
-        return range(startInclusive, endExclusive, 1);
+        if (startInclusive >= endExclusive) {
+            return empty();
+        } else if (endExclusive - startInclusive < 0) {
+            // Size of range > Long.MAX_VALUE
+            // Split the range in two and concatenate
+            // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE) then
+            // the lower range, [Long.MIN_VALUE, 0) will be further split in two
+//            long m = startInclusive + Long.divideUnsigned(endExclusive - startInclusive, 2) + 1;
+//            return Streams.concat(range(startInclusive, m), range(m, endExclusive));
+            // This is temporary until Streams.concat is supported
+            throw new UnsupportedOperationException();
+        } else {
+            return StreamSupport.longStream(
+                    new Streams.RangeLongSpliterator(startInclusive, endExclusive, false));
+        }
     }
 
     /**
      * Returns a sequential {@code LongStream} from {@code startInclusive}
-     * (inclusive) to {@code endExclusive} (exclusive) by {@code step}. If
-     * {@code startInclusive} is greater than or equal to {@code
-     * endExclusive}, an empty stream is returned.
+     * (inclusive) to {@code endInclusive} (inclusive) by an incremental step of
+     * {@code 1}.
      *
+     * @apiNote
      * <p>An equivalent sequence of increasing values can be produced
      * sequentially using a {@code for} loop as follows:
      * <pre>{@code
-     *     for (long i = startInclusive; i < endExclusive ; i += step) { ... }
+     *     for (long i = startInclusive; i <= endInclusive ; i++) { ... }
      * }</pre>
      *
      * @param startInclusive the (inclusive) initial value
-     * @param endExclusive the exclusive upper bound
-     * @param step the difference between consecutive values
+     * @param endInclusive the inclusive upper bound
      * @return a sequential {@code LongStream} for the range of {@code long}
      *         elements
-     * @throws IllegalArgumentException if {@code step} is less than or equal to
-     *                                  0
      */
-    public static LongStream range(long startInclusive, final long endExclusive, final long step) {
-        if (step <= 0) {
-            throw new IllegalArgumentException(String.format("Illegal step: %d", step));
-        } else if (startInclusive >= endExclusive) {
+    public static LongStream rangeClosed(long startInclusive, final long endInclusive) {
+        if (startInclusive > endInclusive) {
             return empty();
+        } else if (endInclusive - startInclusive + 1 <= 0) {
+            // Size of range > Long.MAX_VALUE
+            // Split the range in two and concatenate
+            // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE] then
+            // the lower range, [Long.MIN_VALUE, 0), and upper range,
+            // [0, Long.MAX_VALUE], will both be further split in two
+//            long m = startInclusive + Long.divideUnsigned(endInclusive - startInclusive, 2) + 1;
+//            return Streams.concat(range(startInclusive, m), rangeClosed(m, endInclusive));
+            // This is temporary until Streams.concat is supported
+            throw new UnsupportedOperationException();
         } else {
-            return StreamSupport.longStream(new Streams.RangeLongSpliterator(startInclusive, endExclusive, step));
+            return StreamSupport.longStream(
+                    new Streams.RangeLongSpliterator(startInclusive, endInclusive, true));
         }
     }
 }
--- a/jdk/src/share/classes/java/util/stream/Node.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/stream/Node.java	Wed Jul 05 19:00:49 2017 +0200
@@ -242,7 +242,7 @@
          * an instance of an Integer[] array with a length of {@link #count()}
          * and then invokes {@link #copyInto(Integer[], int)} with that
          * Integer[] array at an offset of 0.  This is not efficient and it is
-         * recommended to invoke {@link #asIntArray()}.
+         * recommended to invoke {@link #asPrimitiveArray()}.
          */
         @Override
         default Integer[] asArray(IntFunction<Integer[]> generator) {
@@ -254,7 +254,7 @@
         /**
          * {@inheritDoc}
          *
-         * @implSpec the default implementation invokes {@link #asIntArray()} to
+         * @implSpec the default implementation invokes {@link #asPrimitiveArray()} to
          * obtain an int[] array then and copies the elements from that int[]
          * array into the boxed Integer[] array.  This is not efficient and it
          * is recommended to invoke {@link #copyInto(int[], int)}.
@@ -264,7 +264,7 @@
             if (Tripwire.ENABLED)
                 Tripwire.trip(getClass(), "{0} calling Node.OfInt.copyInto(Integer[], int)");
 
-            int[] array = asIntArray();
+            int[] array = asPrimitiveArray();
             for (int i = 0; i < array.length; i++) {
                 boxed[offset + i] = array[i];
             }
@@ -285,7 +285,7 @@
          *
          * @return an array containing the contents of this {@code Node}
          */
-        int[] asIntArray();
+        int[] asPrimitiveArray();
 
         /**
          * Copies the content of this {@code Node} into an int[] array, starting
@@ -362,7 +362,7 @@
          * an instance of a Long[] array with a length of {@link #count()} and
          * then invokes {@link #copyInto(Long[], int)} with that Long[] array at
          * an offset of 0.  This is not efficient and it is recommended to
-         * invoke {@link #asLongArray()}.
+         * invoke {@link #asPrimitiveArray()}.
          */
         @Override
         default Long[] asArray(IntFunction<Long[]> generator) {
@@ -374,7 +374,7 @@
         /**
          * {@inheritDoc}
          *
-         * @implSpec the default implementation invokes {@link #asLongArray()}
+         * @implSpec the default implementation invokes {@link #asPrimitiveArray()}
          * to obtain a long[] array then and copies the elements from that
          * long[] array into the boxed Long[] array.  This is not efficient and
          * it is recommended to invoke {@link #copyInto(long[], int)}.
@@ -384,7 +384,7 @@
             if (Tripwire.ENABLED)
                 Tripwire.trip(getClass(), "{0} calling Node.OfInt.copyInto(Long[], int)");
 
-            long[] array = asLongArray();
+            long[] array = asPrimitiveArray();
             for (int i = 0; i < array.length; i++) {
                 boxed[offset + i] = array[i];
             }
@@ -405,7 +405,7 @@
          *
          * @return an array containing the contents of this {@code Node}
          */
-        long[] asLongArray();
+        long[] asPrimitiveArray();
 
         /**
          * Copies the content of this {@code Node} into a long[] array, starting
@@ -485,7 +485,7 @@
          * an instance of a Double[] array with a length of {@link #count()} and
          * then invokes {@link #copyInto(Double[], int)} with that Double[]
          * array at an offset of 0.  This is not efficient and it is recommended
-         * to invoke {@link #asDoubleArray()}.
+         * to invoke {@link #asPrimitiveArray()}.
          */
         @Override
         default Double[] asArray(IntFunction<Double[]> generator) {
@@ -497,7 +497,7 @@
         /**
          * {@inheritDoc}
          *
-         * @implSpec the default implementation invokes {@link #asDoubleArray()}
+         * @implSpec the default implementation invokes {@link #asPrimitiveArray()}
          * to obtain a double[] array then and copies the elements from that
          * double[] array into the boxed Double[] array.  This is not efficient
          * and it is recommended to invoke {@link #copyInto(double[], int)}.
@@ -507,7 +507,7 @@
             if (Tripwire.ENABLED)
                 Tripwire.trip(getClass(), "{0} calling Node.OfDouble.copyInto(Double[], int)");
 
-            double[] array = asDoubleArray();
+            double[] array = asPrimitiveArray();
             for (int i = 0; i < array.length; i++) {
                 boxed[offset + i] = array[i];
             }
@@ -528,7 +528,7 @@
          *
          * @return an array containing the contents of this {@code Node}
          */
-        double[] asDoubleArray();
+        double[] asPrimitiveArray();
 
         /**
          * Copies the content of this {@code Node} into a double[] array, starting
--- a/jdk/src/share/classes/java/util/stream/Nodes.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/stream/Nodes.java	Wed Jul 05 19:00:49 2017 +0200
@@ -679,7 +679,7 @@
             }
 
             @Override
-            public int[] asIntArray() {
+            public int[] asPrimitiveArray() {
                 return EMPTY_INT_ARRAY;
             }
         }
@@ -696,7 +696,7 @@
             }
 
             @Override
-            public long[] asLongArray() {
+            public long[] asPrimitiveArray() {
                 return EMPTY_LONG_ARRAY;
             }
         }
@@ -713,7 +713,7 @@
             }
 
             @Override
-            public double[] asDoubleArray() {
+            public double[] asPrimitiveArray() {
                 return EMPTY_DOUBLE_ARRAY;
             }
         }
@@ -1395,7 +1395,7 @@
         }
 
         @Override
-        public int[] asIntArray() {
+        public int[] asPrimitiveArray() {
             if (array.length == curSize) {
                 return array;
             } else {
@@ -1449,7 +1449,7 @@
         }
 
         @Override
-        public long[] asLongArray() {
+        public long[] asPrimitiveArray() {
             if (array.length == curSize) {
                 return array;
             } else {
@@ -1503,7 +1503,7 @@
         }
 
         @Override
-        public double[] asDoubleArray() {
+        public double[] asPrimitiveArray() {
             if (array.length == curSize) {
                 return array;
             } else {
@@ -1561,7 +1561,7 @@
         }
 
         @Override
-        public int[] asIntArray() {
+        public int[] asPrimitiveArray() {
             int[] array = new int[(int) count()];
             copyInto(array, 0);
             return array;
@@ -1594,7 +1594,7 @@
         }
 
         @Override
-        public long[] asLongArray() {
+        public long[] asPrimitiveArray() {
             long[] array = new long[(int) count()];
             copyInto(array, 0);
             return array;
@@ -1627,7 +1627,7 @@
         }
 
         @Override
-        public double[] asDoubleArray() {
+        public double[] asPrimitiveArray() {
             double[] array = new double[(int) count()];
             copyInto(array, 0);
             return array;
@@ -1844,9 +1844,9 @@
         }
 
         @Override
-        public int[] asIntArray() {
+        public int[] asPrimitiveArray() {
             assert !building : "during building";
-            return super.asIntArray();
+            return super.asPrimitiveArray();
         }
 
         @Override
@@ -1904,9 +1904,9 @@
         }
 
         @Override
-        public long[] asLongArray() {
+        public long[] asPrimitiveArray() {
             assert !building : "during building";
-            return super.asLongArray();
+            return super.asPrimitiveArray();
         }
 
         @Override
@@ -1964,9 +1964,9 @@
         }
 
         @Override
-        public double[] asDoubleArray() {
+        public double[] asPrimitiveArray() {
             assert !building : "during building";
-            return super.asDoubleArray();
+            return super.asPrimitiveArray();
         }
 
         @Override
--- a/jdk/src/share/classes/java/util/stream/ReferencePipeline.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/stream/ReferencePipeline.java	Wed Jul 05 19:00:49 2017 +0200
@@ -137,7 +137,7 @@
 
     @Override
     public final Iterator<P_OUT> iterator() {
-        return Spliterators.iteratorFromSpliterator(spliterator());
+        return Spliterators.iterator(spliterator());
     }
 
 
--- a/jdk/src/share/classes/java/util/stream/SortedOps.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/stream/SortedOps.java	Wed Jul 05 19:00:49 2017 +0200
@@ -192,7 +192,7 @@
             else {
                 Node.OfInt n = (Node.OfInt) helper.evaluate(spliterator, true, generator);
 
-                int[] content = n.asIntArray();
+                int[] content = n.asPrimitiveArray();
                 Arrays.parallelSort(content);
 
                 return Nodes.node(content);
@@ -231,7 +231,7 @@
             else {
                 Node.OfLong n = (Node.OfLong) helper.evaluate(spliterator, true, generator);
 
-                long[] content = n.asLongArray();
+                long[] content = n.asPrimitiveArray();
                 Arrays.parallelSort(content);
 
                 return Nodes.node(content);
@@ -270,7 +270,7 @@
             else {
                 Node.OfDouble n = (Node.OfDouble) helper.evaluate(spliterator, true, generator);
 
-                double[] content = n.asDoubleArray();
+                double[] content = n.asPrimitiveArray();
                 Arrays.parallelSort(content);
 
                 return Nodes.node(content);
@@ -401,7 +401,7 @@
 
         @Override
         public void end() {
-            int[] ints = b.asIntArray();
+            int[] ints = b.asPrimitiveArray();
             Arrays.sort(ints);
             downstream.begin(ints.length);
             for (int anInt : ints)
@@ -466,7 +466,7 @@
 
         @Override
         public void end() {
-            long[] longs = b.asLongArray();
+            long[] longs = b.asPrimitiveArray();
             Arrays.sort(longs);
             downstream.begin(longs.length);
             for (long aLong : longs)
@@ -531,7 +531,7 @@
 
         @Override
         public void end() {
-            double[] doubles = b.asDoubleArray();
+            double[] doubles = b.asPrimitiveArray();
             Arrays.sort(doubles);
             downstream.begin(doubles.length);
             for (double aDouble : doubles)
--- a/jdk/src/share/classes/java/util/stream/SpinedBuffer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/stream/SpinedBuffer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -227,7 +227,7 @@
 
     @Override
     public Iterator<E> iterator() {
-        return Spliterators.iteratorFromSpliterator(spliterator());
+        return Spliterators.iterator(spliterator());
     }
 
     @Override
@@ -269,25 +269,45 @@
      * Return a {@link Spliterator} describing the contents of the buffer.
      */
     public Spliterator<E> spliterator() {
-        return new Spliterator<E>() {
+        class Splitr implements Spliterator<E> {
             // The current spine index
             int splSpineIndex;
 
+            // Last spine index
+            final int lastSpineIndex;
+
             // The current element index into the current spine
             int splElementIndex;
 
-            // When splSpineIndex >= spineIndex and splElementIndex >= elementIndex then
+            // Last spine's last element index + 1
+            final int lastSpineElementFence;
+
+            // When splSpineIndex >= lastSpineIndex and
+            // splElementIndex >= lastSpineElementFence then
             // this spliterator is fully traversed
             // tryAdvance can set splSpineIndex > spineIndex if the last spine is full
 
             // The current spine array
-            E[] splChunk = (spine == null) ? curChunk : spine[0];
+            E[] splChunk;
+
+            Splitr(int firstSpineIndex, int lastSpineIndex,
+                   int firstSpineElementIndex, int lastSpineElementFence) {
+                this.splSpineIndex = firstSpineIndex;
+                this.lastSpineIndex = lastSpineIndex;
+                this.splElementIndex = firstSpineElementIndex;
+                this.lastSpineElementFence = lastSpineElementFence;
+                assert spine != null || firstSpineIndex == 0 && lastSpineIndex == 0;
+                splChunk = (spine == null) ? curChunk : spine[firstSpineIndex];
+            }
 
             @Override
             public long estimateSize() {
-                return (spine == null)
-                       ? (elementIndex - splElementIndex)
-                       : count() - (priorElementCount[splSpineIndex] + splElementIndex);
+                return (splSpineIndex == lastSpineIndex)
+                       ? (long) lastSpineElementFence - splElementIndex
+                       : // # of elements prior to end -
+                       priorElementCount[lastSpineIndex] + lastSpineElementFence -
+                       // # of elements prior to current
+                       priorElementCount[splSpineIndex] - splElementIndex;
             }
 
             @Override
@@ -297,14 +317,14 @@
 
             @Override
             public boolean tryAdvance(Consumer<? super E> consumer) {
-                if (splSpineIndex < spineIndex
-                    || (splSpineIndex == spineIndex && splElementIndex < elementIndex)) {
+                if (splSpineIndex < lastSpineIndex
+                    || (splSpineIndex == lastSpineIndex && splElementIndex < lastSpineElementFence)) {
                     consumer.accept(splChunk[splElementIndex++]);
 
                     if (splElementIndex == splChunk.length) {
                         splElementIndex = 0;
                         ++splSpineIndex;
-                        if (spine != null && splSpineIndex < spine.length)
+                        if (spine != null && splSpineIndex <= lastSpineIndex)
                             splChunk = spine[splSpineIndex];
                     }
                     return true;
@@ -314,45 +334,47 @@
 
             @Override
             public void forEachRemaining(Consumer<? super E> consumer) {
-                if (splSpineIndex < spineIndex
-                    || (splSpineIndex == spineIndex && splElementIndex < elementIndex)) {
+                if (splSpineIndex < lastSpineIndex
+                    || (splSpineIndex == lastSpineIndex && splElementIndex < lastSpineElementFence)) {
                     int i = splElementIndex;
                     // completed chunks, if any
-                    for (int sp = splSpineIndex; sp < spineIndex; sp++) {
+                    for (int sp = splSpineIndex; sp < lastSpineIndex; sp++) {
                         E[] chunk = spine[sp];
                         for (; i < chunk.length; i++) {
                             consumer.accept(chunk[i]);
                         }
                         i = 0;
                     }
-
-                    // current chunk
-                    E[] chunk = curChunk;
-                    int hElementIndex = elementIndex;
+                    // last (or current uncompleted) chunk
+                    E[] chunk = (splSpineIndex == lastSpineIndex) ? splChunk : spine[lastSpineIndex];
+                    int hElementIndex = lastSpineElementFence;
                     for (; i < hElementIndex; i++) {
                         consumer.accept(chunk[i]);
                     }
-
-                    splSpineIndex = spineIndex;
-                    splElementIndex = elementIndex;
+                    // mark consumed
+                    splSpineIndex = lastSpineIndex;
+                    splElementIndex = lastSpineElementFence;
                 }
             }
 
             @Override
             public Spliterator<E> trySplit() {
-                if (splSpineIndex < spineIndex) {
-                    Spliterator<E> ret = Arrays.spliterator(spine[splSpineIndex],
-                                                            splElementIndex, spine[splSpineIndex].length);
-                    splChunk = spine[++splSpineIndex];
+                if (splSpineIndex < lastSpineIndex) {
+                    // split just before last chunk (if it is full this means 50:50 split)
+                    Spliterator<E> ret = new Splitr(splSpineIndex, lastSpineIndex - 1,
+                                                    splElementIndex, spine[lastSpineIndex-1].length);
+                    // position to start of last chunk
+                    splSpineIndex = lastSpineIndex;
                     splElementIndex = 0;
+                    splChunk = spine[splSpineIndex];
                     return ret;
                 }
-                else if (splSpineIndex == spineIndex) {
-                    int t = (elementIndex - splElementIndex) / 2;
+                else if (splSpineIndex == lastSpineIndex) {
+                    int t = (lastSpineElementFence - splElementIndex) / 2;
                     if (t == 0)
                         return null;
                     else {
-                        Spliterator<E> ret = Arrays.spliterator(curChunk, splElementIndex, splElementIndex + t);
+                        Spliterator<E> ret = Arrays.spliterator(splChunk, splElementIndex, splElementIndex + t);
                         splElementIndex += t;
                         return ret;
                     }
@@ -361,7 +383,8 @@
                     return null;
                 }
             }
-        };
+        }
+        return new Splitr(0, spineIndex, 0, elementIndex);
     }
 
     /**
@@ -436,7 +459,7 @@
         protected abstract T_ARR[] newArrayArray(int size);
 
         /** Create a new array of the proper type and size */
-        protected abstract T_ARR newArray(int size);
+        public abstract T_ARR newArray(int size);
 
         /** Get the length of an array */
         protected abstract int arrayLength(T_ARR array);
@@ -555,30 +578,53 @@
             arrayForEach(curChunk, 0, elementIndex, consumer);
         }
 
-        abstract class BaseSpliterator<T_SPLITER extends Spliterator<E>>
-                implements Spliterator<E> {
+        abstract class BaseSpliterator<T_SPLITR extends Spliterator.OfPrimitive<E, T_CONS, T_SPLITR>>
+                implements Spliterator.OfPrimitive<E, T_CONS, T_SPLITR> {
             // The current spine index
             int splSpineIndex;
 
+            // Last spine index
+            final int lastSpineIndex;
+
             // The current element index into the current spine
             int splElementIndex;
 
-            // When splSpineIndex >= spineIndex and splElementIndex >= elementIndex then
+            // Last spine's last element index + 1
+            final int lastSpineElementFence;
+
+            // When splSpineIndex >= lastSpineIndex and
+            // splElementIndex >= lastSpineElementFence then
             // this spliterator is fully traversed
             // tryAdvance can set splSpineIndex > spineIndex if the last spine is full
 
             // The current spine array
-            T_ARR splChunk = (spine == null) ? curChunk : spine[0];
+            T_ARR splChunk;
+
+            BaseSpliterator(int firstSpineIndex, int lastSpineIndex,
+                            int firstSpineElementIndex, int lastSpineElementFence) {
+                this.splSpineIndex = firstSpineIndex;
+                this.lastSpineIndex = lastSpineIndex;
+                this.splElementIndex = firstSpineElementIndex;
+                this.lastSpineElementFence = lastSpineElementFence;
+                assert spine != null || firstSpineIndex == 0 && lastSpineIndex == 0;
+                splChunk = (spine == null) ? curChunk : spine[firstSpineIndex];
+            }
+
+            abstract T_SPLITR newSpliterator(int firstSpineIndex, int lastSpineIndex,
+                                             int firstSpineElementIndex, int lastSpineElementFence);
 
             abstract void arrayForOne(T_ARR array, int index, T_CONS consumer);
 
-            abstract T_SPLITER arraySpliterator(T_ARR array, int offset, int len);
+            abstract T_SPLITR arraySpliterator(T_ARR array, int offset, int len);
 
             @Override
             public long estimateSize() {
-                return (spine == null)
-                       ? (elementIndex - splElementIndex)
-                       : count() - (priorElementCount[splSpineIndex] + splElementIndex);
+                return (splSpineIndex == lastSpineIndex)
+                       ? (long) lastSpineElementFence - splElementIndex
+                       : // # of elements prior to end -
+                       priorElementCount[lastSpineIndex] + lastSpineElementFence -
+                       // # of elements prior to current
+                       priorElementCount[splSpineIndex] - splElementIndex;
             }
 
             @Override
@@ -586,15 +632,16 @@
                 return SPLITERATOR_CHARACTERISTICS;
             }
 
+            @Override
             public boolean tryAdvance(T_CONS consumer) {
-                if (splSpineIndex < spineIndex
-                    || (splSpineIndex == spineIndex && splElementIndex < elementIndex)) {
+                if (splSpineIndex < lastSpineIndex
+                    || (splSpineIndex == lastSpineIndex && splElementIndex < lastSpineElementFence)) {
                     arrayForOne(splChunk, splElementIndex++, consumer);
 
                     if (splElementIndex == arrayLength(splChunk)) {
                         splElementIndex = 0;
                         ++splSpineIndex;
-                        if (spine != null && splSpineIndex < spine.length)
+                        if (spine != null && splSpineIndex <= lastSpineIndex)
                             splChunk = spine[splSpineIndex];
                     }
                     return true;
@@ -602,39 +649,44 @@
                 return false;
             }
 
+            @Override
             public void forEachRemaining(T_CONS consumer) {
-                if (splSpineIndex < spineIndex
-                    || (splSpineIndex == spineIndex && splElementIndex < elementIndex)) {
+                if (splSpineIndex < lastSpineIndex
+                    || (splSpineIndex == lastSpineIndex && splElementIndex < lastSpineElementFence)) {
                     int i = splElementIndex;
                     // completed chunks, if any
-                    for (int sp = splSpineIndex; sp < spineIndex; sp++) {
+                    for (int sp = splSpineIndex; sp < lastSpineIndex; sp++) {
                         T_ARR chunk = spine[sp];
                         arrayForEach(chunk, i, arrayLength(chunk), consumer);
                         i = 0;
                     }
-
-                    arrayForEach(curChunk, i, elementIndex, consumer);
-
-                    splSpineIndex = spineIndex;
-                    splElementIndex = elementIndex;
+                    // last (or current uncompleted) chunk
+                    T_ARR chunk = (splSpineIndex == lastSpineIndex) ? splChunk : spine[lastSpineIndex];
+                    arrayForEach(chunk, i, lastSpineElementFence, consumer);
+                    // mark consumed
+                    splSpineIndex = lastSpineIndex;
+                    splElementIndex = lastSpineElementFence;
                 }
             }
 
             @Override
-            public T_SPLITER trySplit() {
-                if (splSpineIndex < spineIndex) {
-                    T_SPLITER ret = arraySpliterator(spine[splSpineIndex], splElementIndex,
-                                                     arrayLength(spine[splSpineIndex]) - splElementIndex);
-                    splChunk = spine[++splSpineIndex];
+            public T_SPLITR trySplit() {
+                if (splSpineIndex < lastSpineIndex) {
+                    // split just before last chunk (if it is full this means 50:50 split)
+                    T_SPLITR ret = newSpliterator(splSpineIndex, lastSpineIndex - 1,
+                                                  splElementIndex, arrayLength(spine[lastSpineIndex - 1]));
+                    // position us to start of last chunk
+                    splSpineIndex = lastSpineIndex;
                     splElementIndex = 0;
+                    splChunk = spine[splSpineIndex];
                     return ret;
                 }
-                else if (splSpineIndex == spineIndex) {
-                    int t = (elementIndex - splElementIndex) / 2;
+                else if (splSpineIndex == lastSpineIndex) {
+                    int t = (lastSpineElementFence - splElementIndex) / 2;
                     if (t == 0)
                         return null;
                     else {
-                        T_SPLITER ret = arraySpliterator(curChunk, splElementIndex, t);
+                        T_SPLITR ret = arraySpliterator(splChunk, splElementIndex, t);
                         splElementIndex += t;
                         return ret;
                     }
@@ -675,7 +727,7 @@
         }
 
         @Override
-        protected int[] newArray(int size) {
+        public int[] newArray(int size) {
             return new int[size];
         }
 
@@ -706,18 +758,26 @@
                 return spine[ch][(int) (index-priorElementCount[ch])];
         }
 
-        public int[] asIntArray() {
-            return asPrimitiveArray();
-        }
-
         @Override
         public PrimitiveIterator.OfInt iterator() {
-            return Spliterators.iteratorFromSpliterator(spliterator());
+            return Spliterators.iterator(spliterator());
         }
 
         public Spliterator.OfInt spliterator() {
             class Splitr extends BaseSpliterator<Spliterator.OfInt>
                     implements Spliterator.OfInt {
+                Splitr(int firstSpineIndex, int lastSpineIndex,
+                       int firstSpineElementIndex, int lastSpineElementFence) {
+                    super(firstSpineIndex, lastSpineIndex,
+                          firstSpineElementIndex, lastSpineElementFence);
+                }
+
+                @Override
+                Splitr newSpliterator(int firstSpineIndex, int lastSpineIndex,
+                                      int firstSpineElementIndex, int lastSpineElementFence) {
+                    return new Splitr(firstSpineIndex, lastSpineIndex,
+                                      firstSpineElementIndex, lastSpineElementFence);
+                }
 
                 @Override
                 void arrayForOne(int[] array, int index, IntConsumer consumer) {
@@ -728,13 +788,13 @@
                 Spliterator.OfInt arraySpliterator(int[] array, int offset, int len) {
                     return Arrays.spliterator(array, offset, offset+len);
                 }
-            };
-            return new Splitr();
+            }
+            return new Splitr(0, spineIndex, 0, elementIndex);
         }
 
         @Override
         public String toString() {
-            int[] array = asIntArray();
+            int[] array = asPrimitiveArray();
             if (array.length < 200) {
                 return String.format("%s[length=%d, chunks=%d]%s",
                                      getClass().getSimpleName(), array.length,
@@ -778,7 +838,7 @@
         }
 
         @Override
-        protected long[] newArray(int size) {
+        public long[] newArray(int size) {
             return new long[size];
         }
 
@@ -809,19 +869,28 @@
                 return spine[ch][(int) (index-priorElementCount[ch])];
         }
 
-        public long[] asLongArray() {
-            return asPrimitiveArray();
-        }
-
         @Override
         public PrimitiveIterator.OfLong iterator() {
-            return Spliterators.iteratorFromSpliterator(spliterator());
+            return Spliterators.iterator(spliterator());
         }
 
 
         public Spliterator.OfLong spliterator() {
             class Splitr extends BaseSpliterator<Spliterator.OfLong>
                     implements Spliterator.OfLong {
+                Splitr(int firstSpineIndex, int lastSpineIndex,
+                       int firstSpineElementIndex, int lastSpineElementFence) {
+                    super(firstSpineIndex, lastSpineIndex,
+                          firstSpineElementIndex, lastSpineElementFence);
+                }
+
+                @Override
+                Splitr newSpliterator(int firstSpineIndex, int lastSpineIndex,
+                                      int firstSpineElementIndex, int lastSpineElementFence) {
+                    return new Splitr(firstSpineIndex, lastSpineIndex,
+                                      firstSpineElementIndex, lastSpineElementFence);
+                }
+
                 @Override
                 void arrayForOne(long[] array, int index, LongConsumer consumer) {
                     consumer.accept(array[index]);
@@ -831,13 +900,13 @@
                 Spliterator.OfLong arraySpliterator(long[] array, int offset, int len) {
                     return Arrays.spliterator(array, offset, offset+len);
                 }
-            };
-            return new Splitr();
+            }
+            return new Splitr(0, spineIndex, 0, elementIndex);
         }
 
         @Override
         public String toString() {
-            long[] array = asLongArray();
+            long[] array = asPrimitiveArray();
             if (array.length < 200) {
                 return String.format("%s[length=%d, chunks=%d]%s",
                                      getClass().getSimpleName(), array.length,
@@ -882,7 +951,7 @@
         }
 
         @Override
-        protected double[] newArray(int size) {
+        public double[] newArray(int size) {
             return new double[size];
         }
 
@@ -913,18 +982,27 @@
                 return spine[ch][(int) (index-priorElementCount[ch])];
         }
 
-        public double[] asDoubleArray() {
-            return asPrimitiveArray();
-        }
-
         @Override
         public PrimitiveIterator.OfDouble iterator() {
-            return Spliterators.iteratorFromSpliterator(spliterator());
+            return Spliterators.iterator(spliterator());
         }
 
         public Spliterator.OfDouble spliterator() {
             class Splitr extends BaseSpliterator<Spliterator.OfDouble>
                     implements Spliterator.OfDouble {
+                Splitr(int firstSpineIndex, int lastSpineIndex,
+                       int firstSpineElementIndex, int lastSpineElementFence) {
+                    super(firstSpineIndex, lastSpineIndex,
+                          firstSpineElementIndex, lastSpineElementFence);
+                }
+
+                @Override
+                Splitr newSpliterator(int firstSpineIndex, int lastSpineIndex,
+                                      int firstSpineElementIndex, int lastSpineElementFence) {
+                    return new Splitr(firstSpineIndex, lastSpineIndex,
+                                      firstSpineElementIndex, lastSpineElementFence);
+                }
+
                 @Override
                 void arrayForOne(double[] array, int index, DoubleConsumer consumer) {
                     consumer.accept(array[index]);
@@ -935,12 +1013,12 @@
                     return Arrays.spliterator(array, offset, offset+len);
                 }
             }
-            return new Splitr();
+            return new Splitr(0, spineIndex, 0, elementIndex);
         }
 
         @Override
         public String toString() {
-            double[] array = asDoubleArray();
+            double[] array = asPrimitiveArray();
             if (array.length < 200) {
                 return String.format("%s[length=%d, chunks=%d]%s",
                                      getClass().getSimpleName(), array.length,
--- a/jdk/src/share/classes/java/util/stream/Streams.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/stream/Streams.java	Wed Jul 05 19:00:49 2017 +0200
@@ -25,7 +25,6 @@
 package java.util.stream;
 
 import java.util.Comparator;
-import java.util.Iterator;
 import java.util.Objects;
 import java.util.Spliterator;
 import java.util.Spliterators;
@@ -62,39 +61,62 @@
      * An {@code int} range spliterator.
      */
     static final class RangeIntSpliterator implements Spliterator.OfInt {
+        // Can never be greater that upTo, this avoids overflow if upper bound
+        // is Integer.MAX_VALUE
+        // All elements are traversed if from == upTo & last == 0
         private int from;
         private final int upTo;
-        private final int step;
+        // 1 if the range is closed and the last element has not been traversed
+        // Otherwise, 0 if the range is open, or is a closed range and all
+        // elements have been traversed
+        private int last;
 
-        RangeIntSpliterator(int from, int upTo, int step) {
+        RangeIntSpliterator(int from, int upTo, boolean closed) {
+            this(from, upTo, closed ? 1 : 0);
+        }
+
+        private RangeIntSpliterator(int from, int upTo, int last) {
             this.from = from;
             this.upTo = upTo;
-            this.step = step;
+            this.last = last;
         }
 
         @Override
         public boolean tryAdvance(IntConsumer consumer) {
-            boolean hasNext = from < upTo;
-            if (hasNext) {
-                consumer.accept(from);
-                from += step;
+            final int i = from;
+            if (i < upTo) {
+                from++;
+                consumer.accept(i);
+                return true;
             }
-            return hasNext;
+            else if (last > 0) {
+                last = 0;
+                consumer.accept(i);
+                return true;
+            }
+            return false;
         }
 
         @Override
         public void forEachRemaining(IntConsumer consumer) {
-            int hUpTo = upTo;
-            int hStep = step; // hoist accesses and checks from loop
-            for (int i = from; i < hUpTo; i += hStep)
+            int i = from;
+            final int hUpTo = upTo;
+            int hLast = last;
+            from = upTo;
+            last = 0;
+            while (i < hUpTo) {
+                consumer.accept(i++);
+            }
+            if (hLast > 0) {
+                // Last element of closed range
                 consumer.accept(i);
-            from = upTo;
+            }
         }
 
         @Override
         public long estimateSize() {
-            int d = upTo - from;
-            return (d / step) + ((d % step == 0) ? 0 : 1);
+            // Ensure ranges of size > Integer.MAX_VALUE report the correct size
+            return ((long) upTo) - from + last;
         }
 
         @Override
@@ -111,57 +133,108 @@
 
         @Override
         public Spliterator.OfInt trySplit() {
-            return estimateSize() <= 1
+            long size = estimateSize();
+            return size <= 1
                    ? null
-                   : new RangeIntSpliterator(from, from = from + midPoint(), step);
+                   // Left split always has a half-open range
+                   : new RangeIntSpliterator(from, from = from + splitPoint(size), 0);
         }
 
-        private int midPoint() {
-            // Size is known to be >= 2
-            int bisection = (upTo - from) / 2;
-            // If bisection > step then round down to nearest multiple of step
-            // otherwise round up to step
-            return bisection > step ? bisection - bisection % step : step;
+        /**
+         * The spliterator size below which the spliterator will be split
+         * at the mid-point to produce balanced splits. Above this size the
+         * spliterator will be split at a ratio of
+         * 1:(RIGHT_BALANCED_SPLIT_RATIO - 1)
+         * to produce right-balanced splits.
+         *
+         * <p>Such splitting ensures that for very large ranges that the left
+         * side of the range will more likely be processed at a lower-depth
+         * than a balanced tree at the expense of a higher-depth for the right
+         * side of the range.
+         *
+         * <p>This is optimized for cases such as IntStream.ints() that is
+         * implemented as range of 0 to Integer.MAX_VALUE but is likely to be
+         * augmented with a limit operation that limits the number of elements
+         * to a count lower than this threshold.
+         */
+        private static final int BALANCED_SPLIT_THRESHOLD = 1 << 24;
+
+        /**
+         * The split ratio of the left and right split when the spliterator
+         * size is above BALANCED_SPLIT_THRESHOLD.
+         */
+        private static final int RIGHT_BALANCED_SPLIT_RATIO = 1 << 3;
+
+        private int splitPoint(long size) {
+            int d = (size < BALANCED_SPLIT_THRESHOLD) ? 2 : RIGHT_BALANCED_SPLIT_RATIO;
+            // 2 <= size <= 2^32
+            return (int) (size / d);
         }
     }
 
     /**
      * A {@code long} range spliterator.
+     *
+     * This implementation cannot be used for ranges whose size is greater
+     * than Long.MAX_VALUE
      */
     static final class RangeLongSpliterator implements Spliterator.OfLong {
+        // Can never be greater that upTo, this avoids overflow if upper bound
+        // is Long.MAX_VALUE
+        // All elements are traversed if from == upTo & last == 0
         private long from;
         private final long upTo;
-        private final long step;
+        // 1 if the range is closed and the last element has not been traversed
+        // Otherwise, 0 if the range is open, or is a closed range and all
+        // elements have been traversed
+        private int last;
 
-        RangeLongSpliterator(long from, long upTo, long step) {
+        RangeLongSpliterator(long from, long upTo, boolean closed) {
+            this(from, upTo, closed ? 1 : 0);
+        }
+
+        private RangeLongSpliterator(long from, long upTo, int last) {
+            assert upTo - from + last > 0;
             this.from = from;
             this.upTo = upTo;
-            this.step = step;
+            this.last = last;
         }
 
         @Override
         public boolean tryAdvance(LongConsumer consumer) {
-            boolean hasNext = from < upTo;
-            if (hasNext) {
-                consumer.accept(from);
-                from += step;
+            final long i = from;
+            if (i < upTo) {
+                from++;
+                consumer.accept(i);
+                return true;
             }
-            return hasNext;
+            else if (last > 0) {
+                last = 0;
+                consumer.accept(i);
+                return true;
+            }
+            return false;
         }
 
         @Override
         public void forEachRemaining(LongConsumer consumer) {
-            long hUpTo = upTo;
-            long hStep = step; // hoist accesses and checks from loop
-            for (long i = from; i < hUpTo; i += hStep)
+            long i = from;
+            final long hUpTo = upTo;
+            int hLast = last;
+            from = upTo;
+            last = 0;
+            while (i < hUpTo) {
+                consumer.accept(i++);
+            }
+            if (hLast > 0) {
+                // Last element of closed range
                 consumer.accept(i);
-            from = upTo;
+            }
         }
 
         @Override
         public long estimateSize() {
-            long d = upTo - from;
-            return (d / step) + ((d % step == 0) ? 0 : 1);
+            return upTo - from + last;
         }
 
         @Override
@@ -178,98 +251,42 @@
 
         @Override
         public Spliterator.OfLong trySplit() {
-            return estimateSize() <= 1
+            long size = estimateSize();
+            return size <= 1
                    ? null
-                   : new RangeLongSpliterator(from, from = from + midPoint(), step);
-        }
-
-        private long midPoint() {
-            // Size is known to be >= 2
-            long bisection = (upTo - from) / 2;
-            // If bisection > step then round down to nearest multiple of step
-            // otherwise round up to step
-            return bisection > step ? bisection - bisection % step : step;
-        }
-    }
-
-    /**
-     * A {@code double} range spliterator.
-     *
-     * <p>The traversing and splitting logic is equivalent to that of
-     * {@code RangeLongSpliterator} for increasing values with a {@code step} of
-     * {@code 1}.
-     *
-     *  <p>A {@code double} value is calculated from the function
-     * {@code start + i * step} where {@code i} is the absolute position of the
-     * value when traversing an instance of this class that has not been split.
-     * This ensures the same values are produced at the same absolute positions
-     * regardless of how an instance of this class is split or traversed.
-     */
-    static final class RangeDoubleSpliterator implements Spliterator.OfDouble {
-        private final double from;
-        private final double upTo;
-        private final double step;
-
-        private long lFrom;
-        private final long lUpTo;
-
-        RangeDoubleSpliterator(double from, double upTo, double step, long lFrom, long lUpTo) {
-            this.from = from;
-            this.upTo = upTo;
-            this.step = step;
-            this.lFrom = lFrom;
-            this.lUpTo = lUpTo;
+                   // Left split always has a half-open range
+                   : new RangeLongSpliterator(from, from = from + splitPoint(size), 0);
         }
 
-        @Override
-        public boolean tryAdvance(DoubleConsumer consumer) {
-            boolean hasNext = lFrom < lUpTo;
-            if (hasNext) {
-                consumer.accept(from + lFrom * step);
-                lFrom++;
-            }
-            return hasNext;
-        }
-
-        @Override
-        public void forEachRemaining(DoubleConsumer consumer) {
-            double hOrigin = from;
-            double hStep = step;
-            long hLUpTo = lUpTo;
-            long i = lFrom;
-            for (; i < hLUpTo; i++) {
-                consumer.accept(hOrigin + i * hStep);
-            }
-            lFrom = i;
-        }
+        /**
+         * The spliterator size below which the spliterator will be split
+         * at the mid-point to produce balanced splits. Above this size the
+         * spliterator will be split at a ratio of
+         * 1:(RIGHT_BALANCED_SPLIT_RATIO - 1)
+         * to produce right-balanced splits.
+         *
+         * <p>Such splitting ensures that for very large ranges that the left
+         * side of the range will more likely be processed at a lower-depth
+         * than a balanced tree at the expense of a higher-depth for the right
+         * side of the range.
+         *
+         * <p>This is optimized for cases such as LongStream.longs() that is
+         * implemented as range of 0 to Long.MAX_VALUE but is likely to be
+         * augmented with a limit operation that limits the number of elements
+         * to a count lower than this threshold.
+         */
+        private static final long BALANCED_SPLIT_THRESHOLD = 1 << 24;
 
-        @Override
-        public long estimateSize() {
-            return lUpTo - lFrom;
-        }
-
-        @Override
-        public int characteristics() {
-            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED |
-                   Spliterator.IMMUTABLE | Spliterator.NONNULL |
-                   Spliterator.DISTINCT | Spliterator.SORTED;
-        }
+        /**
+         * The split ratio of the left and right split when the spliterator
+         * size is above BALANCED_SPLIT_THRESHOLD.
+         */
+        private static final long RIGHT_BALANCED_SPLIT_RATIO = 1 << 3;
 
-        @Override
-        public Comparator<? super Double> getComparator() {
-            return null;
-        }
-
-        @Override
-        public Spliterator.OfDouble trySplit() {
-            return estimateSize() <= 1
-                   ? null
-                   : new RangeDoubleSpliterator(from, upTo, step, lFrom, lFrom = lFrom + midPoint());
-        }
-
-        private long midPoint() {
-            // Size is known to be >= 2
-            return (lUpTo - lFrom) / 2;
+        private long splitPoint(long size) {
+            long d = (size < BALANCED_SPLIT_THRESHOLD) ? 2 : RIGHT_BALANCED_SPLIT_RATIO;
+            // 2 <= size <= Long.MAX_VALUE
+            return size / d;
         }
     }
 
--- a/jdk/src/share/classes/java/util/stream/package-info.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/stream/package-info.java	Wed Jul 05 19:00:49 2017 +0200
@@ -141,7 +141,7 @@
  * parallelism is explicitly requested.  For example, {@code Collection} has methods
  * {@link java.util.Collection#stream} and {@link java.util.Collection#parallelStream},
  * which produce sequential and parallel streams respectively; other stream-bearing methods
- * such as {@link java.util.stream.Streams#intRange(int, int)} produce sequential
+ * such as {@link java.util.stream.IntStream#range(int, int)} produce sequential
  * streams but these can be efficiently parallelized by calling {@code parallel()} on the
  * result. The set of operations on serial and parallel streams is identical. To execute the
  * "sum of weights of blocks" query in parallel, we would do:
--- a/jdk/src/share/classes/java/util/zip/DeflaterInputStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/zip/DeflaterInputStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -97,7 +97,7 @@
      * @param in input stream to read the uncompressed data to
      * @param defl compressor ("deflater") for this stream
      * @param bufLen compression buffer size
-     * @throws IllegalArgumentException if {@code bufLen} is <= 0
+     * @throws IllegalArgumentException if {@code bufLen <= 0}
      * @throws NullPointerException if {@code in} or {@code defl} is null
      */
     public DeflaterInputStream(InputStream in, Deflater defl, int bufLen) {
@@ -163,8 +163,7 @@
      * @param len maximum number of compressed bytes to read into {@code b}
      * @return the actual number of bytes read, or -1 if the end of the
      * uncompressed input stream is reached
-     * @throws IndexOutOfBoundsException  if {@code len} > {@code b.length -
-     * off}
+     * @throws IndexOutOfBoundsException  if {@code len > b.length - off}
      * @throws IOException if an I/O error occurs or if this input stream is
      * already closed
      */
--- a/jdk/src/share/classes/java/util/zip/DeflaterOutputStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/zip/DeflaterOutputStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -71,7 +71,7 @@
      *        {@link Deflater#SYNC_FLUSH} before flushing the output
      *        stream, otherwise only flushes the output stream
      *
-     * @throws IllegalArgumentException if size is <= 0
+     * @throws IllegalArgumentException if {@code size <= 0}
      *
      * @since 1.7
      */
@@ -101,7 +101,7 @@
      * @param out the output stream
      * @param def the compressor ("deflater")
      * @param size the output buffer size
-     * @exception IllegalArgumentException if size is <= 0
+     * @exception IllegalArgumentException if {@code size <= 0}
      */
     public DeflaterOutputStream(OutputStream out, Deflater def, int size) {
         this(out, def, size, false);
--- a/jdk/src/share/classes/java/util/zip/GZIPInputStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/zip/GZIPInputStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -71,7 +71,7 @@
      * @exception ZipException if a GZIP format error has occurred or the
      *                         compression method used is unsupported
      * @exception IOException if an I/O error has occurred
-     * @exception IllegalArgumentException if size is <= 0
+     * @exception IllegalArgumentException if {@code size <= 0}
      */
     public GZIPInputStream(InputStream in, int size) throws IOException {
         super(in, new Inflater(true), size);
--- a/jdk/src/share/classes/java/util/zip/GZIPOutputStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/zip/GZIPOutputStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -61,8 +61,7 @@
      * @param out the output stream
      * @param size the output buffer size
      * @exception IOException If an I/O error has occurred.
-     * @exception IllegalArgumentException if size is <= 0
-
+     * @exception IllegalArgumentException if {@code size <= 0}
      */
     public GZIPOutputStream(OutputStream out, int size) throws IOException {
         this(out, size, false);
@@ -81,7 +80,7 @@
      *        {@link Deflater#SYNC_FLUSH} before flushing the output
      *        stream, otherwise only flushes the output stream
      * @exception IOException If an I/O error has occurred.
-     * @exception IllegalArgumentException if size is <= 0
+     * @exception IllegalArgumentException if {@code size <= 0}
      *
      * @since 1.7
      */
--- a/jdk/src/share/classes/java/util/zip/InflaterInputStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/zip/InflaterInputStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -75,7 +75,7 @@
      * @param in the input stream
      * @param inf the decompressor ("inflater")
      * @param size the input buffer size
-     * @exception IllegalArgumentException if size is <= 0
+     * @exception IllegalArgumentException if {@code size <= 0}
      */
     public InflaterInputStream(InputStream in, Inflater inf, int size) {
         super(in);
@@ -191,7 +191,7 @@
      * @param n the number of bytes to skip
      * @return the actual number of bytes skipped.
      * @exception IOException if an I/O error has occurred
-     * @exception IllegalArgumentException if n < 0
+     * @exception IllegalArgumentException if {@code n < 0}
      */
     public long skip(long n) throws IOException {
         if (n < 0) {
--- a/jdk/src/share/classes/java/util/zip/InflaterOutputStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/zip/InflaterOutputStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -97,7 +97,7 @@
      * @param out output stream to write the uncompressed data to
      * @param infl decompressor ("inflater") for this stream
      * @param bufLen decompression buffer size
-     * @throws IllegalArgumentException if {@code bufLen} is <= 0
+     * @throws IllegalArgumentException if {@code bufLen <= 0}
      * @throws NullPointerException if {@code out} or {@code infl} is null
      */
     public InflaterOutputStream(OutputStream out, Inflater infl, int bufLen) {
@@ -211,8 +211,8 @@
      * the output stream
      * @param off starting offset of the compressed data within {@code b}
      * @param len number of bytes to decompress from {@code b}
-     * @throws IndexOutOfBoundsException if {@code off} < 0, or if
-     * {@code len} < 0, or if {@code len} > {@code b.length - off}
+     * @throws IndexOutOfBoundsException if {@code off < 0}, or if
+     * {@code len < 0}, or if {@code len > b.length - off}
      * @throws IOException if an I/O error occurs or this stream is already
      * closed
      * @throws NullPointerException if {@code b} is null
--- a/jdk/src/share/classes/java/util/zip/ZipFile.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/zip/ZipFile.java	Wed Jul 05 19:00:49 2017 +0200
@@ -59,9 +59,10 @@
  */
 public
 class ZipFile implements ZipConstants, Closeable {
-    private long jzfile;  // address of jzfile data
-    private String name;  // zip file name
-    private int total;    // total number of entries
+    private long jzfile;           // address of jzfile data
+    private final String name;     // zip file name
+    private final int total;       // total number of entries
+    private final boolean locsig;  // if zip file starts with LOCSIG (usually true)
     private volatile boolean closeRequested = false;
 
     private static final int STORED = ZipEntry.STORED;
@@ -221,6 +222,7 @@
         sun.misc.PerfCounter.getZipFileCount().increment();
         this.name = name;
         this.total = getTotal(jzfile);
+        this.locsig = startsWithLOC(jzfile);
     }
 
     /**
@@ -805,10 +807,28 @@
         }
     }
 
+    static {
+        sun.misc.SharedSecrets.setJavaUtilZipFileAccess(
+            new sun.misc.JavaUtilZipFileAccess() {
+                public boolean startsWithLocHeader(ZipFile zip) {
+                    return zip.startsWithLocHeader();
+                }
+             }
+        );
+    }
+
+    /**
+     * Returns {@code true} if, and only if, the zip file begins with {@code
+     * LOCSIG}.
+     */
+    private boolean startsWithLocHeader() {
+        return locsig;
+    }
 
     private static native long open(String name, int mode, long lastModified,
                                     boolean usemmap) throws IOException;
     private static native int getTotal(long jzfile);
+    private static native boolean startsWithLOC(long jzfile);
     private static native int read(long jzfile, long jzentry,
                                    long pos, byte[] b, int off, int len);
 
--- a/jdk/src/share/classes/java/util/zip/ZipInputStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/java/util/zip/ZipInputStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -232,7 +232,7 @@
      * @return the actual number of bytes skipped
      * @exception ZipException if a ZIP file error has occurred
      * @exception IOException if an I/O error has occurred
-     * @exception IllegalArgumentException if n < 0
+     * @exception IllegalArgumentException if {@code n < 0}
      */
     public long skip(long n) throws IOException {
         if (n < 0) {
--- a/jdk/src/share/classes/javax/crypto/spec/IvParameterSpec.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/crypto/spec/IvParameterSpec.java	Wed Jul 05 19:00:49 2017 +0200
@@ -68,7 +68,7 @@
      * starts.
      * @param len the number of IV bytes.
      * @throws IllegalArgumentException if <code>iv</code> is <code>null</code>
-     * or <code>(iv.length - offset < len)</code>
+     * or {@code (iv.length - offset < len)}
      * @throws ArrayIndexOutOfBoundsException is thrown if <code>offset</code>
      * or <code>len</code> index bytes outside the <code>iv</code>.
      */
--- a/jdk/src/share/classes/javax/crypto/spec/RC5ParameterSpec.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/crypto/spec/RC5ParameterSpec.java	Wed Jul 05 19:00:49 2017 +0200
@@ -80,7 +80,7 @@
      * </code> bytes of the buffer are copied to protect against subsequent
      * modification.
      * @exception IllegalArgumentException if <code>iv</code> is
-     * <code>null</code> or <code>(iv.length < 2 * (wordSize / 8))</code>
+     * <code>null</code> or {@code (iv.length < 2 * (wordSize / 8))}
      */
     public RC5ParameterSpec(int version, int rounds, int wordSize, byte[] iv) {
         this(version, rounds, wordSize, iv, 0);
@@ -107,7 +107,7 @@
      * @param offset the offset in <code>iv</code> where the IV starts.
      * @exception IllegalArgumentException if <code>iv</code> is
      * <code>null</code> or
-     * <code>(iv.length - offset < 2 * (wordSize / 8))</code>
+     * {@code (iv.length - offset < 2 * (wordSize / 8))}
      */
     public RC5ParameterSpec(int version, int rounds, int wordSize,
                             byte[] iv, int offset) {
--- a/jdk/src/share/classes/javax/crypto/spec/SecretKeySpec.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/crypto/spec/SecretKeySpec.java	Wed Jul 05 19:00:49 2017 +0200
@@ -130,7 +130,7 @@
      * for information about standard algorithm names.
      * @exception IllegalArgumentException if <code>algorithm</code>
      * is null or <code>key</code> is null, empty, or too short,
-     * i.e. <code>key.length-offset<len</code>.
+     * i.e. {@code key.length-offset<len}.
      * @exception ArrayIndexOutOfBoundsException is thrown if
      * <code>offset</code> or <code>len</code> index bytes outside the
      * <code>key</code>.
--- a/jdk/src/share/classes/javax/management/JMX.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/management/JMX.java	Wed Jul 05 19:00:49 2017 +0200
@@ -27,7 +27,9 @@
 
 import com.sun.jmx.mbeanserver.Introspector;
 import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Modifier;
 import java.lang.reflect.Proxy;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * Static methods from the JMX API.  There are no instances of this class.
@@ -203,11 +205,7 @@
                                       ObjectName objectName,
                                       Class<T> interfaceClass,
                                       boolean notificationEmitter) {
-        return MBeanServerInvocationHandler.newProxyInstance(
-                connection,
-                objectName,
-                interfaceClass,
-                notificationEmitter);
+        return createProxy(connection, objectName, interfaceClass, notificationEmitter, false);
     }
 
     /**
@@ -345,26 +343,7 @@
                                        ObjectName objectName,
                                        Class<T> interfaceClass,
                                        boolean notificationEmitter) {
-        // Check interface for MXBean compliance
-        //
-        try {
-            Introspector.testComplianceMXBeanInterface(interfaceClass);
-        } catch (NotCompliantMBeanException e) {
-            throw new IllegalArgumentException(e);
-        }
-        InvocationHandler handler = new MBeanServerInvocationHandler(
-                connection, objectName, true);
-        final Class<?>[] interfaces;
-        if (notificationEmitter) {
-            interfaces =
-                new Class<?>[] {interfaceClass, NotificationEmitter.class};
-        } else
-            interfaces = new Class<?>[] {interfaceClass};
-        Object proxy = Proxy.newProxyInstance(
-                interfaceClass.getClassLoader(),
-                interfaces,
-                handler);
-        return interfaceClass.cast(proxy);
+        return createProxy(connection, objectName, interfaceClass, notificationEmitter, true);
     }
 
     /**
@@ -392,4 +371,65 @@
         // exactly the string "MXBean" since that would mean there
         // was no package name, which is pretty unlikely in practice.
     }
+
+    /**
+     * Centralised M(X)Bean proxy creation code
+     * @param connection {@linkplain MBeanServerConnection} to use
+     * @param objectName M(X)Bean object name
+     * @param interfaceClass M(X)Bean interface class
+     * @param notificationEmitter Is a notification emitter?
+     * @param isMXBean Is an MXBean?
+     * @return Returns an M(X)Bean proxy generated for the provided interface class
+     * @throws SecurityException
+     * @throws IllegalArgumentException
+     */
+    private static <T> T createProxy(MBeanServerConnection connection,
+                                     ObjectName objectName,
+                                     Class<T> interfaceClass,
+                                     boolean notificationEmitter,
+                                     boolean isMXBean) {
+
+        if (System.getSecurityManager() != null) {
+            checkProxyInterface(interfaceClass);
+        }
+        try {
+            if (isMXBean) {
+                // Check interface for MXBean compliance
+                Introspector.testComplianceMXBeanInterface(interfaceClass);
+            } else {
+                // Check interface for MBean compliance
+                Introspector.testComplianceMBeanInterface(interfaceClass);
+            }
+        } catch (NotCompliantMBeanException e) {
+            throw new IllegalArgumentException(e);
+        }
+
+        InvocationHandler handler = new MBeanServerInvocationHandler(
+                connection, objectName, isMXBean);
+        final Class<?>[] interfaces;
+        if (notificationEmitter) {
+            interfaces =
+                new Class<?>[] {interfaceClass, NotificationEmitter.class};
+        } else
+            interfaces = new Class<?>[] {interfaceClass};
+
+        Object proxy = Proxy.newProxyInstance(
+                interfaceClass.getClassLoader(),
+                interfaces,
+                handler);
+        return interfaceClass.cast(proxy);
+    }
+
+    /**
+     * Checks for the M(X)Bean proxy interface being public and not restricted
+     * @param interfaceClass MBean proxy interface
+     * @throws SecurityException when the proxy interface comes from a restricted
+     *                           package or is not public
+     */
+    private static void checkProxyInterface(Class<?> interfaceClass) {
+        if (!Modifier.isPublic(interfaceClass.getModifiers())) {
+            throw new SecurityException("mbean proxy interface non-public");
+        }
+        ReflectUtil.checkPackageAccess(interfaceClass);
+    }
 }
--- a/jdk/src/share/classes/javax/management/MBeanServerFactory.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/management/MBeanServerFactory.java	Wed Jul 05 19:00:49 2017 +0200
@@ -34,6 +34,7 @@
 import java.util.ArrayList;
 import java.util.logging.Level;
 import javax.management.loading.ClassLoaderRepository;
+import sun.reflect.misc.ReflectUtil;
 
 
 /**
@@ -446,7 +447,7 @@
         }
 
         // No context class loader? Try with Class.forName()
-        return Class.forName(builderClassName);
+        return ReflectUtil.forName(builderClassName);
     }
 
     /**
--- a/jdk/src/share/classes/javax/management/MBeanServerInvocationHandler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/management/MBeanServerInvocationHandler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -231,20 +231,7 @@
                                          ObjectName objectName,
                                          Class<T> interfaceClass,
                                          boolean notificationBroadcaster) {
-        final InvocationHandler handler =
-            new MBeanServerInvocationHandler(connection, objectName);
-        final Class<?>[] interfaces;
-        if (notificationBroadcaster) {
-            interfaces =
-                new Class<?>[] {interfaceClass, NotificationEmitter.class};
-        } else
-            interfaces = new Class<?>[] {interfaceClass};
-
-        Object proxy =
-            Proxy.newProxyInstance(interfaceClass.getClassLoader(),
-                                   interfaces,
-                                   handler);
-        return interfaceClass.cast(proxy);
+        return JMX.newMBeanProxy(connection, objectName, interfaceClass, notificationBroadcaster);
     }
 
     public Object invoke(Object proxy, Method method, Object[] args)
--- a/jdk/src/share/classes/javax/management/NotificationBroadcasterSupport.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/management/NotificationBroadcasterSupport.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 
 import java.util.Collections;
 import java.util.List;
+import java.util.Objects;
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.Executor;
 
@@ -288,6 +289,7 @@
             this.handback = handback;
         }
 
+        @Override
         public boolean equals(Object o) {
             if (!(o instanceof ListenerInfo))
                 return false;
@@ -298,6 +300,11 @@
                 return (li.listener == listener && li.filter == filter
                         && li.handback == handback);
         }
+
+        @Override
+        public int hashCode() {
+            return Objects.hashCode(listener);
+        }
     }
 
     private static class WildcardListenerInfo extends ListenerInfo {
@@ -305,10 +312,16 @@
             super(listener, null, null);
         }
 
+        @Override
         public boolean equals(Object o) {
             assert (!(o instanceof WildcardListenerInfo));
             return o.equals(this);
         }
+
+        @Override
+        public int hashCode() {
+            return super.hashCode();
+        }
     }
 
     private List<ListenerInfo> listenerList =
--- a/jdk/src/share/classes/javax/management/StandardEmitterMBean.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/management/StandardEmitterMBean.java	Wed Jul 05 19:00:49 2017 +0200
@@ -64,6 +64,9 @@
 public class StandardEmitterMBean extends StandardMBean
         implements NotificationEmitter {
 
+    private static final MBeanNotificationInfo[] NO_NOTIFICATION_INFO =
+        new MBeanNotificationInfo[0];
+
     private final NotificationEmitter emitter;
     private final MBeanNotificationInfo[] notificationInfo;
 
@@ -99,11 +102,7 @@
      */
     public <T> StandardEmitterMBean(T implementation, Class<T> mbeanInterface,
                                     NotificationEmitter emitter) {
-        super(implementation, mbeanInterface, false);
-        if (emitter == null)
-            throw new IllegalArgumentException("Null emitter");
-        this.emitter = emitter;
-        this.notificationInfo = emitter.getNotificationInfo();
+        this(implementation, mbeanInterface, false, emitter);
     }
 
     /**
@@ -148,7 +147,12 @@
         if (emitter == null)
             throw new IllegalArgumentException("Null emitter");
         this.emitter = emitter;
-        this.notificationInfo = emitter.getNotificationInfo();
+        MBeanNotificationInfo[] infos = emitter.getNotificationInfo();
+        if (infos == null || infos.length == 0) {
+            this.notificationInfo = NO_NOTIFICATION_INFO;
+        } else {
+            this.notificationInfo = infos.clone();
+        }
     }
 
     /**
@@ -184,11 +188,7 @@
      */
     protected StandardEmitterMBean(Class<?> mbeanInterface,
                                    NotificationEmitter emitter) {
-        super(mbeanInterface, false);
-        if (emitter == null)
-            throw new IllegalArgumentException("Null emitter");
-        this.emitter = emitter;
-        this.notificationInfo = emitter.getNotificationInfo();
+        this(mbeanInterface, false, emitter);
     }
 
     /**
@@ -231,7 +231,12 @@
         if (emitter == null)
             throw new IllegalArgumentException("Null emitter");
         this.emitter = emitter;
-        this.notificationInfo = emitter.getNotificationInfo();
+        MBeanNotificationInfo[] infos = emitter.getNotificationInfo();
+        if (infos == null || infos.length == 0) {
+            this.notificationInfo = NO_NOTIFICATION_INFO;
+        } else {
+            this.notificationInfo = infos.clone();
+        }
     }
 
     public void removeNotificationListener(NotificationListener listener)
@@ -253,7 +258,16 @@
     }
 
     public MBeanNotificationInfo[] getNotificationInfo() {
-        return notificationInfo;
+        // this getter might get called from the super constructor
+        // when the notificationInfo has not been properly set yet
+        if (notificationInfo == null) {
+            return NO_NOTIFICATION_INFO;
+        }
+        if (notificationInfo.length == 0) {
+            return notificationInfo;
+        } else {
+            return notificationInfo.clone();
+        }
     }
 
     /**
--- a/jdk/src/share/classes/javax/management/openmbean/CompositeDataInvocationHandler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/management/openmbean/CompositeDataInvocationHandler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -169,6 +169,8 @@
                    the only non-final methods in Object that are not
                    handled above are finalize and clone, and these
                    are not overridden in generated proxies.  */
+                // this plain Method.invoke is called only if the declaring class
+                // is Object and so it's safe.
                 return method.invoke(this, args);
             }
         }
--- a/jdk/src/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/management/openmbean/OpenMBeanAttributeInfoSupport.java	Wed Jul 05 19:00:49 2017 +0200
@@ -45,6 +45,9 @@
 import javax.management.ImmutableDescriptor;
 import javax.management.MBeanAttributeInfo;
 import com.sun.jmx.remote.util.EnvHelp;
+import sun.reflect.misc.ConstructorUtil;
+import sun.reflect.misc.MethodUtil;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * Describes an attribute of an open MBean.
@@ -690,6 +693,7 @@
     private static <T> T convertFromString(String s, OpenType<T> openType) {
         Class<T> c;
         try {
+            ReflectUtil.checkPackageAccess(openType.safeGetClassName());
             c = cast(Class.forName(openType.safeGetClassName()));
         } catch (ClassNotFoundException e) {
             throw new NoClassDefFoundError(e.toString());  // can't happen
@@ -698,6 +702,8 @@
         // Look for: public static T valueOf(String)
         Method valueOf;
         try {
+            // It is safe to call this plain Class.getMethod because the class "c"
+            // was checked before by ReflectUtil.checkPackageAccess(openType.safeGetClassName());
             valueOf = c.getMethod("valueOf", String.class);
             if (!Modifier.isStatic(valueOf.getModifiers()) ||
                     valueOf.getReturnType() != c)
@@ -707,7 +713,7 @@
         }
         if (valueOf != null) {
             try {
-                return c.cast(valueOf.invoke(null, s));
+                return c.cast(MethodUtil.invoke(valueOf, null, new Object[] {s}));
             } catch (Exception e) {
                 final String msg =
                     "Could not convert \"" + s + "\" using method: " + valueOf;
@@ -718,6 +724,8 @@
         // Look for: public T(String)
         Constructor<T> con;
         try {
+            // It is safe to call this plain Class.getConstructor because the class "c"
+            // was checked before by ReflectUtil.checkPackageAccess(openType.safeGetClassName());
             con = c.getConstructor(String.class);
         } catch (NoSuchMethodException e) {
             con = null;
--- a/jdk/src/share/classes/javax/management/relation/RelationNotification.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/management/relation/RelationNotification.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
 import javax.management.Notification;
 import javax.management.ObjectName;
 
+import java.io.InvalidObjectException;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
@@ -37,8 +38,11 @@
 import java.security.PrivilegedAction;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
 
 import com.sun.jmx.mbeanserver.GetPropertyAction;
 import static com.sun.jmx.mbeanserver.Util.cast;
@@ -256,21 +260,14 @@
 
         super(notifType, sourceObj, sequence, timeStamp, message);
 
-        // Can throw IllegalArgumentException
-        initMembers(1,
-                    notifType,
-                    sourceObj,
-                    sequence,
-                    timeStamp,
-                    message,
-                    id,
-                    typeName,
-                    objectName,
-                    unregMBeanList,
-                    null,
-                    null,
-                    null);
-        return;
+        if (!isValidBasic(notifType,sourceObj,id,typeName) || !isValidCreate(notifType)) {
+            throw new IllegalArgumentException("Invalid parameter.");
+        }
+
+        relationId = id;
+        relationTypeName = typeName;
+        relationObjName = safeGetObjectName(objectName);
+        unregisterMBeanList = safeGetObjectNameList(unregMBeanList);
     }
 
     /**
@@ -313,21 +310,17 @@
 
         super(notifType, sourceObj, sequence, timeStamp, message);
 
-        // Can throw IllegalArgumentException
-        initMembers(2,
-                    notifType,
-                    sourceObj,
-                    sequence,
-                    timeStamp,
-                    message,
-                    id,
-                    typeName,
-                    objectName,
-                    null,
-                    name,
-                    newValue,
-                    oldValue);
-        return;
+        if (!isValidBasic(notifType,sourceObj,id,typeName) || !isValidUpdate(notifType,name,newValue,oldValue)) {
+            throw new IllegalArgumentException("Invalid parameter.");
+        }
+
+        relationId = id;
+        relationTypeName = typeName;
+        relationObjName = safeGetObjectName(objectName);
+
+        roleName = name;
+        oldRoleValue = safeGetObjectNameList(oldValue);
+        newRoleValue = safeGetObjectNameList(newValue);
     }
 
     //
@@ -463,83 +456,64 @@
     //  - no role name (for role update)
     //  - no role old value (for role update)
     //  - no role new value (for role update)
-    private void initMembers(int notifKind,
-                             String notifType,
-                             Object sourceObj,
-                             long sequence,
-                             long timeStamp,
-                             String message,
-                             String id,
-                             String typeName,
-                             ObjectName objectName,
-                             List<ObjectName> unregMBeanList,
-                             String name,
-                             List<ObjectName> newValue,
-                             List<ObjectName> oldValue)
-            throws IllegalArgumentException {
 
-        boolean badInitFlg = false;
+    private boolean isValidBasic(String notifType, Object sourceObj, String id, String typeName){
+        if (notifType == null || sourceObj == null ||
+            id == null || typeName == null) {
+            return false;
+        }
 
-        if (notifType == null ||
-            sourceObj == null ||
-            (!(sourceObj instanceof RelationService) &&
-             !(sourceObj instanceof ObjectName)) ||
-            id == null ||
-            typeName == null) {
-
-            badInitFlg = true;
+        if (!(sourceObj instanceof RelationService) &&
+            !(sourceObj instanceof ObjectName)) {
+            return false;
         }
 
-        if (notifKind == 1) {
+        return true;
+    }
 
-            if ((!(notifType.equals(RelationNotification.RELATION_BASIC_CREATION)))
-                &&
-                (!(notifType.equals(RelationNotification.RELATION_MBEAN_CREATION)))
-                &&
-                (!(notifType.equals(RelationNotification.RELATION_BASIC_REMOVAL)))
-                &&
-                (!(notifType.equals(RelationNotification.RELATION_MBEAN_REMOVAL)))
-                ) {
+    private boolean isValidCreate(String notifType) {
+        String[] validTypes= {RelationNotification.RELATION_BASIC_CREATION,
+                              RelationNotification.RELATION_MBEAN_CREATION,
+                              RelationNotification.RELATION_BASIC_REMOVAL,
+                              RelationNotification.RELATION_MBEAN_REMOVAL};
+
+        Set<String> ctSet = new HashSet<String>(Arrays.asList(validTypes));
+        return ctSet.contains(notifType);
+    }
+
+    private boolean isValidUpdate(String notifType, String name,
+                                  List<ObjectName> newValue, List<ObjectName> oldValue) {
 
-                // Creation/removal
-                badInitFlg = true;
-            }
+        if (!(notifType.equals(RelationNotification.RELATION_BASIC_UPDATE)) &&
+            !(notifType.equals(RelationNotification.RELATION_MBEAN_UPDATE))) {
+            return false;
+        }
 
-        } else if (notifKind == 2) {
+        if (name == null || oldValue == null || newValue == null) {
+            return false;
+        }
 
-            if (((!(notifType.equals(RelationNotification.RELATION_BASIC_UPDATE)))
-                 &&
-                 (!(notifType.equals(RelationNotification.RELATION_MBEAN_UPDATE))))
-                || name == null ||
-                oldValue == null ||
-                newValue == null) {
+        return true;
+    }
 
-                // Role update
-                badInitFlg = true;
+    private ArrayList<ObjectName> safeGetObjectNameList(List<ObjectName> src){
+        ArrayList<ObjectName> dest = null;
+        if (src != null) {
+            dest = new ArrayList<ObjectName>();
+            for (ObjectName item : src) {
+                // NPE thrown if we attempt to add null object
+                dest.add(ObjectName.getInstance(item));
             }
         }
-
-        if (badInitFlg) {
-            String excMsg = "Invalid parameter.";
-            throw new IllegalArgumentException(excMsg);
-        }
+        return dest;
+    }
 
-        relationId = id;
-        relationTypeName = typeName;
-        relationObjName = objectName;
-        if (unregMBeanList != null) {
-            unregisterMBeanList = new ArrayList<ObjectName>(unregMBeanList);
+    private ObjectName safeGetObjectName(ObjectName src){
+        ObjectName dest = null;
+        if (src != null) {
+            dest = ObjectName.getInstance(src);
         }
-        if (name != null) {
-            roleName = name;
-        }
-        if (oldValue != null) {
-            oldRoleValue = new ArrayList<ObjectName>(oldValue);
-        }
-        if (newValue != null) {
-            newRoleValue = new ArrayList<ObjectName>(newValue);
-        }
-        return;
+        return dest;
     }
 
     /**
@@ -547,53 +521,56 @@
      */
     private void readObject(ObjectInputStream in)
             throws IOException, ClassNotFoundException {
-      if (compat)
-      {
-        // Read an object serialized in the old serial form
-        //
+
+        String tmpRelationId, tmpRelationTypeName, tmpRoleName;
+
+        ObjectName tmpRelationObjName;
+        List<ObjectName> tmpNewRoleValue, tmpOldRoleValue, tmpUnregMBeanList;
+
         ObjectInputStream.GetField fields = in.readFields();
-        newRoleValue = cast(fields.get("myNewRoleValue", null));
-        if (fields.defaulted("myNewRoleValue"))
-        {
-          throw new NullPointerException("newRoleValue");
-        }
-        oldRoleValue = cast(fields.get("myOldRoleValue", null));
-        if (fields.defaulted("myOldRoleValue"))
-        {
-          throw new NullPointerException("oldRoleValue");
-        }
-        relationId = (String) fields.get("myRelId", null);
-        if (fields.defaulted("myRelId"))
-        {
-          throw new NullPointerException("relationId");
+
+        if (compat) {
+            tmpRelationId = (String)fields.get("myRelId", null);
+            tmpRelationTypeName = (String)fields.get("myRelTypeName", null);
+            tmpRoleName = (String)fields.get("myRoleName", null);
+
+            tmpRelationObjName = (ObjectName)fields.get("myRelObjName", null);
+            tmpNewRoleValue = cast(fields.get("myNewRoleValue", null));
+            tmpOldRoleValue = cast(fields.get("myOldRoleValue", null));
+            tmpUnregMBeanList = cast(fields.get("myUnregMBeanList", null));
         }
-        relationObjName = (ObjectName) fields.get("myRelObjName", null);
-        if (fields.defaulted("myRelObjName"))
-        {
-          throw new NullPointerException("relationObjName");
-        }
-        relationTypeName = (String) fields.get("myRelTypeName", null);
-        if (fields.defaulted("myRelTypeName"))
-        {
-          throw new NullPointerException("relationTypeName");
+        else {
+            tmpRelationId = (String)fields.get("relationId", null);
+            tmpRelationTypeName = (String)fields.get("relationTypeName", null);
+            tmpRoleName = (String)fields.get("roleName", null);
+
+            tmpRelationObjName = (ObjectName)fields.get("relationObjName", null);
+            tmpNewRoleValue = cast(fields.get("newRoleValue", null));
+            tmpOldRoleValue = cast(fields.get("oldRoleValue", null));
+            tmpUnregMBeanList = cast(fields.get("unregisterMBeanList", null));
         }
-        roleName = (String) fields.get("myRoleName", null);
-        if (fields.defaulted("myRoleName"))
-        {
-          throw new NullPointerException("roleName");
+
+        // Validate fields we just read, throw InvalidObjectException
+        // if something goes wrong
+
+        String notifType = super.getType();
+        if (!isValidBasic(notifType,super.getSource(),tmpRelationId,tmpRelationTypeName)  ||
+            (!isValidCreate(notifType) &&
+             !isValidUpdate(notifType,tmpRoleName,tmpNewRoleValue,tmpOldRoleValue))) {
+
+            super.setSource(null);
+            throw new InvalidObjectException("Invalid object read");
         }
-        unregisterMBeanList = cast(fields.get("myUnregMBeanList", null));
-        if (fields.defaulted("myUnregMBeanList"))
-        {
-          throw new NullPointerException("unregisterMBeanList");
-        }
-      }
-      else
-      {
-        // Read an object serialized in the new serial form
-        //
-        in.defaultReadObject();
-      }
+
+        // assign deserialized vaules to object fields
+        relationObjName = safeGetObjectName(tmpRelationObjName);
+        newRoleValue = safeGetObjectNameList(tmpNewRoleValue);
+        oldRoleValue = safeGetObjectNameList(tmpOldRoleValue);
+        unregisterMBeanList = safeGetObjectNameList(tmpUnregMBeanList);
+
+        relationId = tmpRelationId;
+        relationTypeName = tmpRelationTypeName;
+        roleName = tmpRoleName;
     }
 
 
--- a/jdk/src/share/classes/javax/management/remote/JMXConnectorFactory.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/management/remote/JMXConnectorFactory.java	Wed Jul 05 19:00:49 2017 +0200
@@ -39,6 +39,7 @@
 
 import com.sun.jmx.remote.util.ClassLogger;
 import com.sun.jmx.remote.util.EnvHelp;
+import sun.reflect.misc.ReflectUtil;
 
 
 /**
@@ -412,10 +413,10 @@
     }
 
     static <T> T getProvider(JMXServiceURL serviceURL,
-                             Map<String, Object> environment,
+                             final Map<String, Object> environment,
                              String providerClassName,
                              Class<T> targetInterface,
-                             ClassLoader loader)
+                             final ClassLoader loader)
             throws IOException {
 
         final String protocol = serviceURL.getProtocol();
@@ -425,11 +426,14 @@
         T instance = null;
 
         if (pkgs != null) {
-            environment.put(PROTOCOL_PROVIDER_CLASS_LOADER, loader);
-
             instance =
                 getProvider(protocol, pkgs, loader, providerClassName,
                             targetInterface);
+
+            if (instance != null) {
+                boolean needsWrap = (loader != instance.getClass().getClassLoader());
+                environment.put(PROTOCOL_PROVIDER_CLASS_LOADER, needsWrap ? wrap(loader) : loader);
+            }
         }
 
         return instance;
@@ -442,6 +446,21 @@
        return serviceLoader.iterator();
     }
 
+    private static ClassLoader wrap(final ClassLoader parent) {
+        return parent != null ? AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
+            @Override
+            public ClassLoader run() {
+                return new ClassLoader(parent) {
+                    @Override
+                    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
+                        ReflectUtil.checkPackageAccess(name);
+                        return super.loadClass(name, resolve);
+                    }
+                };
+            }
+        }) : null;
+    }
+
     private static JMXConnector getConnectorAsService(ClassLoader loader,
                                                       JMXServiceURL url,
                                                       Map<String, ?> map)
@@ -542,14 +561,9 @@
             }
         }
 
-        if (loader == null)
-            loader = AccessController.doPrivileged(
-                    new PrivilegedAction<ClassLoader>() {
-                        public ClassLoader run() {
-                            return
-                                Thread.currentThread().getContextClassLoader();
-                        }
-                    });
+        if (loader == null) {
+            loader = Thread.currentThread().getContextClassLoader();
+        }
 
         return loader;
     }
@@ -557,5 +571,4 @@
     private static String protocol2package(String protocol) {
         return protocol.replace('+', '.').replace('-', '_');
     }
-
 }
--- a/jdk/src/share/classes/javax/management/remote/NotificationResult.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/management/remote/NotificationResult.java	Wed Jul 05 19:00:49 2017 +0200
@@ -89,7 +89,7 @@
 
         this.earliestSequenceNumber = earliestSequenceNumber;
         this.nextSequenceNumber = nextSequenceNumber;
-        this.targetedNotifications = targetedNotifications;
+        this.targetedNotifications = (targetedNotifications.length == 0 ? targetedNotifications : targetedNotifications.clone());
     }
 
     /**
@@ -122,7 +122,7 @@
      * listeners they correspond to.  This array can be empty.
      */
     public TargetedNotification[] getTargetedNotifications() {
-        return targetedNotifications;
+        return targetedNotifications.length == 0 ? targetedNotifications : targetedNotifications.clone();
     }
 
     /**
--- a/jdk/src/share/classes/javax/management/remote/rmi/RMIConnectionImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/management/remote/rmi/RMIConnectionImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -48,6 +48,7 @@
 import javax.management.remote.NotificationResult;
 import javax.management.remote.TargetedNotification;
 import javax.security.auth.Subject;
+import sun.reflect.misc.ReflectUtil;
 
 import static com.sun.jmx.mbeanserver.Util.cast;
 import com.sun.jmx.remote.internal.ServerCommunicatorAdmin;
@@ -1792,6 +1793,7 @@
         @Override
         protected Class<?> loadClass(String name, boolean resolve)
         throws ClassNotFoundException {
+            ReflectUtil.checkPackageAccess(name);
             try {
                 super.loadClass(name, resolve);
             } catch(Exception e) {
--- a/jdk/src/share/classes/javax/management/remote/rmi/RMIConnector.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/management/remote/rmi/RMIConnector.java	Wed Jul 05 19:00:49 2017 +0200
@@ -103,6 +103,7 @@
 import javax.naming.NamingException;
 import javax.rmi.ssl.SslRMIClientSocketFactory;
 import javax.security.auth.Subject;
+import sun.reflect.misc.ReflectUtil;
 import sun.rmi.server.UnicastRef2;
 import sun.rmi.transport.LiveRef;
 
@@ -2002,7 +2003,9 @@
         @Override
         protected Class<?> resolveClass(ObjectStreamClass classDesc)
                 throws IOException, ClassNotFoundException {
-            return Class.forName(classDesc.getName(), false, loader);
+            String name = classDesc.getName();
+            ReflectUtil.checkPackageAccess(name);
+            return Class.forName(name, false, loader);
         }
 
         private final ClassLoader loader;
--- a/jdk/src/share/classes/javax/naming/BinaryRefAddr.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/naming/BinaryRefAddr.java	Wed Jul 05 19:00:49 2017 +0200
@@ -89,9 +89,9 @@
       * @param src      The non-null contents of the address as a byte array.
       *                 The contents of src is copied into the new BinaryRefAddr.
       * @param offset   The starting index in src to get the bytes.
-      *                 0 <= offset <= src.length.
+      *                 {@code 0 <= offset <= src.length}.
       * @param count    The number of bytes to extract from src.
-      *                 0 <= count <= src.length-offset.
+      *                 {@code 0 <= count <= src.length-offset}.
       */
     public BinaryRefAddr(String addrType, byte[] src, int offset, int count) {
         super(addrType);
--- a/jdk/src/share/classes/javax/naming/directory/Attribute.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/naming/directory/Attribute.java	Wed Jul 05 19:00:49 2017 +0200
@@ -265,7 +265,7 @@
      * If the attribute values are unordered,
      * this method returns the value that happens to be at that index.
      * @param ix The index of the value in the ordered list of attribute values.
-     * 0 <= <tt>ix</tt> < <tt>size()</tt>.
+     * {@code 0 <= ix < size()}.
      * @return The possibly null attribute value at index <tt>ix</tt>;
      *   null if the attribute value is null.
      * @exception NamingException If a naming exception was encountered while
@@ -284,7 +284,7 @@
      * the front of the list (and their indices decremented by one).
      *
      * @param ix The index of the value to remove.
-     * 0 <= <tt>ix</tt> < <tt>size()</tt>.
+     * {@code 0 <= ix < size()}.
      * @return The possibly null attribute value at index <tt>ix</tt> that was removed;
      *   null if the attribute value is null.
      * @exception IndexOutOfBoundsException If <tt>ix</tt> is outside the specified range.
@@ -302,7 +302,7 @@
      * <tt>IllegalStateException</tt> is thrown.
      *
      * @param ix The index in the ordered list of attribute values to add the new value.
-     * 0 <= <tt>ix</tt> <= <tt>size()</tt>.
+     * {@code 0 <= ix <= size()}.
      * @param attrVal The possibly null attribute value to add; if null, null is
      * the value added.
      * @exception IndexOutOfBoundsException If <tt>ix</tt> is outside the specified range.
@@ -322,7 +322,7 @@
      * In that case, <tt>IllegalStateException</tt> is thrown.
      *
      * @param ix The index of the value in the ordered list of attribute values.
-     * 0 <= <tt>ix</tt> < <tt>size()</tt>.
+     * {@code 0 <= ix < size()}.
      * @param attrVal The possibly null attribute value to use.
      * If null, 'null' replaces the old value.
      * @return The possibly null attribute value at index ix that was replaced.
--- a/jdk/src/share/classes/javax/naming/ldap/LdapName.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/naming/ldap/LdapName.java	Wed Jul 05 19:00:49 2017 +0200
@@ -443,7 +443,7 @@
      * @throws  InvalidNameException if <tt>suffix</tt> is not a valid LDAP
      *          name, or if the addition of the components would violate the
      *          syntax rules of this LDAP name.
-     * @throws  IndexOutOfBoundsException.
+     * @throws  IndexOutOfBoundsException
      *          If posn is outside the specified range.
      */
     public Name addAll(int posn, Name suffix)
@@ -474,7 +474,7 @@
      *                          Must be in the range [0,size()].
      *
      * @return  The updated name (not a new instance).
-     * @throws  IndexOutOfBoundsException.
+     * @throws  IndexOutOfBoundsException
      *          If posn is outside the specified range.
      */
     public Name addAll(int posn, List<Rdn> suffixRdns) {
@@ -527,7 +527,7 @@
      *                  Must be in the range [0,size()].
      * @return          The updated LdapName, not a new instance.
      *                  Cannot be null.
-     * @exception       IndexOutOfBoundsException.
+     * @exception       IndexOutOfBoundsException
      *                  If posn is outside the specified range.
      * @exception       InvalidNameException If adding comp at the
      *                  specified position would violate the name's syntax.
--- a/jdk/src/share/classes/javax/naming/ldap/PagedResultsControl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/naming/ldap/PagedResultsControl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -36,7 +36,7 @@
  * at which it invokes search operations.
  * <p>
  * The following code sample shows how the class may be used:
- * <pre>
+ * <pre>{@code
  *
  *     // Open an LDAP association
  *     LdapContext ctx = new InitialLdapContext();
@@ -89,13 +89,13 @@
  *     ctx.close();
  *     ...
  *
- * </pre>
+ * } </pre>
  * <p>
  * This class implements the LDAPv3 Control for paged-results as defined in
  * <a href="http://www.ietf.org/rfc/rfc2696.txt">RFC 2696</a>.
  *
  * The control's value has the following ASN.1 definition:
- * <pre>
+ * <pre>{@code
  *
  *     realSearchControlValue ::= SEQUENCE {
  *         size      INTEGER (0..maxInt),
@@ -104,7 +104,7 @@
  *         cookie    OCTET STRING
  *     }
  *
- * </pre>
+ * }</pre>
  *
  * @since 1.5
  * @see PagedResultsResponseControl
--- a/jdk/src/share/classes/javax/naming/ldap/SortControl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/naming/ldap/SortControl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -40,7 +40,7 @@
  * then the search operation is not performed and an error is returned.
  * <p>
  * The following code sample shows how the class may be used:
- * <pre>
+ * <pre>{@code
  *
  *     // Open an LDAP association
  *     LdapContext ctx = new InitialLdapContext();
@@ -85,7 +85,7 @@
  *     ctx.close();
  *     ...
  *
- * </pre>
+ * }</pre>
  * <p>
  * This class implements the LDAPv3 Request Control for server-side sorting
  * as defined in
--- a/jdk/src/share/classes/javax/net/ssl/SNIHostName.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/net/ssl/SNIHostName.java	Wed Jul 05 19:00:49 2017 +0200
@@ -295,8 +295,8 @@
      *         representing the hostname(s) to match
      * @throws NullPointerException if {@code regex} is
      *         {@code null}
-     * @throws PatternSyntaxException if the regular expression's syntax
-     *         is invalid
+     * @throws java.util.regex.PatternSyntaxException if the regular expression's
+     *         syntax is invalid
      */
     public static SNIMatcher createSNIMatcher(String regex) {
         if (regex == null) {
--- a/jdk/src/share/classes/javax/net/ssl/SSLEngine.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/net/ssl/SSLEngine.java	Wed Jul 05 19:00:49 2017 +0200
@@ -211,7 +211,7 @@
  * that the source buffer has enough room to hold a record (enlarging if
  * necessary), and then obtain more inbound data.
  *
- * <pre>
+ * <pre>{@code
  *   SSLEngineResult r = engine.unwrap(src, dst);
  *   switch (r.getStatus()) {
  *   BUFFER_OVERFLOW:
@@ -238,7 +238,7 @@
  *       break;
  *   // other cases: CLOSED, OK.
  *   }
- * </pre>
+ * }</pre>
  *
  * <P>
  * Unlike <code>SSLSocket</code>, all methods of SSLEngine are
@@ -442,7 +442,7 @@
      * <blockquote><pre>
      * {@link #wrap(ByteBuffer [], int, int, ByteBuffer)
      *     engine.wrap(new ByteBuffer [] { src }, 0, 1, dst);}
-     * </pre</blockquote>
+     * </pre></blockquote>
      *
      * @param   src
      *          a <code>ByteBuffer</code> containing outbound application data
@@ -478,7 +478,7 @@
      * <blockquote><pre>
      * {@link #wrap(ByteBuffer [], int, int, ByteBuffer)
      *     engine.wrap(srcs, 0, srcs.length, dst);}
-     * </pre</blockquote>
+     * </pre></blockquote>
      *
      * @param   srcs
      *          an array of <code>ByteBuffers</code> containing the
@@ -597,7 +597,7 @@
      * <blockquote><pre>
      * {@link #unwrap(ByteBuffer, ByteBuffer [], int, int)
      *     engine.unwrap(src, new ByteBuffer [] { dst }, 0, 1);}
-     * </pre</blockquote>
+     * </pre></blockquote>
      *
      * @param   src
      *          a <code>ByteBuffer</code> containing inbound network data.
@@ -633,7 +633,7 @@
      * <blockquote><pre>
      * {@link #unwrap(ByteBuffer, ByteBuffer [], int, int)
      *     engine.unwrap(src, dsts, 0, dsts.length);}
-     * </pre</blockquote>
+     * </pre></blockquote>
      *
      * @param   src
      *          a <code>ByteBuffer</code> containing inbound network data.
--- a/jdk/src/share/classes/javax/net/ssl/SSLEngineResult.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/net/ssl/SSLEngineResult.java	Wed Jul 05 19:00:49 2017 +0200
@@ -173,7 +173,7 @@
      *
      * @throws  IllegalArgumentException
      *          if the <code>status</code> or <code>handshakeStatus</code>
-     *          arguments are null, or if <<code>bytesConsumed</code> or
+     *          arguments are null, or if <code>bytesConsumed</code> or
      *          <code>bytesProduced</code> is negative.
      */
     public SSLEngineResult(Status status, HandshakeStatus handshakeStatus,
--- a/jdk/src/share/classes/javax/net/ssl/SSLSessionContext.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/net/ssl/SSLSessionContext.java	Wed Jul 05 19:00:49 2017 +0200
@@ -90,7 +90,7 @@
      * @param seconds the new session timeout limit in seconds; zero means
      *          there is no limit.
      *
-     * @exception IllegalArgumentException if the timeout specified is < 0.
+     * @exception IllegalArgumentException if the timeout specified is {@code < 0}.
      * @see #getSessionTimeout
      */
     public void setSessionTimeout(int seconds)
@@ -122,7 +122,7 @@
      *
      * @param size the new session cache size limit; zero means there is no
      * limit.
-     * @exception IllegalArgumentException if the specified size is < 0.
+     * @exception IllegalArgumentException if the specified size is {@code < 0}.
      * @see #getSessionCacheSize
      */
     public void setSessionCacheSize(int size)
--- a/jdk/src/share/classes/javax/script/ScriptEngineFactory.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/script/ScriptEngineFactory.java	Wed Jul 05 19:00:49 2017 +0200
@@ -144,8 +144,7 @@
      * of the supported scripting language.  For instance, an implementaton for a Javascript
      * engine might be;
      * <p>
-     * <pre>
-     * <code>
+     * <pre>{@code
      * public String getMethodCallSyntax(String obj,
      *                                   String m, String... args) {
      *      String ret = obj;
@@ -159,8 +158,7 @@
      *      ret += ")";
      *      return ret;
      * }
-     *</code>
-     *</pre>
+     * } </pre>
      * <p>
      *
      * @param obj The name representing the object whose method is to be invoked. The
@@ -200,17 +198,17 @@
      * Returns A valid scripting language executable progam with given statements.
      * For instance an implementation for a PHP engine might be:
      * <p>
-     * <pre><code>
+     * <pre>{@code
      * public String getProgram(String... statements) {
-     *      $retval = "&lt;?\n";
+     *      $retval = "<?\n";
      *      int len = statements.length;
      *      for (int i = 0; i < len; i++) {
      *          $retval += statements[i] + ";\n";
      *      }
-     *      $retval += "?&gt;";
+     *      $retval += "?>";
      *
      * }
-     * </code></pre>
+     * }</pre>
      *
      *  @param statements The statements to be executed.  May be return values of
      *  calls to the <code>getMethodCallSyntax</code> and <code>getOutputStatement</code> methods.
--- a/jdk/src/share/classes/javax/script/ScriptEngineManager.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/script/ScriptEngineManager.java	Wed Jul 05 19:00:49 2017 +0200
@@ -28,9 +28,6 @@
 import java.security.*;
 import java.util.ServiceLoader;
 import java.util.ServiceConfigurationError;
-import sun.reflect.CallerSensitive;
-import sun.reflect.Reflection;
-import sun.security.util.SecurityConstants;
 
 /**
  * The <code>ScriptEngineManager</code> implements a discovery and instantiation
@@ -54,23 +51,14 @@
 public class ScriptEngineManager  {
     private static final boolean DEBUG = false;
     /**
-     * If the thread context ClassLoader can be accessed by the caller,
-     * then the effect of calling this constructor is the same as calling
+     * The effect of calling this constructor is the same as calling
      * <code>ScriptEngineManager(Thread.currentThread().getContextClassLoader())</code>.
-     * Otherwise, the effect is the same as calling <code>ScriptEngineManager(null)</code>.
      *
      * @see java.lang.Thread#getContextClassLoader
      */
-    @CallerSensitive
     public ScriptEngineManager() {
         ClassLoader ctxtLoader = Thread.currentThread().getContextClassLoader();
-        if (canCallerAccessLoader(ctxtLoader, Reflection.getCallerClass())) {
-            if (DEBUG) System.out.println("using " + ctxtLoader);
-            init(ctxtLoader);
-        } else {
-            if (DEBUG) System.out.println("using bootstrap loader");
-            init(null);
-        }
+        init(ctxtLoader);
     }
 
     /**
@@ -420,41 +408,4 @@
 
     /** Global bindings associated with script engines created by this manager. */
     private Bindings globalScope;
-
-    private boolean canCallerAccessLoader(ClassLoader loader, Class<?> caller) {
-        SecurityManager sm = System.getSecurityManager();
-        if (sm != null) {
-            ClassLoader callerLoader = getClassLoader(caller);
-            if (!sun.misc.VM.isSystemDomainLoader(callerLoader)) {
-                if (loader != callerLoader || !isAncestor(loader, callerLoader)) {
-                    try {
-                        sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
-                    } catch (SecurityException exp) {
-                        if (DEBUG) exp.printStackTrace();
-                        return false;
-                    }
-                } // else fallthru..
-            } // else fallthru..
-        } // else fallthru..
-
-        return true;
-    }
-
-    // Note that this code is same as ClassLoader.getClassLoader().
-    // But, that method is package private and hence we can't call here.
-    private ClassLoader getClassLoader(Class<?> caller) {
-        if (caller == null) {
-            return null;
-        }
-        return caller.getClassLoader();
-    }
-
-    // is cl1 ancestor of cl2?
-    private boolean isAncestor(ClassLoader cl1, ClassLoader cl2) {
-        do {
-            cl2 = cl2.getParent();
-            if (cl1 == cl2) return true;
-        } while (cl2 != null);
-        return false;
-    }
 }
--- a/jdk/src/share/classes/javax/security/auth/callback/CallbackHandler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/security/auth/callback/CallbackHandler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -79,7 +79,7 @@
      * This example code is for guidance only.  Many details,
      * including proper error handling, are left out for simplicity.
      *
-     * <pre>
+     * <pre>{@code
      * public void handle(Callback[] callbacks)
      * throws IOException, UnsupportedCallbackException {
      *
@@ -133,7 +133,7 @@
      * private char[] readPassword(InputStream in) throws IOException {
      *    // insert code to read a user password from the input stream
      * }
-     * </pre>
+     * }</pre>
      *
      * @param callbacks an array of <code>Callback</code> objects provided
      *          by an underlying security service which contains
--- a/jdk/src/share/classes/javax/security/sasl/Sasl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/security/sasl/Sasl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -278,7 +278,7 @@
      *
      * This method uses the
 <a href="{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#Provider">JCA Security Provider Framework</a>, described in the
-     * "Java Cryptography Architecture API Specification & Reference", for
+     * "Java Cryptography Architecture API Specification &amp; Reference", for
      * locating and selecting a <tt>SaslClient</tt> implementation.
      *
      * First, it
@@ -303,7 +303,7 @@
      * <tt>SaslClientFactory.DIGEST-MD5 com.wiz.sasl.digest.ClientFactory</tt>
      *<p>
      * See the
-     * "Java Cryptography Architecture API Specification & Reference"
+     * "Java Cryptography Architecture API Specification &amp; Reference"
      * for information about how to install and configure security service
      *  providers.
      *
@@ -428,7 +428,7 @@
      * This method uses the
 <a href="{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#Provider">JCA Security Provider Framework</a>,
      * described in the
-     * "Java Cryptography Architecture API Specification & Reference", for
+     * "Java Cryptography Architecture API Specification &amp; Reference", for
      * locating and selecting a <tt>SaslServer</tt> implementation.
      *
      * First, it
@@ -453,7 +453,7 @@
      * <tt>SaslServerFactory.DIGEST-MD5  com.wiz.sasl.digest.ServerFactory</tt>
      *<p>
      * See the
-     * "Java Cryptography Architecture API Specification & Reference"
+     * "Java Cryptography Architecture API Specification &amp; Reference"
      * for information about how to install and configure security
      * service providers.
      *
--- a/jdk/src/share/classes/javax/security/sasl/SaslClient.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/security/sasl/SaslClient.java	Wed Jul 05 19:00:49 2017 +0200
@@ -38,13 +38,13 @@
  *<p>
  * Here's an example of how an LDAP library might use a <tt>SaslClient</tt>.
  * It first gets an instance of a <tt>SaslClient</tt>:
- *<blockquote><pre>
+ *<blockquote><pre>{@code
  * SaslClient sc = Sasl.createSaslClient(mechanisms,
  *     authorizationId, protocol, serverName, props, callbackHandler);
- *</pre></blockquote>
+ *}</pre></blockquote>
  * It can then proceed to use the client for authentication.
  * For example, an LDAP library might use the client as follows:
- *<blockquote><pre>
+ *<blockquote><pre>{@code
  * // Get initial response and send to server
  * byte[] response = (sc.hasInitialResponse() ? sc.evaluateChallenge(new byte[0]) :
  *     null);
@@ -74,7 +74,7 @@
  *      ldap.out = new SecureOutputStream(sc, ldap.out);
  *    }
  * }
- *</pre></blockquote>
+ *}</pre></blockquote>
  *
  * If the mechanism has an initial response, the library invokes
  * <tt>evaluateChallenge()</tt> with an empty
--- a/jdk/src/share/classes/javax/security/sasl/SaslServer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/security/sasl/SaslServer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -47,7 +47,7 @@
  * For example, suppose the LDAP server received an LDAP BIND request
  * containing the name of the SASL mechanism and an (optional) initial
  * response. It then might use the server as follows:
- *<blockquote><pre>
+ *<blockquote><pre>{@code
  * while (!ss.isComplete()) {
  *     try {
  *         byte[] challenge = ss.evaluateResponse(response);
@@ -75,7 +75,7 @@
  *      ldap.out = new SecureOutputStream(ss, ldap.out);
  *    }
  * }
- *</pre></blockquote>
+ *}</pre></blockquote>
  *
  * @since 1.5
  *
--- a/jdk/src/share/classes/javax/smartcardio/ResponseAPDU.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/smartcardio/ResponseAPDU.java	Wed Jul 05 19:00:49 2017 +0200
@@ -121,7 +121,7 @@
      * Returns the value of the status bytes SW1 and SW2 as a single
      * status word SW.
      * It is defined as
-     * <code>(getSW1() << 8) | getSW2()</code>.
+     * {@code (getSW1() << 8) | getSW2()}
      *
      * @return the value of the status word SW.
      */
--- a/jdk/src/share/classes/javax/sound/midi/MetaMessage.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/sound/midi/MetaMessage.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,10 +25,6 @@
 
 package javax.sound.midi;
 
-import java.io.ByteArrayOutputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-
 
 /**
  * A <code>MetaMessage</code> is a <code>{@link MidiMessage}</code> that is not meaningful to synthesizers, but
@@ -71,14 +67,6 @@
      */
     public static final int META                                                = 0xFF; // 255
 
-
-    // Default meta message data: just the META status byte value
-    // $$kk: 09.09.99: need a real event here!!
-
-    private static byte[] defaultMessage                                = { (byte)META, 0 };
-
-
-
     // Instance variables
 
     /**
@@ -98,8 +86,8 @@
      * to set them subsequently.
      */
     public MetaMessage() {
-        //super(defaultMessage);
-        this(defaultMessage);
+        // Default meta message data: just the META status byte value
+        this(new byte[]{(byte) META, 0});
     }
 
     /**
--- a/jdk/src/share/classes/javax/sound/sampled/Mixer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/sound/sampled/Mixer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -253,22 +253,22 @@
         /**
          * Mixer name.
          */
-        private /*final*/ String name;
+        private final String name;
 
         /**
          * Mixer vendor.
          */
-        private /*final*/ String vendor;
+        private final String vendor;
 
         /**
          * Mixer description.
          */
-        private /*final*/ String description;
+        private final String description;
 
         /**
          * Mixer version.
          */
-        private /*final*/ String version;
+        private final String version;
 
         /**
          * Constructs a mixer's info object, passing it the given
--- a/jdk/src/share/classes/javax/sql/DataSource.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/sql/DataSource.java	Wed Jul 05 19:00:49 2017 +0200
@@ -82,7 +82,7 @@
    *
    * @return  a connection to the data source
    * @exception SQLException if a database access error occurs
-   * @throws SQLTimeoutException  when the driver has determined that the
+   * @throws java.sql.SQLTimeoutException  when the driver has determined that the
    * timeout value specified by the {@code setLoginTimeout} method
    * has been exceeded and has at least tried to cancel the
    * current database connection attempt
@@ -98,7 +98,7 @@
    * @param password the user's password
    * @return  a connection to the data source
    * @exception SQLException if a database access error occurs
-   * @throws SQLTimeoutException  when the driver has determined that the
+   * @throws java.sql.SQLTimeoutException  when the driver has determined that the
    * timeout value specified by the {@code setLoginTimeout} method
    * has been exceeded and has at least tried to cancel the
    * current database connection attempt
--- a/jdk/src/share/classes/javax/sql/rowset/BaseRowSet.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/sql/rowset/BaseRowSet.java	Wed Jul 05 19:00:49 2017 +0200
@@ -109,10 +109,10 @@
  * <code>CachedRowSet</code><sup><font size=-2>TM</font></sup>
  * object <code>crs</code> might have its command property set.  Note that if a
  * tool is used to set properties, this is the code that the tool would use.
- * <PRE>
+ * <PRE>{@code
  *    crs.setCommand("SELECT FIRST_NAME, LAST_NAME, ADDRESS FROM CUSTOMERS" +
  *                   "WHERE CREDIT_LIMIT > ? AND REGION = ?");
- * </PRE>
+ * }</PRE>
  * <P>
  * In this example, the values for <code>CREDIT_LIMIT</code> and
  * <code>REGION</code> are placeholder parameters, which are indicated with a
@@ -129,16 +129,16 @@
  * <P>
  * The following code fragment demonstrates
  * setting the two parameters in the query from the previous example.
- * <PRE>
+ * <PRE>{@code
  *    crs.setInt(1, 5000);
  *    crs.setString(2, "West");
- * </PRE>
+ * }</PRE>
  * If the <code>execute</code> method is called at this point, the query
  * sent to the DBMS will be:
- * <PRE>
+ * <PRE>{@code
  *    "SELECT FIRST_NAME, LAST_NAME, ADDRESS FROM CUSTOMERS" +
  *                   "WHERE CREDIT_LIMIT > 5000 AND REGION = 'West'"
- * </PRE>
+ * }</PRE>
  * NOTE: Setting <code>Array</code>, <code>Clob</code>, <code>Blob</code> and
  * <code>Ref</code> objects as a command parameter, stores these values as
  * <code>SerialArray</code>, <code>SerialClob</code>, <code>SerialBlob</code>
@@ -158,7 +158,7 @@
  * When the method <code>execute</code> is called, the values in the
  * <code>Hashtable</code> object are substituted for the appropriate placeholder
  * parameters in the command.
- * <P)>
+ * <P>
  * A call to the method <code>getParams</code> returns the values stored in the
  * <code>Hashtable</code> object as an array of <code>Object</code> instances.
  * An element in this array may be a simple <code>Object</code> instance or an
@@ -2535,7 +2535,7 @@
      * specific abstract data types.
      * <P>
      * The parameter value set by this method is stored internally and
-     * will be supplied as the appropriate parameter in this <code>RowSet</code
+     * will be supplied as the appropriate parameter in this <code>RowSet</code>
      * object's command when the method <code>execute</code> is called.
      * Methods such as <code>execute</code> and <code>populate</code> must be
      * provided in any class that extends this class and implements one or
--- a/jdk/src/share/classes/javax/sql/rowset/CachedRowSet.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/sql/rowset/CachedRowSet.java	Wed Jul 05 19:00:49 2017 +0200
@@ -118,7 +118,7 @@
  * <P>
  * There are two ways for a <code>CachedRowSet</code> object to specify which
  * <code>SyncProvider</code> object it will use.
- * <UL)
+ * <UL>
  *     <LI>Supplying the name of the implementation to the constructor<BR>
  *     The following line of code creates the <code>CachedRowSet</code>
  *     object <i>crs2</i> that is initialized with default values except that its
@@ -135,7 +135,7 @@
  *      <PRE>
  *           crs.setSyncProvider("com.fred.providers.HighAvailabilityProvider");
  *      </PRE>
- * </UL)
+ * </UL>
  * See the comments for <code>SyncFactory</code> and <code>SyncProvider</code> for
  * more details.
  *
@@ -426,10 +426,10 @@
  * The following code fragment illustrates how the <code>CachedRowSet</code>
  * object <code>crs</code> might have its command property set.  Note that if a
  * tool is used to set properties, this is the code that the tool would use.
- * <PRE>
+ * <PRE>{@code
  *    crs.setCommand("SELECT FIRST_NAME, LAST_NAME, ADDRESS FROM CUSTOMERS " +
  *                   "WHERE CREDIT_LIMIT > ? AND REGION = ?");
- * </PRE>
+ * } </PRE>
  * <P>
  * The values that will be used to set the command's placeholder parameters are
  * contained in the <code>RowSet</code> object's <code>params</code> field, which is a
@@ -457,7 +457,7 @@
  * The following code fragment gives an idea of how the reader
  * does this, after obtaining the <code>Connection</code> object
  * <code>con</code>.
- * <PRE>
+ * <PRE>{@code
  *    PreparedStatement pstmt = con.prepareStatement(crs.getCommand());
  *    reader.decodeParams();
  *    // decodeParams figures out which setter methods to use and does something
@@ -465,16 +465,16 @@
  *    //    for (i = 0; i < params.length; i++) {
  *    //        pstmt.setObject(i + 1, params[i]);
  *    //    }
- * </PRE>
+ * }</PRE>
  * <P>
- * At this point, the command for <code>crs</code> is the query <code>"SELECT
+ * At this point, the command for <code>crs</code> is the query {@code "SELECT
  * FIRST_NAME, LAST_NAME, ADDRESS FROM CUSTOMERS WHERE CREDIT_LIMIT > 5000
- * AND REGION = "West"</code>.  After the <code>readData</code> method executes
+ * AND REGION = "West"}.  After the <code>readData</code> method executes
  * this command with the following line of code, it will have the data from
  * <code>rs</code> with which to populate <code>crs</code>.
- * <PRE>
+ * <PRE>{@code
  *     ResultSet rs = pstmt.executeQuery();
- * </PRE>
+ * }</PRE>
  * <P>
  * The preceding code fragments give an idea of what goes on behind the
  * scenes; they would not appear in an application, which would not invoke
@@ -484,13 +484,13 @@
  * the command. Simply by calling the <code>execute</code> method,
  * <code>crs</code> populates itself with the requested data from the
  * table <code>CUSTOMERS</code>.
- * <PRE>
+ * <PRE>{@code
  *    crs.setCommand("SELECT FIRST_NAME, LAST_NAME, ADDRESS FROM CUSTOMERS" +
  *                   "WHERE CREDIT_LIMIT > ? AND REGION = ?");
  *    crs.setInt(1, 5000);
  *    crs.setString(2, "West");
  *    crs.execute();
- * </PRE>
+ * }</PRE>
  *
  * <h3>10.0 Paging Data</h3>
  * Because a <code>CachedRowSet</code> object stores data in memory,
--- a/jdk/src/share/classes/javax/sql/rowset/Predicate.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/sql/rowset/Predicate.java	Wed Jul 05 19:00:49 2017 +0200
@@ -53,8 +53,7 @@
  * and application motivated implementations of <code>Predicate</code> to emerge.
  * <p>
  * A sample implementation would look something like this:
- * <pre>
- * <code>
+ * <pre>{@code
  *    public class Range implements Predicate {
  *
  *       private Object lo[];
@@ -79,19 +78,19 @@
  *              if ((rs.getObject(idx[i]) >= lo[i]) &&
  *                  (rs.getObject(idx[i]) >= hi[i]) {
  *                  bool1 = true; // within filter constraints
+ *              } else {
+ *                  bool2 = true; // outside of filter constraints
+ *              }
+ *          }
+ *
+ *          if (bool2) {
+ *             return false;
  *          } else {
- *            bool2 = true; // outside of filter constraints
+ *             return true;
  *          }
  *      }
- *
- *      if (bool2) {
- *         return false;
- *      } else {
- *         return true;
- *      }
  *  }
- * </code>
- * </pre>
+ * }</pre>
  * <P>
  * The example above implements a simple range predicate. Note, that
  * implementations should but are not required to provider <code>String</code>
--- a/jdk/src/share/classes/javax/sql/rowset/RowSetMetaDataImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/sql/rowset/RowSetMetaDataImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -159,7 +159,7 @@
      * @param property <code>true</code> if the given column is
      *                 automatically incremented; <code>false</code>
      *                 otherwise
-     * @throws <code>SQLException</code> if a database access error occurs or
+     * @throws SQLException if a database access error occurs or
      *         the given index is out of bounds
      */
     public void setAutoIncrement(int columnIndex, boolean property) throws SQLException {
@@ -195,7 +195,7 @@
      *                 value can be used in a <code>WHERE</code> clause;
      *                 <code>false</code> otherwise
      *
-     * @throws <code>SQLException</code> if a database access error occurs or
+     * @throws SQLException if a database access error occurs or
      *         the given column number is out of bounds
      */
     public void setSearchable(int columnIndex, boolean property)
@@ -212,7 +212,7 @@
      * must be between <code>1</code> and the number of columns,
      * inclusive between <code>1</code> and the number of columns, inclusive
      * @param property true if the value is a cash value; false otherwise.
-     * @throws <code>SQLException</code> if a database access error occurs
+     * @throws SQLException if a database access error occurs
      *         or the given column number is out of bounds
      */
     public void setCurrency(int columnIndex, boolean property)
@@ -233,7 +233,7 @@
      *                 <code>columnNullable</code>, or
      *                 <code>columnNullableUnknown</code>
      *
-     * @throws <code>SQLException</code> if a database access error occurs,
+     * @throws SQLException if a database access error occurs,
      *         the given column number is out of bounds, or the value supplied
      *         for the <i>property</i> parameter is not one of the following
      *         constants:
--- a/jdk/src/share/classes/javax/sql/rowset/serial/SerialJavaObject.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/sql/rowset/serial/SerialJavaObject.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,9 @@
 import java.util.Arrays;
 import java.util.Vector;
 import javax.sql.rowset.RowSetWarning;
+import sun.reflect.CallerSensitive;
+import sun.reflect.Reflection;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * A serializable mapping in the Java programming language of an SQL
@@ -119,10 +122,31 @@
      * @return an array of <code>Field</code> objects
      * @throws SerialException if an error is encountered accessing
      * the serialized object
+     * @throws  SecurityException  If a security manager, <i>s</i>, is present
+     * and the caller's class loader is not the same as or an
+     * ancestor of the class loader for the class of the
+     * {@linkplain #getObject object} being serialized
+     * and invocation of {@link SecurityManager#checkPackageAccess
+     * s.checkPackageAccess()} denies access to the package
+     * of that class.
+     * @see Class#getFields
      */
+    @CallerSensitive
     public Field[] getFields() throws SerialException {
         if (fields != null) {
             Class<?> c = this.obj.getClass();
+            SecurityManager sm = System.getSecurityManager();
+            if (sm != null) {
+                /*
+                 * Check if the caller is allowed to access the specified class's package.
+                 * If access is denied, throw a SecurityException.
+                 */
+                Class<?> caller = sun.reflect.Reflection.getCallerClass();
+                if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
+                                                        c.getClassLoader())) {
+                    ReflectUtil.checkPackageAccess(c);
+                }
+            }
             return c.getFields();
         } else {
             throw new SerialException("SerialJavaObject does not contain" +
--- a/jdk/src/share/classes/javax/sql/rowset/serial/SerialRef.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/sql/rowset/serial/SerialRef.java	Wed Jul 05 19:00:49 2017 +0200
@@ -202,7 +202,7 @@
     }
 
     /**
-     * Returns a clone of this {@code SerialRef}. .
+     * Returns a clone of this {@code SerialRef}.
      * The underlying {@code Ref} object will be set to null.
      *
      * @return  a clone of this SerialRef
--- a/jdk/src/share/classes/javax/sql/rowset/serial/SerialStruct.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/sql/rowset/serial/SerialStruct.java	Wed Jul 05 19:00:49 2017 +0200
@@ -87,6 +87,7 @@
      * object for custom mapping the SQL structured type or any of its
      * attributes that are SQL structured types.
      *
+     * @param in an instance of {@code Struct}
      * @param map a <code>java.util.Map</code> object in which
      *        each entry consists of 1) a <code>String</code> object
      *        giving the fully qualified name of a UDT and 2) the
--- a/jdk/src/share/classes/javax/sql/rowset/spi/SyncFactory.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/sql/rowset/spi/SyncFactory.java	Wed Jul 05 19:00:49 2017 +0200
@@ -627,8 +627,6 @@
      * required
      * @throws java.lang.SecurityException if a security manager exists and its
      *   {@code checkPermission} method denies calling {@code setLogger}
-     * @throws java.util.logging.LoggingPermission if a security manager exists and its
-     *   {@code checkPermission} method denies calling {@code setLevel}
      * @throws NullPointerException if the logger is null
      * @see SecurityManager#checkPermission
      * @see LoggingPermission
--- a/jdk/src/share/classes/javax/sql/rowset/spi/SyncResolver.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/sql/rowset/spi/SyncResolver.java	Wed Jul 05 19:00:49 2017 +0200
@@ -193,7 +193,7 @@
  * code fragment, the value in <i>crs</i> is the one set as the resolved value, which means
  * that it will be used to overwrite the conflict value in the data source.
  *
- * <PRE>
+ * <PRE>{@code
  *     try {
  *
  *         crs.acceptChanges(con);
@@ -202,8 +202,8 @@
  *
  *         SyncResolver resolver = spe.getSyncResolver();
  *
- *         Object crsValue;  // value in the <code>RowSet</code> object
- *         Object resolverValue:  // value in the <code>SyncResolver</code> object
+ *         Object crsValue;  // value in the RowSet object
+ *         Object resolverValue:  // value in the SyncResolver object
  *         Object resolvedValue:  // value to be persisted
  *
  *         while(resolver.nextConflict())  {
@@ -227,7 +227,7 @@
  *              }
  *          }
  *      }
- * </PRE>
+ * }</PRE>
  * @author  Jonathan Bruce
  */
 
--- a/jdk/src/share/classes/javax/swing/BufferStrategyPaintManager.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/swing/BufferStrategyPaintManager.java	Wed Jul 05 19:00:49 2017 +0200
@@ -215,7 +215,7 @@
     }
 
     private void dispose(java.util.List<BufferInfo> bufferInfos) {
-        if (LOGGER.isLoggable(PlatformLogger.FINER)) {
+        if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
             LOGGER.finer("BufferStrategyPaintManager disposed",
                          new RuntimeException());
         }
@@ -300,7 +300,7 @@
             }
         }
         // Invalid root, do what Swing has always done.
-        if (LOGGER.isLoggable(PlatformLogger.FINER)) {
+        if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
             LOGGER.finer("prepare failed");
         }
         return super.paint(paintingComponent, bufferComponent, g, x, y, w, h);
@@ -332,7 +332,7 @@
             }
             accumulate(x + xOffset + deltaX, y + yOffset + deltaY, w, h);
         } else {
-            if (LOGGER.isLoggable(PlatformLogger.FINER)) {
+            if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
                 LOGGER.finer("copyArea: prepare failed or not in sync");
             }
             // Prepare failed, or not in sync. By calling super.copyArea
@@ -360,7 +360,7 @@
                 }
             }
         }
-        if (LOGGER.isLoggable(PlatformLogger.FINEST)) {
+        if (LOGGER.isLoggable(PlatformLogger.Level.FINEST)) {
             LOGGER.finest("beginPaint");
         }
         // Reset the area that needs to be painted.
@@ -368,7 +368,7 @@
     }
 
     public void endPaint() {
-        if (LOGGER.isLoggable(PlatformLogger.FINEST)) {
+        if (LOGGER.isLoggable(PlatformLogger.Level.FINEST)) {
             LOGGER.finest("endPaint: region " + accumulatedX + " " +
                        accumulatedY + " " +  accumulatedMaxX + " " +
                        accumulatedMaxY);
@@ -417,7 +417,7 @@
                 contentsLost = bufferStrategy.contentsLost();
             }
             if (contentsLost) {
-                if (LOGGER.isLoggable(PlatformLogger.FINER)) {
+                if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
                     LOGGER.finer("endPaint: contents lost");
                 }
                 // Shown region was bogus, mark buffer as out of sync.
@@ -511,7 +511,7 @@
                 contentsLost = true;
                 bufferInfo = new BufferInfo(root);
                 bufferInfos.add(bufferInfo);
-                if (LOGGER.isLoggable(PlatformLogger.FINER)) {
+                if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
                     LOGGER.finer("prepare: new BufferInfo: " + root);
                 }
             }
@@ -522,7 +522,7 @@
                     bsg = bufferStrategy.getDrawGraphics();
                     if (bufferStrategy.contentsRestored()) {
                         contentsLost = true;
-                        if (LOGGER.isLoggable(PlatformLogger.FINER)) {
+                        if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
                             LOGGER.finer("prepare: contents restored in prepare");
                         }
                     }
@@ -535,7 +535,7 @@
                 if (bufferInfo.getContentsLostDuringExpose()) {
                     contentsLost = true;
                     bufferInfo.setContentsLostDuringExpose(false);
-                    if (LOGGER.isLoggable(PlatformLogger.FINER)) {
+                    if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
                         LOGGER.finer("prepare: contents lost on expose");
                     }
                 }
@@ -638,7 +638,7 @@
             if (biRoot == null) {
                 // Window gc'ed
                 bufferInfos.remove(counter);
-                if (LOGGER.isLoggable(PlatformLogger.FINER)) {
+                if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
                     LOGGER.finer("BufferInfo pruned, root null");
                 }
             }
@@ -744,7 +744,7 @@
                 if (bs != null) {
                     weakBS = new WeakReference<BufferStrategy>(bs);
                 }
-                if (LOGGER.isLoggable(PlatformLogger.FINER)) {
+                if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
                     LOGGER.finer("getBufferStrategy: created bs: " + bs);
                 }
             }
@@ -802,7 +802,7 @@
             BufferStrategy bs = null;
             if (SwingUtilities3.isVsyncRequested(root)) {
                 bs = createBufferStrategy(root, true);
-                if (LOGGER.isLoggable(PlatformLogger.FINER)) {
+                if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
                     LOGGER.finer("createBufferStrategy: using vsynced strategy");
                 }
             }
@@ -844,7 +844,7 @@
                                             invoke(root);
                 } catch (InvocationTargetException ite) {
                     // Type is not supported
-                    if (LOGGER.isLoggable(PlatformLogger.FINER)) {
+                    if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
                         LOGGER.finer("createBufferStratety failed",
                                      ite);
                     }
@@ -860,7 +860,7 @@
                     bs = ((Window)root).getBufferStrategy();
                 } catch (AWTException e) {
                     // Type not supported
-                    if (LOGGER.isLoggable(PlatformLogger.FINER)) {
+                    if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
                         LOGGER.finer("createBufferStratety failed",
                                      e);
                     }
@@ -874,7 +874,7 @@
          */
         public void dispose() {
             Container root = getRoot();
-            if (LOGGER.isLoggable(PlatformLogger.FINER)) {
+            if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
                 LOGGER.finer("disposed BufferInfo for: " + root);
             }
             if (root != null) {
--- a/jdk/src/share/classes/javax/swing/JFileChooser.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/swing/JFileChooser.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1146,9 +1146,25 @@
      * @see #resetChoosableFileFilters
      */
     public boolean removeChoosableFileFilter(FileFilter f) {
-        if(filters.contains(f)) {
+        int index = filters.indexOf(f);
+        if (index >= 0) {
             if(getFileFilter() == f) {
-                setFileFilter(null);
+                if (isAcceptAllFileFilterUsed()) {
+                    // choose default filter if it is used
+                    setFileFilter(getAcceptAllFileFilter());
+                }
+                else if (index > 0) {
+                    // choose the first filter, because it is not removed
+                    setFileFilter(filters.get(0));
+                }
+                else if (filters.size() > 1) {
+                    // choose the second filter, because the first one is removed
+                    setFileFilter(filters.get(1));
+                }
+                else {
+                    // no more filters
+                    setFileFilter(null);
+                }
             }
             FileFilter[] oldValue = getChoosableFileFilters();
             filters.removeElement(f);
--- a/jdk/src/share/classes/javax/swing/JTree.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/swing/JTree.java	Wed Jul 05 19:00:49 2017 +0200
@@ -3751,7 +3751,7 @@
      * the nodes identified by in <code>e</code>.
      */
     void removeDescendantSelectedPaths(TreeModelEvent e) {
-        TreePath            pPath = e.getTreePath();
+        TreePath            pPath = SwingUtilities2.getTreePath(e, getModel());
         Object[]            oldChildren = e.getChildren();
         TreeSelectionModel  sm = getSelectionModel();
 
@@ -3785,7 +3785,7 @@
             // and update BasicTreeUIs treeStructureChanged method
             // to update descendants in response to a treeStructureChanged
             // event, all the children of the event won't collapse!
-            TreePath            parent = e.getTreePath();
+            TreePath            parent = SwingUtilities2.getTreePath(e, getModel());
 
             if(parent == null)
                 return;
@@ -3822,7 +3822,7 @@
             if(e == null)
                 return;
 
-            TreePath            parent = e.getTreePath();
+            TreePath            parent = SwingUtilities2.getTreePath(e, getModel());
             Object[]            children = e.getChildren();
 
             if(children == null)
--- a/jdk/src/share/classes/javax/swing/RepaintManager.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/swing/RepaintManager.java	Wed Jul 05 19:00:49 2017 +0200
@@ -354,7 +354,7 @@
 
         // Queue a Runnable to invoke paintDirtyRegions and
         // validateInvalidComponents.
-        scheduleProcessingRunnable();
+        scheduleProcessingRunnable(SunToolkit.targetToAppContext(invalidComponent));
     }
 
 
@@ -443,7 +443,7 @@
 
         // Queue a Runnable to invoke paintDirtyRegions and
         // validateInvalidComponents.
-        scheduleProcessingRunnable();
+        scheduleProcessingRunnable(SunToolkit.targetToAppContext(c));
     }
 
     /**
@@ -1389,10 +1389,6 @@
         return paintManager;
     }
 
-    private void scheduleProcessingRunnable() {
-        scheduleProcessingRunnable(AppContext.getAppContext());
-    }
-
     private void scheduleProcessingRunnable(AppContext context) {
         if (processingRunnable.markPending()) {
             Toolkit tk = Toolkit.getDefaultToolkit();
--- a/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/swing/SortingFocusTraversalPolicy.java	Wed Jul 05 19:00:49 2017 +0200
@@ -115,7 +115,7 @@
         try {
             index = Collections.binarySearch(cycle, aComponent, comparator);
         } catch (ClassCastException e) {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("### During the binary search for " + aComponent + " the exception occured: ", e);
             }
             return -1;
@@ -193,7 +193,7 @@
                 if (getImplicitDownCycleTraversal()) {
                     retComp = cont.getFocusTraversalPolicy().getDefaultComponent(cont);
 
-                    if (retComp != null && log.isLoggable(PlatformLogger.FINE)) {
+                    if (retComp != null && log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("### Transfered focus down-cycle to " + retComp +
                                  " in the focus cycle root " + cont);
                     }
@@ -205,7 +205,7 @@
                            cont.getFocusTraversalPolicy().getDefaultComponent(cont) :
                            cont.getFocusTraversalPolicy().getLastComponent(cont));
 
-                if (retComp != null && log.isLoggable(PlatformLogger.FINE)) {
+                if (retComp != null && log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("### Transfered focus to " + retComp + " in the FTP provider " + cont);
                 }
             }
@@ -236,7 +236,7 @@
      *         aComponent is null
      */
     public Component getComponentAfter(Container aContainer, Component aComponent) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### Searching in " + aContainer + " for component after " + aComponent);
         }
 
@@ -260,7 +260,7 @@
         // See if the component is inside of policy provider.
         Container provider = getTopmostProvider(aContainer, aComponent);
         if (provider != null) {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("### Asking FTP " + provider + " for component after " + aComponent);
             }
 
@@ -271,7 +271,7 @@
             // Null result means that we overstepped the limit of the FTP's cycle.
             // In that case we must quit the cycle, otherwise return the component found.
             if (afterComp != null) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("### FTP returned " + afterComp);
                 }
                 return afterComp;
@@ -281,14 +281,14 @@
 
         List<Component> cycle = getFocusTraversalCycle(aContainer);
 
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### Cycle is " + cycle + ", component is " + aComponent);
         }
 
         int index = getComponentIndex(cycle, aComponent);
 
         if (index < 0) {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("### Didn't find component " + aComponent + " in a cycle " + aContainer);
             }
             return getFirstComponent(aContainer);
@@ -353,7 +353,7 @@
         // See if the component is inside of policy provider.
         Container provider = getTopmostProvider(aContainer, aComponent);
         if (provider != null) {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("### Asking FTP " + provider + " for component after " + aComponent);
             }
 
@@ -364,7 +364,7 @@
             // Null result means that we overstepped the limit of the FTP's cycle.
             // In that case we must quit the cycle, otherwise return the component found.
             if (beforeComp != null) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("### FTP returned " + beforeComp);
                 }
                 return beforeComp;
@@ -379,14 +379,14 @@
 
         List<Component> cycle = getFocusTraversalCycle(aContainer);
 
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### Cycle is " + cycle + ", component is " + aComponent);
         }
 
         int index = getComponentIndex(cycle, aComponent);
 
         if (index < 0) {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("### Didn't find component " + aComponent + " in a cycle " + aContainer);
             }
             return getLastComponent(aContainer);
@@ -432,7 +432,7 @@
     public Component getFirstComponent(Container aContainer) {
         List<Component> cycle;
 
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### Getting first component in " + aContainer);
         }
         if (aContainer == null) {
@@ -446,12 +446,12 @@
         }
 
         if (cycle.size() == 0) {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("### Cycle is empty");
             }
             return null;
         }
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### Cycle is " + cycle);
         }
 
@@ -480,7 +480,7 @@
      */
     public Component getLastComponent(Container aContainer) {
         List<Component> cycle;
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### Getting last component in " + aContainer);
         }
 
@@ -495,12 +495,12 @@
         }
 
         if (cycle.size() == 0) {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("### Cycle is empty");
             }
             return null;
         }
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### Cycle is " + cycle);
         }
 
--- a/jdk/src/share/classes/javax/swing/event/TreeModelEvent.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/swing/event/TreeModelEvent.java	Wed Jul 05 19:00:49 2017 +0200
@@ -128,7 +128,7 @@
     public TreeModelEvent(Object source, Object[] path, int[] childIndices,
                           Object[] children)
     {
-        this(source, new TreePath(path), childIndices, children);
+        this(source, (path == null) ? null : new TreePath(path), childIndices, children);
     }
 
     /**
@@ -183,7 +183,7 @@
      */
     public TreeModelEvent(Object source, Object[] path)
     {
-        this(source, new TreePath(path));
+        this(source, (path == null) ? null : new TreePath(path));
     }
 
     /**
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxEditor.java	Wed Jul 05 19:00:49 2017 +0200
@@ -73,6 +73,9 @@
 
         if ( anObject != null )  {
             text = anObject.toString();
+            if (text == null) {
+                text = "";
+            }
             oldValue = anObject;
         } else {
             text = "";
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicTreeUI.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicTreeUI.java	Wed Jul 05 19:00:49 2017 +0200
@@ -3827,7 +3827,7 @@
         //
         public void treeNodesChanged(TreeModelEvent e) {
             if(treeState != null && e != null) {
-                TreePath parentPath = e.getTreePath();
+                TreePath parentPath = SwingUtilities2.getTreePath(e, getModel());
                 int[] indices = e.getChildIndices();
                 if (indices == null || indices.length == 0) {
                     // The root has changed
@@ -3882,7 +3882,7 @@
 
                 updateLeadSelectionRow();
 
-                TreePath       path = e.getTreePath();
+                TreePath       path = SwingUtilities2.getTreePath(e, getModel());
 
                 if(treeState.isExpanded(path)) {
                     updateSize();
@@ -3907,7 +3907,7 @@
 
                 updateLeadSelectionRow();
 
-                TreePath       path = e.getTreePath();
+                TreePath       path = SwingUtilities2.getTreePath(e, getModel());
 
                 if(treeState.isExpanded(path) ||
                    treeModel.getChildCount(path.getLastPathComponent()) == 0)
@@ -3921,7 +3921,7 @@
 
                 updateLeadSelectionRow();
 
-                TreePath       pPath = e.getTreePath();
+                TreePath       pPath = SwingUtilities2.getTreePath(e, getModel());
 
                 if (pPath != null) {
                     pPath = pPath.getParentPath();
--- a/jdk/src/share/classes/javax/swing/text/View.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/swing/text/View.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1174,7 +1174,7 @@
         // formed by added elements (i.e. they will be updated
         // by initialization.
         index0 = Math.max(index0, 0);
-        index1 = getViewIndex(elem.getDocument().getLength(), Position.Bias.Forward);
+        index1 = Math.max((getViewCount() - 1), 0);
         for (int i = index0; i <= index1; i++) {
             if (! ((i >= hole0) && (i <= hole1))) {
                 v = getView(i);
--- a/jdk/src/share/classes/javax/swing/tree/FixedHeightLayoutCache.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/swing/tree/FixedHeightLayoutCache.java	Wed Jul 05 19:00:49 2017 +0200
@@ -26,13 +26,14 @@
 package javax.swing.tree;
 
 import javax.swing.event.TreeModelEvent;
-import java.awt.Dimension;
 import java.awt.Rectangle;
 import java.util.Enumeration;
 import java.util.Hashtable;
 import java.util.NoSuchElementException;
 import java.util.Stack;
 
+import sun.swing.SwingUtilities2;
+
 /**
  * NOTE: This will become more open in a future release.
  * <p>
@@ -346,7 +347,7 @@
         if(e != null) {
             int                 changedIndexs[];
             FHTreeStateNode     changedParent = getNodeForPath
-                                  (e.getTreePath(), false, false);
+                                  (SwingUtilities2.getTreePath(e, getModel()), false, false);
             int                 maxCounter;
 
             changedIndexs = e.getChildIndices();
@@ -390,7 +391,7 @@
         if(e != null) {
             int                 changedIndexs[];
             FHTreeStateNode     changedParent = getNodeForPath
-                                  (e.getTreePath(), false, false);
+                                  (SwingUtilities2.getTreePath(e, getModel()), false, false);
             int                 maxCounter;
 
             changedIndexs = e.getChildIndices();
@@ -429,7 +430,7 @@
         if(e != null) {
             int                  changedIndexs[];
             int                  maxCounter;
-            TreePath             parentPath = e.getTreePath();
+            TreePath             parentPath = SwingUtilities2.getTreePath(e, getModel());
             FHTreeStateNode      changedParentNode = getNodeForPath
                                        (parentPath, false, false);
 
@@ -475,7 +476,7 @@
      */
     public void treeStructureChanged(TreeModelEvent e) {
         if(e != null) {
-            TreePath          changedPath = e.getTreePath();
+            TreePath          changedPath = SwingUtilities2.getTreePath(e, getModel());
             FHTreeStateNode   changedNode = getNodeForPath
                                                 (changedPath, false, false);
 
--- a/jdk/src/share/classes/javax/swing/tree/VariableHeightLayoutCache.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/swing/tree/VariableHeightLayoutCache.java	Wed Jul 05 19:00:49 2017 +0200
@@ -26,7 +26,6 @@
 package javax.swing.tree;
 
 import javax.swing.event.TreeModelEvent;
-import java.awt.Dimension;
 import java.awt.Rectangle;
 import java.util.Enumeration;
 import java.util.Hashtable;
@@ -34,6 +33,8 @@
 import java.util.Stack;
 import java.util.Vector;
 
+import sun.swing.SwingUtilities2;
+
 /**
  * NOTE: This will become more open in a future release.
  * <p>
@@ -413,7 +414,7 @@
             TreeStateNode     changedNode;
 
             changedIndexs = e.getChildIndices();
-            changedNode = getNodeForPath(e.getTreePath(), false, false);
+            changedNode = getNodeForPath(SwingUtilities2.getTreePath(e, getModel()), false, false);
             if(changedNode != null) {
                 Object            changedValue = changedNode.getValue();
 
@@ -466,7 +467,7 @@
             TreeStateNode     changedParentNode;
 
             changedIndexs = e.getChildIndices();
-            changedParentNode = getNodeForPath(e.getTreePath(), false, false);
+            changedParentNode = getNodeForPath(SwingUtilities2.getTreePath(e, getModel()), false, false);
             /* Only need to update the children if the node has been
                expanded once. */
             // PENDING(scott): make sure childIndexs is sorted!
@@ -540,7 +541,7 @@
             TreeStateNode     changedParentNode;
 
             changedIndexs = e.getChildIndices();
-            changedParentNode = getNodeForPath(e.getTreePath(), false, false);
+            changedParentNode = getNodeForPath(SwingUtilities2.getTreePath(e, getModel()), false, false);
             // PENDING(scott): make sure that changedIndexs are sorted in
             // ascending order.
             if(changedParentNode != null && changedIndexs != null &&
@@ -628,7 +629,7 @@
     public void treeStructureChanged(TreeModelEvent e) {
         if(e != null)
         {
-            TreePath          changedPath = e.getTreePath();
+            TreePath          changedPath = SwingUtilities2.getTreePath(e, getModel());
             TreeStateNode     changedNode;
 
             changedNode = getNodeForPath(changedPath, false, false);
--- a/jdk/src/share/classes/javax/xml/crypto/dsig/Manifest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/xml/crypto/dsig/Manifest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -35,15 +35,15 @@
  * the <a href="http://www.w3.org/TR/xmldsig-core/">
  * W3C Recommendation for XML-Signature Syntax and Processing</a>.
  * The XML Schema Definition is defined as:
- * <pre><code>
- * &lt;element name="Manifest" type="ds:ManifestType"/&gt;
- *   &lt;complexType name="ManifestType"&gt;
- *     &lt;sequence>
- *       &lt;element ref="ds:Reference" maxOccurs="unbounded"/&gt;
- *     &lt;/sequence&gt;
- *     &lt;attribute name="Id" type="ID" use="optional"/&gt;
- *   &lt;/complexType&gt;
- * </code></pre>
+ * <pre>{@code
+ * <element name="Manifest" type="ds:ManifestType"/>
+ *   <complexType name="ManifestType">
+ *     <sequence>
+ *       <element ref="ds:Reference" maxOccurs="unbounded"/>
+ *     </sequence>
+ *     <attribute name="Id" type="ID" use="optional"/>
+ *   </complexType>
+ * }</pre>
  *
  * A <code>Manifest</code> instance may be created by invoking
  * one of the {@link XMLSignatureFactory#newManifest newManifest}
--- a/jdk/src/share/classes/javax/xml/crypto/dsig/dom/DOMValidateContext.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/javax/xml/crypto/dsig/dom/DOMValidateContext.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013 Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -74,11 +74,7 @@
         if (ks == null) {
             throw new NullPointerException("key selector is null");
         }
-        if (node == null) {
-            throw new NullPointerException("node is null");
-        }
-        setKeySelector(ks);
-        this.node = node;
+        init(node, ks);
     }
 
     /**
@@ -97,11 +93,20 @@
         if (validatingKey == null) {
             throw new NullPointerException("validatingKey is null");
         }
+        init(node, KeySelector.singletonKeySelector(validatingKey));
+    }
+
+    private void init(Node node, KeySelector ks) {
         if (node == null) {
             throw new NullPointerException("node is null");
         }
-        setKeySelector(KeySelector.singletonKeySelector(validatingKey));
+
         this.node = node;
+        super.setKeySelector(ks);
+        if (System.getSecurityManager() != null) {
+            super.setProperty("org.jcp.xml.dsig.secureValidation",
+                              Boolean.TRUE);
+        }
     }
 
     /**
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -193,7 +193,7 @@
 
         if (apacheTransform == null) {
             try {
-                apacheTransform = Transform.getInstance
+                apacheTransform = new Transform
                     (ownerDoc, getAlgorithm(), transformElem.getChildNodes());
                 apacheTransform.setElement(transformElem, xc.getBaseURI());
                 if (log.isLoggable(Level.FINE)) {
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java	Wed Jul 05 19:00:49 2017 +0200
@@ -48,7 +48,7 @@
 
     public Iterator iterator() {
         // If nodefilters are set, must execute them first to create node-set
-        if (xi.getNodeFilters() != null) {
+        if (xi.getNodeFilters() != null && !xi.getNodeFilters().isEmpty()) {
             return Collections.unmodifiableSet
                 (getNodeSet(xi.getNodeFilters())).iterator();
         }
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java	Wed Jul 05 19:00:49 2017 +0200
@@ -38,6 +38,7 @@
 
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.transforms.Transform;
+import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 
 import javax.xml.crypto.*;
 import javax.xml.crypto.dom.DOMCryptoContext;
@@ -117,7 +118,7 @@
 
         if (apacheTransform == null) {
             try {
-                apacheTransform = Transform.getInstance
+                apacheTransform = new Transform
                     (ownerDoc, getAlgorithm(), transformElem.getChildNodes());
                 apacheTransform.setElement(transformElem, xc.getBaseURI());
                 if (log.isLoggable(Level.FINE)) {
@@ -130,6 +131,15 @@
             }
         }
 
+        if (Utils.secureValidation(xc)) {
+            String algorithm = getAlgorithm();
+            if (Transforms.TRANSFORM_XSLT.equals(algorithm)) {
+                throw new TransformException(
+                    "Transform " + algorithm +
+                    " is forbidden when secure validation is enabled");
+            }
+        }
+
         XMLSignatureInput in;
         if (data instanceof ApacheData) {
             if (log.isLoggable(Level.FINE)) {
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java	Wed Jul 05 19:00:49 2017 +0200
@@ -51,6 +51,11 @@
     public DOMCanonicalizationMethod(TransformService spi)
         throws InvalidAlgorithmParameterException {
         super(spi);
+        if (!(spi instanceof ApacheCanonicalizer) &&
+                !isC14Nalg(spi.getAlgorithm())) {
+            throw new InvalidAlgorithmParameterException(
+                "Illegal CanonicalizationMethod");
+        }
     }
 
     /**
@@ -63,6 +68,10 @@
     public DOMCanonicalizationMethod(Element cmElem, XMLCryptoContext context,
         Provider provider) throws MarshalException {
         super(cmElem, context, provider);
+        if (!(spi instanceof ApacheCanonicalizer) &&
+                !isC14Nalg(spi.getAlgorithm())) {
+            throw new MarshalException("Illegal CanonicalizationMethod");
+        }
     }
 
     /**
@@ -101,4 +110,13 @@
         return (getAlgorithm().equals(ocm.getAlgorithm()) &&
             DOMUtils.paramsEqual(getParameterSpec(), ocm.getParameterSpec()));
     }
+
+    private static boolean isC14Nalg(String alg) {
+        return (alg.equals(CanonicalizationMethod.INCLUSIVE) ||
+                alg.equals(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS) ||
+                alg.equals(CanonicalizationMethod.EXCLUSIVE) ||
+                alg.equals(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS) ||
+                alg.equals(DOMCanonicalXMLC14N11Method.C14N_11) ||
+                alg.equals(DOMCanonicalXMLC14N11Method.C14N_11_WITH_COMMENTS));
+    }
 }
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java	Wed Jul 05 19:00:49 2017 +0200
@@ -34,6 +34,7 @@
 
 import java.security.Provider;
 import java.util.*;
+import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -87,7 +88,13 @@
     public DOMKeyInfo(Element kiElem, XMLCryptoContext context,
         Provider provider) throws MarshalException {
         // get Id attribute, if specified
-        id = DOMUtils.getAttributeValue(kiElem, "Id");
+        Attr attr = kiElem.getAttributeNodeNS(null, "Id");
+        if (attr != null) {
+            id = attr.getValue();
+            kiElem.setIdAttributeNode(attr, true);
+        } else {
+            id = null;
+        }
 
         // get all children nodes
         NodeList nl = kiElem.getChildNodes();
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -32,6 +32,7 @@
 
 import java.security.Provider;
 import java.util.*;
+import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -85,12 +86,30 @@
      */
     public DOMManifest(Element manElem, XMLCryptoContext context,
         Provider provider) throws MarshalException {
-        this.id = DOMUtils.getAttributeValue(manElem, "Id");
+        Attr attr = manElem.getAttributeNodeNS(null, "Id");
+        if (attr != null) {
+            this.id = attr.getValue();
+            manElem.setIdAttributeNode(attr, true);
+        } else {
+            this.id = null;
+        }
+
+        boolean secVal = Utils.secureValidation(context);
         Element refElem = DOMUtils.getFirstChildElement(manElem);
         List refs = new ArrayList();
+        int refCount = 0;
         while (refElem != null) {
             refs.add(new DOMReference(refElem, context, provider));
             refElem = DOMUtils.getNextSiblingElement(refElem);
+
+            refCount++;
+            if (secVal && (refCount > DOMSignedInfo.MAXIMUM_REFERENCE_COUNT)) {
+                String error = "A maxiumum of " +
+                               DOMSignedInfo.MAXIMUM_REFERENCE_COUNT +
+                               " references per Manifest are allowed with" +
+                               " secure validation";
+                throw new MarshalException(error);
+            }
         }
         this.references = Collections.unmodifiableList(refs);
     }
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java	Wed Jul 05 19:00:49 2017 +0200
@@ -51,6 +51,7 @@
 import org.w3c.dom.Node;
 
 import org.jcp.xml.dsig.internal.DigesterOutputStream;
+import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
 import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 import com.sun.org.apache.xml.internal.security.utils.Base64;
@@ -65,6 +66,12 @@
 public final class DOMReference extends DOMStructure
     implements Reference, DOMURIReference {
 
+    /**
+     * The maximum number of transforms per reference, if secure validation
+     * is enabled.
+     */
+    public static final int MAXIMUM_TRANSFORM_COUNT = 5;
+
    /**
     * Look up useC14N11 system property. If true, an explicit C14N11 transform
     * will be added if necessary when generating the signature. See section
@@ -184,15 +191,27 @@
      */
     public DOMReference(Element refElem, XMLCryptoContext context,
         Provider provider) throws MarshalException {
+        boolean secVal = Utils.secureValidation(context);
+
         // unmarshal Transforms, if specified
         Element nextSibling = DOMUtils.getFirstChildElement(refElem);
         List transforms = new ArrayList(5);
         if (nextSibling.getLocalName().equals("Transforms")) {
             Element transformElem = DOMUtils.getFirstChildElement(nextSibling);
+
+            int transformCount = 0;
             while (transformElem != null) {
                 transforms.add
                     (new DOMTransform(transformElem, context, provider));
                 transformElem = DOMUtils.getNextSiblingElement(transformElem);
+
+                transformCount++;
+                if (secVal && (transformCount > MAXIMUM_TRANSFORM_COUNT)) {
+                    String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT +
+                                   " transforms per Reference are allowed" +
+                                   " with secure validation";
+                    throw new MarshalException(error);
+                }
             }
             nextSibling = DOMUtils.getNextSiblingElement(nextSibling);
         }
@@ -200,6 +219,14 @@
         // unmarshal DigestMethod
         Element dmElem = nextSibling;
         this.digestMethod = DOMDigestMethod.unmarshal(dmElem);
+        String digestMethodAlgorithm = this.digestMethod.getAlgorithm();
+        if (secVal
+            && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm))
+        {
+             throw new MarshalException("It is forbidden to use algorithm " +
+                                        digestMethod +
+                                        " when secure validation is enabled");
+        }
 
         // unmarshal DigestValue
         try {
@@ -211,7 +238,14 @@
 
         // unmarshal attributes
         this.uri = DOMUtils.getAttributeValue(refElem, "URI");
-        this.id = DOMUtils.getAttributeValue(refElem, "Id");
+
+        Attr attr = refElem.getAttributeNodeNS(null, "Id");
+        if (attr != null) {
+            this.id = attr.getValue();
+            refElem.setIdAttributeNode(attr, true);
+        } else {
+            this.id = null;
+        }
 
         this.type = DOMUtils.getAttributeValue(refElem, "Type");
         this.here = refElem.getAttributeNodeNS(null, "URI");
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java	Wed Jul 05 19:00:49 2017 +0200
@@ -38,6 +38,7 @@
 import java.net.URISyntaxException;
 import java.security.Provider;
 import java.util.*;
+import javax.xml.XMLConstants;
 import javax.xml.crypto.*;
 import javax.xml.crypto.dsig.*;
 import javax.xml.crypto.dom.DOMCryptoContext;
@@ -124,9 +125,13 @@
         // get here node
         here = rmElem.getAttributeNodeNS(null, "URI");
 
+        boolean secVal = Utils.secureValidation(context);
+
         // get Transforms, if specified
         List transforms = new ArrayList();
         Element transformsElem = DOMUtils.getFirstChildElement(rmElem);
+
+        int transformCount = 0;
         if (transformsElem != null) {
             Element transformElem =
                 DOMUtils.getFirstChildElement(transformsElem);
@@ -134,6 +139,17 @@
                 transforms.add
                     (new DOMTransform(transformElem, context, provider));
                 transformElem = DOMUtils.getNextSiblingElement(transformElem);
+
+                transformCount++;
+                if (secVal &&
+                    (transformCount > DOMReference.MAXIMUM_TRANSFORM_COUNT))
+                {
+                    String error = "A maxiumum of " +
+                                   DOMReference.MAXIMUM_TRANSFORM_COUNT +
+                                   " transforms per Reference are allowed" +
+                                   " with secure validation";
+                    throw new MarshalException(error);
+                }
             }
         }
         if (transforms.isEmpty()) {
@@ -214,6 +230,21 @@
         } catch (Exception e) {
             throw new URIReferenceException(e);
         }
+
+        // guard against RetrievalMethod loops
+        if ((data instanceof NodeSetData) && Utils.secureValidation(context)) {
+            NodeSetData nsd = (NodeSetData)data;
+            Iterator i = nsd.iterator();
+            if (i.hasNext()) {
+                Node root = (Node)i.next();
+                if ("RetrievalMethod".equals(root.getLocalName())) {
+                    throw new URIReferenceException(
+                        "It is forbidden to have one RetrievalMethod point " +
+                        "to another when secure validation is enabled");
+                }
+            }
+        }
+
         return data;
     }
 
@@ -224,6 +255,8 @@
             ApacheData data = (ApacheData) dereference(context);
             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
             dbf.setNamespaceAware(true);
+            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
+                           Boolean.TRUE);
             DocumentBuilder db = dbf.newDocumentBuilder();
             Document doc = db.parse(new ByteArrayInputStream
                 (data.getXMLSignatureInput().getBytes()));
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java	Wed Jul 05 19:00:49 2017 +0200
@@ -31,6 +31,7 @@
 import javax.xml.crypto.dsig.*;
 
 import java.util.*;
+import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -86,7 +87,13 @@
      */
     public DOMSignatureProperties(Element propsElem) throws MarshalException{
         // unmarshal attributes
-        id = DOMUtils.getAttributeValue(propsElem, "Id");
+        Attr attr = propsElem.getAttributeNodeNS(null, "Id");
+        if (attr != null) {
+            id = attr.getValue();
+            propsElem.setIdAttributeNode(attr, true);
+        } else {
+            id = null;
+        }
 
         NodeList nodes = propsElem.getChildNodes();
         int length = nodes.getLength();
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java	Wed Jul 05 19:00:49 2017 +0200
@@ -31,6 +31,7 @@
 import javax.xml.crypto.dsig.*;
 
 import java.util.*;
+import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -94,7 +95,13 @@
         if (target == null) {
             throw new MarshalException("target cannot be null");
         }
-        id = DOMUtils.getAttributeValue(propElem, "Id");
+        Attr attr = propElem.getAttributeNodeNS(null, "Id");
+        if (attr != null) {
+            id = attr.getValue();
+            propElem.setIdAttributeNode(attr, true);
+        } else {
+            id = null;
+        }
 
         NodeList nodes = propElem.getChildNodes();
         int length = nodes.getLength();
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java	Wed Jul 05 19:00:49 2017 +0200
@@ -45,6 +45,7 @@
 import org.w3c.dom.Node;
 
 import com.sun.org.apache.xml.internal.security.utils.Base64;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 
@@ -55,7 +56,22 @@
  */
 public final class DOMSignedInfo extends DOMStructure implements SignedInfo {
 
+    /**
+     * The maximum number of references per Manifest, if secure validation is
+     * enabled.
+     */
+    public static final int MAXIMUM_REFERENCE_COUNT = 30;
+
     private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+
+    /** Signature - NOT Recommended RSAwithMD5 */
+    private static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 =
+        Constants.MoreAlgorithmsSpecNS + "rsa-md5";
+
+    /** HMAC - NOT Recommended HMAC-MD5 */
+    private static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 =
+        Constants.MoreAlgorithmsSpecNS + "hmac-md5";
+
     private List references;
     private CanonicalizationMethod canonicalizationMethod;
     private SignatureMethod signatureMethod;
@@ -143,12 +159,31 @@
         Element smElem = DOMUtils.getNextSiblingElement(cmElem);
         signatureMethod = DOMSignatureMethod.unmarshal(smElem);
 
+        boolean secVal = Utils.secureValidation(context);
+        String sigMethAlg = signatureMethod.getAlgorithm();
+        if (secVal && ((ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(sigMethAlg)
+            || ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(sigMethAlg))))
+        {
+            throw new MarshalException("It is forbidden to use algorithm " +
+                                       signatureMethod +
+                                       " when secure validation is enabled");
+        }
+
         // unmarshal References
         ArrayList refList = new ArrayList(5);
         Element refElem = DOMUtils.getNextSiblingElement(smElem);
+        int refCount = 0;
         while (refElem != null) {
             refList.add(new DOMReference(refElem, context, provider));
             refElem = DOMUtils.getNextSiblingElement(refElem);
+
+            refCount++;
+            if (secVal && (refCount > MAXIMUM_REFERENCE_COUNT)) {
+                String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT +
+                               " references per SignedInfo are allowed with" +
+                               " secure validation";
+                throw new MarshalException(error);
+            }
         }
         references = Collections.unmodifiableList(refList);
     }
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -31,7 +31,7 @@
 import org.w3c.dom.Node;
 
 import com.sun.org.apache.xml.internal.security.Init;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
 
@@ -68,8 +68,11 @@
         Attr uriAttr = (Attr) domRef.getHere();
         String uri = uriRef.getURI();
         DOMCryptoContext dcc = (DOMCryptoContext) context;
+        String baseURI = context.getBaseURI();
 
-        // Check if same-document URI and register ID
+        boolean secVal = Utils.secureValidation(context);
+
+        // Check if same-document URI and already registered on the context
         if (uri != null && uri.length() != 0 && uri.charAt(0) == '#') {
             String id = uri.substring(1);
 
@@ -79,19 +82,38 @@
                 id = id.substring(i1+1, i2);
             }
 
-            // this is a bit of a hack to check for registered
-            // IDRefs and manually register them with Apache's IdResolver
-            // map which includes builtin schema knowledge of DSig/Enc IDs
-            Node referencedElem = dcc.getElementById(id);
-            if (referencedElem != null) {
-                IdResolver.registerElementById((Element) referencedElem, id);
+            Node refElem = dcc.getElementById(id);
+            if (refElem != null) {
+                if (secVal) {
+                    Element start =
+                        refElem.getOwnerDocument().getDocumentElement();
+                    if (!XMLUtils.protectAgainstWrappingAttack(start,
+                                                               (Element)refElem,
+                                                               id)) {
+                        String error = "Multiple Elements with the same ID " +
+                                       id + " were detected";
+                        throw new URIReferenceException(error);
+                    }
+                }
+
+                XMLSignatureInput result = new XMLSignatureInput(refElem);
+                if (!uri.substring(1).startsWith("xpointer(id(")) {
+                    result.setExcludeComments(true);
+                }
+
+                result.setMIMEType("text/xml");
+                if (baseURI != null && baseURI.length() > 0) {
+                    result.setSourceURI(baseURI.concat(uriAttr.getNodeValue()));
+                } else {
+                    result.setSourceURI(uriAttr.getNodeValue());
+                }
+                return new ApacheNodeSetData(result);
             }
         }
 
         try {
-            String baseURI = context.getBaseURI();
             ResourceResolver apacheResolver =
-                ResourceResolver.getInstance(uriAttr, baseURI);
+                ResourceResolver.getInstance(uriAttr, baseURI, secVal);
             XMLSignatureInput in = apacheResolver.resolve(uriAttr, baseURI);
             if (in.isOctetStream()) {
                 return new ApacheOctetStreamData(in);
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java	Wed Jul 05 19:00:49 2017 +0200
@@ -38,8 +38,6 @@
 import javax.xml.crypto.dsig.*;
 import javax.xml.crypto.dsig.spec.*;
 
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
-
 /**
  * Useful static DOM utility methods.
  *
@@ -107,7 +105,7 @@
     public static void setAttributeID(Element elem, String name, String value) {
         if (value == null) return;
         elem.setAttributeNS(null, name, value);
-        IdResolver.registerElementById(elem, value);
+        elem.setIdAttributeNS(null, name, true);
     }
 
     /**
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java	Wed Jul 05 19:00:49 2017 +0200
@@ -32,6 +32,7 @@
 
 import java.security.Provider;
 import java.util.*;
+import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -91,7 +92,14 @@
         Provider provider) throws MarshalException {
         // unmarshal attributes
         this.encoding = DOMUtils.getAttributeValue(objElem, "Encoding");
-        this.id = DOMUtils.getAttributeValue(objElem, "Id");
+
+        Attr attr = objElem.getAttributeNodeNS(null, "Id");
+        if (attr != null) {
+            this.id = attr.getValue();
+            objElem.setIdAttributeNode(attr, true);
+        } else {
+            this.id = null;
+        }
         this.mimeType = DOMUtils.getAttributeValue(objElem, "MimeType");
 
         NodeList nodes = objElem.getChildNodes();
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java	Wed Jul 05 19:00:49 2017 +0200
@@ -50,6 +50,7 @@
 import java.util.List;
 import java.util.logging.Level;
 import java.util.logging.Logger;
+import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -492,7 +493,13 @@
                 throw new MarshalException(bde);
             }
 
-            id = DOMUtils.getAttributeValue(sigValueElem, "Id");
+            Attr attr = sigValueElem.getAttributeNodeNS(null, "Id");
+            if (attr != null) {
+                id = attr.getValue();
+                sigValueElem.setIdAttributeNode(attr, true);
+            } else {
+                id = null;
+            }
             this.sigValueElem = sigValueElem;
         }
 
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java	Wed Jul 05 19:00:49 2017 +0200
@@ -30,6 +30,7 @@
 import java.io.InputStream;
 import java.io.IOException;
 import java.util.*;
+import javax.xml.crypto.XMLCryptoContext;
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
 
@@ -104,4 +105,16 @@
     public static boolean sameDocumentURI(String uri) {
         return (uri != null && (uri.length() == 0 || uri.charAt(0) == '#'));
     }
+
+    static boolean secureValidation(XMLCryptoContext xc) {
+        if (xc == null) {
+            return false;
+        }
+        return getBoolean(xc, "org.jcp.xml.dsig.secureValidation");
+    }
+
+    private static boolean getBoolean(XMLCryptoContext xc, String name) {
+        Boolean value = (Boolean)xc.getProperty(name);
+        return (value != null && value.booleanValue());
+    }
 }
--- a/jdk/src/share/classes/sun/applet/AppletSecurity.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/applet/AppletSecurity.java	Wed Jul 05 19:00:49 2017 +0200
@@ -52,7 +52,6 @@
  */
 public
 class AppletSecurity extends AWTSecurityManager {
-    private AppContext mainAppContext;
 
     //URLClassLoader.acc
     private static Field facc = null;
@@ -77,7 +76,6 @@
      */
     public AppletSecurity() {
         reset();
-        mainAppContext = AppContext.getAppContext();
     }
 
     // Cache to store known restricted packages
@@ -312,7 +310,7 @@
         AppContext appContext = AppContext.getAppContext();
         AppletClassLoader appletClassLoader = currentAppletClassLoader();
 
-        if ((appContext == mainAppContext) && (appletClassLoader != null)) {
+        if (AppContext.isMainContext(appContext) && (appletClassLoader != null)) {
             // If we're about to allow access to the main EventQueue,
             // and anything untrusted is on the class context stack,
             // disallow access.
--- a/jdk/src/share/classes/sun/applet/resources/MsgAppletViewer_zh_CN.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/applet/resources/MsgAppletViewer_zh_CN.java	Wed Jul 05 19:00:49 2017 +0200
@@ -137,7 +137,7 @@
             {"appletpanel.fileexception", "\u52A0\u8F7D\u65F6\u51FA\u73B0{0}\u5F02\u5E38\u9519\u8BEF: {1}"},
             {"appletpanel.filedeath", "\u52A0\u8F7D\u65F6\u5DF2\u7EC8\u6B62{0}: {1}"},
             {"appletpanel.fileerror", "\u52A0\u8F7D\u65F6\u51FA\u73B0{0}\u9519\u8BEF: {1}"},
-            {"appletpanel.badattribute.exception", "HTML \u8BED\u6CD5\u5206\u6790: \u5BBD\u5EA6/\u9AD8\u5EA6\u5C5E\u6027\u7684\u503C\u4E0D\u6B63\u786E"},
+            {"appletpanel.badattribute.exception", "HTML \u89E3\u6790: \u5BBD\u5EA6/\u9AD8\u5EA6\u5C5E\u6027\u7684\u503C\u4E0D\u6B63\u786E"},
             {"appletillegalargumentexception.objectinputstream", "AppletObjectInputStream \u9700\u8981\u975E\u7A7A\u52A0\u8F7D\u5668"},
             {"appletprops.title", "AppletViewer \u5C5E\u6027"},
             {"appletprops.label.http.server", "Http \u4EE3\u7406\u670D\u52A1\u5668:"},
--- a/jdk/src/share/classes/sun/applet/resources/MsgAppletViewer_zh_TW.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/applet/resources/MsgAppletViewer_zh_TW.java	Wed Jul 05 19:00:49 2017 +0200
@@ -73,7 +73,7 @@
             {"appletviewer.parse.warning.embed.requiresheight", "\u8B66\u544A: <embed> \u6A19\u8A18\u9700\u8981\u9AD8\u5EA6\u5C6C\u6027\u3002"},
             {"appletviewer.parse.warning.embed.requireswidth", "\u8B66\u544A: <embed> \u6A19\u8A18\u9700\u8981\u5BEC\u5EA6\u5C6C\u6027\u3002"},
             {"appletviewer.parse.warning.appnotLongersupported", "\u8B66\u544A: \u4E0D\u518D\u652F\u63F4 <app> \u6A19\u8A18\uFF0C\u8ACB\u6539\u7528 <applet>:"},
-            {"appletviewer.usage", "\u7528\u6CD5: appletviewer <\u9078\u9805> url(s)\n\n\u5176\u4E2D\u7684 <\u9078\u9805> \u5305\u62EC:\n  -debug                  \u5728 Java \u9664\u932F\u7A0B\u5F0F\u4E2D\u555F\u52D5 Applet \u6AA2\u8996\u5668\n  -encoding <\u7DE8\u78BC>    \u6307\u5B9A HTML \u6A94\u6848\u4F7F\u7528\u7684\u5B57\u5143\u7DE8\u78BC\n  -J<\u57F7\u884C\u968E\u6BB5\u65D7\u6A19>        \u5C07\u5F15\u6578\u50B3\u9001\u81F3 java \u89E3\u8B6F\u5668\n\n -J \u9078\u9805\u4E0D\u662F\u6A19\u6E96\u9078\u9805\uFF0C\u82E5\u6709\u8B8A\u66F4\u4E0D\u53E6\u884C\u901A\u77E5\u3002"},
+            {"appletviewer.usage", "\u7528\u6CD5: appletviewer <options> url(s)\n\n\u5176\u4E2D\u7684 <options> \u5305\u62EC:\n  -debug                  \u5728 Java \u9664\u932F\u7A0B\u5F0F\u4E2D\u555F\u52D5 Applet \u6AA2\u8996\u5668\n  -encoding <encoding>    \u6307\u5B9A HTML \u6A94\u6848\u4F7F\u7528\u7684\u5B57\u5143\u7DE8\u78BC\n  -J<runtime flag>        \u5C07\u5F15\u6578\u50B3\u9001\u81F3 java \u89E3\u8B6F\u5668\n\n -J \u9078\u9805\u4E0D\u662F\u6A19\u6E96\u9078\u9805\uFF0C\u82E5\u6709\u8B8A\u66F4\u4E0D\u53E6\u884C\u901A\u77E5\u3002"},
             {"appletviewer.main.err.unsupportedopt", "\u4E0D\u652F\u63F4\u7684\u9078\u9805: {0}"},
             {"appletviewer.main.err.unrecognizedarg", "\u7121\u6CD5\u8FA8\u8B58\u7684\u5F15\u6578: {0}"},
             {"appletviewer.main.err.dupoption", "\u91CD\u8907\u4F7F\u7528\u9078\u9805: {0}"},
--- a/jdk/src/share/classes/sun/audio/AudioData.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/audio/AudioData.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -48,7 +48,7 @@
   */
 
 
-public class AudioData {
+public final class AudioData {
 
     private static final AudioFormat DEFAULT_FORMAT =
         new AudioFormat(AudioFormat.Encoding.ULAW,
--- a/jdk/src/share/classes/sun/audio/AudioDataStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/audio/AudioDataStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,8 +26,6 @@
 package sun.audio;
 
 import java.io.*;
-import javax.sound.sampled.*;
-import javax.sound.midi.*;
 
 /**
  * An input stream to play AudioData.
@@ -39,18 +37,18 @@
  */
 public class AudioDataStream extends ByteArrayInputStream {
 
-    AudioData ad;
+    private final AudioData ad;
 
     /**
      * Constructor
      */
-    public AudioDataStream(AudioData data) {
+    public AudioDataStream(final AudioData data) {
 
         super(data.buffer);
         this.ad = data;
     }
 
-    AudioData getAudioData() {
+    final AudioData getAudioData() {
         return ad;
     }
 }
--- a/jdk/src/share/classes/sun/audio/AudioDevice.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/audio/AudioDevice.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,12 +27,9 @@
 
 import java.util.Hashtable;
 import java.util.Vector;
-import java.util.Enumeration;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.BufferedInputStream;
-import java.io.OutputStream;
-import java.io.ByteArrayInputStream;
 
 import javax.sound.sampled.*;
 import javax.sound.midi.*;
@@ -57,8 +54,7 @@
  * @author Florian Bomers
  */
 
-public class
-    AudioDevice {
+public final class AudioDevice {
 
     private boolean DEBUG = false  /*true*/ ;
 
@@ -404,11 +400,11 @@
 
     // INFO CLASS
 
-    class Info implements MetaEventListener {
+    final class Info implements MetaEventListener {
 
-        Sequencer   sequencer;
-        InputStream in;
-        DataPusher  datapusher;
+        final Sequencer   sequencer;
+        final InputStream in;
+        final DataPusher  datapusher;
 
         Info( Sequencer sequencer, InputStream in, DataPusher datapusher ) {
 
--- a/jdk/src/share/classes/sun/audio/AudioPlayer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/audio/AudioPlayer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,13 +25,7 @@
 
 package sun.audio;
 
-import java.util.Vector;
-import java.util.Enumeration;
-import java.io.IOException;
 import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.FileOutputStream;
-
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 
@@ -69,11 +63,10 @@
  * @author Arthur van Hoff, Thomas Ball
  */
 
-public
-    class AudioPlayer extends Thread {
+public final class AudioPlayer extends Thread {
 
-        private AudioDevice devAudio;
-        private static boolean DEBUG = false /*true*/;
+        private final AudioDevice devAudio;
+        private final static boolean DEBUG = false /*true*/;
 
         /**
          * The default audio player. This audio player is initialized
--- a/jdk/src/share/classes/sun/audio/AudioStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/audio/AudioStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,9 +26,7 @@
 package sun.audio;
 
 import java.io.InputStream;
-import java.io.DataInputStream;
 import java.io.FilterInputStream;
-import java.io.ByteArrayInputStream;
 import java.io.BufferedInputStream;
 import java.io.IOException;
 
@@ -41,13 +39,13 @@
  */
 
 
-public class AudioStream extends FilterInputStream {
+public final class AudioStream extends FilterInputStream {
 
     // AudioContainerInputStream acis;
-    protected AudioInputStream ais = null;
-    protected AudioFormat format = null;
-    protected MidiFileFormat midiformat = null;
-    protected InputStream stream = null;
+    AudioInputStream ais = null;
+    AudioFormat format = null;
+    MidiFileFormat midiformat = null;
+    InputStream stream = null;
 
 
     /*
--- a/jdk/src/share/classes/sun/audio/AudioStreamSequence.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/audio/AudioStreamSequence.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 
 package sun.audio;
 
-import java.io.IOException;
 import java.io.InputStream;
 import java.io.SequenceInputStream;
 import java.util.Enumeration;
@@ -44,8 +43,8 @@
  * @see AudioPlayer
  * @author Arthur van Hoff
  */
-public
-    class AudioStreamSequence extends SequenceInputStream {
+public final class AudioStreamSequence extends SequenceInputStream {
+
         Enumeration e;
         InputStream in;
 
--- a/jdk/src/share/classes/sun/audio/AudioTranslatorStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/audio/AudioTranslatorStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,18 +26,15 @@
 package sun.audio;
 
 import java.io.InputStream;
-import java.io.DataInputStream;
-import java.io.FilterInputStream;
 import java.io.IOException;
 
 /**
  * Translator for native audio formats (not implemented in this release).
  *
  */
-public
-    class AudioTranslatorStream extends NativeAudioStream {
+public final class AudioTranslatorStream extends NativeAudioStream {
 
-        private int length = 0;
+        private final int length = 0;
 
         public AudioTranslatorStream(InputStream in) throws IOException {
             super(in);
--- a/jdk/src/share/classes/sun/audio/ContinuousAudioDataStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/audio/ContinuousAudioDataStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,11 +42,10 @@
  * @author Arthur van Hoff
  */
 
-public
-    class ContinuousAudioDataStream extends AudioDataStream {
+public final class ContinuousAudioDataStream extends AudioDataStream {
 
 
-        /**
+    /**
          * Create a continuous stream of audio.
          */
         public ContinuousAudioDataStream(AudioData data) {
--- a/jdk/src/share/classes/sun/audio/InvalidAudioFormatException.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/audio/InvalidAudioFormatException.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,20 +29,20 @@
 /**
  * Signals an invalid audio stream for the stream handler.
  */
-class InvalidAudioFormatException extends IOException {
+final class InvalidAudioFormatException extends IOException {
 
 
     /**
      * Constructor.
      */
-    public InvalidAudioFormatException() {
+    InvalidAudioFormatException() {
         super();
     }
 
     /**
      * Constructor with a detail message.
      */
-    public InvalidAudioFormatException(String s) {
+    InvalidAudioFormatException(String s) {
         super(s);
     }
 }
--- a/jdk/src/share/classes/sun/awt/AWTAutoShutdown.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/AWTAutoShutdown.java	Wed Jul 05 19:00:49 2017 +0200
@@ -375,7 +375,7 @@
     }
 
     final void dumpPeers(final PlatformLogger aLog) {
-        if (aLog.isLoggable(PlatformLogger.FINE)) {
+        if (aLog.isLoggable(PlatformLogger.Level.FINE)) {
             synchronized (activationLock) {
                 synchronized (mainLock) {
                     aLog.fine("Mapped peers:");
--- a/jdk/src/share/classes/sun/awt/AppContext.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/AppContext.java	Wed Jul 05 19:00:49 2017 +0200
@@ -162,7 +162,8 @@
     }
 
     /* The main "system" AppContext, used by everything not otherwise
-       contained in another AppContext.
+       contained in another AppContext. It is implicitly created for
+       standalone apps only (i.e. not applets)
      */
     private static volatile AppContext mainAppContext = null;
 
@@ -189,10 +190,16 @@
     public static final String DISPOSED_PROPERTY_NAME = "disposed";
     public static final String GUI_DISPOSED = "guidisposed";
 
-    private volatile boolean isDisposed = false; // true if AppContext is disposed
+    private enum State {
+        VALID,
+        BEING_DISPOSED,
+        DISPOSED
+    };
+
+    private volatile State state = State.VALID;
 
     public boolean isDisposed() {
-        return isDisposed;
+        return state == State.DISPOSED;
     }
 
     /*
@@ -204,25 +211,6 @@
      */
     private static final AtomicInteger numAppContexts = new AtomicInteger(0);
 
-    static {
-        // On the main Thread, we get the ThreadGroup, make a corresponding
-        // AppContext, and instantiate the Java EventQueue.  This way, legacy
-        // code is unaffected by the move to multiple AppContext ability.
-        AccessController.doPrivileged(new PrivilegedAction<Void>() {
-            public Void run() {
-                ThreadGroup currentThreadGroup =
-                        Thread.currentThread().getThreadGroup();
-                ThreadGroup parentThreadGroup = currentThreadGroup.getParent();
-                while (parentThreadGroup != null) {
-                    // Find the root ThreadGroup to construct our main AppContext
-                    currentThreadGroup = parentThreadGroup;
-                    parentThreadGroup = currentThreadGroup.getParent();
-                }
-                mainAppContext = new AppContext(currentThreadGroup);
-                return null;
-            }
-        });
-    }
 
     /*
      * The context ClassLoader that was used to create this AppContext.
@@ -266,6 +254,27 @@
     private static final ThreadLocal<AppContext> threadAppContext =
             new ThreadLocal<AppContext>();
 
+    private final static void initMainAppContext() {
+        // On the main Thread, we get the ThreadGroup, make a corresponding
+        // AppContext, and instantiate the Java EventQueue.  This way, legacy
+        // code is unaffected by the move to multiple AppContext ability.
+        AccessController.doPrivileged(new PrivilegedAction<Void>() {
+            public Void run() {
+                ThreadGroup currentThreadGroup =
+                        Thread.currentThread().getThreadGroup();
+                ThreadGroup parentThreadGroup = currentThreadGroup.getParent();
+                while (parentThreadGroup != null) {
+                    // Find the root ThreadGroup to construct our main AppContext
+                    currentThreadGroup = parentThreadGroup;
+                    parentThreadGroup = currentThreadGroup.getParent();
+                }
+
+                mainAppContext = SunToolkit.createNewAppContext(currentThreadGroup);
+                return null;
+            }
+        });
+    }
+
     /**
      * Returns the appropriate AppContext for the caller,
      * as determined by its ThreadGroup.  If the main "system" AppContext
@@ -278,8 +287,10 @@
      * @since   1.2
      */
     public final static AppContext getAppContext() {
-        if (numAppContexts.get() == 1)   // If there's only one system-wide,
-            return mainAppContext; // return the main system AppContext.
+        // we are standalone app, return the main app context
+        if (numAppContexts.get() == 1 && mainAppContext != null) {
+            return mainAppContext;
+        }
 
         AppContext appContext = threadAppContext.get();
 
@@ -293,29 +304,37 @@
                     // when new AppContext objects are created.
                     ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup();
                     ThreadGroup threadGroup = currentThreadGroup;
+
+                    // Special case: we implicitly create the main app context
+                    // if no contexts have been created yet. This covers standalone apps
+                    // and excludes applets because by the time applet starts
+                    // a number of contexts have already been created by the plugin.
+                    if (numAppContexts.get() == 0) {
+                        // This check is not necessary, its purpose is to help
+                        // Plugin devs to catch all the cases of main AC creation.
+                        if (System.getProperty("javaplugin.version") == null &&
+                                System.getProperty("javawebstart.version") == null) {
+                            initMainAppContext();
+                        }
+                    }
+
                     AppContext context = threadGroup2appContext.get(threadGroup);
                     while (context == null) {
                         threadGroup = threadGroup.getParent();
                         if (threadGroup == null) {
-                            // If we get here, we're running under a ThreadGroup that
-                            // has no AppContext associated with it.  This should never
-                            // happen, because createNewContext() should be used by the
-                            // toolkit to create the ThreadGroup that everything runs
-                            // under.
-                            throw new RuntimeException("Invalid ThreadGroup");
+                            return null;
                         }
                         context = threadGroup2appContext.get(threadGroup);
                     }
+
                     // In case we did anything in the above while loop, we add
                     // all the intermediate ThreadGroups to threadGroup2appContext
                     // so we won't spin again.
                     for (ThreadGroup tg = currentThreadGroup; tg != threadGroup; tg = tg.getParent()) {
                         threadGroup2appContext.put(tg, context);
                     }
+
                     // Now we're done, so we cache the latest key/value pair.
-                    // (we do this before checking with any AWTSecurityManager, so if
-                    // this Thread equates with the main AppContext in the cache, it
-                    // still will)
                     threadAppContext.set(context);
 
                     return context;
@@ -323,17 +342,18 @@
             });
         }
 
-        if (appContext == mainAppContext)  {
-            // Before we return the main "system" AppContext, check to
-            // see if there's an AWTSecurityManager installed.  If so,
-            // allow it to choose the AppContext to return.
-            AppContext secAppContext = getExecutionAppContext();
-            if (secAppContext != null) {
-                appContext = secAppContext; // Return what we're told
-            }
-        }
+        return appContext;
+    }
 
-        return appContext;
+    /**
+     * Returns true if the specified AppContext is the main AppContext.
+     *
+     * @param   ctx the context to compare with the main context
+     * @return  true if the specified AppContext is the main AppContext.
+     * @since   1.8
+     */
+    public final static boolean isMainContext(AppContext ctx) {
+        return (ctx != null && ctx == mainAppContext);
     }
 
     private final static AppContext getExecutionAppContext() {
@@ -348,16 +368,6 @@
         return null;
     }
 
-    /**
-     * Returns the main ("system") AppContext.
-     *
-     * @return  the main AppContext
-     * @since   1.8
-     */
-    final static AppContext getMainAppContext() {
-        return mainAppContext;
-    }
-
     private long DISPOSAL_TIMEOUT = 5000;  // Default to 5-second timeout
                                            // for disposal of all Frames
                                            // (we wait for this time twice,
@@ -389,10 +399,11 @@
         }
 
         synchronized(this) {
-            if (this.isDisposed) {
-                return; // If already disposed, bail.
+            if (this.state != State.VALID) {
+                return; // If already disposed or being disposed, bail.
             }
-            this.isDisposed = true;
+
+            this.state = State.BEING_DISPOSED;
         }
 
         final PropertyChangeSupport changeSupport = this.changeSupport;
@@ -462,6 +473,11 @@
             } catch (InterruptedException e) { }
         }
 
+        // We are done with posting events, so change the state to disposed
+        synchronized(this) {
+            this.state = State.DISPOSED;
+        }
+
         // Next, we interrupt all Threads in the ThreadGroup
         this.threadGroup.interrupt();
             // Note, the EventDispatchThread we've interrupted may dump an
@@ -798,19 +814,27 @@
     static {
         sun.misc.SharedSecrets.setJavaAWTAccess(new sun.misc.JavaAWTAccess() {
             public Object get(Object key) {
-                return getAppContext().get(key);
+                AppContext ac = getAppContext();
+                return (ac == null) ? null : ac.get(key);
             }
             public void put(Object key, Object value) {
-                getAppContext().put(key, value);
+                AppContext ac = getAppContext();
+                if (ac != null) {
+                    ac.put(key, value);
+                }
             }
             public void remove(Object key) {
-                getAppContext().remove(key);
+                AppContext ac = getAppContext();
+                if (ac != null) {
+                    ac.remove(key);
+                }
             }
             public boolean isDisposed() {
-                return getAppContext().isDisposed();
+                AppContext ac = getAppContext();
+                return (ac == null) ? true : ac.isDisposed();
             }
             public boolean isMainAppContext() {
-                return (numAppContexts.get() == 1);
+                return (numAppContexts.get() == 1 && mainAppContext != null);
             }
             public Object getContext() {
                 return getAppContext();
--- a/jdk/src/share/classes/sun/awt/DebugSettings.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/DebugSettings.java	Wed Jul 05 19:00:49 2017 +0200
@@ -128,7 +128,7 @@
             });
 
         // echo the initial property settings to stdout
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("DebugSettings:\n{0}", this);
         }
     }
@@ -250,7 +250,7 @@
     }
 
     private void println(Object object) {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer(object.toString());
         }
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/awt/IconInfo.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,237 @@
+/*
+ * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package sun.awt;
+import java.awt.*;
+import java.awt.color.*;
+import java.awt.image.*;
+import sun.awt.image.ToolkitImage;
+import sun.awt.image.ImageRepresentation;
+import java.util.Arrays;
+
+public class IconInfo {
+    /**
+     * Representation of image as an int array.
+     * It's used on platforms where icon data
+     * is expected to be in 32-bit format.
+     */
+    private int[] intIconData;
+    /**
+     * Representation of image as an long array.
+     * It's used on platforms where icon data
+     * is expected to be in 64-bit format.
+     */
+    private long[] longIconData;
+    /**
+     * Icon image.
+     */
+    private Image image;
+    /**
+     * Width of icon image. Being set in constructor.
+     */
+    private final int width;
+    /**
+     * Height of icon image. Being set in constructor.
+     */
+    private final int height;
+    /**
+     * Width of scaled icon image. Can be set in setScaledDimension.
+     */
+    private int scaledWidth;
+    /**
+     * Height of scaled icon image. Can be set in setScaledDimension.
+     */
+    private int scaledHeight;
+    /**
+     * Length of raw data. Being set in constructor / setScaledDimension.
+     */
+    private int rawLength;
+
+    public IconInfo(int[] intIconData) {
+        this.intIconData =
+            (null == intIconData) ? null : Arrays.copyOf(intIconData, intIconData.length);
+        this.width = intIconData[0];
+        this.height = intIconData[1];
+        this.scaledWidth = width;
+        this.scaledHeight = height;
+        this.rawLength = width * height + 2;
+    }
+
+    public IconInfo(long[] longIconData) {
+        this.longIconData =
+        (null == longIconData) ? null : Arrays.copyOf(longIconData, longIconData.length);
+        this.width = (int)longIconData[0];
+        this.height = (int)longIconData[1];
+        this.scaledWidth = width;
+        this.scaledHeight = height;
+        this.rawLength = width * height + 2;
+    }
+
+    public IconInfo(Image image) {
+        this.image = image;
+        if (image instanceof ToolkitImage) {
+            ImageRepresentation ir = ((ToolkitImage)image).getImageRep();
+            ir.reconstruct(ImageObserver.ALLBITS);
+            this.width = ir.getWidth();
+            this.height = ir.getHeight();
+        } else {
+            this.width = image.getWidth(null);
+            this.height = image.getHeight(null);
+        }
+        this.scaledWidth = width;
+        this.scaledHeight = height;
+        this.rawLength = width * height + 2;
+    }
+
+    /*
+     * It sets size of scaled icon.
+     */
+    public void setScaledSize(int width, int height) {
+        this.scaledWidth = width;
+        this.scaledHeight = height;
+        this.rawLength = width * height + 2;
+    }
+
+    public boolean isValid() {
+        return (width > 0 && height > 0);
+    }
+
+    public int getWidth() {
+        return width;
+    }
+
+    public int getHeight() {
+        return height;
+    }
+
+    public String toString() {
+        return "IconInfo[w=" + width + ",h=" + height + ",sw=" + scaledWidth + ",sh=" + scaledHeight + "]";
+    }
+
+    public int getRawLength() {
+        return rawLength;
+    }
+
+    public int[] getIntData() {
+        if (this.intIconData == null) {
+            if (this.longIconData != null) {
+                this.intIconData = longArrayToIntArray(longIconData);
+            } else if (this.image != null) {
+                this.intIconData = imageToIntArray(this.image, scaledWidth, scaledHeight);
+            }
+        }
+        return this.intIconData;
+    }
+
+    public long[] getLongData() {
+        if (this.longIconData == null) {
+            if (this.intIconData != null) {
+                this.longIconData = intArrayToLongArray(this.intIconData);
+            } else if (this.image != null) {
+                int[] intIconData = imageToIntArray(this.image, scaledWidth, scaledHeight);
+                this.longIconData = intArrayToLongArray(intIconData);
+            }
+        }
+        return this.longIconData;
+    }
+
+    public Image getImage() {
+        if (this.image == null) {
+            if (this.intIconData != null) {
+                this.image = intArrayToImage(this.intIconData);
+            } else if (this.longIconData != null) {
+                int[] intIconData = longArrayToIntArray(this.longIconData);
+                this.image = intArrayToImage(intIconData);
+            }
+        }
+        return this.image;
+    }
+
+    private static int[] longArrayToIntArray(long[] longData) {
+        int[] intData = new int[longData.length];
+        for (int i = 0; i < longData.length; i++) {
+            // Such a conversion is valid since the
+            // original data (see
+            // make/sun/xawt/ToBin.java) were ints
+            intData[i] = (int)longData[i];
+        }
+        return intData;
+    }
+
+    private static long[] intArrayToLongArray(int[] intData) {
+        long[] longData = new long[intData.length];
+        for (int i = 0; i < intData.length; i++) {
+            longData[i] = (int)intData[i];
+        }
+        return longData;
+    }
+
+    static Image intArrayToImage(int[] raw) {
+        ColorModel cm =
+            new DirectColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), 32,
+                                 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000,
+                                 false, DataBuffer.TYPE_INT);
+        DataBuffer buffer = new DataBufferInt(raw, raw.length-2, 2);
+        WritableRaster raster =
+            Raster.createPackedRaster(buffer, raw[0], raw[1],
+                                      raw[0],
+                                      new int[] {0x00ff0000, 0x0000ff00,
+                                                 0x000000ff, 0xff000000},
+                                      null);
+        BufferedImage im = new BufferedImage(cm, raster, false, null);
+        return im;
+    }
+
+    /*
+     * Returns array of integers which holds data for the image.
+     * It scales the image if necessary.
+     */
+    static int[] imageToIntArray(Image image, int width, int height) {
+        if (width <= 0 || height <= 0) {
+            return null;
+        }
+        ColorModel cm =
+            new DirectColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), 32,
+                                 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000,
+                                 false, DataBuffer.TYPE_INT);
+        DataBufferInt buffer = new DataBufferInt(width * height);
+        WritableRaster raster =
+            Raster.createPackedRaster(buffer, width, height,
+                                      width,
+                                      new int[] {0x00ff0000, 0x0000ff00,
+                                                 0x000000ff, 0xff000000},
+                                      null);
+        BufferedImage im = new BufferedImage(cm, raster, false, null);
+        Graphics g = im.getGraphics();
+        g.drawImage(image, 0, 0, width, height, null);
+        g.dispose();
+        int[] data = buffer.getData();
+        int[] raw = new int[width * height + 2];
+        raw[0] = width;
+        raw[1] = height;
+        System.arraycopy(data, 0, raw, 2, width * height);
+        return raw;
+    }
+
+}
--- a/jdk/src/share/classes/sun/awt/KeyboardFocusManagerPeerImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/KeyboardFocusManagerPeerImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -57,7 +57,7 @@
     public void clearGlobalFocusOwner(Window activeWindow) {
         if (activeWindow != null) {
             Component focusOwner = activeWindow.getFocusOwner();
-            if (focusLog.isLoggable(PlatformLogger.FINE)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
                 focusLog.fine("Clearing global focus owner " + focusOwner);
             }
             if (focusOwner != null) {
@@ -127,7 +127,7 @@
             FocusEvent fl = new CausedFocusEvent(currentOwner, FocusEvent.FOCUS_LOST,
                                                  false, lightweightChild, cause);
 
-            if (focusLog.isLoggable(PlatformLogger.FINER)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                 focusLog.finer("Posting focus event: " + fl);
             }
             SunToolkit.postEvent(SunToolkit.targetToAppContext(currentOwner), fl);
@@ -136,7 +136,7 @@
         FocusEvent fg = new CausedFocusEvent(lightweightChild, FocusEvent.FOCUS_GAINED,
                                              false, currentOwner, cause);
 
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer("Posting focus event: " + fg);
         }
         SunToolkit.postEvent(SunToolkit.targetToAppContext(lightweightChild), fg);
--- a/jdk/src/share/classes/sun/awt/ScrollPaneWheelScroller.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/ScrollPaneWheelScroller.java	Wed Jul 05 19:00:49 2017 +0200
@@ -47,7 +47,7 @@
      * Called from ScrollPane.processMouseWheelEvent()
      */
     public static void handleWheelScrolling(ScrollPane sp, MouseWheelEvent e) {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("x = " + e.getX() + ", y = " + e.getY() + ", src is " + e.getSource());
         }
         int increment = 0;
@@ -56,7 +56,7 @@
             Adjustable adj = getAdjustableToScroll(sp);
             if (adj != null) {
                 increment = getIncrementFromAdjustable(adj, e);
-                if (log.isLoggable(PlatformLogger.FINER)) {
+                if (log.isLoggable(PlatformLogger.Level.FINER)) {
                     log.finer("increment from adjustable(" + adj.getClass() + ") : " + increment);
                 }
                 scrollAdjustable(adj, increment);
@@ -74,7 +74,7 @@
         // if policy is display always or never, use vert
         if (policy == ScrollPane.SCROLLBARS_ALWAYS ||
             policy == ScrollPane.SCROLLBARS_NEVER) {
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("using vertical scrolling due to scrollbar policy");
             }
             return sp.getVAdjustable();
@@ -85,7 +85,7 @@
             Insets ins = sp.getInsets();
             int vertScrollWidth = sp.getVScrollbarWidth();
 
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("insets: l = " + ins.left + ", r = " + ins.right +
                  ", t = " + ins.top + ", b = " + ins.bottom);
                 log.finer("vertScrollWidth = " + vertScrollWidth);
@@ -94,7 +94,7 @@
             // Check if scrollbar is showing by examining insets of the
             // ScrollPane
             if (ins.right >= vertScrollWidth) {
-                if (log.isLoggable(PlatformLogger.FINER)) {
+                if (log.isLoggable(PlatformLogger.Level.FINER)) {
                     log.finer("using vertical scrolling because scrollbar is present");
                 }
                 return sp.getVAdjustable();
@@ -102,13 +102,13 @@
             else {
                 int horizScrollHeight = sp.getHScrollbarHeight();
                 if (ins.bottom >= horizScrollHeight) {
-                    if (log.isLoggable(PlatformLogger.FINER)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINER)) {
                         log.finer("using horiz scrolling because scrollbar is present");
                     }
                     return sp.getHAdjustable();
                 }
                 else {
-                    if (log.isLoggable(PlatformLogger.FINER)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINER)) {
                         log.finer("using NO scrollbar becsause neither is present");
                     }
                     return null;
@@ -124,7 +124,7 @@
      */
     public static int getIncrementFromAdjustable(Adjustable adj,
                                                  MouseWheelEvent e) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             if (adj == null) {
                 log.fine("Assertion (adj != null) failed");
             }
@@ -146,7 +146,7 @@
      * bounds and sets the new value to the Adjustable.
      */
     public static void scrollAdjustable(Adjustable adj, int amount) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             if (adj == null) {
                 log.fine("Assertion (adj != null) failed");
             }
@@ -157,7 +157,7 @@
 
         int current = adj.getValue();
         int upperLimit = adj.getMaximum() - adj.getVisibleAmount();
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("doScrolling by " + amount);
         }
 
--- a/jdk/src/share/classes/sun/awt/SunDisplayChanger.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/SunDisplayChanger.java	Wed Jul 05 19:00:49 2017 +0200
@@ -71,12 +71,12 @@
      * notified when the display is changed.
      */
     public void add(DisplayChangedListener theListener) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             if (theListener == null) {
                 log.fine("Assertion (theListener != null) failed");
             }
         }
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("Adding listener: " + theListener);
         }
         listeners.put(theListener, null);
@@ -86,12 +86,12 @@
      * Remove the given DisplayChangeListener from this SunDisplayChanger.
      */
     public void remove(DisplayChangedListener theListener) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             if (theListener == null) {
                 log.fine("Assertion (theListener != null) failed");
             }
         }
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("Removing listener: " + theListener);
         }
         listeners.remove(theListener);
@@ -102,7 +102,7 @@
      * taken place by calling their displayChanged() methods.
      */
     public void notifyListeners() {
-        if (log.isLoggable(PlatformLogger.FINEST)) {
+        if (log.isLoggable(PlatformLogger.Level.FINEST)) {
             log.finest("notifyListeners");
         }
     // This method is implemented by making a clone of the set of listeners,
@@ -126,7 +126,7 @@
         while (itr.hasNext()) {
             DisplayChangedListener current = itr.next();
             try {
-                if (log.isLoggable(PlatformLogger.FINEST)) {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                     log.finest("displayChanged for listener: " + current);
                 }
                 current.displayChanged();
@@ -146,7 +146,7 @@
      * taken place by calling their paletteChanged() methods.
      */
     public void notifyPaletteChanged() {
-        if (log.isLoggable(PlatformLogger.FINEST)) {
+        if (log.isLoggable(PlatformLogger.Level.FINEST)) {
             log.finest("notifyPaletteChanged");
         }
     // This method is implemented by making a clone of the set of listeners,
@@ -169,7 +169,7 @@
         while (itr.hasNext()) {
             DisplayChangedListener current = itr.next();
             try {
-                if (log.isLoggable(PlatformLogger.FINEST)) {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                     log.finest("paletteChanged for listener: " + current);
                 }
                 current.paletteChanged();
--- a/jdk/src/share/classes/sun/awt/SunGraphicsCallback.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/SunGraphicsCallback.java	Wed Jul 05 19:00:49 2017 +0200
@@ -88,7 +88,7 @@
         int ncomponents = comps.length;
         Shape clip = g.getClip();
 
-        if (log.isLoggable(PlatformLogger.FINER) && (clip != null)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER) && (clip != null)) {
             Rectangle newrect = clip.getBounds();
             log.finer("x = " + newrect.x + ", y = " + newrect.y +
                       ", width = " + newrect.width +
--- a/jdk/src/share/classes/sun/awt/SunToolkit.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/SunToolkit.java	Wed Jul 05 19:00:49 2017 +0200
@@ -58,7 +58,7 @@
     implements WindowClosingSupport, WindowClosingListener,
     ComponentFactory, InputMethodSupport, KeyboardFocusManagerPeerProvider {
 
-    private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.SunToolkit");
+    // 8014718: logging has been removed from SunToolkit
 
     /* Load debug settings for native code */
     static {
@@ -97,6 +97,14 @@
      */
     public final static int MAX_BUTTONS_SUPPORTED = 20;
 
+    /**
+     * Creates and initializes EventQueue instance for the specified
+     * AppContext.
+     * Note that event queue must be created from createNewAppContext()
+     * only in order to ensure that EventQueue constructor obtains
+     * the correct AppContext.
+     * @param appContext AppContext to associate with the event queue
+     */
     private static void initEQ(AppContext appContext) {
         EventQueue eventQueue;
 
@@ -117,8 +125,6 @@
     }
 
     public SunToolkit() {
-        // 7122796: Always create an EQ for the main AppContext
-        initEQ(AppContext.getMainAppContext());
     }
 
     public boolean useBufferPerWindow() {
@@ -281,11 +287,14 @@
      */
     public static AppContext createNewAppContext() {
         ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
+        return createNewAppContext(threadGroup);
+    }
+
+    static final AppContext createNewAppContext(ThreadGroup threadGroup) {
         // Create appContext before initialization of EventQueue, so all
         // the calls to AppContext.getAppContext() from EventQueue ctor
         // return correct values
         AppContext appContext = new AppContext(threadGroup);
-
         initEQ(appContext);
 
         return appContext;
@@ -487,9 +496,7 @@
         setSystemGenerated(event);
         AppContext eventContext = targetToAppContext(event.getSource());
         if (eventContext != null && !eventContext.equals(appContext)) {
-            if (log.isLoggable(PlatformLogger.FINE)) {
-                log.fine("Event posted on wrong app context : " + event);
-            }
+            throw new RuntimeException("Event posted on wrong app context : " + event);
         }
         PostEventQueue postEventQueue =
             (PostEventQueue)appContext.get(POST_EVENT_QUEUE_KEY);
@@ -880,10 +887,6 @@
             //with scale factors x1, x3/4, x2/3, xN, x1/N.
             Image im = i.next();
             if (im == null) {
-                if (log.isLoggable(PlatformLogger.FINER)) {
-                    log.finer("SunToolkit.getScaledIconImage: " +
-                              "Skipping the image passed into Java because it's null.");
-                }
                 continue;
             }
             if (im instanceof ToolkitImage) {
@@ -896,10 +899,6 @@
                 iw = im.getWidth(null);
                 ih = im.getHeight(null);
             } catch (Exception e){
-                if (log.isLoggable(PlatformLogger.FINER)) {
-                    log.finer("SunToolkit.getScaledIconImage: " +
-                              "Perhaps the image passed into Java is broken. Skipping this icon.");
-                }
                 continue;
             }
             if (iw > 0 && ih > 0) {
@@ -971,14 +970,6 @@
         try {
             int x = (width - bestWidth) / 2;
             int y = (height - bestHeight) / 2;
-            if (log.isLoggable(PlatformLogger.FINER)) {
-                log.finer("WWindowPeer.getScaledIconData() result : " +
-                        "w : " + width + " h : " + height +
-                        " iW : " + bestImage.getWidth(null) + " iH : " + bestImage.getHeight(null) +
-                        " sim : " + bestSimilarity + " sf : " + bestScaleFactor +
-                        " adjW : " + bestWidth + " adjH : " + bestHeight +
-                        " x : " + x + " y : " + y);
-            }
             g.drawImage(bestImage, x, y, bestWidth, bestHeight, null);
         } finally {
             g.dispose();
@@ -989,10 +980,6 @@
     public static DataBufferInt getScaledIconData(java.util.List<Image> imageList, int width, int height) {
         BufferedImage bimage = getScaledIconImage(imageList, width, height);
         if (bimage == null) {
-             if (log.isLoggable(PlatformLogger.FINER)) {
-                 log.finer("SunToolkit.getScaledIconData: " +
-                           "Perhaps the image passed into Java is broken. Skipping this icon.");
-             }
             return null;
         }
         Raster raster = bimage.getRaster();
--- a/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -398,7 +398,7 @@
      * "text".
      */
     public static boolean doesSubtypeSupportCharset(DataFlavor flavor) {
-        if (dtLog.isLoggable(PlatformLogger.FINE)) {
+        if (dtLog.isLoggable(PlatformLogger.Level.FINE)) {
             if (!"text".equals(flavor.getPrimaryType())) {
                 dtLog.fine("Assertion (\"text\".equals(flavor.getPrimaryType())) failed");
             }
--- a/jdk/src/share/classes/sun/awt/dnd/SunDropTargetContextPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/dnd/SunDropTargetContextPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -869,7 +869,7 @@
 
         void registerEvent(SunDropTargetEvent e) {
             handler.lock();
-            if (!eventSet.add(e) && dndLog.isLoggable(PlatformLogger.FINE)) {
+            if (!eventSet.add(e) && dndLog.isLoggable(PlatformLogger.Level.FINE)) {
                 dndLog.fine("Event is already registered: " + e);
             }
             handler.unlock();
--- a/jdk/src/share/classes/sun/awt/im/InputContext.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/im/InputContext.java	Wed Jul 05 19:00:49 2017 +0200
@@ -387,7 +387,7 @@
             }
             previousInputMethod = null;
 
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("Current client component " + currentClientComponent);
             }
             if (inputMethod instanceof InputMethodAdapter) {
@@ -887,7 +887,7 @@
 
     private void logCreationFailed(Throwable throwable) {
         PlatformLogger logger = PlatformLogger.getLogger("sun.awt.im");
-        if (logger.isLoggable(PlatformLogger.CONFIG)) {
+        if (logger.isLoggable(PlatformLogger.Level.CONFIG)) {
             String errorTextFormat = Toolkit.getProperty("AWT.InputMethodCreationFailed",
                                                          "Could not create {0}. Reason: {1}");
             Object[] args =
--- a/jdk/src/share/classes/sun/awt/image/ByteBandedRaster.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/image/ByteBandedRaster.java	Wed Jul 05 19:00:49 2017 +0200
@@ -159,7 +159,7 @@
             throw new RasterFormatException("ByteBandedRasters must have"+
                 "BandedSampleModels");
         }
-        verify(false);
+        verify();
     }
 
 
@@ -731,16 +731,37 @@
     }
 
     /**
-     * Verify that the layout parameters are consistent with
-     * the data.  If strictCheck
-     * is false, this method will check for ArrayIndexOutOfBounds conditions.  If
-     * strictCheck is true, this method will check for additional error
-     * conditions such as line wraparound (width of a line greater than
-     * the scanline stride).
-     * @return   String   Error string, if the layout is incompatible with
-     *                    the data.  Otherwise returns null.
+     * Verify that the layout parameters are consistent with the data.
+     * Verifies whether the data buffer has enough data for the raster,
+     * taking into account offsets, after ensuring all offsets are >=0.
+     * @throws RasterFormatException if a problem is detected.
      */
-    private void verify (boolean strictCheck) {
+    private void verify() {
+
+        /* Need to re-verify the dimensions since a sample model may be
+         * specified to the constructor
+         */
+        if (width <= 0 || height <= 0 ||
+            height > (Integer.MAX_VALUE / width))
+        {
+            throw new RasterFormatException("Invalid raster dimension");
+        }
+
+        if (scanlineStride < 0 ||
+            scanlineStride > (Integer.MAX_VALUE / height))
+        {
+            // integer overflow
+            throw new RasterFormatException("Incorrect scanline stride: "
+                    + scanlineStride);
+        }
+
+        for (int i = 0; i < data.length; i++) {
+            if (scanlineStride > data[i].length) {
+                throw new RasterFormatException("Incorrect scanline stride: "
+                    + scanlineStride);
+            }
+        }
+
         // Make sure data for Raster is in a legal range
         for (int i=0; i < dataOffsets.length; i++) {
             if (dataOffsets[i] < 0) {
@@ -750,32 +771,42 @@
             }
         }
 
-        int maxSize = 0;
-        int size;
+        int lastScanOffset = (height - 1) * scanlineStride;
+
+        if ((width - 1) > (Integer.MAX_VALUE - lastScanOffset)) {
+            throw new RasterFormatException("Invalid raster dimension");
+        }
+        int lastPixelOffset = lastScanOffset + (width-1);
+
+        int maxIndex = 0;
+        int index;
 
         for (int i=0; i < numDataElements; i++) {
-            size = (height-1)*scanlineStride + (width-1) + dataOffsets[i];
-            if (size > maxSize) {
-                maxSize = size;
+            if (dataOffsets[i] > (Integer.MAX_VALUE - lastPixelOffset)) {
+                throw new RasterFormatException("Invalid raster dimension");
+            }
+            index = lastPixelOffset + dataOffsets[i];
+            if (index > maxIndex) {
+                maxIndex = index;
             }
         }
 
         if (data.length == 1) {
-            if (data[0].length < maxSize*numDataElements) {
+            if (data[0].length <= maxIndex*numDataElements) {
                 throw new RasterFormatException("Data array too small "+
                                                 "(it is "+data[0].length+
-                                                " and should be "+
-                                                (maxSize*numDataElements)+
+                                                " and should be > "+
+                                                (maxIndex*numDataElements)+
                                                 " )");
             }
         }
         else {
             for (int i=0; i < numDataElements; i++) {
-                if (data[i].length < maxSize) {
+                if (data[i].length <= maxIndex) {
                     throw new RasterFormatException("Data array too small "+
                                                     "(it is "+data[i].length+
-                                                    " and should be "+
-                                                    maxSize+" )");
+                                                    " and should be > "+
+                                                    maxIndex+" )");
                 }
             }
         }
--- a/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java	Wed Jul 05 19:00:49 2017 +0200
@@ -885,12 +885,10 @@
             }
         }
 
-        int maxSize = 0;
-        int size;
-
         // we can be sure that width and height are greater than 0
         if (scanlineStride < 0 ||
-            scanlineStride > (Integer.MAX_VALUE / height))
+            scanlineStride > (Integer.MAX_VALUE / height) ||
+            scanlineStride > data.length)
         {
             // integer overflow
             throw new RasterFormatException("Incorrect scanline stride: "
@@ -899,7 +897,8 @@
         int lastScanOffset = (height - 1) * scanlineStride;
 
         if (pixelStride < 0 ||
-            pixelStride > (Integer.MAX_VALUE / width))
+            pixelStride > (Integer.MAX_VALUE / width) ||
+            pixelStride > data.length)
         {
             // integer overflow
             throw new RasterFormatException("Incorrect pixel stride: "
@@ -913,6 +912,8 @@
         }
         lastPixelOffset += lastScanOffset;
 
+        int index;
+        int maxIndex = 0;
         for (int i = 0; i < numDataElements; i++) {
             if (dataOffsets[i] > (Integer.MAX_VALUE - lastPixelOffset)) {
                 throw new RasterFormatException("Incorrect band offset: "
@@ -920,15 +921,15 @@
 
             }
 
-            size = lastPixelOffset + dataOffsets[i];
+            index = lastPixelOffset + dataOffsets[i];
 
-            if (size > maxSize) {
-                maxSize = size;
+            if (index > maxIndex) {
+                maxIndex = index;
             }
         }
-        if (data.length < maxSize) {
-            throw new RasterFormatException("Data array too small (should be "
-                    + maxSize + " )");
+        if (data.length <= maxIndex) {
+            throw new RasterFormatException("Data array too small (should be > "
+                    + maxIndex + " )");
         }
     }
 
--- a/jdk/src/share/classes/sun/awt/image/BytePackedRaster.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/image/BytePackedRaster.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1387,7 +1387,8 @@
         }
 
         if (scanlineStride < 0 ||
-            scanlineStride > (Integer.MAX_VALUE / height))
+            scanlineStride > (Integer.MAX_VALUE / height) ||
+            scanlineStride > data.length)
         {
             throw new RasterFormatException("Invalid scanline stride");
         }
--- a/jdk/src/share/classes/sun/awt/image/IntegerComponentRaster.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/image/IntegerComponentRaster.java	Wed Jul 05 19:00:49 2017 +0200
@@ -654,12 +654,10 @@
                                             ") must be >= 0");
         }
 
-        int maxSize = 0;
-        int size;
-
         // we can be sure that width and height are greater than 0
         if (scanlineStride < 0 ||
-            scanlineStride > (Integer.MAX_VALUE / height))
+            scanlineStride > (Integer.MAX_VALUE / height) ||
+            scanlineStride > data.length)
         {
             // integer overflow
             throw new RasterFormatException("Incorrect scanline stride: "
@@ -668,7 +666,8 @@
         int lastScanOffset = (height - 1) * scanlineStride;
 
         if (pixelStride < 0 ||
-            pixelStride > (Integer.MAX_VALUE / width))
+            pixelStride > (Integer.MAX_VALUE / width) ||
+            pixelStride > data.length)
         {
             // integer overflow
             throw new RasterFormatException("Incorrect pixel stride: "
@@ -682,21 +681,23 @@
         }
         lastPixelOffset += lastScanOffset;
 
+        int index;
+        int maxIndex = 0;
         for (int i = 0; i < numDataElements; i++) {
             if (dataOffsets[i] > (Integer.MAX_VALUE - lastPixelOffset)) {
                 throw new RasterFormatException("Incorrect band offset: "
                             + dataOffsets[i]);
             }
 
-            size = lastPixelOffset + dataOffsets[i];
+            index = lastPixelOffset + dataOffsets[i];
 
-            if (size > maxSize) {
-                maxSize = size;
+            if (index > maxIndex) {
+                maxIndex = index;
             }
         }
-        if (data.length < maxSize) {
-            throw new RasterFormatException("Data array too small (should be "
-                    + maxSize + " )");
+        if (data.length <= maxIndex) {
+            throw new RasterFormatException("Data array too small (should be > "
+                    + maxIndex + " )");
         }
     }
 
--- a/jdk/src/share/classes/sun/awt/image/ShortBandedRaster.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/image/ShortBandedRaster.java	Wed Jul 05 19:00:49 2017 +0200
@@ -156,7 +156,7 @@
             throw new RasterFormatException("ShortBandedRasters must have "+
                 "BandedSampleModels");
         }
-        verify(false);
+        verify();
     }
 
     /**
@@ -730,16 +730,37 @@
     }
 
     /**
-     * Verify that the layout parameters are consistent with
-     * the data.  If strictCheck
-     * is false, this method will check for ArrayIndexOutOfBounds conditions.  If
-     * strictCheck is true, this method will check for additional error
-     * conditions such as line wraparound (width of a line greater than
-     * the scanline stride).
-     * @return   String   Error string, if the layout is incompatible with
-     *                    the data.  Otherwise returns null.
+     * Verify that the layout parameters are consistent with the data.
+     * Verifies whether the data buffer has enough data for the raster,
+     * taking into account offsets, after ensuring all offsets are >=0.
+     * @throws RasterFormatException if a problem is detected.
      */
-    private void verify (boolean strictCheck) {
+    private void verify() {
+
+        /* Need to re-verify the dimensions since a sample model may be
+         * specified to the constructor
+         */
+        if (width <= 0 || height <= 0 ||
+            height > (Integer.MAX_VALUE / width))
+        {
+            throw new RasterFormatException("Invalid raster dimension");
+        }
+
+        if (scanlineStride < 0 ||
+            scanlineStride > (Integer.MAX_VALUE / height))
+        {
+            // integer overflow
+            throw new RasterFormatException("Incorrect scanline stride: "
+                    + scanlineStride);
+        }
+
+        for (int i = 0; i < data.length; i++) {
+            if (scanlineStride > data[i].length) {
+                throw new RasterFormatException("Incorrect scanline stride: "
+                    + scanlineStride);
+            }
+        }
+
         // Make sure data for Raster is in a legal range
         for (int i=0; i < dataOffsets.length; i++) {
             if (dataOffsets[i] < 0) {
@@ -749,19 +770,28 @@
             }
         }
 
-        int maxSize = 0;
-        int size;
+        int lastScanOffset = (height - 1) * scanlineStride;
+        if ((width - 1) > (Integer.MAX_VALUE - lastScanOffset)) {
+            throw new RasterFormatException("Invalid raster dimension");
+        }
+        int lastPixelOffset = lastScanOffset + (width - 1);
+
+        int maxIndex = 0;
+        int index;
 
         for (int i=0; i < numDataElements; i++) {
-            size = (height-1)*scanlineStride + (width-1) + dataOffsets[i];
-            if (size > maxSize) {
-                maxSize = size;
+            if (dataOffsets[i] > (Integer.MAX_VALUE - lastPixelOffset)) {
+                throw new RasterFormatException("Invalid raster dimension");
+            }
+            index = lastPixelOffset + dataOffsets[i];
+            if (index > maxIndex) {
+                maxIndex = index;
             }
         }
         for (int i=0; i < numDataElements; i++) {
-            if (data[i].length < maxSize) {
-                throw new RasterFormatException("Data array too small (should be "+
-                                                maxSize+" )");
+            if (data[i].length <= maxIndex) {
+                throw new RasterFormatException("Data array too small " +
+                      "(should be > "+ maxIndex+" )");
             }
         }
     }
--- a/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java	Wed Jul 05 19:00:49 2017 +0200
@@ -819,12 +819,10 @@
             }
         }
 
-        int maxSize = 0;
-        int size;
-
         // we can be sure that width and height are greater than 0
         if (scanlineStride < 0 ||
-            scanlineStride > (Integer.MAX_VALUE / height))
+            scanlineStride > (Integer.MAX_VALUE / height) ||
+            scanlineStride > data.length)
         {
             // integer overflow
             throw new RasterFormatException("Incorrect scanline stride: "
@@ -833,7 +831,8 @@
         int lastScanOffset = (height - 1) * scanlineStride;
 
         if (pixelStride < 0 ||
-            pixelStride > (Integer.MAX_VALUE / width))
+            pixelStride > (Integer.MAX_VALUE / width) ||
+            pixelStride > data.length)
         {
             // integer overflow
             throw new RasterFormatException("Incorrect pixel stride: "
@@ -847,21 +846,23 @@
         }
         lastPixelOffset += lastScanOffset;
 
+        int index;
+        int maxIndex = 0;
         for (int i = 0; i < numDataElements; i++) {
             if (dataOffsets[i] > (Integer.MAX_VALUE - lastPixelOffset)) {
                 throw new RasterFormatException("Incorrect band offset: "
                             + dataOffsets[i]);
             }
 
-            size = lastPixelOffset + dataOffsets[i];
+            index = lastPixelOffset + dataOffsets[i];
 
-            if (size > maxSize) {
-                maxSize = size;
+            if (index > maxIndex) {
+                maxIndex = index;
             }
         }
-        if (data.length < maxSize) {
-            throw new RasterFormatException("Data array too small (should be "
-                    + maxSize + " )");
+        if (data.length <= maxIndex) {
+            throw new RasterFormatException("Data array too small (should be > "
+                    + maxIndex + " )");
         }
     }
 
Binary file jdk/src/share/classes/sun/awt/resources/security-icon-bw16.png has changed
Binary file jdk/src/share/classes/sun/awt/resources/security-icon-bw24.png has changed
Binary file jdk/src/share/classes/sun/awt/resources/security-icon-bw32.png has changed
Binary file jdk/src/share/classes/sun/awt/resources/security-icon-bw48.png has changed
Binary file jdk/src/share/classes/sun/awt/resources/security-icon-interim16.png has changed
Binary file jdk/src/share/classes/sun/awt/resources/security-icon-interim24.png has changed
Binary file jdk/src/share/classes/sun/awt/resources/security-icon-interim32.png has changed
Binary file jdk/src/share/classes/sun/awt/resources/security-icon-interim48.png has changed
Binary file jdk/src/share/classes/sun/awt/resources/security-icon-yellow16.png has changed
Binary file jdk/src/share/classes/sun/awt/resources/security-icon-yellow24.png has changed
Binary file jdk/src/share/classes/sun/awt/resources/security-icon-yellow32.png has changed
Binary file jdk/src/share/classes/sun/awt/resources/security-icon-yellow48.png has changed
--- a/jdk/src/share/classes/sun/font/CreatedFontTracker.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/font/CreatedFontTracker.java	Wed Jul 05 19:00:49 2017 +0200
@@ -25,13 +25,22 @@
 
 package sun.font;
 
+import java.io.File;
+import java.io.OutputStream;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+
+import sun.awt.AppContext;
+
 public class CreatedFontTracker {
 
     public static final int MAX_FILE_SIZE = 32 * 1024 * 1024;
     public static final int MAX_TOTAL_BYTES = 10 * MAX_FILE_SIZE;
 
-    static int numBytes;
     static CreatedFontTracker tracker;
+    int numBytes;
 
     public static synchronized CreatedFontTracker getTracker() {
         if (tracker == null) {
@@ -40,6 +49,10 @@
         return tracker;
     }
 
+    private CreatedFontTracker() {
+        numBytes = 0;
+    }
+
     public synchronized int getNumBytes() {
         return numBytes;
     }
@@ -51,4 +64,108 @@
     public synchronized void subBytes(int sz) {
         numBytes -= sz;
     }
+
+    /**
+     * Returns an AppContext-specific counting semaphore.
+     */
+    private static synchronized Semaphore getCS() {
+        final AppContext appContext = AppContext.getAppContext();
+        Semaphore cs = (Semaphore) appContext.get(CreatedFontTracker.class);
+        if (cs == null) {
+            // Make a semaphore with 5 permits that obeys the first-in first-out
+            // granting of permits.
+            cs = new Semaphore(5, true);
+            appContext.put(CreatedFontTracker.class, cs);
+        }
+        return cs;
+    }
+
+    public boolean acquirePermit() throws InterruptedException {
+        // This does a timed-out wait.
+        return getCS().tryAcquire(120, TimeUnit.SECONDS);
+    }
+
+    public void releasePermit() {
+        getCS().release();
+    }
+
+    public void add(File file) {
+        TempFileDeletionHook.add(file);
+    }
+
+    public void set(File file, OutputStream os) {
+        TempFileDeletionHook.set(file, os);
+    }
+
+    public void remove(File file) {
+        TempFileDeletionHook.remove(file);
+    }
+
+    /**
+     * Helper class for cleanup of temp files created while processing fonts.
+     * Note that this only applies to createFont() from an InputStream object.
+     */
+    private static class TempFileDeletionHook {
+        private static HashMap<File, OutputStream> files = new HashMap<>();
+
+        private static Thread t = null;
+        static void init() {
+            if (t == null) {
+                // Add a shutdown hook to remove the temp file.
+                java.security.AccessController.doPrivileged(
+                   new java.security.PrivilegedAction() {
+                      public Object run() {
+                          /* The thread must be a member of a thread group
+                           * which will not get GCed before VM exit.
+                           * Make its parent the top-level thread group.
+                           */
+                          ThreadGroup tg =
+                              Thread.currentThread().getThreadGroup();
+                          for (ThreadGroup tgn = tg;
+                               tgn != null;
+                               tg = tgn, tgn = tg.getParent());
+                          t = new Thread(tg, new Runnable() {
+                              public void run() {
+                                  runHooks();
+                              }
+                          });
+                          t.setContextClassLoader(null);
+                          Runtime.getRuntime().addShutdownHook(t);
+                          return null;
+                      }
+                   });
+            }
+        }
+
+        private TempFileDeletionHook() {}
+
+        static synchronized void add(File file) {
+            init();
+            files.put(file, null);
+        }
+
+        static synchronized void set(File file, OutputStream os) {
+            files.put(file, os);
+        }
+
+        static synchronized void remove(File file) {
+            files.remove(file);
+        }
+
+        static synchronized void runHooks() {
+            if (files.isEmpty()) {
+                return;
+            }
+
+            for (Map.Entry<File, OutputStream> entry : files.entrySet()) {
+                // Close the associated output stream, and then delete the file.
+                try {
+                    if (entry.getValue() != null) {
+                        entry.getValue().close();
+                    }
+                } catch (Exception e) {}
+                entry.getKey().delete();
+            }
+        }
+    }
 }
--- a/jdk/src/share/classes/sun/font/ExtendedTextSourceLabel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/font/ExtendedTextSourceLabel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -247,6 +247,10 @@
     float aw = 0f;
     float ah = cm.ascent + cm.descent;
 
+    if (charinfo == null || charinfo.length == 0) {
+        return new Rectangle2D.Float(al, at, aw, ah);
+    }
+
     boolean lineIsLTR = (source.getLayoutFlags() & 0x8) == 0;
     int rn = info.length - numvals;
     if (lineIsLTR) {
@@ -350,23 +354,44 @@
 
   public float getCharX(int index) {
     validate(index);
-    return getCharinfo()[l2v(index) * numvals + posx];
+    float[] charinfo = getCharinfo();
+    int idx = l2v(index) * numvals + posx;
+    if (charinfo == null || idx >= charinfo.length) {
+        return 0f;
+    } else {
+        return charinfo[idx];
+    }
   }
 
   public float getCharY(int index) {
     validate(index);
-    return getCharinfo()[l2v(index) * numvals + posy];
+    float[] charinfo = getCharinfo();
+    int idx = l2v(index) * numvals + posy;
+    if (charinfo == null || idx >= charinfo.length) {
+        return 0f;
+    } else {
+        return charinfo[idx];
+    }
   }
 
   public float getCharAdvance(int index) {
     validate(index);
-    return getCharinfo()[l2v(index) * numvals + advx];
+    float[] charinfo = getCharinfo();
+    int idx = l2v(index) * numvals + advx;
+    if (charinfo == null || idx >= charinfo.length) {
+        return 0f;
+    } else {
+        return charinfo[idx];
+    }
   }
 
   public Rectangle2D handleGetCharVisualBounds(int index) {
     validate(index);
     float[] charinfo = getCharinfo();
     index = l2v(index) * numvals;
+    if (charinfo == null || (index+vish) >= charinfo.length) {
+        return new Rectangle2D.Float();
+    }
     return new Rectangle2D.Float(
                                  charinfo[index + visx],
                                  charinfo[index + visy],
@@ -456,7 +481,11 @@
     int length = source.getLength();
     --start;
     while (width >= 0 && ++start < length) {
-      float adv = charinfo[l2v(start) * numvals + advx];
+      int cidx = l2v(start) * numvals + advx;
+      if (cidx >= charinfo.length) {
+          break; // layout bailed for some reason
+      }
+      float adv = charinfo[cidx];
       width -= adv;
     }
 
@@ -469,7 +498,11 @@
     float[] charinfo = getCharinfo();
     --start;
     while (++start < limit) {
-      a += charinfo[l2v(start) * numvals + advx];
+      int cidx = l2v(start) * numvals + advx;
+      if (cidx >= charinfo.length) {
+          break; // layout bailed for some reason
+      }
+      a += charinfo[cidx];
     }
 
     return a;
@@ -501,7 +534,13 @@
       //    }
       //}
 
-      return getCharinfo()[v * numvals + advx] != 0;
+      int idx = v * numvals + advx;
+      float[] charinfo = getCharinfo();
+      if (charinfo == null || idx >= charinfo.length) {
+          return false;
+      } else {
+          return charinfo[idx] != 0;
+      }
   }
 
   private final float[] getCharinfo() {
@@ -593,6 +632,9 @@
     */
 
     int numGlyphs = gv.getNumGlyphs();
+    if (numGlyphs == 0) {
+        return glyphinfo;
+    }
     int[] indices = gv.getGlyphCharIndices(0, numGlyphs, null);
 
     boolean DEBUG = false;
--- a/jdk/src/share/classes/sun/font/GlyphLayout.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/font/GlyphLayout.java	Wed Jul 05 19:00:49 2017 +0200
@@ -464,7 +464,12 @@
                     break;
                 }
                 catch (IndexOutOfBoundsException e) {
-                    _gvdata.grow();
+                    if (_gvdata._count >=0) {
+                        _gvdata.grow();
+                    }
+                }
+                if (_gvdata._count < 0) {
+                    break;
                 }
             }
         }
@@ -473,7 +478,19 @@
         //            _gvdata.adjustPositions(txinfo.invdtx);
         //        }
 
-        StandardGlyphVector gv = _gvdata.createGlyphVector(font, frc, result);
+        // If layout fails (negative glyph count) create an un-laid out GV instead.
+        // ie default positions. This will be a lot better than the alternative of
+        // a complete blank layout.
+        StandardGlyphVector gv;
+        if (_gvdata._count < 0) {
+            gv = new StandardGlyphVector(font, text, offset, count, frc);
+            if (FontUtilities.debugFonts()) {
+               FontUtilities.getLogger().warning("OpenType layout failed on font: " +
+                                                 font);
+            }
+        } else {
+            gv = _gvdata.createGlyphVector(font, frc, result);
+        }
         //        System.err.println("Layout returns: " + gv);
         return gv;
     }
--- a/jdk/src/share/classes/sun/font/SunFontManager.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/font/SunFontManager.java	Wed Jul 05 19:00:49 2017 +0200
@@ -3236,7 +3236,7 @@
             registeredFontFiles.add(fullName);
 
             if (FontUtilities.debugFonts()
-                && FontUtilities.getLogger().isLoggable(PlatformLogger.INFO)) {
+                && FontUtilities.getLogger().isLoggable(PlatformLogger.Level.INFO)) {
                 String message = "Registering font " + fullName;
                 String[] natNames = getNativeNames(fullName, null);
                 if (natNames == null) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/java2d/cmm/ProfileDataVerifier.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.java2d.cmm;
+
+public class ProfileDataVerifier {
+    /**
+     * Throws an IllegalArgumentException if the data does not correspond
+     * to a valid ICC Profile.
+     *
+     * @param data the specified profile data.
+     */
+    public static void verify(byte[] data) {
+        if (data == null) {
+            throw new IllegalArgumentException("Invalid ICC Profile Data");
+        }
+
+        if (data.length < TOC_OFFSET) {
+            // not enough data for profile header
+            throw new IllegalArgumentException("Invalid ICC Profile Data");
+        }
+
+        // check profile size
+        final int size = readInt32(data, 0);
+        final int tagCount = readInt32(data, HEADER_SIZE);
+
+        if (tagCount < 0 || tagCount > MAX_TAG_COUNT) {
+            throw new IllegalArgumentException("Invalid ICC Profile Data");
+        }
+
+        if (size < (TOC_OFFSET + (tagCount * TOC_RECORD_SIZE)) ||
+            size > data.length)
+        {
+            throw new IllegalArgumentException("Invalid ICC Profile Data");
+        }
+
+        final int sig = readInt32(data, 36);
+
+        if (PROFILE_FILE_SIGNATURE != sig) {
+            throw new IllegalArgumentException("Invalid ICC Profile Data");
+        }
+
+        // verify table of content
+        for (int i = 0; i < tagCount; i++) {
+            final int tag_offset = getTagOffset(i, data);
+            final int tag_size = getTagSize(i, data);
+
+            if (tag_offset < TOC_OFFSET || tag_offset > size) {
+                throw new IllegalArgumentException("Invalid ICC Profile Data");
+            }
+
+            if (tag_size < 0 ||
+                tag_size > (Integer.MAX_VALUE - tag_offset) ||
+                tag_size + tag_offset > size)
+            {
+                throw new IllegalArgumentException("Invalid ICC Profile Data");
+            }
+        }
+    }
+
+    private static int getTagOffset(int idx, byte[] data) {
+        final int pos = TOC_OFFSET + idx * TOC_RECORD_SIZE + 4;
+        return readInt32(data, pos);
+    }
+
+    private static int getTagSize(int idx, byte[] data) {
+        final int pos = TOC_OFFSET + idx * TOC_RECORD_SIZE + 8;
+        return readInt32(data, pos);
+    }
+
+    private static int readInt32(byte[] data, int off) {
+        int res = 0;
+        for (int i = 0; i < 4; i++) {
+            res = res << 8;
+
+            res |= (0xff & data[off++]);
+        }
+        return res;
+    }
+
+    /**
+     * Lcms limit for the number of tags: 100
+     * Kcms limit for the number of tags: N/A
+     */
+    private static final int MAX_TAG_COUNT = 100;
+
+    private static final int HEADER_SIZE = 128;
+    private static final int TOC_OFFSET = HEADER_SIZE + 4;
+    private static final int TOC_RECORD_SIZE = 12;
+
+    private static final int PROFILE_FILE_SIGNATURE = 0x61637370;
+}
--- a/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMSImageLayout.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMSImageLayout.java	Wed Jul 05 19:00:49 2017 +0200
@@ -76,6 +76,7 @@
     int width;
     int height;
     int nextRowOffset;
+    private int nextPixelOffset;
     int offset;
 
     /* This flag indicates whether the image can be processed
@@ -93,6 +94,7 @@
         this.pixelType = pixelType;
         width = np;
         height = 1;
+        nextPixelOffset = pixelSize;
         nextRowOffset = safeMult(pixelSize, np);
         offset = 0;
     }
@@ -104,6 +106,7 @@
         this.pixelType = pixelType;
         this.width = width;
         this.height = height;
+        nextPixelOffset = pixelSize;
         nextRowOffset = safeMult(pixelSize, width);
         offset = 0;
     }
@@ -221,6 +224,7 @@
                     IntegerComponentRaster intRaster = (IntegerComponentRaster)
                             image.getRaster();
                     l.nextRowOffset = safeMult(4, intRaster.getScanlineStride());
+                    l.nextPixelOffset = safeMult(4, intRaster.getPixelStride());
                     l.offset = safeMult(4, intRaster.getDataOffset(0));
                     l.dataArray = intRaster.getDataStorage();
                     l.dataArrayLength = 4 * intRaster.getDataStorage().length;
@@ -238,6 +242,8 @@
                     ByteComponentRaster byteRaster = (ByteComponentRaster)
                             image.getRaster();
                     l.nextRowOffset = byteRaster.getScanlineStride();
+                    l.nextPixelOffset = byteRaster.getPixelStride();
+
                     int firstBand = image.getSampleModel().getNumBands() - 1;
                     l.offset = byteRaster.getDataOffset(firstBand);
                     l.dataArray = byteRaster.getDataStorage();
@@ -254,6 +260,8 @@
                     ByteComponentRaster byteRaster = (ByteComponentRaster)
                             image.getRaster();
                     l.nextRowOffset = byteRaster.getScanlineStride();
+                    l.nextPixelOffset = byteRaster.getPixelStride();
+
                     l.dataArrayLength = byteRaster.getDataStorage().length;
                     l.offset = byteRaster.getDataOffset(0);
                     l.dataArray = byteRaster.getDataStorage();
@@ -270,6 +278,8 @@
                     ShortComponentRaster shortRaster = (ShortComponentRaster)
                             image.getRaster();
                     l.nextRowOffset = safeMult(2, shortRaster.getScanlineStride());
+                    l.nextPixelOffset = safeMult(2, shortRaster.getPixelStride());
+
                     l.offset = safeMult(2, shortRaster.getDataOffset(0));
                     l.dataArray = shortRaster.getDataStorage();
                     l.dataArrayLength = 2 * shortRaster.getDataStorage().length;
@@ -331,9 +341,15 @@
             throw new ImageLayoutException("Invalid image layout");
         }
 
-        int lastPixelOffset = safeMult(nextRowOffset, (height - 1));
+        if (nextPixelOffset != getBytesPerPixel(pixelType)) {
+            throw new ImageLayoutException("Invalid image layout");
+        }
 
-        lastPixelOffset = safeAdd(lastPixelOffset, (width - 1));
+        int lastScanOffset = safeMult(nextRowOffset, (height - 1));
+
+        int lastPixelOffset = safeMult(nextPixelOffset, (width -1 ));
+
+        lastPixelOffset = safeAdd(lastPixelOffset, lastScanOffset);
 
         int off = safeAdd(offset, lastPixelOffset);
 
@@ -392,6 +408,8 @@
             }
 
             l.nextRowOffset = br.getScanlineStride();
+            l.nextPixelOffset = br.getPixelStride();
+
             l.offset = br.getDataOffset(firstBand);
             l.dataArray = br.getDataStorage();
             l.dataType = DT_BYTE;
@@ -406,4 +424,25 @@
         }
         return null;
     }
+
+    /**
+     * Derives number of bytes per pixel from the pixel format.
+     * Following bit fields are used here:
+     *  [0..2] - bytes per sample
+     *  [3..6] - number of color samples per pixel
+     *  [7..9] - number of non-color samples per pixel
+     *
+     * A complete description of the pixel format can be found
+     * here: lcms2.h, lines 651 - 667.
+     *
+     * @param pixelType pixel format in lcms2 notation.
+     * @return number of bytes per pixel for given pixel format.
+     */
+    private static int getBytesPerPixel(int pixelType) {
+        int bytesPerSample = (0x7 & pixelType);
+        int colorSamplesPerPixel = 0xF & (pixelType >> 3);
+        int extraSamplesPerPixel = 0x7 & (pixelType >> 7);
+
+        return bytesPerSample * (colorSamplesPerPixel + extraSamplesPerPixel);
+    }
 }
--- a/jdk/src/share/classes/sun/launcher/resources/launcher_de.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/launcher/resources/launcher_de.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -37,7 +37,7 @@
 java.launcher.opt.footer     =\    -cp <Klassensuchpfad von Verzeichnissen und ZIP-/JAR-Dateien>\n    -classpath <Klassensuchpfad von Verzeichnissen und ZIP-/JAR-Dateien>\n                  Eine durch {0} getrennte Liste mit Verzeichnissen, JAR-Archiven\n                  und ZIP-Archiven zur Suche nach Klassendateien.\n    -D<name>=<value>\n                  Legt eine Systemeigenschaft fest\n    -verbose[:class|gc|jni]\n                  Aktiviert die Verbose-Ausgabe\n    -version      Druckt Produktversion und beendet das Programm\n    -version:<value>\n                  Erfordert die angegebene Version zur Ausf\u00FChrung\n    -showversion  Druckt Produktversion und f\u00E4hrt fort\n    -jre-restrict-search | -no-jre-restrict-search\n                  Bezieht private JREs des Benutzers in Versionssuche ein bzw. schlie\u00DFt sie aus\n    -? -help      Druckt diese Hilfemeldung\n    -X            Druckt Hilfe zu Nicht-Standardoptionen\n    -ea[:<packagename>...|:<classname>]\n    -enableassertions[:<packagename>...|:<classname>]\n                  Aktiviert Assertionen mit angegebener Granularit\u00E4t\n    -da[:<packagename>...|:<classname>]\n    -disableassertions[:<packagename>...|:<classname>]\n                  Deaktiviert Assertionen mit angegebener Granularit\u00E4t\n    -esa | -enablesystemassertions\n                  Aktiviert Systemassertionen\n    -dsa | -disablesystemassertions\n                  Deaktiviert Systemassertionen\n    -agentlib:<libname>[=<options>]\n                  L\u00E4dt native Agent Library <libname>, z.B. -agentlib:hprof\n                  siehe auch -agentlib:jdwp=help und -agentlib:hprof=help\n    -agentpath:<pathname>[=<options>]\n                  L\u00E4dt native Agent Library nach vollem Pfadnamen\n    -javaagent:<jarpath>[=<options>]\n                  L\u00E4dt Java-Programmiersprachen-Agent, siehe java.lang.instrument\n    -splash:<imagepath>\n                  Zeigt Startbildschirm mit angegebenem Bild\nWeitere Einzelheiten finden Sie unter http://www.oracle.com/technetwork/java/javase/documentation/index.html
 
 # Translators please note do not translate the options themselves
-java.launcher.X.usage=\    -Xmixed           Ausf\u00FChrung im gemischten Modus (Standard)\n    -Xint             Nur Ausf\u00FChrung im interpretierten Modus\n    -Xbootclasspath:<Verzeichnisse und ZIP-/JAR-Dateien durch {0} getrennt>\n                      Legt Suchpfad f\u00FCr Bootstrap-Klassen und Ressourcen fest\n    -Xbootclasspath/a:<Verzeichnisse und ZIP-/JAR-Dateien durch {0} getrennt>\n                      H\u00E4ngt an das Ende des Bootstrap Classpath an\n    -Xbootclasspath/p:<Verzeichnisse und ZIP-/JAR-Dateien durch {0} getrennt>\n                      Stellt Bootstrap Classpath voran\n    -Xdiag            Zeigt zus\u00E4tzliche Diagnosemeldungen an\n    -Xnoclassgc       Deaktiviert Klassen-Garbage Collection\n    -Xincgc           Aktiviert inkrementelle Garbage Collection\n    -Xloggc:<file>    Loggt GC-Status in einer Datei mit Zeitstempeln\n    -Xbatch           Deaktiviert Hintergrundkompilierung\n    -Xms<size>        Legt anf\u00E4ngliche Java Heap-Gr\u00F6\u00DFe fest\n    -Xmx<size>        Legt maximale Java Heap-Gr\u00F6\u00DFe fest\n    -Xss<size>        Legt Java-Thread-Stack-Gr\u00F6\u00DFe fest\n    -Xprof            Gibt CPU-Profiling-Daten aus\n    -Xfuture          Aktiviert strengste Pr\u00FCfungen, antizipiert zuk\u00FCnftigen Standardwert\n    -Xrs              Reduziert Verwendung von BS-Signalen durch Java/VM (siehe Dokumentation)\n    -Xcheck:jni       F\u00FChrt zus\u00E4tzliche Pr\u00FCfungen f\u00FCr JNI-Funktionen durch\n    -Xshare:off       Kein Versuch, gemeinsame Klassendaten zu verwenden\n    -Xshare:auto      Verwendet gemeinsame Klassendaten, wenn m\u00F6glich (Standard)\n    -Xshare:on        Erfordert die Verwendung gemeinsamer Klassendaten, sonst verl\u00E4uft der Vorgang nicht erfolgreich.\n    -XshowSettings    Zeigt alle Einstellungen und f\u00E4hrt fort\n    -XshowSettings:all\n                      Zeigt alle Einstellungen und f\u00E4hrt fort\n    -XshowSettings:vm Zeigt alle VM-bezogenen Einstellungen und f\u00E4hrt fort\n    -XshowSettings:properties\n                      Zeigt alle Eigenschaftseinstellungen und f\u00E4hrt fort\n    -XshowSettings:locale\n                      Zeigt alle gebietsschemabezogenen Einstellungen und f\u00E4hrt fort\n\nDie -X-Optionen sind keine Standardoptionen und k\u00F6nnen ohne Vorank\u00FCndigung ge\u00E4ndert werden.\n
+java.launcher.X.usage=\    -Xmixed           Ausf\u00FChrung im gemischten Modus (Standard)\n    -Xint             Nur Ausf\u00FChrung im interpretierten Modus\n    -Xbootclasspath:<Verzeichnisse und ZIP-/JAR-Dateien durch {0} getrennt>\n                      Legt Suchpfad f\u00FCr Bootstrap-Klassen und Ressourcen fest\n    -Xbootclasspath/a:<Verzeichnisse und ZIP-/JAR-Dateien durch {0} getrennt>\n                      H\u00E4ngt an das Ende des Bootstrap Classpath an\n    -Xbootclasspath/p:<Verzeichnisse und ZIP-/JAR-Dateien durch {0} getrennt>\n                      Stellt Bootstrap Classpath voran\n    -Xdiag            Zeigt zus\u00E4tzliche Diagnosemeldungen an\n    -Xnoclassgc       Deaktiviert Klassen-Garbage Collection\n    -Xincgc           Aktiviert inkrementelle Garbage Collection\n    -Xloggc:<file>    Loggt GC-Status in einer Datei mit Zeitstempeln\n    -Xbatch           Deaktiviert Hintergrundkompilierung\n    -Xms<size>        Legt anf\u00E4ngliche Java Heap-Gr\u00F6\u00DFe fest\n    -Xmx<size>        Legt maximale Java Heap-Gr\u00F6\u00DFe fest\n    -Xss<size>        Legt Java-Thread-Stackgr\u00F6\u00DFe fest\n    -Xprof            Gibt CPU-Profiling-Daten aus\n    -Xfuture          Aktiviert strengste Pr\u00FCfungen, antizipiert zuk\u00FCnftigen Standardwert\n    -Xrs              Reduziert Verwendung von BS-Signalen durch Java/VM (siehe Dokumentation)\n    -Xcheck:jni       F\u00FChrt zus\u00E4tzliche Pr\u00FCfungen f\u00FCr JNI-Funktionen durch\n    -Xshare:off       Kein Versuch, gemeinsame Klassendaten zu verwenden\n    -Xshare:auto      Verwendet gemeinsame Klassendaten, wenn m\u00F6glich (Standard)\n    -Xshare:on        Erfordert die Verwendung gemeinsamer Klassendaten, sonst verl\u00E4uft der Vorgang nicht erfolgreich.\n    -XshowSettings    Zeigt alle Einstellungen und f\u00E4hrt fort\n    -XshowSettings:all\n                      Zeigt alle Einstellungen und f\u00E4hrt fort\n    -XshowSettings:vm Zeigt alle VM-bezogenen Einstellungen und f\u00E4hrt fort\n    -XshowSettings:properties\n                      Zeigt alle Eigenschaftseinstellungen und f\u00E4hrt fort\n    -XshowSettings:locale\n                      Zeigt alle gebietsschemabezogenen Einstellungen und f\u00E4hrt fort\n\nDie -X-Optionen sind keine Standardoptionen und k\u00F6nnen ohne Vorank\u00FCndigung ge\u00E4ndert werden.\n
 
 # Translators please note do not translate the options themselves
 java.launcher.X.macosx.usage=\nDie folgenden Optionen sind f\u00FCr Mac OS X spezifisch:\n    -XstartOnFirstThread\n                      f\u00FChrt die main()-Methode f\u00FCr den ersten (AppKit) Thread aus\n    -Xdock:name=<Anwendungsname>"\n                      \u00DCberschreibt den in der Uhr angezeigten Standardanwendungsnamen\n    -Xdock:icon=<Pfad zu Symboldatei>\n                      \u00DCberschreibt das in der Uhr angezeigte Standardsymbol\n\n
@@ -50,5 +50,7 @@
 java.launcher.jar.error1=Fehler: Beim Versuch, Datei {0} zu \u00F6ffnen, ist ein unerwarteter Fehler aufgetreten
 java.launcher.jar.error2=Manifest in {0} nicht gefunden
 java.launcher.jar.error3=kein Hauptmanifestattribut, in {0}
+java.launcher.jar.error4=kein Profilmanifestattribut in {0}
+java.launcher.jar.error5=Das f\u00FCr {1} erforderliche Profil {0} wird von dieser Runtime-Anwendung nicht unterst\u00FCtzt
 java.launcher.init.error=Initialisierungsfehler
 java.launcher.javafx.error1=Fehler: Die JavaFX-Methode launchApplication hat die falsche Signatur, sie\nmuss als statisch deklariert werden und einen Wert vom Typ VOID zur\u00FCckgeben
--- a/jdk/src/share/classes/sun/launcher/resources/launcher_es.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/launcher/resources/launcher_es.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -34,10 +34,10 @@
 java.launcher.ergo.message2  =\                  porque la ejecuci\u00F3n se est\u00E1 llevando a cabo en una m\u00E1quina de clase de servidor.\n
 
 # Translators please note do not translate the options themselves
-java.launcher.opt.footer     =\    -cp <ruta de acceso de b\u00FAsqueda de clases de los directorios y los archivos zip/jar>\n\\    -classpath <ruta de acceso de b\u00FAsqueda de clases de los directorios y los archivos zip/jar>\n\\                  Lista separada por {0} de directorios, archivos JAR\n\\                  y archivos ZIP para buscar archivos de clase.\n\\    -D<nombre>=<valor>\n\\                  definir una propiedad del sistema\n\\    -verbose:[class|gc|jni]\n\\                  activar la salida verbose\n\\    -version      imprimir la versi\u00F3n del producto y salir\n\\    -version:<valor>\n\\                  es necesario que se ejecute la versi\u00F3n especificada\n\\    -showversion  imprimir la versi\u00F3n del producto y continuar\n\\    -jre-restrict-search | -no-jre-restrict-search\n\\                  incluir/excluir JRE privados de usuario en la b\u00FAsqueda de versi\u00F3n\n\\    -? -help      imprimir este mensaje de ayuda\n\\    -X            imprimir la ayuda sobre las opciones que no sean est\u00E1ndar\n\\    -ea[:<nombre_paquete>...|:<nombre_clase>]\n\\    -enableassertions[:<nombre_paquete>...|:<nombre_clase>]\n\\                  activar afirmaciones con la granularidad especificada\n\\    -da[:<nombre_paquete>...|:<nombre_clase>]\n\\    -disableassertions[:<nombre_paquete>...|:<nombre_clase>]\n\\                  desactivar afirmaciones con la granularidad especificada\n\\    -esa | -enablesystemassertions\n\\                  activar afirmaciones del sistema\n\\    -dsa | -disablesystemassertions\n\\                  desactivar afirmaciones del sistema\n\\    -agentlib:<nombre_bib>[=<opciones>]\n\\                  cargar la biblioteca de agente nativa <nombre_bib>, como -agentlib:hprof\n\\                  v\u00E9ase tambi\u00E9n -agentlib:jdwp=help y -agentlib:hprof=help\n\\    -agentpath:<nombre_ruta_acceso>[=<opciones>]\n\\                  cargar biblioteca de agente nativa con el nombre de la ruta de acceso completa\n\\    -javaagent:<ruta_acceso_jar>[=<opciones>]\n\\                  cargar agente de lenguaje de programaci\u00F3n Java, v\u00E9ase java.lang.instrument\n\\    -splash:<ruta_acceso_imagen>\n\\                  mostrar una pantalla de presentaci\u00F3n con la imagen especificada\nConsulte http://www.oracle.com/technetwork/java/javase/documentation/index.html para obtener m\u00E1s informaci\u00F3n.
+java.launcher.opt.footer     =\    -cp <ruta de acceso de b\u00FAsqueda de clases de los directorios y los archivos zip/jar>\n    -classpath <ruta de acceso de b\u00FAsqueda de clases de los directorios y los archivos zip/jar>\n                  Lista separada por {0} de directorios, archivos JAR\n                  y archivos ZIP para buscar archivos de clase.\n    -D<nombre>=<valor>\n                  definir una propiedad del sistema\n    -verbose:[class|gc|jni]\n                  activar la salida verbose\n    -version      imprimir la versi\u00F3n del producto y salir\n    -version:<valor>\n                  es necesario que se ejecute la versi\u00F3n especificada\n    -showversion  imprimir la versi\u00F3n del producto y continuar\n    -jre-restrict-search | -no-jre-restrict-search\n                  incluir/excluir JRE privados de usuario en la b\u00FAsqueda de versi\u00F3n\n    -? -help      imprimir este mensaje de ayuda\n    -X            imprimir la ayuda sobre las opciones que no sean est\u00E1ndar\n    -ea[:<nombre_paquete>...|:<nombre_clase>]\n    -enableassertions[:<nombre_paquete>...|:<nombre_clase>]\n                  activar afirmaciones con la granularidad especificada\n    -da[:<nombre_paquete>...|:<nombre_clase>]\n    -disableassertions[:<nombre_paquete>...|:<nombre_clase>]\n                  desactivar afirmaciones con la granularidad especificada\n    -esa | -enablesystemassertions\n                  activar afirmaciones del sistema\n    -dsa | -disablesystemassertions\n                  desactivar afirmaciones del sistema\n    -agentlib:<nombre_bib>[=<opciones>]\n                  cargar la biblioteca de agente nativa <nombre_bib>, como -agentlib:hprof\n                  v\u00E9ase tambi\u00E9n -agentlib:jdwp=help y -agentlib:hprof=help\n    -agentpath:<nombre_ruta_acceso>[=<opciones>]\n                  cargar biblioteca de agente nativa con el nombre de la ruta de acceso completa\n    -javaagent:<ruta_acceso_jar>[=<opciones>]\n                  cargar agente de lenguaje de programaci\u00F3n Java, v\u00E9ase java.lang.instrument\n    -splash:<ruta_acceso_imagen>\n                  mostrar una pantalla de presentaci\u00F3n con la imagen especificada\nConsulte http://www.oracle.com/technetwork/java/javase/documentation/index.html para obtener m\u00E1s informaci\u00F3n.
 
 # Translators please note do not translate the options themselves
-java.launcher.X.usage=\    -Xmixed           ejecuci\u00F3n de modo mixto (por defecto)\n    -Xint             s\u00F3lo ejecuci\u00F3n de modo interpretado\n    -Xbootclasspath:<directorios y archivos zip/jar separados por {0}>\n                      definir la ruta de acceso de b\u00FAsqueda para los recursos y clases de inicializaci\u00F3n de datos\n    -Xbootclasspath/a:<directorios y archivos zip/jar separados por {0}>\n                      agregar al final de la ruta de acceso de la clase de inicializaci\u00F3n de datos\n    -Xbootclasspath/p:<directorios y archivos zip/jar separados por {0}>\n                      anteponer a la ruta de acceso de la clase de inicializaci\u00F3n de datos\n    -Xdiag            mostrar mensajes de diagn\u00F3stico adicionales\n    -Xnoclassgc       desactivar la recolecci\u00F3n de basura de clases\n    -Xincgc           activar la recolecci\u00F3n de basura de clases\n    -Xloggc:<archivo>    registrar el estado de GC en un archivo con registros de hora\n    -Xbatch           desactivar compilaci\u00F3n en segundo plano\n    -Xms<tama\u00F1o>        definir tama\u00F1o de pila Java inicial\n    -Xmx<tama\u00F1o>        definir tama\u00F1o de pila Java m\u00E1ximo\n    -Xss<tama\u00F1o>        definir tama\u00F1o de la pila del thread de Java\n    -Xprof            datos de salida de creaci\u00F3n de perfil de CPU\n    -Xfuture          activar las comprobaciones m\u00E1s estrictas, anticip\u00E1ndose al futuro valor por defecto\n    -Xrs              reducir el uso de se\u00F1ales de sistema operativo por parte de Java/VM (consulte la documentaci\u00F3n)\n    -Xcheck:jni       realizar comprobaciones adicionales para las funciones de JNI\n    -Xshare:off       no intentar usar datos de clase compartidos\n    -Xshare:auto      usar datos de clase compartidos si es posible (valor por defecto)\n    -Xshare:on        es obligatorio el uso de datos de clase compartidos, de lo contrario se emitir\u00E1 un fallo.\n    -XshowSettings    mostrar todos los valores y continuar\n    -XshowSettings:all\n                      mostrar todos los valores y continuar\n    -XshowSettings:vm mostrar todos los valores de la VM y continuar\n    -XshowSettings:properties\n                      mostrar todos los valores de las propiedades y continuar\n    -XshowSettings:locale\n                      mostrar todos los valores relacionados con la configuraci\u00F3n regional y continuar\n\nLas opciones -X no son est\u00E1ndar, por lo que podr\u00EDan cambiarse sin previo aviso.\n
+java.launcher.X.usage=\    -Xmixed           ejecuci\u00F3n de modo mixto (por defecto)\n    -Xint             s\u00F3lo ejecuci\u00F3n de modo interpretado\n    -Xbootclasspath:<directorios y archivos zip/jar separados por {0}>\n                      definir la ruta de acceso de b\u00FAsqueda para los recursos y clases de inicializaci\u00F3n de datos\n    -Xbootclasspath/a:<directorios y archivos zip/jar separados por {0}>\n                      agregar al final de la ruta de acceso de la clase de inicializaci\u00F3n de datos\n    -Xbootclasspath/p:<directorios y archivos zip/jar separados por {0}>\n                      anteponer a la ruta de acceso de la clase de inicializaci\u00F3n de datos\n    -Xdiag            mostrar mensajes de diagn\u00F3stico adicionales\n    -Xnoclassgc       desactivar la recolecci\u00F3n de basura de clases\n    -Xincgc           activar la recolecci\u00F3n de basura de clases\n    -Xloggc:<archivo> registrar el estado de GC en un archivo con registros de hora\n    -Xbatch           desactivar compilaci\u00F3n en segundo plano\n    -Xms<tama\u00F1o>      definir tama\u00F1o de pila Java inicial\n    -Xmx<tama\u00F1o>      definir tama\u00F1o de pila Java m\u00E1ximo\n    -Xss<tama\u00F1o>      definir tama\u00F1o de la pila del thread de Java\n    -Xprof            datos de salida de creaci\u00F3n de perfil de CPU\n    -Xfuture          activar las comprobaciones m\u00E1s estrictas, anticip\u00E1ndose al futuro valor por defecto\n    -Xrs              reducir el uso de se\u00F1ales de sistema operativo por parte de Java/VM (consulte la documentaci\u00F3n)\n    -Xcheck:jni       realizar comprobaciones adicionales para las funciones de JNI\n    -Xshare:off       no intentar usar datos de clase compartidos\n    -Xshare:auto      usar datos de clase compartidos si es posible (valor por defecto)\n    -Xshare:on        es obligatorio el uso de datos de clase compartidos, de lo contrario se emitir\u00E1 un fallo.\n    -XshowSettings    mostrar todos los valores y continuar\n    -XshowSettings:all\n                      mostrar todos los valores y continuar\n    -XshowSettings:vm mostrar todos los valores de la VM y continuar\n    -XshowSettings:properties\n                      mostrar todos los valores de las propiedades y continuar\n    -XshowSettings:locale\n                      mostrar todos los valores relacionados con la configuraci\u00F3n regional y continuar\n\nLas opciones -X no son est\u00E1ndar, por lo que podr\u00EDan cambiarse sin previo aviso.\n
 
 # Translators please note do not translate the options themselves
 java.launcher.X.macosx.usage=\nLas siguientes opciones son espec\u00EDficas para Mac OS X:\n    -XstartOnFirstThread\n                      ejecuta el m\u00E9todo main() del primer thread (AppKit)\n    -Xdock:name=<nombre de aplicaci\u00F3n>"\n                      sustituye al nombre por defecto de la aplicaci\u00F3n que se muestra en el Dock\n    -Xdock:icon=<ruta de acceso a archivo de icono>\n                      sustituye al icono por defecto que se muestra en el Dock\n\n
@@ -50,5 +50,7 @@
 java.launcher.jar.error1=Error: se ha producido un error inesperado al intentar abrir el archivo {0}
 java.launcher.jar.error2=no se ha encontrado el manifiesto en {0}
 java.launcher.jar.error3=no hay ning\u00FAn atributo de manifiesto principal en {0}
+java.launcher.jar.error4=no hay ning\u00FAn atributo de manifiesto de perfil en {0}
+java.launcher.jar.error5=El perfil {0} que necesita {1} no est\u00E1 soportado por este tiempo de ejecuci\u00F3n
 java.launcher.init.error=error de inicializaci\u00F3n
 java.launcher.javafx.error1=Error: el m\u00E9todo launchApplication de JavaFX tiene una firma que no es correcta.\\nSe debe declarar est\u00E1tico y devolver un valor de tipo nulo
--- a/jdk/src/share/classes/sun/launcher/resources/launcher_fr.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/launcher/resources/launcher_fr.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -50,5 +50,7 @@
 java.launcher.jar.error1=Erreur : une erreur inattendue est survenue lors de la tentative d''ouverture du fichier {0}
 java.launcher.jar.error2=fichier manifeste introuvable dans {0}
 java.launcher.jar.error3=aucun attribut manifest principal dans {0}
+java.launcher.jar.error4=aucun attribut manifest ''Profile'' dans {0}
+java.launcher.jar.error5=Profil {0} requis par {1} non pris en charge par cette ex\u00E9cution
 java.launcher.init.error=erreur d'initialisation
 java.launcher.javafx.error1=Erreur : la signature de la m\u00E9thode launchApplication JavaFX est incorrecte, la\nm\u00E9thode doit \u00EAtre d\u00E9clar\u00E9e statique et renvoyer une valeur de type void
--- a/jdk/src/share/classes/sun/launcher/resources/launcher_it.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/launcher/resources/launcher_it.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -34,7 +34,7 @@
 java.launcher.ergo.message2  =\                  perch\u00E9 si utilizza un computer di classe server.\n
 
 # Translators please note do not translate the options themselves
-java.launcher.opt.footer     =\    -cp <classpath di ricerca di directory e file zip/jar>\n\\    -classpath <classpath di ricerca di directory e file zip/jar>\n\\                  Una lista separata da {0} di directory, archivi JAR,\n\\                  e archivi ZIP utilizzata per la ricerca di file di classe.\n\\    -D<nome>=<valore>\n\\                  imposta una propriet\u00E0 di sistema\n\\    -verbose:[class|gc|jni]\n\\                  abilita l''output descrittivo\n\\    -version      stampa la versione del prodotto ed esce\n\\    -version:<valore>\n\\                  richiede l''esecuzione della versione specificata\n\\    -showversion  stampa la versione del prodotto e continua\n\\    -jre-restrict-search | -no-jre-restrict-search\n\\                  include/esclude gli ambienti JRE privati dell''utente nella ricerca della versione\n\\    -? -help      stampa questo messaggio della Guida\n\\    -X            stampa la Guida sulle opzioni non standard\n\\    -ea[:<nomepackage>...|:<nomeclasse>]\n\\    -enableassertions[:<nomepackage>...|:<nomeclasse>]\n\\                  abilita le asserzioni con la granularit\u00E0 specificata\n\\    -da[:<nomepackage>...|:<nomeclasse>]\n\\    -disableassertions[:<nomepackage>...|:<nomeclasse>]\n\\                  disabilita le asserzioni con la granularit\u00E0 specificata\n\\    -esa | -enablesystemassertions\n\\                  abilita le asserzioni di sistema\n\\    -dsa | -disablesystemassertions\n\\                  disabilita le asserzioni di sistema\n\\    -agentlib:<nomelib>[=<opzioni>]\n\\                  carica la libreria agenti nativa <nomelib>, ad esempio -agentlib:hprof\n\\                  vedere anche, -agentlib:jdwp=help and -agentlib:hprof=help\n\\    -agentpath:<nomepercorso>[=<opzioni>]\n\\                  carica la libreria agenti nativa con il percorso completo\n\\    -javaagent:<percorsojar>[=<opzioni>]\n\\                  carica l''agente del linguaggio di programmazione Java. Vedere java.lang.instrument\n\\    -splash:<percorsoimmagine>\n\\                  mostra la schermata iniziale con l''immagine specificata\nPer ulteriori dettagli, vedere http://www.oracle.com/technetwork/java/javase/documentation/index.html.
+java.launcher.opt.footer     =\    -cp <classpath di ricerca di directory e file zip/jar>\n    -classpath <classpath di ricerca di directory e file zip/jar>\n                  Una lista separata da {0} di directory, archivi JAR,\n                  e archivi ZIP utilizzata per la ricerca di file di classe.\n    -D<nome>=<valore>\n                  imposta una propriet\u00E0 di sistema\n    -verbose:[class|gc|jni]\n                  abilita l''output descrittivo\n    -version      stampa la versione del prodotto ed esce\n    -version:<valore>\n                  richiede l''esecuzione della versione specificata\n    -showversion  stampa la versione del prodotto e continua\n    -jre-restrict-search | -no-jre-restrict-search\n                  include/esclude gli ambienti JRE privati dell''utente nella ricerca della versione\n    -? -help      stampa questo messaggio della Guida\n    -X            stampa la Guida sulle opzioni non standard\n    -ea[:<nomepackage>...|:<nomeclasse>]\n    -enableassertions[:<nomepackage>...|:<nomeclasse>]\n                  abilita le asserzioni con la granularit\u00E0 specificata\n    -da[:<nomepackage>...|:<nomeclasse>]\n    -disableassertions[:<nomepackage>...|:<nomeclasse>]\n                  disabilita le asserzioni con la granularit\u00E0 specificata\n    -esa | -enablesystemassertions\n                  abilita le asserzioni di sistema\n    -dsa | -disablesystemassertions\n                  disabilita le asserzioni di sistema\n    -agentlib:<nomelib>[=<opzioni>]\n                  carica la libreria agenti nativa <nomelib>, ad esempio -agentlib:hprof\n                  vedere anche, -agentlib:jdwp=help and -agentlib:hprof=help\n    -agentpath:<nomepercorso>[=<opzioni>]\n                  carica la libreria agenti nativa con il percorso completo\n    -javaagent:<percorsojar>[=<opzioni>]\n                  carica l''agente del linguaggio di programmazione Java. Vedere java.lang.instrument\n    -splash:<percorsoimmagine>\n                  mostra la schermata iniziale con l''immagine specificata\nPer ulteriori dettagli, vedere http://www.oracle.com/technetwork/java/javase/documentation/index.html.
 
 # Translators please note do not translate the options themselves
 java.launcher.X.usage=\    -Xmixed           esecuzione in modalit\u00E0 mista (impostazione predefinita)\n    -Xint             esecuzione solo in modalit\u00E0 convertita\n    -Xbootclasspath:<directory e file zip/jar separati da {0}>\n                      imposta il percorso di ricerca per le classi e le risorse di bootstrap\n    -Xbootclasspath/a:<directory e file zip/jar separati da {0}>\n                      aggiunge alla fine del classpath di bootstrap\n    -Xbootclasspath/p:<directory e file zip/jar separati da {0}>\n                      antepone al classpath di bootstrap\n    -Xdiag            mostra messaggi di diagnostica aggiuntivi\n    -Xnoclassgc       disabilita la garbage collection della classe\n    -Xincgc           abilita la garbage collection incrementale\n    -Xloggc:<file>    registra lo stato GC in un file di log con indicatori orari\n    -Xbatch           disabilita la compilazione in background\n    -Xms<dimensione>        imposta la dimensione heap Java iniziale\n    -Xmx<dimensione>        imposta la dimensione heap Java massima\n    -Xss<dimensione>        imposta la dimensione dello stack di thread Java\n    -Xprof            visualizza i dati di profilo della CPU\n    -Xfuture          abilita i controlli pi\u00F9 limitativi anticipando le impostazioni predefinite future\n    -Xrs              riduce l''uso di segnali del sistema operativo da Java/VM (vedere la documentazione)\n    -Xcheck:jni       esegue controlli aggiuntivi per le funzioni JNI\n    -Xshare:off       non tenta di utilizzare i dati della classe condivisi\n    -Xshare:auto      utilizza i dati di classe condivisi se possibile (impostazione predefinita)\n    -Xshare:on        richiede l''uso dei dati di classe condivisi, altrimenti l''esecuzione non riesce.\n    -XshowSettings    mostra tutte le impostazioni e continua\n    -XshowSettings:all\n                      mostra tutte le impostazioni e continua\n    -XshowSettings:vm mostra tutte le impostazioni correlate alla VM e continua\n    -XshowSettings:properties\n                      mostra tutte le impostazioni delle propriet\u00E0 e continua\n    -XshowSettings:locale\n                      mostra tutte le impostazioni correlate alle impostazioni nazionali e continua\n\nLe opzioni -X non sono opzioni standard e sono soggette a modifiche senza preavviso.\n
@@ -50,5 +50,7 @@
 java.launcher.jar.error1=Errore: si \u00E8 verificato un errore imprevisto durante il tentativo di aprire il file {0}
 java.launcher.jar.error2=manifest non trovato in {0}
 java.launcher.jar.error3=nessun attributo manifest principale in {0}
+java.launcher.jar.error4=nessun attributo manifest di profilo in {0}
+java.launcher.jar.error5=Il profilo {0} richiesto da {1} non \u00E8 supportato da questo runtime
 java.launcher.init.error=errore di inizializzazione
 java.launcher.javafx.error1=Errore: il metodo JavaFX launchApplication dispone di una firma errata, \nla firma deve essere dichiarata static e restituire un valore di tipo void
--- a/jdk/src/share/classes/sun/launcher/resources/launcher_ja.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/launcher/resources/launcher_ja.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -37,7 +37,8 @@
 java.launcher.opt.footer     =\    -cp <class search path of directories and zip/jar files>\n    -classpath <class search path of directories and zip/jar files>\n                  \u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u691C\u7D22\u3059\u308B\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3001\n                  JAR\u30A2\u30FC\u30AB\u30A4\u30D6\u304A\u3088\u3073ZIP\u30A2\u30FC\u30AB\u30A4\u30D6\u306E{0}\u3067\u533A\u5207\u3089\u308C\u305F\u30EA\u30B9\u30C8\u3067\u3059\u3002\n    -D<name>=<value>\n                  \u30B7\u30B9\u30C6\u30E0\u30FB\u30D7\u30ED\u30D1\u30C6\u30A3\u3092\u8A2D\u5B9A\u3059\u308B\n    -verbose:[class|gc|jni]\n                  \u8A73\u7D30\u306A\u51FA\u529B\u3092\u884C\u3046\n    -version      \u88FD\u54C1\u30D0\u30FC\u30B8\u30E7\u30F3\u3092\u51FA\u529B\u3057\u3066\u7D42\u4E86\u3059\u308B\n    -version:<value>\n                  \u6307\u5B9A\u3057\u305F\u30D0\u30FC\u30B8\u30E7\u30F3\u3092\u5B9F\u884C\u306B\u5FC5\u9808\u306B\u3059\u308B\n    -showversion  \u88FD\u54C1\u30D0\u30FC\u30B8\u30E7\u30F3\u3092\u51FA\u529B\u3057\u3066\u7D9A\u884C\u3059\u308B\n    -jre-restrict-search | -no-jre-restrict-search\n                  \u30E6\u30FC\u30B6\u30FC\u306E\u30D7\u30E9\u30A4\u30D9\u30FC\u30C8JRE\u3092\u30D0\u30FC\u30B8\u30E7\u30F3\u691C\u7D22\u306B\u542B\u3081\u308B/\u9664\u5916\u3059\u308B\n    -? -help      \u3053\u306E\u30D8\u30EB\u30D7\u30FB\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u51FA\u529B\u3059\u308B\n    -X            \u975E\u6A19\u6E96\u30AA\u30D7\u30B7\u30E7\u30F3\u306B\u95A2\u3059\u308B\u30D8\u30EB\u30D7\u3092\u51FA\u529B\u3059\u308B\n    -ea[:<packagename>...|:<classname>]\n    -enableassertions[:<packagename>...|:<classname>]\n                  \u6307\u5B9A\u3057\u305F\u7C92\u5EA6\u3067\u30A2\u30B5\u30FC\u30B7\u30E7\u30F3\u3092\u6709\u52B9\u306B\u3059\u308B\n    -da[:<packagename>...|:<classname>]\n    -disableassertions[:<packagename>...|:<classname>]\n                  \u6307\u5B9A\u3057\u305F\u7C92\u5EA6\u3067\u30A2\u30B5\u30FC\u30B7\u30E7\u30F3\u3092\u7121\u52B9\u306B\u3059\u308B\n    -esa | -enablesystemassertions\n                  \u30B7\u30B9\u30C6\u30E0\u30FB\u30A2\u30B5\u30FC\u30B7\u30E7\u30F3\u3092\u6709\u52B9\u306B\u3059\u308B\n    -dsa | -disablesystemassertions\n                  \u30B7\u30B9\u30C6\u30E0\u30FB\u30A2\u30B5\u30FC\u30B7\u30E7\u30F3\u3092\u7121\u52B9\u306B\u3059\u308B\n    -agentlib:<libname>[=<options>]\n                  \u30CD\u30A4\u30C6\u30A3\u30D6\u30FB\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u30FB\u30E9\u30A4\u30D6\u30E9\u30EA<libname>\u3092\u30ED\u30FC\u30C9\u3059\u308B\u3002\u4F8B: -agentlib:hprof\n                  -agentlib:jdwp=help\u3068-agentlib:hprof=help\u3082\u53C2\u7167\n    -agentpath:<pathname>[=<options>]\n                  \u30D5\u30EB\u30D1\u30B9\u540D\u3067\u30CD\u30A4\u30C6\u30A3\u30D6\u30FB\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u30FB\u30E9\u30A4\u30D6\u30E9\u30EA\u3092\u30ED\u30FC\u30C9\u3059\u308B\n    -javaagent:<jarpath>[=<options>]\n                  Java\u30D7\u30ED\u30B0\u30E9\u30DF\u30F3\u30B0\u8A00\u8A9E\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u30ED\u30FC\u30C9\u3059\u308B\u3002java.lang.instrument\u3092\u53C2\u7167\n    -splash:<imagepath>\n                  \u6307\u5B9A\u3057\u305F\u30A4\u30E1\u30FC\u30B8\u3067\u30B9\u30D7\u30E9\u30C3\u30B7\u30E5\u753B\u9762\u3092\u8868\u793A\u3059\u308B\n\u8A73\u7D30\u306Fhttp://www.oracle.com/technetwork/java/javase/documentation/index.html\u3092\u53C2\u7167\u3057\u3066\u304F\u3060\u3055\u3044\u3002
 
 # Translators please note do not translate the options themselves
-java.launcher.X.usage=\    -Xmixed           \u6DF7\u5408\u30E2\u30FC\u30C9\u306E\u5B9F\u884C(\u30C7\u30D5\u30A9\u30EB\u30C8)\n    -Xint             \u30A4\u30F3\u30BF\u30D7\u30EA\u30BF\u30FB\u30E2\u30FC\u30C9\u306E\u5B9F\u884C\u306E\u307F\n    -Xbootclasspath:<directories and zip/jar files separated by {0}>\n                      \u30D6\u30FC\u30C8\u30B9\u30C8\u30E9\u30C3\u30D7\u306E\u30AF\u30E9\u30B9\u3068\u30EA\u30BD\u30FC\u30B9\u306E\u691C\u7D22\u30D1\u30B9\u3092\u8A2D\u5B9A\u3059\u308B\n    -Xbootclasspath/a:<directories and zip/jar files separated by {0}>\n                      \u30D6\u30FC\u30C8\u30B9\u30C8\u30E9\u30C3\u30D7\u30FB\u30AF\u30E9\u30B9\u30FB\u30D1\u30B9\u306E\u6700\u5F8C\u306B\u8FFD\u52A0\u3059\u308B\n    -Xbootclasspath/p:<directories and zip/jar files separated by {0}>\n                      \u30D6\u30FC\u30C8\u30B9\u30C8\u30E9\u30C3\u30D7\u30FB\u30AF\u30E9\u30B9\u30FB\u30D1\u30B9\u306E\u524D\u306B\u4ED8\u52A0\u3059\u308B\n    -Xdiag            \u8FFD\u52A0\u306E\u8A3A\u65AD\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u8868\u793A\u3059\u308B\n    -Xnoclassgc       \u30AF\u30E9\u30B9\u306E\u30AC\u30D9\u30FC\u30B8\u30FB\u30B3\u30EC\u30AF\u30B7\u30E7\u30F3\u3092\u7121\u52B9\u306B\u3059\u308B\n    -Xincgc           \u5897\u5206\u30AC\u30D9\u30FC\u30B8\u30FB\u30B3\u30EC\u30AF\u30B7\u30E7\u30F3\u3092\u6709\u52B9\u306B\u3059\u308B\n    -Xloggc:<file>    \u30BF\u30A4\u30E0\u30B9\u30BF\u30F3\u30D7\u304C\u4ED8\u3044\u305F\u30D5\u30A1\u30A4\u30EB\u306BGC\u30B9\u30C6\u30FC\u30BF\u30B9\u306E\u30ED\u30B0\u3092\u8A18\u9332\u3059\u308B\n    -Xbatch           \u30D0\u30C3\u30AF\u30B0\u30E9\u30A6\u30F3\u30C9\u306E\u30B3\u30F3\u30D1\u30A4\u30EB\u3092\u7121\u52B9\u306B\u3059\u308B\n    -Xms<size>        Java\u306E\u521D\u671F\u30D2\u30FC\u30D7\u30FB\u30B5\u30A4\u30BA\u3092\u8A2D\u5B9A\u3059\u308B\n    -Xmx<size>        Java\u306E\u6700\u5927\u30D2\u30FC\u30D7\u30FB\u30B5\u30A4\u30BA\u3092\u8A2D\u5B9A\u3059\u308B\n    -Xss<size>        Java\u306E\u30B9\u30EC\u30C3\u30C9\u30FB\u30B9\u30BF\u30C3\u30AF\u30FB\u30B5\u30A4\u30BA\u3092\u8A2D\u5B9A\u3059\u308B\n    -Xprof            CPU\u30D7\u30ED\u30D5\u30A1\u30A4\u30EB\u30FB\u30C7\u30FC\u30BF\u3092\u51FA\u529B\u3059\u308B\n    -Xfuture          \u5C06\u6765\u306E\u30C7\u30D5\u30A9\u30EB\u30C8\u3092\u898B\u8D8A\u3057\u3066\u3001\u6700\u3082\u53B3\u5BC6\u306A\u30C1\u30A7\u30C3\u30AF\u3092\u6709\u52B9\u306B\u3059\u308B\n    -Xrs              Java/VM\u306B\u3088\u308BOS\u30B7\u30B0\u30CA\u30EB\u306E\u4F7F\u7528\u3092\u524A\u6E1B\u3059\u308B(\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u3092\u53C2\u7167)\n    -Xcheck:jni       JNI\u95A2\u6570\u306B\u5BFE\u3059\u308B\u8FFD\u52A0\u306E\u30C1\u30A7\u30C3\u30AF\u3092\u5B9F\u884C\u3059\u308B\n    -Xshare:off       \u5171\u6709\u30AF\u30E9\u30B9\u306E\u30C7\u30FC\u30BF\u3092\u4F7F\u7528\u3057\u3088\u3046\u3068\u3057\u306A\u3044\n    -Xshare:auto      \u53EF\u80FD\u3067\u3042\u308C\u3070\u5171\u6709\u30AF\u30E9\u30B9\u306E\u30C7\u30FC\u30BF\u3092\u4F7F\u7528\u3059\u308B(\u30C7\u30D5\u30A9\u30EB\u30C8)\n    -Xshare:on        \u5171\u6709\u30AF\u30E9\u30B9\u30FB\u30C7\u30FC\u30BF\u306E\u4F7F\u7528\u3092\u5FC5\u9808\u306B\u3057\u3001\u3067\u304D\u306A\u3051\u308C\u3070\u5931\u6557\u3059\u308B\u3002\n    -XshowSettings    \u3059\u3079\u3066\u306E\u8A2D\u5B9A\u3092\u8868\u793A\u3057\u3066\u7D9A\u884C\u3059\u308B\n    -XshowSettings:all\n                      \u3059\u3079\u3066\u306E\u8A2D\u5B9A\u3092\u8868\u793A\u3057\u3066\u7D9A\u884C\u3059\u308B\n    -XshowSettings:vm \u3059\u3079\u3066\u306EVM\u95A2\u9023\u306E\u8A2D\u5B9A\u3092\u8868\u793A\u3057\u3066\u7D9A\u884C\u3059\u308B\n    -XshowSettings:properties\n                      \u3059\u3079\u3066\u306E\u30D7\u30ED\u30D1\u30C6\u30A3\u8A2D\u5B9A\u3092\u8868\u793A\u3057\u3066\u7D9A\u884C\u3059\u308B\n    -XshowSettings:locale\n                      \u3059\u3079\u3066\u306E\u30ED\u30B1\u30FC\u30EB\u95A2\u9023\u306E\u8A2D\u5B9A\u3092\u8868\u793A\u3057\u3066\u7D9A\u884C\u3059\u308B\n\n-X\u30AA\u30D7\u30B7\u30E7\u30F3\u306F\u975E\u6A19\u6E96\u306A\u306E\u3067\u3001\u4E88\u544A\u306A\u304F\u5909\u66F4\u3055\u308C\u308B\u5834\u5408\u304C\u3042\u308A\u307E\u3059\u3002\n
+java.launcher.X.usage=\    -Xmixed           \u6DF7\u5408\u30E2\u30FC\u30C9\u306E\u5B9F\u884C(\u30C7\u30D5\u30A9\u30EB\u30C8)\n    -Xint             \u30A4\u30F3\u30BF\u30D7\u30EA\u30BF\u30FB\u30E2\u30FC\u30C9\u306E\u5B9F\u884C\u306E\u307F\n    -Xbootclasspath:<directories and zip/jar files separated by {0}>\n                      \u30D6\u30FC\u30C8\u30B9\u30C8\u30E9\u30C3\u30D7\u306E\u30AF\u30E9\u30B9\u3068\u30EA\u30BD\u30FC\u30B9\u306E\u691C\u7D22\u30D1\u30B9\u3092\u8A2D\u5B9A\u3059\u308B\n    -Xbootclasspath/a:<directories and zip/jar files separated by {0}>\n                      \u30D6\u30FC\u30C8\u30B9\u30C8\u30E9\u30C3\u30D7\u30FB\u30AF\u30E9\u30B9\u30FB\u30D1\u30B9\u306E\u6700\u5F8C\u306B\u8FFD\u52A0\u3059\u308B\n    -Xbootclasspath/p:<directories and zip/jar files separated by {0}>\n                      \u30D6\u30FC\u30C8\u30B9\u30C8\u30E9\u30C3\u30D7\u30FB\u30AF\u30E9\u30B9\u30FB\u30D1\u30B9\u306E\u524D\u306B\u4ED8\u52A0\u3059\u308B\n    -Xdiag            \u8FFD\u52A0\u306E\u8A3A\u65AD\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u8868\u793A\u3059\u308B\n    -Xnoclassgc       \u30AF\u30E9\u30B9\u306E\u30AC\u30D9\u30FC\u30B8\u30FB\u30B3\u30EC\u30AF\u30B7\u30E7\u30F3\u3092\u7121\u52B9\u306B\u3059\u308B\n    -Xincgc           \u5897\u5206\u30AC\u30D9\u30FC\u30B8\u30FB\u30B3\u30EC\u30AF\u30B7\u30E7\u30F3\u3092\u6709\u52B9\u306B\u3059\u308B\n    -Xloggc:<file>    \u30BF\u30A4\u30E0\u30B9\u30BF\u30F3\u30D7\u304C\u4ED8\u3044\u305F\u30D5\u30A1\u30A4\u30EB\u306BGC\u30B9\u30C6\u30FC\u30BF\u30B9\u306E\u30ED\u30B0\u3092\u8A18\u9332\u3059\u308B\n    -Xbatch           \u30D0\u30C3\u30AF\u30B0\u30E9\u30A6\u30F3\u30C9\u306E\u30B3\u30F3\u30D1\u30A4\u30EB\u3092\u7121\u52B9\u306B\u3059\u308B\n    -Xms<size>        Java\u306E\u521D\u671F\u30D2\u30FC\u30D7\u30FB\u30B5\u30A4\u30BA\u3092\u8A2D\u5B9A\u3059\u308B\n    -Xmx<size>        Java\u306E\u6700\u5927\u30D2\u30FC\u30D7\u30FB\u30B5\u30A4\u30BA\u3092\u8A2D\u5B9A\u3059\u308B\n    -Xss<size>        Java\u306E\u30B9\u30EC\u30C3\u30C9\u30FB\u30B9\u30BF\u30C3\u30AF\u30FB\u30B5\u30A4\u30BA\u3092\u8A2D\u5B9A\u3059\u308B\n    -Xprof            CPU\u30D7\u30ED\u30D5\u30A1\u30A4\u30EB\u30FB\u30C7\u30FC\u30BF\u3092\u51FA\u529B\u3059\u308B\n    -Xfuture          \u5C06\u6765\u306E\u30C7\u30D5\u30A9\u30EB\u30C8\u3092\u898B\u8D8A\u3057\u3066\u3001\u6700\u3082\u53B3\u5BC6\u306A\u30C1\u30A7\u30C3\u30AF\u3092\u6709\u52B9\u306B\u3059\u308B\n    -Xrs              Java/VM\u306B\u3088\u308BOS\u30B7\u30B0\u30CA\u30EB\u306E\u4F7F\u7528\u3092\u524A\u6E1B\u3059\u308B(\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u3092\u53C2\u7167)\n    -Xcheck:jni       JNI\u95A2\u6570\u306B\u5BFE\u3059\u308B\u8FFD\u52A0\u306E\u30C1\u30A7\u30C3\u30AF\u3092\u5B9F\u884C\u3059\u308B\n    -Xshare:off       \u5171\u6709\u30AF\u30E9\u30B9\u306E\u30C7\u30FC\u30BF\u3092\u4F7F\u7528\u3057\u3088\u3046\u3068\u3057\u306A\u3044\n    -Xshare:auto      \u53EF\u80FD\u3067\u3042\u308C\u3070\u5171\u6709\u30AF\u30E9\u30B9\u306E\u30C7\u30FC\u30BF\u3092\u4F7F\u7528\u3059\u308B(\u30C7\u30D5\u30A9\u30EB\u30C8)\n    -Xshare:on        \u5171\u6709\u30AF\u30E9\u30B9\u30FB\u30C7\u30FC\u30BF\u306E\u4F7F\u7528\u3092\u5FC5\u9808\u306B\u3057\u3001\u3067\u304D\u306A\u3051\u308C\u3070\u5931\u6557\u3059\u308B\u3002\n    -XshowSettings    \u3059\u3079\u3066\u306E\u8A2D\u5B9A\u3092\u8868\u793A\u3057\u3066\u7D9A\u884C\u3059\u308B\n    -XshowSettings:all\n                      \u3059\u3079\u3066\u306E\u8A2D\u5B9A\u3092\u8868\u793A\u3057\u3066\u7D9A\u884C\u3059\u308B\n    -XshowSettings:vm \u3059\u3079\u3066\u306EVM\u95A2\u9023\u306E\u8A2D\u5B9A\u3092\u8868\u793A\u3057\u3066\u7D9A\u884C\u3059\u308B\n    -XshowSettings:properties\n                      \u3059\u3079\u3066\u306E\u30D7\u30ED\u30D1\u30C6\u30A3\u8A2D\u5B9A\u3092\u8868\u793A\u3057\u3066\u7D9A\u884C\u3059\u308B\n    -XshowSettings:locale\n                      \
+\u3059\u3079\u3066\u306E\u30ED\u30B1\u30FC\u30EB\u95A2\u9023\u306E\u8A2D\u5B9A\u3092\u8868\u793A\u3057\u3066\u7D9A\u884C\u3059\u308B\n\n-X\u30AA\u30D7\u30B7\u30E7\u30F3\u306F\u975E\u6A19\u6E96\u306A\u306E\u3067\u3001\u4E88\u544A\u306A\u304F\u5909\u66F4\u3055\u308C\u308B\u5834\u5408\u304C\u3042\u308A\u307E\u3059\u3002\n
 
 # Translators please note do not translate the options themselves
 java.launcher.X.macosx.usage=\n\u6B21\u306E\u30AA\u30D7\u30B7\u30E7\u30F3\u306FMac OS X\u56FA\u6709\u3067\u3059\u3002\n    -XstartOnFirstThread\n                      main()\u30E1\u30BD\u30C3\u30C9\u3092\u6700\u521D(AppKit)\u306E\u30B9\u30EC\u30C3\u30C9\u3067\u5B9F\u884C\u3059\u308B\n    -Xdock:name=<application name>"\n                      Dock\u306B\u8868\u793A\u3055\u308C\u308B\u30C7\u30D5\u30A9\u30EB\u30C8\u30FB\u30A2\u30D7\u30EA\u30B1\u30FC\u30B7\u30E7\u30F3\u540D\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3059\u308B\n    -Xdock:icon=<path to icon file>\n                      Dock\u306B\u8868\u793A\u3055\u308C\u308B\u30C7\u30D5\u30A9\u30EB\u30C8\u30FB\u30A2\u30A4\u30B3\u30F3\u3092\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3059\u308B\n\n
@@ -50,5 +51,7 @@
 java.launcher.jar.error1=\u30A8\u30E9\u30FC: \u30D5\u30A1\u30A4\u30EB{0}\u3092\u958B\u3053\u3046\u3068\u3057\u3066\u3044\u308B\u3068\u304D\u306B\u3001\u4E88\u671F\u3057\u306A\u3044\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F
 java.launcher.jar.error2={0}\u306B\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093
 java.launcher.jar.error3={0}\u306B\u30E1\u30A4\u30F3\u30FB\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u5C5E\u6027\u304C\u3042\u308A\u307E\u305B\u3093
+java.launcher.jar.error4={0}\u306B\u30D7\u30ED\u30D5\u30A1\u30A4\u30EB\u30FB\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u5C5E\u6027\u304C\u3042\u308A\u307E\u305B\u3093
+java.launcher.jar.error5={1}\u306B\u5FC5\u8981\u306A\u30D7\u30ED\u30D5\u30A1\u30A4\u30EB{0}\u306F\u3053\u306E\u30E9\u30F3\u30BF\u30A4\u30E0\u3067\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093
 java.launcher.init.error=\u521D\u671F\u5316\u30A8\u30E9\u30FC
 java.launcher.javafx.error1=\u30A8\u30E9\u30FC: JavaFX launchApplication\u30E1\u30BD\u30C3\u30C9\u306B\u8AA4\u3063\u305F\u30B7\u30B0\u30CD\u30C1\u30E3\u304C\u3042\u308A\u3001\nstatic\u3092\u5BA3\u8A00\u3057\u3066void\u578B\u306E\u5024\u3092\u8FD4\u3059\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059
--- a/jdk/src/share/classes/sun/launcher/resources/launcher_ko.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/launcher/resources/launcher_ko.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -34,7 +34,7 @@
 java.launcher.ergo.message2  =\                  \uC11C\uBC84\uAE09 \uC2DC\uC2A4\uD15C\uC5D0\uC11C \uC2E4\uD589 \uC911\uC774\uAE30 \uB54C\uBB38\uC785\uB2C8\uB2E4.\n
 
 # Translators please note do not translate the options themselves
-java.launcher.opt.footer     =\    -cp <class search path of directories and zip/jar files>\n\\    -classpath <class search path of directories and zip/jar files>\n\\                  \uD074\uB798\uC2A4 \uD30C\uC77C\uC744 \uAC80\uC0C9\uD560 {0}(\uC73C)\uB85C \uAD6C\uBD84\uB41C \uB514\uB809\uD1A0\uB9AC,\n\\                  JAR \uC544\uCE74\uC774\uBE0C \uBC0F ZIP \uC544\uCE74\uC774\uBE0C \uBAA9\uB85D\uC785\uB2C8\uB2E4.\n\\    -D<name>=<value>\n\\                  \uC2DC\uC2A4\uD15C \uC18D\uC131\uC744 \uC124\uC815\uD569\uB2C8\uB2E4.\n\\    -verbose:[class|gc|jni]\n\\                  \uC0C1\uC138 \uC815\uBCF4 \uCD9C\uB825\uC744 \uC0AC\uC6A9\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\n\\    -version      \uC81C\uD488 \uBC84\uC804\uC744 \uC778\uC1C4\uD55C \uD6C4 \uC885\uB8CC\uD569\uB2C8\uB2E4.\n\\    -version:<value>\n\\                  \uC2E4\uD589\uD560 \uBC84\uC804\uC744 \uC9C0\uC815\uD574\uC57C \uD569\uB2C8\uB2E4.\n\\    -showversion  \uC81C\uD488 \uBC84\uC804\uC744 \uC778\uC1C4\uD55C \uD6C4 \uACC4\uC18D\uD569\uB2C8\uB2E4.\n\\    -jre-restrict-search | -no-jre-restrict-search\n\\                  \uBC84\uC804 \uAC80\uC0C9\uC5D0\uC11C \uC0AC\uC6A9\uC790 \uC804\uC6A9 JRE\uB97C \uD3EC\uD568/\uC81C\uC678\uD569\uB2C8\uB2E4.\n\\    -? -help      \uC774 \uB3C4\uC6C0\uB9D0 \uBA54\uC2DC\uC9C0\uB97C \uC778\uC1C4\uD569\uB2C8\uB2E4.\n\\    -X            \uBE44\uD45C\uC900 \uC635\uC158\uC5D0 \uB300\uD55C \uB3C4\uC6C0\uB9D0\uC744 \uC778\uC1C4\uD569\uB2C8\uB2E4.\n\\    -ea[:<packagename>...|:<classname>]\n\\    -enableassertions[:<packagename>...|:<classname>]\n\\                  \uC138\uBD84\uC131\uC774 \uC9C0\uC815\uB41C \uAC80\uC99D\uC744 \uC0AC\uC6A9\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\n\\    -da[:<packagename>...|:<classname>]\n\\    -disableassertions[:<packagename>...|:<classname>]\n\\                  \uC138\uBD84\uC131\uC774 \uC9C0\uC815\uB41C \uAC80\uC99D\uC744 \uC0AC\uC6A9 \uC548\uD568\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\n\\    -esa | -enablesystemassertions\n\\                  \uC2DC\uC2A4\uD15C \uAC80\uC99D\uC744 \uC0AC\uC6A9\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\n\\    -dsa | -disablesystemassertions\n\\                  \uC2DC\uC2A4\uD15C \uAC80\uC99D\uC744 \uC0AC\uC6A9 \uC548\uD568\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\n\\    -agentlib:<libname>[=<options>]\n\\                  <libname> \uACE0\uC720 \uC5D0\uC774\uC804\uD2B8 \uB77C\uC774\uBE0C\uB7EC\uB9AC\uB97C \uB85C\uB4DC\uD569\uB2C8\uB2E4(\uC608: -agentlib:hprof).\n\\                  -agentlib:jdwp=help \uBC0F -agentlib:hprof=help\uB3C4 \uCC38\uC870\uD558\uC2ED\uC2DC\uC624.\n\\    -agentpath:<pathname>[=<options>]\n\\                  \uC804\uCCB4 \uACBD\uB85C\uBA85\uC744 \uC0AC\uC6A9\uD558\uC5EC \uACE0\uC720 \uC5D0\uC774\uC804\uD2B8 \uB77C\uC774\uBE0C\uB7EC\uB9AC\uB97C \uB85C\uB4DC\uD569\uB2C8\uB2E4.\n\\    -javaagent:<jarpath>[=<options>]\n\\                  Java \uD504\uB85C\uADF8\uB798\uBC0D \uC5B8\uC5B4 \uC5D0\uC774\uC804\uD2B8\uB97C \uB85C\uB4DC\uD569\uB2C8\uB2E4. java.lang.instrument\uB97C \uCC38\uC870\uD558\uC2ED\uC2DC\uC624.\n\\    -splash:<imagepath>\n\\                  \uC774\uBBF8\uC9C0\uAC00 \uC9C0\uC815\uB41C \uC2A4\uD50C\uB798\uC2DC \uD654\uBA74\uC744 \uD45C\uC2DC\uD569\uB2C8\uB2E4.\n\uC790\uC138\uD55C \uB0B4\uC6A9\uC740 http://www.oracle.com/technetwork/java/javase/documentation/index.html\uC744 \uCC38\uC870\uD558\uC2ED\uC2DC\uC624.
+java.launcher.opt.footer     =\    -cp <class search path of directories and zip/jar files>\\n    -classpath <class search path of directories and zip/jar files>\\n                  \uD074\uB798\uC2A4 \uD30C\uC77C\uC744 \uAC80\uC0C9\uD560 {0}(\uC73C)\uB85C \uAD6C\uBD84\uB41C \uB514\uB809\uD1A0\uB9AC,\\n                  JAR \uC544\uCE74\uC774\uBE0C \uBC0F ZIP \uC544\uCE74\uC774\uBE0C \uBAA9\uB85D\uC785\uB2C8\uB2E4.\\n    -D<name>=<value>\\n                  \uC2DC\uC2A4\uD15C \uC18D\uC131\uC744 \uC124\uC815\uD569\uB2C8\uB2E4.\\n    -verbose:[class|gc|jni]\\n                  \uC0C1\uC138 \uC815\uBCF4 \uCD9C\uB825\uC744 \uC0AC\uC6A9\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\\n    -version      \uC81C\uD488 \uBC84\uC804\uC744 \uC778\uC1C4\uD55C \uD6C4 \uC885\uB8CC\uD569\uB2C8\uB2E4.\\n    -version:<value>\\n                  \uC2E4\uD589\uD560 \uBC84\uC804\uC744 \uC9C0\uC815\uD574\uC57C \uD569\uB2C8\uB2E4.\\n    -showversion  \uC81C\uD488 \uBC84\uC804\uC744 \uC778\uC1C4\uD55C \uD6C4 \uACC4\uC18D\uD569\uB2C8\uB2E4.\\n    -jre-restrict-search | -no-jre-restrict-search\\n                  \uBC84\uC804 \uAC80\uC0C9\uC5D0\uC11C \uC0AC\uC6A9\uC790 \uC804\uC6A9 JRE\uB97C \uD3EC\uD568/\uC81C\uC678\uD569\uB2C8\uB2E4.\\n    -? -help      \uC774 \uB3C4\uC6C0\uB9D0 \uBA54\uC2DC\uC9C0\uB97C \uC778\uC1C4\uD569\uB2C8\uB2E4.\\n    -X            \uBE44\uD45C\uC900 \uC635\uC158\uC5D0 \uB300\uD55C \uB3C4\uC6C0\uB9D0\uC744 \uC778\uC1C4\uD569\uB2C8\uB2E4.\\n    -ea[:<packagename>...|:<classname>]\\n    -enableassertions[:<packagename>...|:<classname>]\\n                  \uC138\uBD84\uC131\uC774 \uC9C0\uC815\uB41C \uAC80\uC99D\uC744 \uC0AC\uC6A9\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\\n    -da[:<packagename>...|:<classname>]\\n    -disableassertions[:<packagename>...|:<classname>]\\n                  \uC138\uBD84\uC131\uC774 \uC9C0\uC815\uB41C \uAC80\uC99D\uC744 \uC0AC\uC6A9 \uC548\uD568\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\\n    -esa | -enablesystemassertions\\n                  \uC2DC\uC2A4\uD15C \uAC80\uC99D\uC744 \uC0AC\uC6A9\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\\n    -dsa | -disablesystemassertions\\n                  \uC2DC\uC2A4\uD15C \uAC80\uC99D\uC744 \uC0AC\uC6A9 \uC548\uD568\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\\n    -agentlib:<libname>[=<options>]\\n                  <libname> \uACE0\uC720 \uC5D0\uC774\uC804\uD2B8 \uB77C\uC774\uBE0C\uB7EC\uB9AC\uB97C \uB85C\uB4DC\uD569\uB2C8\uB2E4(\uC608: -agentlib:hprof).\\n                  -agentlib:jdwp=help \uBC0F -agentlib:hprof=help\uB3C4 \uCC38\uC870\uD558\uC2ED\uC2DC\uC624.\\n    -agentpath:<pathname>[=<options>]\\n                  \uC804\uCCB4 \uACBD\uB85C\uBA85\uC744 \uC0AC\uC6A9\uD558\uC5EC \uACE0\uC720 \uC5D0\uC774\uC804\uD2B8 \uB77C\uC774\uBE0C\uB7EC\uB9AC\uB97C \uB85C\uB4DC\uD569\uB2C8\uB2E4.\\n    -javaagent:<jarpath>[=<options>]\\n                  Java \uD504\uB85C\uADF8\uB798\uBC0D \uC5B8\uC5B4 \uC5D0\uC774\uC804\uD2B8\uB97C \uB85C\uB4DC\uD569\uB2C8\uB2E4. java.lang.instrument\uB97C \uCC38\uC870\uD558\uC2ED\uC2DC\uC624.\\n    -splash:<imagepath>\\n                  \uC774\uBBF8\uC9C0\uAC00 \uC9C0\uC815\uB41C \uC2A4\uD50C\uB798\uC2DC \uD654\uBA74\uC744 \uD45C\uC2DC\uD569\uB2C8\uB2E4.\\n\uC790\uC138\uD55C \uB0B4\uC6A9\uC740 http://www.oracle.com/technetwork/java/javase/documentation/index.html\uC744 \uCC38\uC870\uD558\uC2ED\uC2DC\uC624.
 
 # Translators please note do not translate the options themselves
 java.launcher.X.usage=\    -Xmixed           \uD63C\uD569 \uBAA8\uB4DC\uB97C \uC2E4\uD589\uD569\uB2C8\uB2E4(\uAE30\uBCF8\uAC12).\n    -Xint             \uD574\uC11D\uB41C \uBAA8\uB4DC\uB9CC \uC2E4\uD589\uD569\uB2C8\uB2E4.\n    -Xbootclasspath:<directories and zip/jar files separated by {0}>\n                      \uBD80\uD2B8\uC2A4\uD2B8\uB7A9 \uD074\uB798\uC2A4 \uBC0F \uB9AC\uC18C\uC2A4\uC5D0 \uB300\uD55C \uAC80\uC0C9 \uACBD\uB85C\uB97C \uC124\uC815\uD569\uB2C8\uB2E4.\n    -Xbootclasspath/a:<directories and zip/jar files separated by {0}>\n                      \uBD80\uD2B8\uC2A4\uD2B8\uB7A9 \uD074\uB798\uC2A4 \uACBD\uB85C \uB05D\uC5D0 \uCD94\uAC00\uD569\uB2C8\uB2E4.\n    -Xbootclasspath/p:<directories and zip/jar files separated by {0}>\n                      \uBD80\uD2B8\uC2A4\uD2B8\uB7A9 \uD074\uB798\uC2A4 \uACBD\uB85C \uC55E\uC5D0 \uCD94\uAC00\uD569\uB2C8\uB2E4.\n    -Xdiag            \uCD94\uAC00 \uC9C4\uB2E8 \uBA54\uC2DC\uC9C0\uB97C \uD45C\uC2DC\uD569\uB2C8\uB2E4.\n    -Xnoclassgc       \uD074\uB798\uC2A4\uC758 \uBD88\uD544\uC694\uD55C \uC815\uBCF4 \uBAA8\uC74C\uC744 \uC0AC\uC6A9 \uC548\uD568\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\n    -Xincgc           \uC99D\uBD84\uC801\uC778 \uBD88\uD544\uC694\uD55C \uC815\uBCF4 \uBAA8\uC74C\uC744 \uC0AC\uC6A9\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\n    -Xloggc:<file>    \uC2DC\uAC04 \uAE30\uB85D\uACFC \uD568\uAED8 \uD30C\uC77C\uC5D0 GC \uC0C1\uD0DC\uB97C \uAE30\uB85D\uD569\uB2C8\uB2E4.\n    -Xbatch           \uBC31\uADF8\uB77C\uC6B4\uB4DC \uCEF4\uD30C\uC77C\uC744 \uC0AC\uC6A9 \uC548\uD568\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\n    -Xms<size>        \uCD08\uAE30 Java \uD799 \uD06C\uAE30\uB97C \uC124\uC815\uD569\uB2C8\uB2E4.\n    -Xmx<size>        \uCD5C\uB300 Java \uD799 \uD06C\uAE30\uB97C \uC124\uC815\uD569\uB2C8\uB2E4.\n    -Xss<size>        Java \uC2A4\uB808\uB4DC \uC2A4\uD0DD \uD06C\uAE30\uB97C \uC124\uC815\uD569\uB2C8\uB2E4.\n    -Xprof            CPU \uD504\uB85C\uD30C\uC77C \uC791\uC131 \uB370\uC774\uD130\uB97C \uCD9C\uB825\uD569\uB2C8\uB2E4.\n    -Xfuture          \uBBF8\uB798 \uAE30\uBCF8\uAC12\uC744 \uC608\uCE21\uD558\uC5EC \uAC00\uC7A5 \uC5C4\uACA9\uD55C \uAC80\uC0AC\uB97C \uC0AC\uC6A9\uC73C\uB85C \uC124\uC815\uD569\uB2C8\uB2E4.\n    -Xrs              Java/VM\uC5D0 \uC758\uD55C OS \uC2E0\uD638 \uC0AC\uC6A9\uC744 \uC904\uC785\uB2C8\uB2E4(\uC124\uBA85\uC11C \uCC38\uC870).\n    -Xcheck:jni       JNI \uD568\uC218\uC5D0 \uB300\uD55C \uCD94\uAC00 \uAC80\uC0AC\uB97C \uC218\uD589\uD569\uB2C8\uB2E4.\n    -Xshare:off       \uACF5\uC720 \uD074\uB798\uC2A4 \uB370\uC774\uD130 \uC0AC\uC6A9\uC744 \uC2DC\uB3C4\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.\n    -Xshare:auto      \uAC00\uB2A5\uD55C \uACBD\uC6B0 \uACF5\uC720 \uD074\uB798\uC2A4 \uB370\uC774\uD130\uB97C \uC0AC\uC6A9\uD569\uB2C8\uB2E4(\uAE30\uBCF8\uAC12).\n    -Xshare:on        \uACF5\uC720 \uD074\uB798\uC2A4 \uB370\uC774\uD130\uB97C \uC0AC\uC6A9\uD574\uC57C \uD569\uB2C8\uB2E4. \uADF8\uB807\uC9C0 \uC54A\uC744 \uACBD\uC6B0 \uC2E4\uD328\uD569\uB2C8\uB2E4.\n    -XshowSettings    \uBAA8\uB4E0 \uC124\uC815\uC744 \uD45C\uC2DC\uD55C \uD6C4 \uACC4\uC18D\uD569\uB2C8\uB2E4.\n    -XshowSettings:all\n                      \uBAA8\uB4E0 \uC124\uC815\uC744 \uD45C\uC2DC\uD55C \uD6C4 \uACC4\uC18D\uD569\uB2C8\uB2E4.\n    -XshowSettings:vm \uBAA8\uB4E0 VM \uAD00\uB828 \uC124\uC815\uC744 \uD45C\uC2DC\uD55C \uD6C4 \uACC4\uC18D\uD569\uB2C8\uB2E4.\n    -XshowSettings:properties\n                      \uBAA8\uB4E0 \uC18D\uC131 \uC124\uC815\uC744 \uD45C\uC2DC\uD55C \uD6C4 \uACC4\uC18D\uD569\uB2C8\uB2E4.\n    -XshowSettings:locale\n                      \uBAA8\uB4E0 \uB85C\uCF00\uC77C \uAD00\uB828 \uC124\uC815\uC744 \uD45C\uC2DC\uD55C \uD6C4 \uACC4\uC18D\uD569\uB2C8\uB2E4.\n\n-X \uC635\uC158\uC740 \uBE44\uD45C\uC900 \uC635\uC158\uC774\uBBC0\uB85C \uD1B5\uC9C0 \uC5C6\uC774 \uBCC0\uACBD\uB420 \uC218 \uC788\uC2B5\uB2C8\uB2E4.\n
@@ -50,5 +50,7 @@
 java.launcher.jar.error1=\uC624\uB958: {0} \uD30C\uC77C\uC744 \uC5F4\uB824\uACE0 \uC2DC\uB3C4\uD558\uB294 \uC911 \uC608\uC0C1\uCE58 \uC54A\uC740 \uC624\uB958\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4.
 java.launcher.jar.error2={0}\uC5D0\uC11C Manifest\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
 java.launcher.jar.error3={0}\uC5D0 \uAE30\uBCF8 Manifest \uC18D\uC131\uC774 \uC5C6\uC2B5\uB2C8\uB2E4.
+java.launcher.jar.error4={0}\uC5D0 Profile manifest \uC18D\uC131\uC774 \uC5C6\uC2B5\uB2C8\uB2E4.
+java.launcher.jar.error5={1}\uC5D0 \uD544\uC694\uD55C {0} \uD504\uB85C\uD30C\uC77C\uC740 \uC774 \uB7F0\uD0C0\uC784\uC5D0\uC11C \uC9C0\uC6D0\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.
 java.launcher.init.error=\uCD08\uAE30\uD654 \uC624\uB958
 java.launcher.javafx.error1=\uC624\uB958: JavaFX launchApplication \uBA54\uC18C\uB4DC\uC5D0 \uC798\uBABB\uB41C \uC11C\uBA85\uC774 \uC788\uC2B5\uB2C8\uB2E4.\\n\uB530\uB77C\uC11C static\uC73C\uB85C \uC120\uC5B8\uD558\uACE0 void \uC720\uD615\uC758 \uAC12\uC744 \uBC18\uD658\uD574\uC57C \uD569\uB2C8\uB2E4.
--- a/jdk/src/share/classes/sun/launcher/resources/launcher_pt_BR.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/launcher/resources/launcher_pt_BR.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -50,5 +50,7 @@
 java.launcher.jar.error1=Erro: ocorreu um erro inesperado ao tentar abrir o arquivo {0}
 java.launcher.jar.error2=manifesto n\u00E3o encontrado em {0}
 java.launcher.jar.error3=nenhum atributo de manifesto principal em {0}
+java.launcher.jar.error4=nenhum atributo de manifesto de Perfil em {0}
+java.launcher.jar.error5=O perfil {0} exigido por {1} n\u00E3o \u00E9 suportado por este runtime
 java.launcher.init.error=erro de inicializa\u00E7\u00E3o
 java.launcher.javafx.error1=Erro: O m\u00E9todo launchApplication do JavaFX tem a assinatura errada. Ele\\ndeve ser declarado como est\u00E1tico e retornar um valor do tipo void
--- a/jdk/src/share/classes/sun/launcher/resources/launcher_sv.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/launcher/resources/launcher_sv.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -50,5 +50,7 @@
 java.launcher.jar.error1=Fel: Ett ov\u00E4ntat fel intr\u00E4ffade n\u00E4r filen {0} skulle \u00F6ppnas
 java.launcher.jar.error2=manifest finns inte i {0}
 java.launcher.jar.error3=inget huvudmanifestattribut i {0}
+java.launcher.jar.error4=inget profilmanifestattribut i {0}
+java.launcher.jar.error5=Profil {0} som kr\u00E4vs av {1} kan inte anv\u00E4ndas av den h\u00E4r k\u00F6rningen
 java.launcher.init.error=initieringsfel
 java.launcher.javafx.error1=Fel: JavaFX launchApplication-metoden har fel signatur, den \nm\u00E5ste ha deklarerats som statisk och returnera ett v\u00E4rde av typen void
--- a/jdk/src/share/classes/sun/launcher/resources/launcher_zh_CN.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/launcher/resources/launcher_zh_CN.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -34,7 +34,7 @@
 java.launcher.ergo.message2  =\                  \u56E0\u4E3A\u60A8\u662F\u5728\u670D\u52A1\u5668\u7C7B\u8BA1\u7B97\u673A\u4E0A\u8FD0\u884C\u3002\n
 
 # Translators please note do not translate the options themselves
-java.launcher.opt.footer     =\    -cp <\u76EE\u5F55\u548C zip/jar \u6587\u4EF6\u7684\u7C7B\u641C\u7D22\u8DEF\u5F84>\n\\    -classpath <\u76EE\u5F55\u548C zip/jar \u6587\u4EF6\u7684\u7C7B\u641C\u7D22\u8DEF\u5F84>\n\\                  \u7528 {0} \u5206\u9694\u7684\u76EE\u5F55, JAR \u6863\u6848\n\\                  \u548C ZIP \u6863\u6848\u5217\u8868, \u7528\u4E8E\u641C\u7D22\u7C7B\u6587\u4EF6\u3002\n\\    -D<\u540D\u79F0>=<\u503C>\n\\                  \u8BBE\u7F6E\u7CFB\u7EDF\u5C5E\u6027\n\\    -verbose:[class|gc|jni]\n\\                  \u542F\u7528\u8BE6\u7EC6\u8F93\u51FA\n\\    -version      \u8F93\u51FA\u4EA7\u54C1\u7248\u672C\u5E76\u9000\u51FA\n\\    -version:<\u503C>\n\\                  \u9700\u8981\u6307\u5B9A\u7684\u7248\u672C\u624D\u80FD\u8FD0\u884C\n\\    -showversion  \u8F93\u51FA\u4EA7\u54C1\u7248\u672C\u5E76\u7EE7\u7EED\n\\    -jre-restrict-search | -no-jre-restrict-search\n\\                  \u5728\u7248\u672C\u641C\u7D22\u4E2D\u5305\u62EC/\u6392\u9664\u7528\u6237\u4E13\u7528 JRE\n\\    -? -help      \u8F93\u51FA\u6B64\u5E2E\u52A9\u6D88\u606F\n\\    -X            \u8F93\u51FA\u975E\u6807\u51C6\u9009\u9879\u7684\u5E2E\u52A9\n\\    -ea[:<packagename>...|:<classname>]\n\\    -enableassertions[:<packagename>...|:<classname>]\n\\                  \u6309\u6307\u5B9A\u7684\u7C92\u5EA6\u542F\u7528\u65AD\u8A00\n\\    -da[:<packagename>...|:<classname>]\n\\    -disableassertions[:<packagename>...|:<classname>]\n\\                  \u7981\u7528\u5177\u6709\u6307\u5B9A\u7C92\u5EA6\u7684\u65AD\u8A00\n\\    -esa | -enablesystemassertions\n\\                  \u542F\u7528\u7CFB\u7EDF\u65AD\u8A00\n\\    -dsa | -disablesystemassertions\n\\                  \u7981\u7528\u7CFB\u7EDF\u65AD\u8A00\n\\    -agentlib:<libname>[=<\u9009\u9879>]\n\\                  \u52A0\u8F7D\u672C\u673A\u4EE3\u7406\u5E93 <libname>, \u4F8B\u5982 -agentlib:hprof\n\\                  \u53E6\u8BF7\u53C2\u9605 -agentlib:jdwp=help \u548C -agentlib:hprof=help\n\\    -agentpath:<pathname>[=<\u9009\u9879>]\n\\                  \u6309\u5B8C\u6574\u8DEF\u5F84\u540D\u52A0\u8F7D\u672C\u673A\u4EE3\u7406\u5E93\n\\    -javaagent:<jarpath>[=<\u9009\u9879>]\n\\                  \u52A0\u8F7D Java \u7F16\u7A0B\u8BED\u8A00\u4EE3\u7406, \u8BF7\u53C2\u9605 java.lang.instrument\n\\    -splash:<imagepath>\n\\                  \u4F7F\u7528\u6307\u5B9A\u7684\u56FE\u50CF\u663E\u793A\u542F\u52A8\u5C4F\u5E55\n\u6709\u5173\u8BE6\u7EC6\u4FE1\u606F, \u8BF7\u53C2\u9605 http://www.oracle.com/technetwork/java/javase/documentation/index.html\u3002
+java.launcher.opt.footer     =\    -cp <\u76EE\u5F55\u548C zip/jar \u6587\u4EF6\u7684\u7C7B\u641C\u7D22\u8DEF\u5F84>\n    -classpath <\u76EE\u5F55\u548C zip/jar \u6587\u4EF6\u7684\u7C7B\u641C\u7D22\u8DEF\u5F84>\n                  \u7528 {0} \u5206\u9694\u7684\u76EE\u5F55, JAR \u6863\u6848\n                  \u548C ZIP \u6863\u6848\u5217\u8868, \u7528\u4E8E\u641C\u7D22\u7C7B\u6587\u4EF6\u3002\n    -D<\u540D\u79F0>=<\u503C>\n                  \u8BBE\u7F6E\u7CFB\u7EDF\u5C5E\u6027\n    -verbose:[class|gc|jni]\n                  \u542F\u7528\u8BE6\u7EC6\u8F93\u51FA\n    -version      \u8F93\u51FA\u4EA7\u54C1\u7248\u672C\u5E76\u9000\u51FA\n    -version:<\u503C>\n                  \u9700\u8981\u6307\u5B9A\u7684\u7248\u672C\u624D\u80FD\u8FD0\u884C\n    -showversion  \u8F93\u51FA\u4EA7\u54C1\u7248\u672C\u5E76\u7EE7\u7EED\n    -jre-restrict-search | -no-jre-restrict-search\n                  \u5728\u7248\u672C\u641C\u7D22\u4E2D\u5305\u62EC/\u6392\u9664\u7528\u6237\u4E13\u7528 JRE\n    -? -help      \u8F93\u51FA\u6B64\u5E2E\u52A9\u6D88\u606F\n    -X            \u8F93\u51FA\u975E\u6807\u51C6\u9009\u9879\u7684\u5E2E\u52A9\n    -ea[:<packagename>...|:<classname>]\n    -enableassertions[:<packagename>...|:<classname>]\n                  \u6309\u6307\u5B9A\u7684\u7C92\u5EA6\u542F\u7528\u65AD\u8A00\n    -da[:<packagename>...|:<classname>]\n    -disableassertions[:<packagename>...|:<classname>]\n                  \u7981\u7528\u5177\u6709\u6307\u5B9A\u7C92\u5EA6\u7684\u65AD\u8A00\n    -esa | -enablesystemassertions\n                  \u542F\u7528\u7CFB\u7EDF\u65AD\u8A00\n    -dsa | -disablesystemassertions\n                  \u7981\u7528\u7CFB\u7EDF\u65AD\u8A00\n    -agentlib:<libname>[=<\u9009\u9879>]\n                  \u52A0\u8F7D\u672C\u673A\u4EE3\u7406\u5E93 <libname>, \u4F8B\u5982 -agentlib:hprof\n                  \u53E6\u8BF7\u53C2\u9605 -agentlib:jdwp=help \u548C -agentlib:hprof=help\n    -agentpath:<pathname>[=<\u9009\u9879>]\n                  \u6309\u5B8C\u6574\u8DEF\u5F84\u540D\u52A0\u8F7D\u672C\u673A\u4EE3\u7406\u5E93\n    -javaagent:<jarpath>[=<\u9009\u9879>]\n                  \u52A0\u8F7D Java \u7F16\u7A0B\u8BED\u8A00\u4EE3\u7406, \u8BF7\u53C2\u9605 java.lang.instrument\n    -splash:<imagepath>\n                  \u4F7F\u7528\u6307\u5B9A\u7684\u56FE\u50CF\u663E\u793A\u542F\u52A8\u5C4F\u5E55\n\u6709\u5173\u8BE6\u7EC6\u4FE1\u606F, \u8BF7\u53C2\u9605 http://www.oracle.com/technetwork/java/javase/documentation/index.html\u3002
 
 # Translators please note do not translate the options themselves
 java.launcher.X.usage=\    -Xmixed           \u6DF7\u5408\u6A21\u5F0F\u6267\u884C (\u9ED8\u8BA4)\n    -Xint             \u4EC5\u89E3\u91CA\u6A21\u5F0F\u6267\u884C\n    -Xbootclasspath:<\u7528 {0} \u5206\u9694\u7684\u76EE\u5F55\u548C zip/jar \u6587\u4EF6>\n                      \u8BBE\u7F6E\u641C\u7D22\u8DEF\u5F84\u4EE5\u5F15\u5BFC\u7C7B\u548C\u8D44\u6E90\n    -Xbootclasspath/a:<\u7528 {0} \u5206\u9694\u7684\u76EE\u5F55\u548C zip/jar \u6587\u4EF6>\n                      \u9644\u52A0\u5728\u5F15\u5BFC\u7C7B\u8DEF\u5F84\u672B\u5C3E\n    -Xbootclasspath/p:<\u7528 {0} \u5206\u9694\u7684\u76EE\u5F55\u548C zip/jar \u6587\u4EF6>\n                      \u7F6E\u4E8E\u5F15\u5BFC\u7C7B\u8DEF\u5F84\u4E4B\u524D\n    -Xdiag            \u663E\u793A\u9644\u52A0\u8BCA\u65AD\u6D88\u606F\n    -Xnoclassgc       \u7981\u7528\u7C7B\u5783\u573E\u6536\u96C6\n    -Xincgc           \u542F\u7528\u589E\u91CF\u5783\u573E\u6536\u96C6\n    -Xloggc:<file>    \u5C06 GC \u72B6\u6001\u8BB0\u5F55\u5728\u6587\u4EF6\u4E2D (\u5E26\u65F6\u95F4\u6233)\n    -Xbatch           \u7981\u7528\u540E\u53F0\u7F16\u8BD1\n    -Xms<size>        \u8BBE\u7F6E\u521D\u59CB Java \u5806\u5927\u5C0F\n    -Xmx<size>        \u8BBE\u7F6E\u6700\u5927 Java \u5806\u5927\u5C0F\n    -Xss<size>        \u8BBE\u7F6E Java \u7EBF\u7A0B\u5806\u6808\u5927\u5C0F\n    -Xprof            \u8F93\u51FA cpu \u914D\u7F6E\u6587\u4EF6\u6570\u636E\n    -Xfuture          \u542F\u7528\u6700\u4E25\u683C\u7684\u68C0\u67E5, \u9884\u671F\u5C06\u6765\u7684\u9ED8\u8BA4\u503C\n    -Xrs              \u51CF\u5C11 Java/VM \u5BF9\u64CD\u4F5C\u7CFB\u7EDF\u4FE1\u53F7\u7684\u4F7F\u7528 (\u8BF7\u53C2\u9605\u6587\u6863)\n    -Xcheck:jni       \u5BF9 JNI \u51FD\u6570\u6267\u884C\u5176\u4ED6\u68C0\u67E5\n    -Xshare:off       \u4E0D\u5C1D\u8BD5\u4F7F\u7528\u5171\u4EAB\u7C7B\u6570\u636E\n    -Xshare:auto      \u5728\u53EF\u80FD\u7684\u60C5\u51B5\u4E0B\u4F7F\u7528\u5171\u4EAB\u7C7B\u6570\u636E (\u9ED8\u8BA4)\n    -Xshare:on        \u8981\u6C42\u4F7F\u7528\u5171\u4EAB\u7C7B\u6570\u636E, \u5426\u5219\u5C06\u5931\u8D25\u3002\n    -XshowSettings    \u663E\u793A\u6240\u6709\u8BBE\u7F6E\u5E76\u7EE7\u7EED\n    -XshowSettings:all\n                      \u663E\u793A\u6240\u6709\u8BBE\u7F6E\u5E76\u7EE7\u7EED\n    -XshowSettings:vm \u663E\u793A\u6240\u6709\u4E0E vm \u76F8\u5173\u7684\u8BBE\u7F6E\u5E76\u7EE7\u7EED\n    -XshowSettings:properties\n                      \u663E\u793A\u6240\u6709\u5C5E\u6027\u8BBE\u7F6E\u5E76\u7EE7\u7EED\n    -XshowSettings:locale\n                      \u663E\u793A\u6240\u6709\u4E0E\u533A\u57DF\u8BBE\u7F6E\u76F8\u5173\u7684\u8BBE\u7F6E\u5E76\u7EE7\u7EED\n\n-X \u9009\u9879\u662F\u975E\u6807\u51C6\u9009\u9879, \u5982\u6709\u66F4\u6539, \u6055\u4E0D\u53E6\u884C\u901A\u77E5\u3002\n
@@ -50,5 +50,7 @@
 java.launcher.jar.error1=\u9519\u8BEF: \u5C1D\u8BD5\u6253\u5F00\u6587\u4EF6{0}\u65F6\u51FA\u73B0\u610F\u5916\u9519\u8BEF
 java.launcher.jar.error2=\u5728{0}\u4E2D\u627E\u4E0D\u5230\u6E05\u5355
 java.launcher.jar.error3={0}\u4E2D\u6CA1\u6709\u4E3B\u6E05\u5355\u5C5E\u6027
+java.launcher.jar.error4={0}\u4E2D\u6CA1\u6709\u914D\u7F6E\u6587\u4EF6\u6E05\u5355\u5C5E\u6027
+java.launcher.jar.error5=\u6B64\u8FD0\u884C\u65F6\u4E0D\u652F\u6301{1}\u6240\u9700\u7684\u914D\u7F6E\u6587\u4EF6{0}
 java.launcher.init.error=\u521D\u59CB\u5316\u9519\u8BEF
 java.launcher.javafx.error1=\u9519\u8BEF: JavaFX launchApplication \u65B9\u6CD5\u5177\u6709\u9519\u8BEF\u7684\u7B7E\u540D, \u5FC5\u987B\n\u5C06\u65B9\u6CD5\u58F0\u660E\u4E3A\u9759\u6001\u65B9\u6CD5\u5E76\u8FD4\u56DE\u7A7A\u7C7B\u578B\u7684\u503C
--- a/jdk/src/share/classes/sun/launcher/resources/launcher_zh_TW.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/launcher/resources/launcher_zh_TW.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -37,7 +37,7 @@
 java.launcher.opt.footer     =\    -cp <class search path of directories and zip/jar files>\n    -classpath <class search path of directories and zip/jar files>\n                  \u4F7F\u7528 {0} \u5340\u9694\u7684\u76EE\u9304\u3001JAR \u5B58\u6A94\u4EE5\u53CA\n                  ZIP \u5B58\u6A94\u6E05\u55AE\u4F86\u641C\u5C0B\u985E\u5225\u6A94\u6848\u3002\n    -D<name>=<value>\n                  \u8A2D\u5B9A\u7CFB\u7D71\u5C6C\u6027\n    -verbose:[class|gc|jni]\n                  \u555F\u7528\u8A73\u7D30\u8CC7\u8A0A\u8F38\u51FA\n    -version      \u5217\u5370\u7522\u54C1\u7248\u672C\u4E26\u7D50\u675F\n    -version:<value>\n                  \u9700\u8981\u6307\u5B9A\u7684\u7248\u672C\u624D\u80FD\u57F7\u884C\n    -showversion  \u5217\u5370\u7522\u54C1\u7248\u672C\u4E26\u7E7C\u7E8C\n    -jre-restrict-search | -no-jre-restrict-search\n                  \u5728\u7248\u672C\u641C\u5C0B\u4E2D\u5305\u62EC/\u6392\u9664\u4F7F\u7528\u8005\u5C08\u7528 JRE\n    -? -help      \u5217\u5370\u6B64\u8AAA\u660E\u8A0A\u606F\n    -X            \u5217\u5370\u975E\u6A19\u6E96\u9078\u9805\u7684\u8AAA\u660E\n    -ea[:<packagename>...|:<classname>]\n    -enableassertions[:<packagename>...|:<classname>]\n                  \u555F\u7528\u542B\u6307\u5B9A\u8A73\u7D30\u7A0B\u5EA6\u7684\u5BA3\u544A\n    -da[:<packagename>...|:<classname>]\n    -disableassertions[:<packagename>...|:<classname>]\n                  \u505C\u7528\u542B\u6307\u5B9A\u8A73\u7D30\u7A0B\u5EA6\u7684\u5BA3\u544A\n    -esa | -enablesystemassertions\n                  \u555F\u7528\u7CFB\u7D71\u5BA3\u544A\n    -dsa | -disablesystemassertions\n                  \u505C\u7528\u7CFB\u7D71\u5BA3\u544A\n    -agentlib:<libname>[=<options>]\n                  \u8F09\u5165\u539F\u751F\u4EE3\u7406\u7A0B\u5F0F\u7A0B\u5F0F\u5EAB <libname>\uFF0C\u4F8B\u5982 -agentlib:hprof\n                  \u53E6\u8ACB\u53C3\u95B1 -agentlib:jdwp=help \u8207 -agentlib:hprof=help\n    -agentpath:<pathname>[=<options>]\n                  \u4F7F\u7528\u5B8C\u6574\u8DEF\u5F91\u540D\u7A31\u8F09\u5165\u539F\u751F\u4EE3\u7406\u7A0B\u5F0F\u7A0B\u5F0F\u5EAB\n    -javaagent:<jarpath>[=<options>]\n                  \u8F09\u5165 Java \u7A0B\u5F0F\u8A9E\u8A00\u4EE3\u7406\u7A0B\u5F0F\uFF0C\u8ACB\u53C3\u95B1 java.lang.instrument\n    -splash:<imagepath>\n                  \u986F\u793A\u6307\u5B9A\u5F71\u50CF\u7684\u8EDF\u9AD4\u8CC7\u8A0A\u756B\u9762\n\u8ACB\u53C3\u95B1 http://www.oracle.com/technetwork/java/javase/documentation/index.html \u66B8\u89E3\u8A73\u7D30\u8CC7\u8A0A\u3002
 
 # Translators please note do not translate the options themselves
-java.launcher.X.usage=\    -Xmixed           \u6DF7\u5408\u6A21\u5F0F\u57F7\u884C (\u9810\u8A2D)\n    -Xint             \u50C5\u9650\u89E3\u8B6F\u6A21\u5F0F\u57F7\u884C\n    -Xbootclasspath:<\u4EE5 {0} \u5206\u9694\u7684\u76EE\u9304\u548C zip/jar \u6A94\u6848>\n                      \u8A2D\u5B9A\u555F\u52D5\u5B89\u88DD\u985E\u5225\u548C\u8CC7\u6E90\u7684\u641C\u5C0B\u8DEF\u5F91\n    -Xbootclasspath/a:<\u4EE5 {0} \u5206\u9694\u7684\u76EE\u9304\u548C zip/jar \u6A94\u6848>\n                      \u9644\u52A0\u5728\u555F\u52D5\u5B89\u88DD\u985E\u5225\u8DEF\u5F91\u7684\u7D50\u5C3E\n    -Xbootclasspath/p:<\u4EE5 {0} \u5206\u9694\u7684\u76EE\u9304\u548C zip/jar \u6A94\u6848>\n                      \u9644\u52A0\u5728\u555F\u52D5\u5B89\u88DD\u985E\u5225\u8DEF\u5F91\u7684\u524D\u9762\n    -Xdiag            \u986F\u793A\u5176\u4ED6\u7684\u8A3A\u65B7\u8A0A\u606F\n    -Xnoclassgc       \u505C\u7528\u985E\u5225\u8CC7\u6E90\u56DE\u6536\n    -Xincgc           \u555F\u7528\u6F38\u9032\u8CC7\u6E90\u56DE\u6536\n    -Xloggc:<file>    \u5229\u7528\u6642\u6233\u5C07 GC \u72C0\u614B\u8A18\u9304\u81F3\u6A94\u6848\u4E2D\n    -Xbatch           \u505C\u7528\u80CC\u666F\u7DE8\u8B6F\n    -Xms<size>        \u8A2D\u5B9A\u8D77\u59CB Java \u5806\u96C6\u5927\u5C0F\n    -Xmx<size>        \u8A2D\u5B9A Java \u5806\u96C6\u5927\u5C0F\u4E0A\u9650\n    -Xss<size>        \u8A2D\u5B9A Java \u57F7\u884C\u7DD2\u5806\u758A\u5927\u5C0F\n    -Xprof            \u8F38\u51FA CPU \u5206\u6790\u8CC7\u6599\n    -Xfuture          \u555F\u7528\u6700\u56B4\u683C\u7684\u6AA2\u67E5\uFF0C\u9810\u5148\u505A\u70BA\u5C07\u4F86\u7684\u9810\u8A2D\n    -Xrs              \u6E1B\u5C11 Java/VM \u4F7F\u7528\u4F5C\u696D\u7CFB\u7D71\u4FE1\u865F (\u8ACB\u53C3\u95B1\u6587\u4EF6)\n    -Xcheck:jni       \u57F7\u884C\u5176\u4ED6\u7684 JNI \u51FD\u6578\u6AA2\u67E5\n    -Xshare:off       \u4E0D\u5617\u8A66\u4F7F\u7528\u5171\u7528\u985E\u5225\u8CC7\u6599\n    -Xshare:auto      \u5118\u53EF\u80FD\u4F7F\u7528\u5171\u7528\u985E\u5225\u8CC7\u6599 (\u9810\u8A2D)\n    -Xshare:on        \u9700\u8981\u4F7F\u7528\u5171\u7528\u985E\u5225\u8CC7\u6599\uFF0C\u5426\u5247\u5931\u6557\u3002\n    -XshowSettings    \u986F\u793A\u6240\u6709\u8A2D\u5B9A\u503C\u4E26\u7E7C\u7E8C\n    -XshowSettings:all\n                      \u986F\u793A\u6240\u6709\u8A2D\u5B9A\u503C\u4E26\u7E7C\u7E8C\n    -XshowSettings:vm \u986F\u793A\u6240\u6709 VM \u76F8\u95DC\u8A2D\u5B9A\u503C\u4E26\u7E7C\u7E8C\n    -XshowSettings:properties\n                      \u986F\u793A\u6240\u6709\u5C6C\u6027\u8A2D\u5B9A\u503C\u4E26\u7E7C\u7E8C\n    -XshowSettings:locale\n                      \u986F\u793A\u6240\u6709\u5730\u5340\u8A2D\u5B9A\u76F8\u95DC\u8A2D\u5B9A\u503C\u4E26\u7E7C\u7E8C\n\n -X \u9078\u9805\u4E0D\u662F\u6A19\u6E96\u9078\u9805\uFF0C\u82E5\u6709\u8B8A\u66F4\u4E0D\u53E6\u884C\u901A\u77E5\u3002\n
+java.launcher.X.usage=\    -Xmixed           \u6DF7\u5408\u6A21\u5F0F\u57F7\u884C (\u9810\u8A2D)\n    -Xint             \u50C5\u9650\u89E3\u8B6F\u6A21\u5F0F\u57F7\u884C\n    -Xbootclasspath:<\u4EE5 {0} \u5206\u9694\u7684\u76EE\u9304\u548C zip/jar \u6A94\u6848>\n                      \u8A2D\u5B9A\u555F\u52D5\u5B89\u88DD\u985E\u5225\u548C\u8CC7\u6E90\u7684\u641C\u5C0B\u8DEF\u5F91\n    -Xbootclasspath/a:<\u4EE5 {0} \u5206\u9694\u7684\u76EE\u9304\u548C zip/jar \u6A94\u6848>\n                      \u9644\u52A0\u5728\u555F\u52D5\u5B89\u88DD\u985E\u5225\u8DEF\u5F91\u7684\u7D50\u5C3E\n    -Xbootclasspath/p:<\u4EE5 {0} \u5206\u9694\u7684\u76EE\u9304\u548C zip/jar \u6A94\u6848>\n                      \u9644\u52A0\u5728\u555F\u52D5\u5B89\u88DD\u985E\u5225\u8DEF\u5F91\u7684\u524D\u9762\n    -Xdiag            \u986F\u793A\u5176\u4ED6\u7684\u8A3A\u65B7\u8A0A\u606F\n    -Xnoclassgc       \u505C\u7528\u985E\u5225\u8CC7\u6E90\u56DE\u6536\n    -Xincgc           \u555F\u7528\u6F38\u9032\u8CC7\u6E90\u56DE\u6536\n    -Xloggc:<file>    \u5229\u7528\u6642\u6233\u5C07 GC \u72C0\u614B\u8A18\u9304\u81F3\u6A94\u6848\u4E2D\n    -Xbatch           \u505C\u7528\u80CC\u666F\u7DE8\u8B6F\n    -Xms<size>        \u8A2D\u5B9A\u8D77\u59CB Java \u5806\u96C6\u5927\u5C0F\n    -Xmx<size>        \u8A2D\u5B9A Java \u5806\u96C6\u5927\u5C0F\u4E0A\u9650\n    -Xss<size>        \u8A2D\u5B9A Java \u57F7\u884C\u7DD2\u5806\u758A\u5927\u5C0F\n    -Xprof            \u8F38\u51FA CPU \u5206\u6790\u8CC7\u6599\n    -Xfuture          \u555F\u7528\u6700\u56B4\u683C\u7684\u6AA2\u67E5\uFF0C\u9810\u5148\u4F5C\u70BA\u5C07\u4F86\u7684\u9810\u8A2D\n    -Xrs              \u6E1B\u5C11 Java/VM \u4F7F\u7528\u4F5C\u696D\u7CFB\u7D71\u4FE1\u865F (\u8ACB\u53C3\u95B1\u6587\u4EF6)\n    -Xcheck:jni       \u57F7\u884C\u5176\u4ED6\u7684 JNI \u51FD\u6578\u6AA2\u67E5\n    -Xshare:off       \u4E0D\u5617\u8A66\u4F7F\u7528\u5171\u7528\u985E\u5225\u8CC7\u6599\n    -Xshare:auto      \u5118\u53EF\u80FD\u4F7F\u7528\u5171\u7528\u985E\u5225\u8CC7\u6599 (\u9810\u8A2D)\n    -Xshare:on        \u9700\u8981\u4F7F\u7528\u5171\u7528\u985E\u5225\u8CC7\u6599\uFF0C\u5426\u5247\u5931\u6557\u3002\n    -XshowSettings    \u986F\u793A\u6240\u6709\u8A2D\u5B9A\u503C\u4E26\u7E7C\u7E8C\n    -XshowSettings:all\n                      \u986F\u793A\u6240\u6709\u8A2D\u5B9A\u503C\u4E26\u7E7C\u7E8C\n    -XshowSettings:vm \u986F\u793A\u6240\u6709 VM \u76F8\u95DC\u8A2D\u5B9A\u503C\u4E26\u7E7C\u7E8C\n    -XshowSettings:properties\n                      \u986F\u793A\u6240\u6709\u5C6C\u6027\u8A2D\u5B9A\u503C\u4E26\u7E7C\u7E8C\n    -XshowSettings:locale\n                      \u986F\u793A\u6240\u6709\u5730\u5340\u8A2D\u5B9A\u76F8\u95DC\u8A2D\u5B9A\u503C\u4E26\u7E7C\u7E8C\n\n -X \u9078\u9805\u4E0D\u662F\u6A19\u6E96\u9078\u9805\uFF0C\u82E5\u6709\u8B8A\u66F4\u4E0D\u53E6\u884C\u901A\u77E5\u3002\n
 
 # Translators please note do not translate the options themselves
 java.launcher.X.macosx.usage=\n\u4E0B\u5217\u662F Mac OS X \u7279\u5B9A\u9078\u9805:\n    -XstartOnFirstThread\n                      \u5728\u7B2C\u4E00\u500B (AppKit) \u57F7\u884C\u7DD2\u57F7\u884C main() \u65B9\u6CD5\n    -Xdock:name=<application name>"\n                      \u8986\u5BEB\u7D50\u5408\u8AAA\u660E\u756B\u9762\u4E2D\u986F\u793A\u7684\u9810\u8A2D\u61C9\u7528\u7A0B\u5F0F\u540D\u7A31\n    -Xdock:icon=<path to icon file>\n                      \u8986\u5BEB\u7D50\u5408\u8AAA\u660E\u756B\u9762\u4E2D\u986F\u793A\u7684\u9810\u8A2D\u5716\u793A\n\n
@@ -50,5 +50,7 @@
 java.launcher.jar.error1=\u932F\u8AA4: \u5617\u8A66\u958B\u555F\u6A94\u6848 {0} \u6642\u767C\u751F\u672A\u9810\u671F\u7684\u932F\u8AA4
 java.launcher.jar.error2=\u5728 {0} \u4E2D\u627E\u4E0D\u5230\u8CC7\u8A0A\u6E05\u55AE
 java.launcher.jar.error3={0} \u4E2D\u6C92\u6709\u4E3B\u8981\u8CC7\u8A0A\u6E05\u55AE\u5C6C\u6027
+java.launcher.jar.error4={0} \u4E2D\u6C92\u6709 Profile \u8CC7\u8A0A\u6E05\u55AE\u5C6C\u6027
+java.launcher.jar.error5=\u6B64\u7A0B\u5F0F\u5BE6\u969B\u57F7\u884C\u4E0D\u652F\u63F4 {1} \u6240\u9700\u7684\u8A2D\u5B9A\u6A94 {0}
 java.launcher.init.error=\u521D\u59CB\u5316\u932F\u8AA4
 java.launcher.javafx.error1=\u932F\u8AA4: JavaFX launchApplication \u65B9\u6CD5\u7684\u7C3D\u7AE0\u932F\u8AA4\uFF0C\u5B83\n\u5FC5\u9808\u5BA3\u544A\u70BA\u975C\u614B\u4E26\u50B3\u56DE void \u985E\u578B\u7684\u503C
--- a/jdk/src/share/classes/sun/misc/FDBigInt.java	Mon Jun 24 14:26:58 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,493 +0,0 @@
-/*
- * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.misc;
-
-/*
- * A really, really simple bigint package
- * tailored to the needs of floating base conversion.
- */
-class FDBigInt {
-    int nWords; // number of words used
-    int data[]; // value: data[0] is least significant
-
-
-    public FDBigInt( int v ){
-        nWords = 1;
-        data = new int[1];
-        data[0] = v;
-    }
-
-    public FDBigInt( long v ){
-        data = new int[2];
-        data[0] = (int)v;
-        data[1] = (int)(v>>>32);
-        nWords = (data[1]==0) ? 1 : 2;
-    }
-
-    public FDBigInt( FDBigInt other ){
-        data = new int[nWords = other.nWords];
-        System.arraycopy( other.data, 0, data, 0, nWords );
-    }
-
-    private FDBigInt( int [] d, int n ){
-        data = d;
-        nWords = n;
-    }
-
-    public FDBigInt( long seed, char digit[], int nd0, int nd ){
-        int n= (nd+8)/9;        // estimate size needed.
-        if ( n < 2 ) n = 2;
-        data = new int[n];      // allocate enough space
-        data[0] = (int)seed;    // starting value
-        data[1] = (int)(seed>>>32);
-        nWords = (data[1]==0) ? 1 : 2;
-        int i = nd0;
-        int limit = nd-5;       // slurp digits 5 at a time.
-        int v;
-        while ( i < limit ){
-            int ilim = i+5;
-            v = (int)digit[i++]-(int)'0';
-            while( i <ilim ){
-                v = 10*v + (int)digit[i++]-(int)'0';
-            }
-            multaddMe( 100000, v); // ... where 100000 is 10^5.
-        }
-        int factor = 1;
-        v = 0;
-        while ( i < nd ){
-            v = 10*v + (int)digit[i++]-(int)'0';
-            factor *= 10;
-        }
-        if ( factor != 1 ){
-            multaddMe( factor, v );
-        }
-    }
-
-    /*
-     * Left shift by c bits.
-     * Shifts this in place.
-     */
-    public void
-    lshiftMe( int c )throws IllegalArgumentException {
-        if ( c <= 0 ){
-            if ( c == 0 )
-                return; // silly.
-            else
-                throw new IllegalArgumentException("negative shift count");
-        }
-        int wordcount = c>>5;
-        int bitcount  = c & 0x1f;
-        int anticount = 32-bitcount;
-        int t[] = data;
-        int s[] = data;
-        if ( nWords+wordcount+1 > t.length ){
-            // reallocate.
-            t = new int[ nWords+wordcount+1 ];
-        }
-        int target = nWords+wordcount;
-        int src    = nWords-1;
-        if ( bitcount == 0 ){
-            // special hack, since an anticount of 32 won't go!
-            System.arraycopy( s, 0, t, wordcount, nWords );
-            target = wordcount-1;
-        } else {
-            t[target--] = s[src]>>>anticount;
-            while ( src >= 1 ){
-                t[target--] = (s[src]<<bitcount) | (s[--src]>>>anticount);
-            }
-            t[target--] = s[src]<<bitcount;
-        }
-        while( target >= 0 ){
-            t[target--] = 0;
-        }
-        data = t;
-        nWords += wordcount + 1;
-        // may have constructed high-order word of 0.
-        // if so, trim it
-        while ( nWords > 1 && data[nWords-1] == 0 )
-            nWords--;
-    }
-
-    /*
-     * normalize this number by shifting until
-     * the MSB of the number is at 0x08000000.
-     * This is in preparation for quoRemIteration, below.
-     * The idea is that, to make division easier, we want the
-     * divisor to be "normalized" -- usually this means shifting
-     * the MSB into the high words sign bit. But because we know that
-     * the quotient will be 0 < q < 10, we would like to arrange that
-     * the dividend not span up into another word of precision.
-     * (This needs to be explained more clearly!)
-     */
-    public int
-    normalizeMe() throws IllegalArgumentException {
-        int src;
-        int wordcount = 0;
-        int bitcount  = 0;
-        int v = 0;
-        for ( src= nWords-1 ; src >= 0 && (v=data[src]) == 0 ; src--){
-            wordcount += 1;
-        }
-        if ( src < 0 ){
-            // oops. Value is zero. Cannot normalize it!
-            throw new IllegalArgumentException("zero value");
-        }
-        /*
-         * In most cases, we assume that wordcount is zero. This only
-         * makes sense, as we try not to maintain any high-order
-         * words full of zeros. In fact, if there are zeros, we will
-         * simply SHORTEN our number at this point. Watch closely...
-         */
-        nWords -= wordcount;
-        /*
-         * Compute how far left we have to shift v s.t. its highest-
-         * order bit is in the right place. Then call lshiftMe to
-         * do the work.
-         */
-        if ( (v & 0xf0000000) != 0 ){
-            // will have to shift up into the next word.
-            // too bad.
-            for( bitcount = 32 ; (v & 0xf0000000) != 0 ; bitcount-- )
-                v >>>= 1;
-        } else {
-            while ( v <= 0x000fffff ){
-                // hack: byte-at-a-time shifting
-                v <<= 8;
-                bitcount += 8;
-            }
-            while ( v <= 0x07ffffff ){
-                v <<= 1;
-                bitcount += 1;
-            }
-        }
-        if ( bitcount != 0 )
-            lshiftMe( bitcount );
-        return bitcount;
-    }
-
-    /*
-     * Multiply a FDBigInt by an int.
-     * Result is a new FDBigInt.
-     */
-    public FDBigInt
-    mult( int iv ) {
-        long v = iv;
-        int r[];
-        long p;
-
-        // guess adequate size of r.
-        r = new int[ ( v * ((long)data[nWords-1]&0xffffffffL) > 0xfffffffL ) ? nWords+1 : nWords ];
-        p = 0L;
-        for( int i=0; i < nWords; i++ ) {
-            p += v * ((long)data[i]&0xffffffffL);
-            r[i] = (int)p;
-            p >>>= 32;
-        }
-        if ( p == 0L){
-            return new FDBigInt( r, nWords );
-        } else {
-            r[nWords] = (int)p;
-            return new FDBigInt( r, nWords+1 );
-        }
-    }
-
-    /*
-     * Multiply a FDBigInt by an int and add another int.
-     * Result is computed in place.
-     * Hope it fits!
-     */
-    public void
-    multaddMe( int iv, int addend ) {
-        long v = iv;
-        long p;
-
-        // unroll 0th iteration, doing addition.
-        p = v * ((long)data[0]&0xffffffffL) + ((long)addend&0xffffffffL);
-        data[0] = (int)p;
-        p >>>= 32;
-        for( int i=1; i < nWords; i++ ) {
-            p += v * ((long)data[i]&0xffffffffL);
-            data[i] = (int)p;
-            p >>>= 32;
-        }
-        if ( p != 0L){
-            data[nWords] = (int)p; // will fail noisily if illegal!
-            nWords++;
-        }
-    }
-
-    /*
-     * Multiply a FDBigInt by another FDBigInt.
-     * Result is a new FDBigInt.
-     */
-    public FDBigInt
-    mult( FDBigInt other ){
-        // crudely guess adequate size for r
-        int r[] = new int[ nWords + other.nWords ];
-        int i;
-        // I think I am promised zeros...
-
-        for( i = 0; i < this.nWords; i++ ){
-            long v = (long)this.data[i] & 0xffffffffL; // UNSIGNED CONVERSION
-            long p = 0L;
-            int j;
-            for( j = 0; j < other.nWords; j++ ){
-                p += ((long)r[i+j]&0xffffffffL) + v*((long)other.data[j]&0xffffffffL); // UNSIGNED CONVERSIONS ALL 'ROUND.
-                r[i+j] = (int)p;
-                p >>>= 32;
-            }
-            r[i+j] = (int)p;
-        }
-        // compute how much of r we actually needed for all that.
-        for ( i = r.length-1; i> 0; i--)
-            if ( r[i] != 0 )
-                break;
-        return new FDBigInt( r, i+1 );
-    }
-
-    /*
-     * Add one FDBigInt to another. Return a FDBigInt
-     */
-    public FDBigInt
-    add( FDBigInt other ){
-        int i;
-        int a[], b[];
-        int n, m;
-        long c = 0L;
-        // arrange such that a.nWords >= b.nWords;
-        // n = a.nWords, m = b.nWords
-        if ( this.nWords >= other.nWords ){
-            a = this.data;
-            n = this.nWords;
-            b = other.data;
-            m = other.nWords;
-        } else {
-            a = other.data;
-            n = other.nWords;
-            b = this.data;
-            m = this.nWords;
-        }
-        int r[] = new int[ n ];
-        for ( i = 0; i < n; i++ ){
-            c += (long)a[i] & 0xffffffffL;
-            if ( i < m ){
-                c += (long)b[i] & 0xffffffffL;
-            }
-            r[i] = (int) c;
-            c >>= 32; // signed shift.
-        }
-        if ( c != 0L ){
-            // oops -- carry out -- need longer result.
-            int s[] = new int[ r.length+1 ];
-            System.arraycopy( r, 0, s, 0, r.length );
-            s[i++] = (int)c;
-            return new FDBigInt( s, i );
-        }
-        return new FDBigInt( r, i );
-    }
-
-    /*
-     * Subtract one FDBigInt from another. Return a FDBigInt
-     * Assert that the result is positive.
-     */
-    public FDBigInt
-    sub( FDBigInt other ){
-        int r[] = new int[ this.nWords ];
-        int i;
-        int n = this.nWords;
-        int m = other.nWords;
-        int nzeros = 0;
-        long c = 0L;
-        for ( i = 0; i < n; i++ ){
-            c += (long)this.data[i] & 0xffffffffL;
-            if ( i < m ){
-                c -= (long)other.data[i] & 0xffffffffL;
-            }
-            if ( ( r[i] = (int) c ) == 0 )
-                nzeros++;
-            else
-                nzeros = 0;
-            c >>= 32; // signed shift
-        }
-        assert c == 0L : c; // borrow out of subtract
-        assert dataInRangeIsZero(i, m, other); // negative result of subtract
-        return new FDBigInt( r, n-nzeros );
-    }
-
-    private static boolean dataInRangeIsZero(int i, int m, FDBigInt other) {
-        while ( i < m )
-            if (other.data[i++] != 0)
-                return false;
-        return true;
-    }
-
-    /*
-     * Compare FDBigInt with another FDBigInt. Return an integer
-     * >0: this > other
-     *  0: this == other
-     * <0: this < other
-     */
-    public int
-    cmp( FDBigInt other ){
-        int i;
-        if ( this.nWords > other.nWords ){
-            // if any of my high-order words is non-zero,
-            // then the answer is evident
-            int j = other.nWords-1;
-            for ( i = this.nWords-1; i > j ; i-- )
-                if ( this.data[i] != 0 ) return 1;
-        }else if ( this.nWords < other.nWords ){
-            // if any of other's high-order words is non-zero,
-            // then the answer is evident
-            int j = this.nWords-1;
-            for ( i = other.nWords-1; i > j ; i-- )
-                if ( other.data[i] != 0 ) return -1;
-        } else{
-            i = this.nWords-1;
-        }
-        for ( ; i > 0 ; i-- )
-            if ( this.data[i] != other.data[i] )
-                break;
-        // careful! want unsigned compare!
-        // use brute force here.
-        int a = this.data[i];
-        int b = other.data[i];
-        if ( a < 0 ){
-            // a is really big, unsigned
-            if ( b < 0 ){
-                return a-b; // both big, negative
-            } else {
-                return 1; // b not big, answer is obvious;
-            }
-        } else {
-            // a is not really big
-            if ( b < 0 ) {
-                // but b is really big
-                return -1;
-            } else {
-                return a - b;
-            }
-        }
-    }
-
-    /*
-     * Compute
-     * q = (int)( this / S )
-     * this = 10 * ( this mod S )
-     * Return q.
-     * This is the iteration step of digit development for output.
-     * We assume that S has been normalized, as above, and that
-     * "this" has been lshift'ed accordingly.
-     * Also assume, of course, that the result, q, can be expressed
-     * as an integer, 0 <= q < 10.
-     */
-    public int
-    quoRemIteration( FDBigInt S )throws IllegalArgumentException {
-        // ensure that this and S have the same number of
-        // digits. If S is properly normalized and q < 10 then
-        // this must be so.
-        if ( nWords != S.nWords ){
-            throw new IllegalArgumentException("disparate values");
-        }
-        // estimate q the obvious way. We will usually be
-        // right. If not, then we're only off by a little and
-        // will re-add.
-        int n = nWords-1;
-        long q = ((long)data[n]&0xffffffffL) / (long)S.data[n];
-        long diff = 0L;
-        for ( int i = 0; i <= n ; i++ ){
-            diff += ((long)data[i]&0xffffffffL) -  q*((long)S.data[i]&0xffffffffL);
-            data[i] = (int)diff;
-            diff >>= 32; // N.B. SIGNED shift.
-        }
-        if ( diff != 0L ) {
-            // damn, damn, damn. q is too big.
-            // add S back in until this turns +. This should
-            // not be very many times!
-            long sum = 0L;
-            while ( sum ==  0L ){
-                sum = 0L;
-                for ( int i = 0; i <= n; i++ ){
-                    sum += ((long)data[i]&0xffffffffL) +  ((long)S.data[i]&0xffffffffL);
-                    data[i] = (int) sum;
-                    sum >>= 32; // Signed or unsigned, answer is 0 or 1
-                }
-                /*
-                 * Originally the following line read
-                 * "if ( sum !=0 && sum != -1 )"
-                 * but that would be wrong, because of the
-                 * treatment of the two values as entirely unsigned,
-                 * it would be impossible for a carry-out to be interpreted
-                 * as -1 -- it would have to be a single-bit carry-out, or
-                 * +1.
-                 */
-                assert sum == 0 || sum == 1 : sum; // carry out of division correction
-                q -= 1;
-            }
-        }
-        // finally, we can multiply this by 10.
-        // it cannot overflow, right, as the high-order word has
-        // at least 4 high-order zeros!
-        long p = 0L;
-        for ( int i = 0; i <= n; i++ ){
-            p += 10*((long)data[i]&0xffffffffL);
-            data[i] = (int)p;
-            p >>= 32; // SIGNED shift.
-        }
-        assert p == 0L : p; // Carry out of *10
-        return (int)q;
-    }
-
-    public long
-    longValue(){
-        // if this can be represented as a long, return the value
-        assert this.nWords > 0 : this.nWords; // longValue confused
-
-        if (this.nWords == 1)
-            return ((long)data[0]&0xffffffffL);
-
-        assert dataInRangeIsZero(2, this.nWords, this); // value too big
-        assert data[1] >= 0;  // value too big
-        return ((long)(data[1]) << 32) | ((long)data[0]&0xffffffffL);
-    }
-
-    public String
-    toString() {
-        StringBuffer r = new StringBuffer(30);
-        r.append('[');
-        int i = Math.min( nWords-1, data.length-1) ;
-        if ( nWords > data.length ){
-            r.append( "("+data.length+"<"+nWords+"!)" );
-        }
-        for( ; i> 0 ; i-- ){
-            r.append( Integer.toHexString( data[i] ) );
-            r.append(' ');
-        }
-        r.append( Integer.toHexString( data[0] ) );
-        r.append(']');
-        return new String( r );
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/misc/FDBigInteger.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,1508 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package sun.misc;
+
+import java.math.BigInteger;
+import java.util.Arrays;
+//@ model import org.jmlspecs.models.JMLMath;
+
+/**
+ * A simple big integer package specifically for floating point base conversion.
+ */
+public /*@ spec_bigint_math @*/ class FDBigInteger {
+
+    //
+    // This class contains many comments that start with "/*@" mark.
+    // They are behavourial specification in
+    // the Java Modelling Language (JML):
+    // http://www.eecs.ucf.edu/~leavens/JML//index.shtml
+    //
+
+    /*@
+    @ public pure model static \bigint UNSIGNED(int v) {
+    @     return v >= 0 ? v : v + (((\bigint)1) << 32);
+    @ }
+    @
+    @ public pure model static \bigint UNSIGNED(long v) {
+    @     return v >= 0 ? v : v + (((\bigint)1) << 64);
+    @ }
+    @
+    @ public pure model static \bigint AP(int[] data, int len) {
+    @     return (\sum int i; 0 <= 0 && i < len; UNSIGNED(data[i]) << (i*32));
+    @ }
+    @
+    @ public pure model static \bigint pow52(int p5, int p2) {
+    @     ghost \bigint v = 1;
+    @     for (int i = 0; i < p5; i++) v *= 5;
+    @     return v << p2;
+    @ }
+    @
+    @ public pure model static \bigint pow10(int p10) {
+    @     return pow52(p10, p10);
+    @ }
+    @*/
+
+    static final int[] SMALL_5_POW = {
+            1,
+            5,
+            5 * 5,
+            5 * 5 * 5,
+            5 * 5 * 5 * 5,
+            5 * 5 * 5 * 5 * 5,
+            5 * 5 * 5 * 5 * 5 * 5,
+            5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5
+    };
+
+    static final long[] LONG_5_POW = {
+            1L,
+            5L,
+            5L * 5,
+            5L * 5 * 5,
+            5L * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+            5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+    };
+
+    // Maximum size of cache of powers of 5 as FDBigIntegers.
+    private static final int MAX_FIVE_POW = 340;
+
+    // Cache of big powers of 5 as FDBigIntegers.
+    private static final FDBigInteger POW_5_CACHE[];
+
+    // Initialize FDBigInteger cache of powers of 5.
+    static {
+        POW_5_CACHE = new FDBigInteger[MAX_FIVE_POW];
+        int i = 0;
+        while (i < SMALL_5_POW.length) {
+            FDBigInteger pow5 = new FDBigInteger(new int[]{SMALL_5_POW[i]}, 0);
+            pow5.makeImmutable();
+            POW_5_CACHE[i] = pow5;
+            i++;
+        }
+        FDBigInteger prev = POW_5_CACHE[i - 1];
+        while (i < MAX_FIVE_POW) {
+            POW_5_CACHE[i] = prev = prev.mult(5);
+            prev.makeImmutable();
+            i++;
+        }
+    }
+
+    // Zero as an FDBigInteger.
+    public static final FDBigInteger ZERO = new FDBigInteger(new int[0], 0);
+
+    // Ensure ZERO is immutable.
+    static {
+        ZERO.makeImmutable();
+    }
+
+    // Constant for casting an int to a long via bitwise AND.
+    private final static long LONG_MASK = 0xffffffffL;
+
+    //@ spec_public non_null;
+    private int data[];  // value: data[0] is least significant
+    //@ spec_public;
+    private int offset;  // number of least significant zero padding ints
+    //@ spec_public;
+    private int nWords;  // data[nWords-1]!=0, all values above are zero
+                 // if nWords==0 -> this FDBigInteger is zero
+    //@ spec_public;
+    private boolean isImmutable = false;
+
+    /*@
+     @ public invariant 0 <= nWords && nWords <= data.length && offset >= 0;
+     @ public invariant nWords == 0 ==> offset == 0;
+     @ public invariant nWords > 0 ==> data[nWords - 1] != 0;
+     @ public invariant (\forall int i; nWords <= i && i < data.length; data[i] == 0);
+     @ public pure model \bigint value() {
+     @     return AP(data, nWords) << (offset*32);
+     @ }
+     @*/
+
+    /**
+     * Constructs an <code>FDBigInteger</code> from data and padding. The
+     * <code>data</code> parameter has the least significant <code>int</code> at
+     * the zeroth index. The <code>offset</code> parameter gives the number of
+     * zero <code>int</code>s to be inferred below the least significant element
+     * of <code>data</code>.
+     *
+     * @param data An array containing all non-zero <code>int</code>s of the value.
+     * @param offset An offset indicating the number of zero <code>int</code>s to pad
+     * below the least significant element of <code>data</code>.
+     */
+    /*@
+     @ requires data != null && offset >= 0;
+     @ ensures this.value() == \old(AP(data, data.length) << (offset*32));
+     @ ensures this.data == \old(data);
+     @*/
+    private FDBigInteger(int[] data, int offset) {
+        this.data = data;
+        this.offset = offset;
+        this.nWords = data.length;
+        trimLeadingZeros();
+    }
+
+    /**
+     * Constructs an <code>FDBigInteger</code> from a starting value and some
+     * decimal digits.
+     *
+     * @param lValue The starting value.
+     * @param digits The decimal digits.
+     * @param kDigits The initial index into <code>digits</code>.
+     * @param nDigits The final index into <code>digits</code>.
+     */
+    /*@
+     @ requires digits != null;
+     @ requires 0 <= kDigits && kDigits <= nDigits && nDigits <= digits.length;
+     @ requires (\forall int i; 0 <= i && i < nDigits; '0' <= digits[i] && digits[i] <= '9');
+     @ ensures this.value() == \old(lValue * pow10(nDigits - kDigits) + (\sum int i; kDigits <= i && i < nDigits; (digits[i] - '0') * pow10(nDigits - i - 1)));
+     @*/
+    public FDBigInteger(long lValue, char[] digits, int kDigits, int nDigits) {
+        int n = Math.max((nDigits + 8) / 9, 2);        // estimate size needed.
+        data = new int[n];      // allocate enough space
+        data[0] = (int) lValue;    // starting value
+        data[1] = (int) (lValue >>> 32);
+        offset = 0;
+        nWords = 2;
+        int i = kDigits;
+        int limit = nDigits - 5;       // slurp digits 5 at a time.
+        int v;
+        while (i < limit) {
+            int ilim = i + 5;
+            v = (int) digits[i++] - (int) '0';
+            while (i < ilim) {
+                v = 10 * v + (int) digits[i++] - (int) '0';
+            }
+            multAddMe(100000, v); // ... where 100000 is 10^5.
+        }
+        int factor = 1;
+        v = 0;
+        while (i < nDigits) {
+            v = 10 * v + (int) digits[i++] - (int) '0';
+            factor *= 10;
+        }
+        if (factor != 1) {
+            multAddMe(factor, v);
+        }
+        trimLeadingZeros();
+    }
+
+    /**
+     * Returns an <code>FDBigInteger</code> with the numerical value
+     * <code>5<sup>p5</sup> * 2<sup>p2</sup></code>.
+     *
+     * @param p5 The exponent of the power-of-five factor.
+     * @param p2 The exponent of the power-of-two factor.
+     * @return <code>5<sup>p5</sup> * 2<sup>p2</sup></code>
+     */
+    /*@
+     @ requires p5 >= 0 && p2 >= 0;
+     @ assignable \nothing;
+     @ ensures \result.value() == \old(pow52(p5, p2));
+     @*/
+    public static FDBigInteger valueOfPow52(int p5, int p2) {
+        if (p5 != 0) {
+            if (p2 == 0) {
+                return big5pow(p5);
+            } else if (p5 < SMALL_5_POW.length) {
+                int pow5 = SMALL_5_POW[p5];
+                int wordcount = p2 >> 5;
+                int bitcount = p2 & 0x1f;
+                if (bitcount == 0) {
+                    return new FDBigInteger(new int[]{pow5}, wordcount);
+                } else {
+                    return new FDBigInteger(new int[]{
+                            pow5 << bitcount,
+                            pow5 >>> (32 - bitcount)
+                    }, wordcount);
+                }
+            } else {
+                return big5pow(p5).leftShift(p2);
+            }
+        } else {
+            return valueOfPow2(p2);
+        }
+    }
+
+    /**
+     * Returns an <code>FDBigInteger</code> with the numerical value
+     * <code>value * 5<sup>p5</sup> * 2<sup>p2</sup></code>.
+     *
+     * @param value The constant factor.
+     * @param p5 The exponent of the power-of-five factor.
+     * @param p2 The exponent of the power-of-two factor.
+     * @return <code>value * 5<sup>p5</sup> * 2<sup>p2</sup></code>
+     */
+    /*@
+     @ requires p5 >= 0 && p2 >= 0;
+     @ assignable \nothing;
+     @ ensures \result.value() == \old(UNSIGNED(value) * pow52(p5, p2));
+     @*/
+    public static FDBigInteger valueOfMulPow52(long value, int p5, int p2) {
+        assert p5 >= 0 : p5;
+        assert p2 >= 0 : p2;
+        int v0 = (int) value;
+        int v1 = (int) (value >>> 32);
+        int wordcount = p2 >> 5;
+        int bitcount = p2 & 0x1f;
+        if (p5 != 0) {
+            if (p5 < SMALL_5_POW.length) {
+                long pow5 = SMALL_5_POW[p5] & LONG_MASK;
+                long carry = (v0 & LONG_MASK) * pow5;
+                v0 = (int) carry;
+                carry >>>= 32;
+                carry = (v1 & LONG_MASK) * pow5 + carry;
+                v1 = (int) carry;
+                int v2 = (int) (carry >>> 32);
+                if (bitcount == 0) {
+                    return new FDBigInteger(new int[]{v0, v1, v2}, wordcount);
+                } else {
+                    return new FDBigInteger(new int[]{
+                            v0 << bitcount,
+                            (v1 << bitcount) | (v0 >>> (32 - bitcount)),
+                            (v2 << bitcount) | (v1 >>> (32 - bitcount)),
+                            v2 >>> (32 - bitcount)
+                    }, wordcount);
+                }
+            } else {
+                FDBigInteger pow5 = big5pow(p5);
+                int[] r;
+                if (v1 == 0) {
+                    r = new int[pow5.nWords + 1 + ((p2 != 0) ? 1 : 0)];
+                    mult(pow5.data, pow5.nWords, v0, r);
+                } else {
+                    r = new int[pow5.nWords + 2 + ((p2 != 0) ? 1 : 0)];
+                    mult(pow5.data, pow5.nWords, v0, v1, r);
+                }
+                return (new FDBigInteger(r, pow5.offset)).leftShift(p2);
+            }
+        } else if (p2 != 0) {
+            if (bitcount == 0) {
+                return new FDBigInteger(new int[]{v0, v1}, wordcount);
+            } else {
+                return new FDBigInteger(new int[]{
+                         v0 << bitcount,
+                        (v1 << bitcount) | (v0 >>> (32 - bitcount)),
+                        v1 >>> (32 - bitcount)
+                }, wordcount);
+            }
+        }
+        return new FDBigInteger(new int[]{v0, v1}, 0);
+    }
+
+    /**
+     * Returns an <code>FDBigInteger</code> with the numerical value
+     * <code>2<sup>p2</sup></code>.
+     *
+     * @param p2 The exponent of 2.
+     * @return <code>2<sup>p2</sup></code>
+     */
+    /*@
+     @ requires p2 >= 0;
+     @ assignable \nothing;
+     @ ensures \result.value() == pow52(0, p2);
+     @*/
+    private static FDBigInteger valueOfPow2(int p2) {
+        int wordcount = p2 >> 5;
+        int bitcount = p2 & 0x1f;
+        return new FDBigInteger(new int[]{1 << bitcount}, wordcount);
+    }
+
+    /**
+     * Removes all leading zeros from this <code>FDBigInteger</code> adjusting
+     * the offset and number of non-zero leading words accordingly.
+     */
+    /*@
+     @ requires data != null;
+     @ requires 0 <= nWords && nWords <= data.length && offset >= 0;
+     @ requires nWords == 0 ==> offset == 0;
+     @ ensures nWords == 0 ==> offset == 0;
+     @ ensures nWords > 0 ==> data[nWords - 1] != 0;
+     @*/
+    private /*@ helper @*/ void trimLeadingZeros() {
+        int i = nWords;
+        if (i > 0 && (data[--i] == 0)) {
+            //for (; i > 0 && data[i - 1] == 0; i--) ;
+            while(i > 0 && data[i - 1] == 0) {
+                i--;
+            }
+            this.nWords = i;
+            if (i == 0) { // all words are zero
+                this.offset = 0;
+            }
+        }
+    }
+
+    /**
+     * Retrieves the normalization bias of the <code>FDBigIntger</code>. The
+     * normalization bias is a left shift such that after it the highest word
+     * of the value will have the 4 highest bits equal to zero:
+     * <code>(highestWord & 0xf0000000) == 0</code>, but the next bit should be 1
+     * <code>(highestWord & 0x08000000) != 0</code>.
+     *
+     * @return The normalization bias.
+     */
+    /*@
+     @ requires this.value() > 0;
+     @*/
+    public /*@ pure @*/ int getNormalizationBias() {
+        if (nWords == 0) {
+            throw new IllegalArgumentException("Zero value cannot be normalized");
+        }
+        int zeros = Integer.numberOfLeadingZeros(data[nWords - 1]);
+        return (zeros < 4) ? 28 + zeros : zeros - 4;
+    }
+
+    // TODO: Why is anticount param needed if it is always 32 - bitcount?
+    /**
+     * Left shifts the contents of one int array into another.
+     *
+     * @param src The source array.
+     * @param idx The initial index of the source array.
+     * @param result The destination array.
+     * @param bitcount The left shift.
+     * @param anticount The left anti-shift, e.g., <code>32-bitcount</code>.
+     * @param prev The prior source value.
+     */
+    /*@
+     @ requires 0 < bitcount && bitcount < 32 && anticount == 32 - bitcount;
+     @ requires src.length >= idx && result.length > idx;
+     @ assignable result[*];
+     @ ensures AP(result, \old(idx + 1)) == \old((AP(src, idx) + UNSIGNED(prev) << (idx*32)) << bitcount);
+     @*/
+    private static void leftShift(int[] src, int idx, int result[], int bitcount, int anticount, int prev){
+        for (; idx > 0; idx--) {
+            int v = (prev << bitcount);
+            prev = src[idx - 1];
+            v |= (prev >>> anticount);
+            result[idx] = v;
+        }
+        int v = prev << bitcount;
+        result[0] = v;
+    }
+
+    /**
+     * Shifts this <code>FDBigInteger</code> to the left. The shift is performed
+     * in-place unless the <code>FDBigInteger</code> is immutable in which case
+     * a new instance of <code>FDBigInteger</code> is returned.
+     *
+     * @param shift The number of bits to shift left.
+     * @return The shifted <code>FDBigInteger</code>.
+     */
+    /*@
+     @ requires this.value() == 0 || shift == 0;
+     @ assignable \nothing;
+     @ ensures \result == this;
+     @
+     @  also
+     @
+     @ requires this.value() > 0 && shift > 0 && this.isImmutable;
+     @ assignable \nothing;
+     @ ensures \result.value() == \old(this.value() << shift);
+     @
+     @  also
+     @
+     @ requires this.value() > 0 && shift > 0 && this.isImmutable;
+     @ assignable \nothing;
+     @ ensures \result == this;
+     @ ensures \result.value() == \old(this.value() << shift);
+     @*/
+    public FDBigInteger leftShift(int shift) {
+        if (shift == 0 || nWords == 0) {
+            return this;
+        }
+        int wordcount = shift >> 5;
+        int bitcount = shift & 0x1f;
+        if (this.isImmutable) {
+            if (bitcount == 0) {
+                return new FDBigInteger(Arrays.copyOf(data, nWords), offset + wordcount);
+            } else {
+                int anticount = 32 - bitcount;
+                int idx = nWords - 1;
+                int prev = data[idx];
+                int hi = prev >>> anticount;
+                int[] result;
+                if (hi != 0) {
+                    result = new int[nWords + 1];
+                    result[nWords] = hi;
+                } else {
+                    result = new int[nWords];
+                }
+                leftShift(data,idx,result,bitcount,anticount,prev);
+                return new FDBigInteger(result, offset + wordcount);
+            }
+        } else {
+            if (bitcount != 0) {
+                int anticount = 32 - bitcount;
+                if ((data[0] << bitcount) == 0) {
+                    int idx = 0;
+                    int prev = data[idx];
+                    for (; idx < nWords - 1; idx++) {
+                        int v = (prev >>> anticount);
+                        prev = data[idx + 1];
+                        v |= (prev << bitcount);
+                        data[idx] = v;
+                    }
+                    int v = prev >>> anticount;
+                    data[idx] = v;
+                    if(v==0) {
+                        nWords--;
+                    }
+                    offset++;
+                } else {
+                    int idx = nWords - 1;
+                    int prev = data[idx];
+                    int hi = prev >>> anticount;
+                    int[] result = data;
+                    int[] src = data;
+                    if (hi != 0) {
+                        if(nWords == data.length) {
+                            data = result = new int[nWords + 1];
+                        }
+                        result[nWords++] = hi;
+                    }
+                    leftShift(src,idx,result,bitcount,anticount,prev);
+                }
+            }
+            offset += wordcount;
+            return this;
+        }
+    }
+
+    /**
+     * Returns the number of <code>int</code>s this <code>FDBigInteger</code> represents.
+     *
+     * @return Number of <code>int</code>s required to represent this <code>FDBigInteger</code>.
+     */
+    /*@
+     @ requires this.value() == 0;
+     @ ensures \result == 0;
+     @
+     @  also
+     @
+     @ requires this.value() > 0;
+     @ ensures ((\bigint)1) << (\result - 1) <= this.value() && this.value() <= ((\bigint)1) << \result;
+     @*/
+    private /*@ pure @*/ int size() {
+        return nWords + offset;
+    }
+
+
+    /**
+     * Computes
+     * <pre>
+     * q = (int)( this / S )
+     * this = 10 * ( this mod S )
+     * Return q.
+     * </pre>
+     * This is the iteration step of digit development for output.
+     * We assume that S has been normalized, as above, and that
+     * "this" has been left-shifted accordingly.
+     * Also assumed, of course, is that the result, q, can be expressed
+     * as an integer, 0 <= q < 10.
+     *
+     * @param The divisor of this <code>FDBigInteger</code>.
+     * @return <code>q = (int)(this / S)</code>.
+     */
+    /*@
+     @ requires !this.isImmutable;
+     @ requires this.size() <= S.size();
+     @ requires this.data.length + this.offset >= S.size();
+     @ requires S.value() >= ((\bigint)1) << (S.size()*32 - 4);
+     @ assignable this.nWords, this.offset, this.data, this.data[*];
+     @ ensures \result == \old(this.value() / S.value());
+     @ ensures this.value() == \old(10 * (this.value() % S.value()));
+     @*/
+    public int quoRemIteration(FDBigInteger S) throws IllegalArgumentException {
+        assert !this.isImmutable : "cannot modify immutable value";
+        // ensure that this and S have the same number of
+        // digits. If S is properly normalized and q < 10 then
+        // this must be so.
+        int thSize = this.size();
+        int sSize = S.size();
+        if (thSize < sSize) {
+            // this value is significantly less than S, result of division is zero.
+            // just mult this by 10.
+            int p = multAndCarryBy10(this.data, this.nWords, this.data);
+            if(p!=0) {
+                this.data[nWords++] = p;
+            } else {
+                trimLeadingZeros();
+            }
+            return 0;
+        } else if (thSize > sSize) {
+            throw new IllegalArgumentException("disparate values");
+        }
+        // estimate q the obvious way. We will usually be
+        // right. If not, then we're only off by a little and
+        // will re-add.
+        long q = (this.data[this.nWords - 1] & LONG_MASK) / (S.data[S.nWords - 1] & LONG_MASK);
+        long diff = multDiffMe(q, S);
+        if (diff != 0L) {
+            //@ assert q != 0;
+            //@ assert this.offset == \old(Math.min(this.offset, S.offset));
+            //@ assert this.offset <= S.offset;
+
+            // q is too big.
+            // add S back in until this turns +. This should
+            // not be very many times!
+            long sum = 0L;
+            int tStart = S.offset - this.offset;
+            //@ assert tStart >= 0;
+            int[] sd = S.data;
+            int[] td = this.data;
+            while (sum == 0L) {
+                for (int sIndex = 0, tIndex = tStart; tIndex < this.nWords; sIndex++, tIndex++) {
+                    sum += (td[tIndex] & LONG_MASK) + (sd[sIndex] & LONG_MASK);
+                    td[tIndex] = (int) sum;
+                    sum >>>= 32; // Signed or unsigned, answer is 0 or 1
+                }
+                //
+                // Originally the following line read
+                // "if ( sum !=0 && sum != -1 )"
+                // but that would be wrong, because of the
+                // treatment of the two values as entirely unsigned,
+                // it would be impossible for a carry-out to be interpreted
+                // as -1 -- it would have to be a single-bit carry-out, or +1.
+                //
+                assert sum == 0 || sum == 1 : sum; // carry out of division correction
+                q -= 1;
+            }
+        }
+        // finally, we can multiply this by 10.
+        // it cannot overflow, right, as the high-order word has
+        // at least 4 high-order zeros!
+        int p = multAndCarryBy10(this.data, this.nWords, this.data);
+        assert p == 0 : p; // Carry out of *10
+        trimLeadingZeros();
+        return (int) q;
+    }
+
+    /**
+     * Multiplies this <code>FDBigInteger</code> by 10. The operation will be
+     * performed in place unless the <code>FDBigInteger</code> is immutable in
+     * which case a new <code>FDBigInteger</code> will be returned.
+     *
+     * @return The <code>FDBigInteger</code> multiplied by 10.
+     */
+    /*@
+     @ requires this.value() == 0;
+     @ assignable \nothing;
+     @ ensures \result == this;
+     @
+     @  also
+     @
+     @ requires this.value() > 0 && this.isImmutable;
+     @ assignable \nothing;
+     @ ensures \result.value() == \old(this.value() * 10);
+     @
+     @  also
+     @
+     @ requires this.value() > 0 && !this.isImmutable;
+     @ assignable this.nWords, this.data, this.data[*];
+     @ ensures \result == this;
+     @ ensures \result.value() == \old(this.value() * 10);
+     @*/
+    public FDBigInteger multBy10() {
+        if (nWords == 0) {
+            return this;
+        }
+        if (isImmutable) {
+            int[] res = new int[nWords + 1];
+            res[nWords] = multAndCarryBy10(data, nWords, res);
+            return new FDBigInteger(res, offset);
+        } else {
+            int p = multAndCarryBy10(this.data, this.nWords, this.data);
+            if (p != 0) {
+                if (nWords == data.length) {
+                    if (data[0] == 0) {
+                        System.arraycopy(data, 1, data, 0, --nWords);
+                        offset++;
+                    } else {
+                        data = Arrays.copyOf(data, data.length + 1);
+                    }
+                }
+                data[nWords++] = p;
+            } else {
+                trimLeadingZeros();
+            }
+            return this;
+        }
+    }
+
+    /**
+     * Multiplies this <code>FDBigInteger</code> by
+     * <code>5<sup>p5</sup> * 2<sup>p2</sup></code>. The operation will be
+     * performed in place if possible, otherwise a new <code>FDBigInteger</code>
+     * will be returned.
+     *
+     * @param p5 The exponent of the power-of-five factor.
+     * @param p2 The exponent of the power-of-two factor.
+     * @return
+     */
+    /*@
+     @ requires this.value() == 0 || p5 == 0 && p2 == 0;
+     @ assignable \nothing;
+     @ ensures \result == this;
+     @
+     @  also
+     @
+     @ requires this.value() > 0 && (p5 > 0 && p2 >= 0 || p5 == 0 && p2 > 0 && this.isImmutable);
+     @ assignable \nothing;
+     @ ensures \result.value() == \old(this.value() * pow52(p5, p2));
+     @
+     @  also
+     @
+     @ requires this.value() > 0 && p5 == 0 && p2 > 0 && !this.isImmutable;
+     @ assignable this.nWords, this.data, this.data[*];
+     @ ensures \result == this;
+     @ ensures \result.value() == \old(this.value() * pow52(p5, p2));
+     @*/
+    public FDBigInteger multByPow52(int p5, int p2) {
+        if (this.nWords == 0) {
+            return this;
+        }
+        FDBigInteger res = this;
+        if (p5 != 0) {
+            int[] r;
+            int extraSize = (p2 != 0) ? 1 : 0;
+            if (p5 < SMALL_5_POW.length) {
+                r = new int[this.nWords + 1 + extraSize];
+                mult(this.data, this.nWords, SMALL_5_POW[p5], r);
+                res = new FDBigInteger(r, this.offset);
+            } else {
+                FDBigInteger pow5 = big5pow(p5);
+                r = new int[this.nWords + pow5.size() + extraSize];
+                mult(this.data, this.nWords, pow5.data, pow5.nWords, r);
+                res = new FDBigInteger(r, this.offset + pow5.offset);
+            }
+        }
+        return res.leftShift(p2);
+    }
+
+    /**
+     * Multiplies two big integers represented as int arrays.
+     *
+     * @param s1 The first array factor.
+     * @param s1Len The number of elements of <code>s1</code> to use.
+     * @param s2 The second array factor.
+     * @param s2Len The number of elements of <code>s2</code> to use.
+     * @param dst The product array.
+     */
+    /*@
+     @ requires s1 != dst && s2 != dst;
+     @ requires s1.length >= s1Len && s2.length >= s2Len && dst.length >= s1Len + s2Len;
+     @ assignable dst[0 .. s1Len + s2Len - 1];
+     @ ensures AP(dst, s1Len + s2Len) == \old(AP(s1, s1Len) * AP(s2, s2Len));
+     @*/
+    private static void mult(int[] s1, int s1Len, int[] s2, int s2Len, int[] dst) {
+        for (int i = 0; i < s1Len; i++) {
+            long v = s1[i] & LONG_MASK;
+            long p = 0L;
+            for (int j = 0; j < s2Len; j++) {
+                p += (dst[i + j] & LONG_MASK) + v * (s2[j] & LONG_MASK);
+                dst[i + j] = (int) p;
+                p >>>= 32;
+            }
+            dst[i + s2Len] = (int) p;
+        }
+    }
+
+    /**
+     * Subtracts the supplied <code>FDBigInteger</code> subtrahend from this
+     * <code>FDBigInteger</code>. Assert that the result is positive.
+     * If the subtrahend is immutable, store the result in this(minuend).
+     * If this(minuend) is immutable a new <code>FDBigInteger</code> is created.
+     *
+     * @param subtrahend The <code>FDBigInteger</code> to be subtracted.
+     * @return This <code>FDBigInteger</code> less the subtrahend.
+     */
+    /*@
+     @ requires this.isImmutable;
+     @ requires this.value() >= subtrahend.value();
+     @ assignable \nothing;
+     @ ensures \result.value() == \old(this.value() - subtrahend.value());
+     @
+     @  also
+     @
+     @ requires !subtrahend.isImmutable;
+     @ requires this.value() >= subtrahend.value();
+     @ assignable this.nWords, this.offset, this.data, this.data[*];
+     @ ensures \result == this;
+     @ ensures \result.value() == \old(this.value() - subtrahend.value());
+     @*/
+    public FDBigInteger leftInplaceSub(FDBigInteger subtrahend) {
+        assert this.size() >= subtrahend.size() : "result should be positive";
+        FDBigInteger minuend;
+        if (this.isImmutable) {
+            minuend = new FDBigInteger(this.data, this.offset);
+        } else {
+            minuend = this;
+        }
+        int offsetDiff = subtrahend.offset - minuend.offset;
+        int[] sData = subtrahend.data;
+        int[] mData = minuend.data;
+        int subLen = subtrahend.nWords;
+        int minLen = minuend.nWords;
+        if (offsetDiff < 0) {
+            // need to expand minuend
+            int rLen = minLen - offsetDiff;
+            if (rLen < mData.length) {
+                System.arraycopy(mData, 0, mData, -offsetDiff, minLen);
+                Arrays.fill(mData, 0, -offsetDiff, 0);
+            } else {
+                int[] r = new int[rLen];
+                System.arraycopy(mData, 0, r, -offsetDiff, minLen);
+                minuend.data = mData = r;
+            }
+            minuend.offset = subtrahend.offset;
+            minuend.nWords = minLen = rLen;
+            offsetDiff = 0;
+        }
+        long borrow = 0L;
+        int mIndex = offsetDiff;
+        for (int sIndex = 0; sIndex < subLen && mIndex < minLen; sIndex++, mIndex++) {
+            long diff = (mData[mIndex] & LONG_MASK) - (sData[sIndex] & LONG_MASK) + borrow;
+            mData[mIndex] = (int) diff;
+            borrow = diff >> 32; // signed shift
+        }
+        for (; borrow != 0 && mIndex < minLen; mIndex++) {
+            long diff = (mData[mIndex] & LONG_MASK) + borrow;
+            mData[mIndex] = (int) diff;
+            borrow = diff >> 32; // signed shift
+        }
+        assert borrow == 0L : borrow; // borrow out of subtract,
+        // result should be positive
+        minuend.trimLeadingZeros();
+        return minuend;
+    }
+
+    /**
+     * Subtracts the supplied <code>FDBigInteger</code> subtrahend from this
+     * <code>FDBigInteger</code>. Assert that the result is positive.
+     * If the this(minuend) is immutable, store the result in subtrahend.
+     * If subtrahend is immutable a new <code>FDBigInteger</code> is created.
+     *
+     * @param subtrahend The <code>FDBigInteger</code> to be subtracted.
+     * @return This <code>FDBigInteger</code> less the subtrahend.
+     */
+    /*@
+     @ requires subtrahend.isImmutable;
+     @ requires this.value() >= subtrahend.value();
+     @ assignable \nothing;
+     @ ensures \result.value() == \old(this.value() - subtrahend.value());
+     @
+     @  also
+     @
+     @ requires !subtrahend.isImmutable;
+     @ requires this.value() >= subtrahend.value();
+     @ assignable subtrahend.nWords, subtrahend.offset, subtrahend.data, subtrahend.data[*];
+     @ ensures \result == subtrahend;
+     @ ensures \result.value() == \old(this.value() - subtrahend.value());
+     @*/
+    public FDBigInteger rightInplaceSub(FDBigInteger subtrahend) {
+        assert this.size() >= subtrahend.size() : "result should be positive";
+        FDBigInteger minuend = this;
+        if (subtrahend.isImmutable) {
+            subtrahend = new FDBigInteger(subtrahend.data, subtrahend.offset);
+        }
+        int offsetDiff = minuend.offset - subtrahend.offset;
+        int[] sData = subtrahend.data;
+        int[] mData = minuend.data;
+        int subLen = subtrahend.nWords;
+        int minLen = minuend.nWords;
+        if (offsetDiff < 0) {
+            int rLen = minLen;
+            if (rLen < sData.length) {
+                System.arraycopy(sData, 0, sData, -offsetDiff, subLen);
+                Arrays.fill(sData, 0, -offsetDiff, 0);
+            } else {
+                int[] r = new int[rLen];
+                System.arraycopy(sData, 0, r, -offsetDiff, subLen);
+                subtrahend.data = sData = r;
+            }
+            subtrahend.offset = minuend.offset;
+            subLen -= offsetDiff;
+            offsetDiff = 0;
+        } else {
+            int rLen = minLen + offsetDiff;
+            if (rLen >= sData.length) {
+                subtrahend.data = sData = Arrays.copyOf(sData, rLen);
+            }
+        }
+        //@ assert minuend == this && minuend.value() == \old(this.value());
+        //@ assert mData == minuend.data && minLen == minuend.nWords;
+        //@ assert subtrahend.offset + subtrahend.data.length >= minuend.size();
+        //@ assert sData == subtrahend.data;
+        //@ assert AP(subtrahend.data, subtrahend.data.length) << subtrahend.offset == \old(subtrahend.value());
+        //@ assert subtrahend.offset == Math.min(\old(this.offset), minuend.offset);
+        //@ assert offsetDiff == minuend.offset - subtrahend.offset;
+        //@ assert 0 <= offsetDiff && offsetDiff + minLen <= sData.length;
+        int sIndex = 0;
+        long borrow = 0L;
+        for (; sIndex < offsetDiff; sIndex++) {
+            long diff = 0L - (sData[sIndex] & LONG_MASK) + borrow;
+            sData[sIndex] = (int) diff;
+            borrow = diff >> 32; // signed shift
+        }
+        //@ assert sIndex == offsetDiff;
+        for (int mIndex = 0; mIndex < minLen; sIndex++, mIndex++) {
+            //@ assert sIndex == offsetDiff + mIndex;
+            long diff = (mData[mIndex] & LONG_MASK) - (sData[sIndex] & LONG_MASK) + borrow;
+            sData[sIndex] = (int) diff;
+            borrow = diff >> 32; // signed shift
+        }
+        assert borrow == 0L : borrow; // borrow out of subtract,
+        // result should be positive
+        subtrahend.nWords = sIndex;
+        subtrahend.trimLeadingZeros();
+        return subtrahend;
+
+    }
+
+    /**
+     * Determines whether all elements of an array are zero for all indices less
+     * than a given index.
+     *
+     * @param a The array to be examined.
+     * @param from The index strictly below which elements are to be examined.
+     * @return Zero if all elements in range are zero, 1 otherwise.
+     */
+    /*@
+     @ requires 0 <= from && from <= a.length;
+     @ ensures \result == (AP(a, from) == 0 ? 0 : 1);
+     @*/
+    private /*@ pure @*/ static int checkZeroTail(int[] a, int from) {
+        while (from > 0) {
+            if (a[--from] != 0) {
+                return 1;
+            }
+        }
+        return 0;
+    }
+
+    /**
+     * Compares the parameter with this <code>FDBigInteger</code>. Returns an
+     * integer accordingly as:
+     * <pre>
+     * >0: this > other
+     *  0: this == other
+     * <0: this < other
+     * </pre>
+     *
+     * @param other The <code>FDBigInteger</code> to compare.
+     * @return A negative value, zero, or a positive value according to the
+     * result of the comparison.
+     */
+    /*@
+     @ ensures \result == (this.value() < other.value() ? -1 : this.value() > other.value() ? +1 : 0);
+     @*/
+    public /*@ pure @*/ int cmp(FDBigInteger other) {
+        int aSize = nWords + offset;
+        int bSize = other.nWords + other.offset;
+        if (aSize > bSize) {
+            return 1;
+        } else if (aSize < bSize) {
+            return -1;
+        }
+        int aLen = nWords;
+        int bLen = other.nWords;
+        while (aLen > 0 && bLen > 0) {
+            int a = data[--aLen];
+            int b = other.data[--bLen];
+            if (a != b) {
+                return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;
+            }
+        }
+        if (aLen > 0) {
+            return checkZeroTail(data, aLen);
+        }
+        if (bLen > 0) {
+            return -checkZeroTail(other.data, bLen);
+        }
+        return 0;
+    }
+
+    /**
+     * Compares this <code>FDBigInteger</code> with
+     * <code>5<sup>p5</sup> * 2<sup>p2</sup></code>.
+     * Returns an integer accordingly as:
+     * <pre>
+     * >0: this > other
+     *  0: this == other
+     * <0: this < other
+     * </pre>
+     * @param p5 The exponent of the power-of-five factor.
+     * @param p2 The exponent of the power-of-two factor.
+     * @return A negative value, zero, or a positive value according to the
+     * result of the comparison.
+     */
+    /*@
+     @ requires p5 >= 0 && p2 >= 0;
+     @ ensures \result == (this.value() < pow52(p5, p2) ? -1 : this.value() >  pow52(p5, p2) ? +1 : 0);
+     @*/
+    public /*@ pure @*/ int cmpPow52(int p5, int p2) {
+        if (p5 == 0) {
+            int wordcount = p2 >> 5;
+            int bitcount = p2 & 0x1f;
+            int size = this.nWords + this.offset;
+            if (size > wordcount + 1) {
+                return 1;
+            } else if (size < wordcount + 1) {
+                return -1;
+            }
+            int a = this.data[this.nWords -1];
+            int b = 1 << bitcount;
+            if (a != b) {
+                return ( (a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;
+            }
+            return checkZeroTail(this.data, this.nWords - 1);
+        }
+        return this.cmp(big5pow(p5).leftShift(p2));
+    }
+
+    /**
+     * Compares this <code>FDBigInteger</code> with <code>x + y</code>. Returns a
+     * value according to the comparison as:
+     * <pre>
+     * -1: this <  x + y
+     *  0: this == x + y
+     *  1: this >  x + y
+     * </pre>
+     * @param x The first addend of the sum to compare.
+     * @param y The second addend of the sum to compare.
+     * @return -1, 0, or 1 according to the result of the comparison.
+     */
+    /*@
+     @ ensures \result == (this.value() < x.value() + y.value() ? -1 : this.value() > x.value() + y.value() ? +1 : 0);
+     @*/
+    public /*@ pure @*/ int addAndCmp(FDBigInteger x, FDBigInteger y) {
+        FDBigInteger big;
+        FDBigInteger small;
+        int xSize = x.size();
+        int ySize = y.size();
+        int bSize;
+        int sSize;
+        if (xSize >= ySize) {
+            big = x;
+            small = y;
+            bSize = xSize;
+            sSize = ySize;
+        } else {
+            big = y;
+            small = x;
+            bSize = ySize;
+            sSize = xSize;
+        }
+        int thSize = this.size();
+        if (bSize == 0) {
+            return thSize == 0 ? 0 : 1;
+        }
+        if (sSize == 0) {
+            return this.cmp(big);
+        }
+        if (bSize > thSize) {
+            return -1;
+        }
+        if (bSize + 1 < thSize) {
+            return 1;
+        }
+        long top = (big.data[big.nWords - 1] & LONG_MASK);
+        if (sSize == bSize) {
+            top += (small.data[small.nWords - 1] & LONG_MASK);
+        }
+        if ((top >>> 32) == 0) {
+            if (((top + 1) >>> 32) == 0) {
+                // good case - no carry extension
+                if (bSize < thSize) {
+                    return 1;
+                }
+                // here sum.nWords == this.nWords
+                long v = (this.data[this.nWords - 1] & LONG_MASK);
+                if (v < top) {
+                    return -1;
+                }
+                if (v > top + 1) {
+                    return 1;
+                }
+            }
+        } else { // (top>>>32)!=0 guaranteed carry extension
+            if (bSize + 1 > thSize) {
+                return -1;
+            }
+            // here sum.nWords == this.nWords
+            top >>>= 32;
+            long v = (this.data[this.nWords - 1] & LONG_MASK);
+            if (v < top) {
+                return -1;
+            }
+            if (v > top + 1) {
+                return 1;
+            }
+        }
+        return this.cmp(big.add(small));
+    }
+
+    /**
+     * Makes this <code>FDBigInteger</code> immutable.
+     */
+    /*@
+     @ assignable this.isImmutable;
+     @ ensures this.isImmutable;
+     @*/
+    public void makeImmutable() {
+        this.isImmutable = true;
+    }
+
+    /**
+     * Multiplies this <code>FDBigInteger</code> by an integer.
+     *
+     * @param i The factor by which to multiply this <code>FDBigInteger</code>.
+     * @return This <code>FDBigInteger</code> multiplied by an integer.
+     */
+    /*@
+     @ requires this.value() == 0;
+     @ assignable \nothing;
+     @ ensures \result == this;
+     @
+     @  also
+     @
+     @ requires this.value() != 0;
+     @ assignable \nothing;
+     @ ensures \result.value() == \old(this.value() * UNSIGNED(i));
+     @*/
+    private FDBigInteger mult(int i) {
+        if (this.nWords == 0) {
+            return this;
+        }
+        int[] r = new int[nWords + 1];
+        mult(data, nWords, i, r);
+        return new FDBigInteger(r, offset);
+    }
+
+    /**
+     * Multiplies this <code>FDBigInteger</code> by another <code>FDBigInteger</code>.
+     *
+     * @param other The <code>FDBigInteger</code> factor by which to multiply.
+     * @return The product of this and the parameter <code>FDBigInteger</code>s.
+     */
+    /*@
+     @ requires this.value() == 0;
+     @ assignable \nothing;
+     @ ensures \result == this;
+     @
+     @  also
+     @
+     @ requires this.value() != 0 && other.value() == 0;
+     @ assignable \nothing;
+     @ ensures \result == other;
+     @
+     @  also
+     @
+     @ requires this.value() != 0 && other.value() != 0;
+     @ assignable \nothing;
+     @ ensures \result.value() == \old(this.value() * other.value());
+     @*/
+    private FDBigInteger mult(FDBigInteger other) {
+        if (this.nWords == 0) {
+            return this;
+        }
+        if (this.size() == 1) {
+            return other.mult(data[0]);
+        }
+        if (other.nWords == 0) {
+            return other;
+        }
+        if (other.size() == 1) {
+            return this.mult(other.data[0]);
+        }
+        int[] r = new int[nWords + other.nWords];
+        mult(this.data, this.nWords, other.data, other.nWords, r);
+        return new FDBigInteger(r, this.offset + other.offset);
+    }
+
+    /**
+     * Adds another <code>FDBigInteger</code> to this <code>FDBigInteger</code>.
+     *
+     * @param other The <code>FDBigInteger</code> to add.
+     * @return The sum of the <code>FDBigInteger</code>s.
+     */
+    /*@
+     @ assignable \nothing;
+     @ ensures \result.value() == \old(this.value() + other.value());
+     @*/
+    private FDBigInteger add(FDBigInteger other) {
+        FDBigInteger big, small;
+        int bigLen, smallLen;
+        int tSize = this.size();
+        int oSize = other.size();
+        if (tSize >= oSize) {
+            big = this;
+            bigLen = tSize;
+            small = other;
+            smallLen = oSize;
+        } else {
+            big = other;
+            bigLen = oSize;
+            small = this;
+            smallLen = tSize;
+        }
+        int[] r = new int[bigLen + 1];
+        int i = 0;
+        long carry = 0L;
+        for (; i < smallLen; i++) {
+            carry += (i < big.offset   ? 0L : (big.data[i - big.offset] & LONG_MASK) )
+                   + ((i < small.offset ? 0L : (small.data[i - small.offset] & LONG_MASK)));
+            r[i] = (int) carry;
+            carry >>= 32; // signed shift.
+        }
+        for (; i < bigLen; i++) {
+            carry += (i < big.offset ? 0L : (big.data[i - big.offset] & LONG_MASK) );
+            r[i] = (int) carry;
+            carry >>= 32; // signed shift.
+        }
+        r[bigLen] = (int) carry;
+        return new FDBigInteger(r, 0);
+    }
+
+
+    /**
+     * Multiplies a <code>FDBigInteger</code> by an int and adds another int. The
+     * result is computed in place. This method is intended only to be invoked
+     * from
+     * <code>
+     * FDBigInteger(long lValue, char[] digits, int kDigits, int nDigits)
+     * </code>.
+     *
+     * @param iv The factor by which to multiply this <code>FDBigInteger</code>.
+     * @param addend The value to add to the product of this
+     * <code>FDBigInteger</code> and <code>iv</code>.
+     */
+    /*@
+     @ requires this.value()*UNSIGNED(iv) + UNSIGNED(addend) < ((\bigint)1) << ((this.data.length + this.offset)*32);
+     @ assignable this.data[*];
+     @ ensures this.value() == \old(this.value()*UNSIGNED(iv) + UNSIGNED(addend));
+     @*/
+    private /*@ helper @*/ void multAddMe(int iv, int addend) {
+        long v = iv & LONG_MASK;
+        // unroll 0th iteration, doing addition.
+        long p = v * (data[0] & LONG_MASK) + (addend & LONG_MASK);
+        data[0] = (int) p;
+        p >>>= 32;
+        for (int i = 1; i < nWords; i++) {
+            p += v * (data[i] & LONG_MASK);
+            data[i] = (int) p;
+            p >>>= 32;
+        }
+        if (p != 0L) {
+            data[nWords++] = (int) p; // will fail noisily if illegal!
+        }
+    }
+
+    //
+    // original doc:
+    //
+    // do this -=q*S
+    // returns borrow
+    //
+    /**
+     * Multiplies the parameters and subtracts them from this
+     * <code>FDBigInteger</code>.
+     *
+     * @param q The integer parameter.
+     * @param S The <code>FDBigInteger</code> parameter.
+     * @return <code>this - q*S</code>.
+     */
+    /*@
+     @ ensures nWords == 0 ==> offset == 0;
+     @ ensures nWords > 0 ==> data[nWords - 1] != 0;
+     @*/
+    /*@
+     @ requires 0 < q && q <= (1L << 31);
+     @ requires data != null;
+     @ requires 0 <= nWords && nWords <= data.length && offset >= 0;
+     @ requires !this.isImmutable;
+     @ requires this.size() == S.size();
+     @ requires this != S;
+     @ assignable this.nWords, this.offset, this.data, this.data[*];
+     @ ensures -q <= \result && \result <= 0;
+     @ ensures this.size() == \old(this.size());
+     @ ensures this.value() + (\result << (this.size()*32)) == \old(this.value() - q*S.value());
+     @ ensures this.offset == \old(Math.min(this.offset, S.offset));
+     @ ensures \old(this.offset <= S.offset) ==> this.nWords == \old(this.nWords);
+     @ ensures \old(this.offset <= S.offset) ==> this.offset == \old(this.offset);
+     @ ensures \old(this.offset <= S.offset) ==> this.data == \old(this.data);
+     @
+     @  also
+     @
+     @ requires q == 0;
+     @ assignable \nothing;
+     @ ensures \result == 0;
+     @*/
+    private /*@ helper @*/ long multDiffMe(long q, FDBigInteger S) {
+        long diff = 0L;
+        if (q != 0) {
+            int deltaSize = S.offset - this.offset;
+            if (deltaSize >= 0) {
+                int[] sd = S.data;
+                int[] td = this.data;
+                for (int sIndex = 0, tIndex = deltaSize; sIndex < S.nWords; sIndex++, tIndex++) {
+                    diff += (td[tIndex] & LONG_MASK) - q * (sd[sIndex] & LONG_MASK);
+                    td[tIndex] = (int) diff;
+                    diff >>= 32; // N.B. SIGNED shift.
+                }
+            } else {
+                deltaSize = -deltaSize;
+                int[] rd = new int[nWords + deltaSize];
+                int sIndex = 0;
+                int rIndex = 0;
+                int[] sd = S.data;
+                for (; rIndex < deltaSize && sIndex < S.nWords; sIndex++, rIndex++) {
+                    diff -= q * (sd[sIndex] & LONG_MASK);
+                    rd[rIndex] = (int) diff;
+                    diff >>= 32; // N.B. SIGNED shift.
+                }
+                int tIndex = 0;
+                int[] td = this.data;
+                for (; sIndex < S.nWords; sIndex++, tIndex++, rIndex++) {
+                    diff += (td[tIndex] & LONG_MASK) - q * (sd[sIndex] & LONG_MASK);
+                    rd[rIndex] = (int) diff;
+                    diff >>= 32; // N.B. SIGNED shift.
+                }
+                this.nWords += deltaSize;
+                this.offset -= deltaSize;
+                this.data = rd;
+            }
+        }
+        return diff;
+    }
+
+
+    /**
+     * Multiplies by 10 a big integer represented as an array. The final carry
+     * is returned.
+     *
+     * @param src The array representation of the big integer.
+     * @param srcLen The number of elements of <code>src</code> to use.
+     * @param dst The product array.
+     * @return The final carry of the multiplication.
+     */
+    /*@
+     @ requires src.length >= srcLen && dst.length >= srcLen;
+     @ assignable dst[0 .. srcLen - 1];
+     @ ensures 0 <= \result && \result < 10;
+     @ ensures AP(dst, srcLen) + (\result << (srcLen*32)) == \old(AP(src, srcLen) * 10);
+     @*/
+    private static int multAndCarryBy10(int[] src, int srcLen, int[] dst) {
+        long carry = 0;
+        for (int i = 0; i < srcLen; i++) {
+            long product = (src[i] & LONG_MASK) * 10L + carry;
+            dst[i] = (int) product;
+            carry = product >>> 32;
+        }
+        return (int) carry;
+    }
+
+    /**
+     * Multiplies by a constant value a big integer represented as an array.
+     * The constant factor is an <code>int</code>.
+     *
+     * @param src The array representation of the big integer.
+     * @param srcLen The number of elements of <code>src</code> to use.
+     * @param value The constant factor by which to multiply.
+     * @param dst The product array.
+     */
+    /*@
+     @ requires src.length >= srcLen && dst.length >= srcLen + 1;
+     @ assignable dst[0 .. srcLen];
+     @ ensures AP(dst, srcLen + 1) == \old(AP(src, srcLen) * UNSIGNED(value));
+     @*/
+    private static void mult(int[] src, int srcLen, int value, int[] dst) {
+        long val = value & LONG_MASK;
+        long carry = 0;
+        for (int i = 0; i < srcLen; i++) {
+            long product = (src[i] & LONG_MASK) * val + carry;
+            dst[i] = (int) product;
+            carry = product >>> 32;
+        }
+        dst[srcLen] = (int) carry;
+    }
+
+    /**
+     * Multiplies by a constant value a big integer represented as an array.
+     * The constant factor is a long represent as two <code>int</code>s.
+     *
+     * @param src The array representation of the big integer.
+     * @param srcLen The number of elements of <code>src</code> to use.
+     * @param v0 The lower 32 bits of the long factor.
+     * @param v1 The upper 32 bits of the long factor.
+     * @param dst The product array.
+     */
+    /*@
+     @ requires src != dst;
+     @ requires src.length >= srcLen && dst.length >= srcLen + 2;
+     @ assignable dst[0 .. srcLen + 1];
+     @ ensures AP(dst, srcLen + 2) == \old(AP(src, srcLen) * (UNSIGNED(v0) + (UNSIGNED(v1) << 32)));
+     @*/
+    private static void mult(int[] src, int srcLen, int v0, int v1, int[] dst) {
+        long v = v0 & LONG_MASK;
+        long carry = 0;
+        for (int j = 0; j < srcLen; j++) {
+            long product = v * (src[j] & LONG_MASK) + carry;
+            dst[j] = (int) product;
+            carry = product >>> 32;
+        }
+        dst[srcLen] = (int) carry;
+        v = v1 & LONG_MASK;
+        carry = 0;
+        for (int j = 0; j < srcLen; j++) {
+            long product = (dst[j + 1] & LONG_MASK) + v * (src[j] & LONG_MASK) + carry;
+            dst[j + 1] = (int) product;
+            carry = product >>> 32;
+        }
+        dst[srcLen + 1] = (int) carry;
+    }
+
+    // Fails assertion for negative exponent.
+    /**
+     * Computes <code>5</code> raised to a given power.
+     *
+     * @param p The exponent of 5.
+     * @return <code>5<sup>p</sup></code>.
+     */
+    private static FDBigInteger big5pow(int p) {
+        assert p >= 0 : p; // negative power of 5
+        if (p < MAX_FIVE_POW) {
+            return POW_5_CACHE[p];
+        }
+        return big5powRec(p);
+    }
+
+    // slow path
+    /**
+     * Computes <code>5</code> raised to a given power.
+     *
+     * @param p The exponent of 5.
+     * @return <code>5<sup>p</sup></code>.
+     */
+    private static FDBigInteger big5powRec(int p) {
+        if (p < MAX_FIVE_POW) {
+            return POW_5_CACHE[p];
+        }
+        // construct the value.
+        // recursively.
+        int q, r;
+        // in order to compute 5^p,
+        // compute its square root, 5^(p/2) and square.
+        // or, let q = p / 2, r = p -q, then
+        // 5^p = 5^(q+r) = 5^q * 5^r
+        q = p >> 1;
+        r = p - q;
+        FDBigInteger bigq = big5powRec(q);
+        if (r < SMALL_5_POW.length) {
+            return bigq.mult(SMALL_5_POW[r]);
+        } else {
+            return bigq.mult(big5powRec(r));
+        }
+    }
+
+    // for debugging ...
+    /**
+     * Converts this <code>FDBigInteger</code> to a hexadecimal string.
+     *
+     * @return The hexadecimal string representation.
+     */
+    public String toHexString(){
+        if(nWords ==0) {
+            return "0";
+        }
+        StringBuilder sb = new StringBuilder((nWords +offset)*8);
+        for(int i= nWords -1; i>=0; i--) {
+            String subStr = Integer.toHexString(data[i]);
+            for(int j = subStr.length(); j<8; j++) {
+                sb.append('0');
+            }
+            sb.append(subStr);
+        }
+        for(int i=offset; i>0; i--) {
+            sb.append("00000000");
+        }
+        return sb.toString();
+    }
+
+    // for debugging ...
+    /**
+     * Converts this <code>FDBigInteger</code> to a <code>BigInteger</code>.
+     *
+     * @return The <code>BigInteger</code> representation.
+     */
+    public BigInteger toBigInteger() {
+        byte[] magnitude = new byte[nWords * 4 + 1];
+        for (int i = 0; i < nWords; i++) {
+            int w = data[i];
+            magnitude[magnitude.length - 4 * i - 1] = (byte) w;
+            magnitude[magnitude.length - 4 * i - 2] = (byte) (w >> 8);
+            magnitude[magnitude.length - 4 * i - 3] = (byte) (w >> 16);
+            magnitude[magnitude.length - 4 * i - 4] = (byte) (w >> 24);
+        }
+        return new BigInteger(magnitude).shiftLeft(offset * 32);
+    }
+
+    // for debugging ...
+    /**
+     * Converts this <code>FDBigInteger</code> to a string.
+     *
+     * @return The string representation.
+     */
+    @Override
+    public String toString(){
+        return toBigInteger().toString();
+    }
+}
--- a/jdk/src/share/classes/sun/misc/FloatingDecimal.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/misc/FloatingDecimal.java	Wed Jul 05 19:00:49 2017 +0200
@@ -25,602 +25,785 @@
 
 package sun.misc;
 
-import sun.misc.DoubleConsts;
-import sun.misc.FloatConsts;
+import java.util.Arrays;
 import java.util.regex.*;
 
+/**
+ * A class for converting between ASCII and decimal representations of a single
+ * or double precision floating point number. Most conversions are provided via
+ * static convenience methods, although a <code>BinaryToASCIIConverter</code>
+ * instance may be obtained and reused.
+ */
 public class FloatingDecimal{
-    boolean     isExceptional;
-    boolean     isNegative;
-    int         decExponent;
-    char        digits[];
-    int         nDigits;
-    int         bigIntExp;
-    int         bigIntNBits;
-    boolean     mustSetRoundDir = false;
-    boolean     fromHex = false;
-    int         roundDir = 0; // set by doubleValue
+    //
+    // Constants of the implementation;
+    // most are IEEE-754 related.
+    // (There are more really boring constants at the end.)
+    //
+    static final int    EXP_SHIFT = DoubleConsts.SIGNIFICAND_WIDTH - 1;
+    static final long   FRACT_HOB = ( 1L<<EXP_SHIFT ); // assumed High-Order bit
+    static final long   EXP_ONE   = ((long)DoubleConsts.EXP_BIAS)<<EXP_SHIFT; // exponent of 1.0
+    static final int    MAX_SMALL_BIN_EXP = 62;
+    static final int    MIN_SMALL_BIN_EXP = -( 63 / 3 );
+    static final int    MAX_DECIMAL_DIGITS = 15;
+    static final int    MAX_DECIMAL_EXPONENT = 308;
+    static final int    MIN_DECIMAL_EXPONENT = -324;
+    static final int    BIG_DECIMAL_EXPONENT = 324; // i.e. abs(MIN_DECIMAL_EXPONENT)
+
+    static final int    SINGLE_EXP_SHIFT  =   FloatConsts.SIGNIFICAND_WIDTH - 1;
+    static final int    SINGLE_FRACT_HOB  =   1<<SINGLE_EXP_SHIFT;
+    static final int    SINGLE_MAX_DECIMAL_DIGITS = 7;
+    static final int    SINGLE_MAX_DECIMAL_EXPONENT = 38;
+    static final int    SINGLE_MIN_DECIMAL_EXPONENT = -45;
+
+    static final int    INT_DECIMAL_DIGITS = 9;
+
+    /**
+     * Converts a double precision floating point value to a <code>String</code>.
+     *
+     * @param d The double precision value.
+     * @return The value converted to a <code>String</code>.
+     */
+    public static String toJavaFormatString(double d) {
+        return getBinaryToASCIIConverter(d).toJavaFormatString();
+    }
 
-    /*
-     * The fields below provides additional information about the result of
-     * the binary to decimal digits conversion done in dtoa() and roundup()
-     * methods. They are changed if needed by those two methods.
+    /**
+     * Converts a single precision floating point value to a <code>String</code>.
+     *
+     * @param f The single precision value.
+     * @return The value converted to a <code>String</code>.
      */
+    public static String toJavaFormatString(float f) {
+        return getBinaryToASCIIConverter(f).toJavaFormatString();
+    }
 
-    // True if the dtoa() binary to decimal conversion was exact.
-    boolean     exactDecimalConversion = false;
+    /**
+     * Appends a double precision floating point value to an <code>Appendable</code>.
+     * @param d The double precision value.
+     * @param buf The <code>Appendable</code> with the value appended.
+     */
+    public static void appendTo(double d, Appendable buf) {
+        getBinaryToASCIIConverter(d).appendTo(buf);
+    }
 
-    // True if the result of the binary to decimal conversion was rounded-up
-    // at the end of the conversion process, i.e. roundUp() method was called.
-    boolean     decimalDigitsRoundedUp = false;
+    /**
+     * Appends a single precision floating point value to an <code>Appendable</code>.
+     * @param f The single precision value.
+     * @param buf The <code>Appendable</code> with the value appended.
+     */
+    public static void appendTo(float f, Appendable buf) {
+        getBinaryToASCIIConverter(f).appendTo(buf);
+    }
 
-    private     FloatingDecimal( boolean negSign, int decExponent, char []digits, int n,  boolean e )
-    {
-        isNegative = negSign;
-        isExceptional = e;
-        this.decExponent = decExponent;
-        this.digits = digits;
-        this.nDigits = n;
+    /**
+     * Converts a <code>String</code> to a double precision floating point value.
+     *
+     * @param s The <code>String</code> to convert.
+     * @return The double precision value.
+     * @throws NumberFormatException If the <code>String</code> does not
+     * represent a properly formatted double precision value.
+     */
+    public static double parseDouble(String s) throws NumberFormatException {
+        return readJavaFormatString(s).doubleValue();
+    }
+
+    /**
+     * Converts a <code>String</code> to a single precision floating point value.
+     *
+     * @param s The <code>String</code> to convert.
+     * @return The single precision value.
+     * @throws NumberFormatException If the <code>String</code> does not
+     * represent a properly formatted single precision value.
+     */
+    public static float parseFloat(String s) throws NumberFormatException {
+        return readJavaFormatString(s).floatValue();
     }
 
-    /*
-     * Constants of the implementation
-     * Most are IEEE-754 related.
-     * (There are more really boring constants at the end.)
+    /**
+     * A converter which can process single or double precision floating point
+     * values into an ASCII <code>String</code> representation.
      */
-    static final long   signMask = 0x8000000000000000L;
-    static final long   expMask  = 0x7ff0000000000000L;
-    static final long   fractMask= ~(signMask|expMask);
-    static final int    expShift = 52;
-    static final int    expBias  = 1023;
-    static final long   fractHOB = ( 1L<<expShift ); // assumed High-Order bit
-    static final long   expOne   = ((long)expBias)<<expShift; // exponent of 1.0
-    static final int    maxSmallBinExp = 62;
-    static final int    minSmallBinExp = -( 63 / 3 );
-    static final int    maxDecimalDigits = 15;
-    static final int    maxDecimalExponent = 308;
-    static final int    minDecimalExponent = -324;
-    static final int    bigDecimalExponent = 324; // i.e. abs(minDecimalExponent)
+    public interface BinaryToASCIIConverter {
+        /**
+         * Converts a floating point value into an ASCII <code>String</code>.
+         * @return The value converted to a <code>String</code>.
+         */
+        public String toJavaFormatString();
+
+        /**
+         * Appends a floating point value to an <code>Appendable</code>.
+         * @param buf The <code>Appendable</code> to receive the value.
+         */
+        public void appendTo(Appendable buf);
 
-    static final long   highbyte = 0xff00000000000000L;
-    static final long   highbit  = 0x8000000000000000L;
-    static final long   lowbytes = ~highbyte;
+        /**
+         * Retrieves the decimal exponent most closely corresponding to this value.
+         * @return The decimal exponent.
+         */
+        public int getDecimalExponent();
+
+        /**
+         * Retrieves the value as an array of digits.
+         * @param digits The digit array.
+         * @return The number of valid digits copied into the array.
+         */
+        public int getDigits(char[] digits);
+
+        /**
+         * Indicates the sign of the value.
+         * @return <code>value < 0.0</code>.
+         */
+        public boolean isNegative();
 
-    static final int    singleSignMask =    0x80000000;
-    static final int    singleExpMask  =    0x7f800000;
-    static final int    singleFractMask =   ~(singleSignMask|singleExpMask);
-    static final int    singleExpShift  =   23;
-    static final int    singleFractHOB  =   1<<singleExpShift;
-    static final int    singleExpBias   =   127;
-    static final int    singleMaxDecimalDigits = 7;
-    static final int    singleMaxDecimalExponent = 38;
-    static final int    singleMinDecimalExponent = -45;
+        /**
+         * Indicates whether the value is either infinite or not a number.
+         *
+         * @return <code>true</code> if and only if the value is <code>NaN</code>
+         * or infinite.
+         */
+        public boolean isExceptional();
 
-    static final int    intDecimalDigits = 9;
-
+        /**
+         * Indicates whether the value was rounded up during the binary to ASCII
+         * conversion.
+         *
+         * @return <code>true</code> if and only if the value was rounded up.
+         */
+        public boolean digitsRoundedUp();
 
-    /*
-     * count number of bits from high-order 1 bit to low-order 1 bit,
-     * inclusive.
+        /**
+         * Indicates whether the binary to ASCII conversion was exact.
+         *
+         * @return <code>true</code> if any only if the conversion was exact.
+         */
+        public boolean decimalDigitsExact();
+    }
+
+    /**
+     * A <code>BinaryToASCIIConverter</code> which represents <code>NaN</code>
+     * and infinite values.
      */
-    private static int
-    countBits( long v ){
-        //
-        // the strategy is to shift until we get a non-zero sign bit
-        // then shift until we have no bits left, counting the difference.
-        // we do byte shifting as a hack. Hope it helps.
-        //
-        if ( v == 0L ) return 0;
+    private static class ExceptionalBinaryToASCIIBuffer implements BinaryToASCIIConverter {
+        final private String image;
+        private boolean isNegative;
 
-        while ( ( v & highbyte ) == 0L ){
-            v <<= 8;
-        }
-        while ( v > 0L ) { // i.e. while ((v&highbit) == 0L )
-            v <<= 1;
+        public ExceptionalBinaryToASCIIBuffer(String image, boolean isNegative) {
+            this.image = image;
+            this.isNegative = isNegative;
         }
 
-        int n = 0;
-        while (( v & lowbytes ) != 0L ){
-            v <<= 8;
-            n += 8;
+        @Override
+        public String toJavaFormatString() {
+            return image;
         }
-        while ( v != 0L ){
-            v <<= 1;
-            n += 1;
-        }
-        return n;
-    }
 
-    /*
-     * Keep big powers of 5 handy for future reference.
-     */
-    private static FDBigInt b5p[];
+        @Override
+        public void appendTo(Appendable buf) {
+            if (buf instanceof StringBuilder) {
+                ((StringBuilder) buf).append(image);
+            } else if (buf instanceof StringBuffer) {
+                ((StringBuffer) buf).append(image);
+            } else {
+                assert false;
+            }
+        }
 
-    private static synchronized FDBigInt
-    big5pow( int p ){
-        assert p >= 0 : p; // negative power of 5
-        if ( b5p == null ){
-            b5p = new FDBigInt[ p+1 ];
-        }else if (b5p.length <= p ){
-            FDBigInt t[] = new FDBigInt[ p+1 ];
-            System.arraycopy( b5p, 0, t, 0, b5p.length );
-            b5p = t;
+        @Override
+        public int getDecimalExponent() {
+            throw new IllegalArgumentException("Exceptional value does not have an exponent");
         }
-        if ( b5p[p] != null )
-            return b5p[p];
-        else if ( p < small5pow.length )
-            return b5p[p] = new FDBigInt( small5pow[p] );
-        else if ( p < long5pow.length )
-            return b5p[p] = new FDBigInt( long5pow[p] );
-        else {
-            // construct the value.
-            // recursively.
-            int q, r;
-            // in order to compute 5^p,
-            // compute its square root, 5^(p/2) and square.
-            // or, let q = p / 2, r = p -q, then
-            // 5^p = 5^(q+r) = 5^q * 5^r
-            q = p >> 1;
-            r = p - q;
-            FDBigInt bigq =  b5p[q];
-            if ( bigq == null )
-                bigq = big5pow ( q );
-            if ( r < small5pow.length ){
-                return (b5p[p] = bigq.mult( small5pow[r] ) );
-            }else{
-                FDBigInt bigr = b5p[ r ];
-                if ( bigr == null )
-                    bigr = big5pow( r );
-                return (b5p[p] = bigq.mult( bigr ) );
-            }
+
+        @Override
+        public int getDigits(char[] digits) {
+            throw new IllegalArgumentException("Exceptional value does not have digits");
+        }
+
+        @Override
+        public boolean isNegative() {
+            return isNegative;
+        }
+
+        @Override
+        public boolean isExceptional() {
+            return true;
+        }
+
+        @Override
+        public boolean digitsRoundedUp() {
+            throw new IllegalArgumentException("Exceptional value is not rounded");
+        }
+
+        @Override
+        public boolean decimalDigitsExact() {
+            throw new IllegalArgumentException("Exceptional value is not exact");
         }
     }
 
-    //
-    // a common operation
-    //
-    private static FDBigInt
-    multPow52( FDBigInt v, int p5, int p2 ){
-        if ( p5 != 0 ){
-            if ( p5 < small5pow.length ){
-                v = v.mult( small5pow[p5] );
-            } else {
-                v = v.mult( big5pow( p5 ) );
-            }
-        }
-        if ( p2 != 0 ){
-            v.lshiftMe( p2 );
-        }
-        return v;
-    }
+    private static final String INFINITY_REP = "Infinity";
+    private static final int INFINITY_LENGTH = INFINITY_REP.length();
+    private static final String NAN_REP = "NaN";
+    private static final int NAN_LENGTH = NAN_REP.length();
+
+    private static final BinaryToASCIIConverter B2AC_POSITIVE_INFINITY = new ExceptionalBinaryToASCIIBuffer(INFINITY_REP, false);
+    private static final BinaryToASCIIConverter B2AC_NEGATIVE_INFINITY = new ExceptionalBinaryToASCIIBuffer("-" + INFINITY_REP, true);
+    private static final BinaryToASCIIConverter B2AC_NOT_A_NUMBER = new ExceptionalBinaryToASCIIBuffer(NAN_REP, false);
+    private static final BinaryToASCIIConverter B2AC_POSITIVE_ZERO = new BinaryToASCIIBuffer(false, new char[]{'0'});
+    private static final BinaryToASCIIConverter B2AC_NEGATIVE_ZERO = new BinaryToASCIIBuffer(true,  new char[]{'0'});
 
-    //
-    // another common operation
-    //
-    private static FDBigInt
-    constructPow52( int p5, int p2 ){
-        FDBigInt v = new FDBigInt( big5pow( p5 ) );
-        if ( p2 != 0 ){
-            v.lshiftMe( p2 );
+    /**
+     * A buffered implementation of <code>BinaryToASCIIConverter</code>.
+     */
+    static class BinaryToASCIIBuffer implements BinaryToASCIIConverter {
+        private boolean isNegative;
+        private int decExponent;
+        private int firstDigitIndex;
+        private int nDigits;
+        private final char[] digits;
+        private final char[] buffer = new char[26];
+
+        //
+        // The fields below provide additional information about the result of
+        // the binary to decimal digits conversion done in dtoa() and roundup()
+        // methods. They are changed if needed by those two methods.
+        //
+
+        // True if the dtoa() binary to decimal conversion was exact.
+        private boolean exactDecimalConversion = false;
+
+        // True if the result of the binary to decimal conversion was rounded-up
+        // at the end of the conversion process, i.e. roundUp() method was called.
+        private boolean decimalDigitsRoundedUp = false;
+
+        /**
+         * Default constructor; used for non-zero values,
+         * <code>BinaryToASCIIBuffer</code> may be thread-local and reused
+         */
+        BinaryToASCIIBuffer(){
+            this.digits = new char[20];
         }
-        return v;
-    }
+
+        /**
+         * Creates a specialized value (positive and negative zeros).
+         */
+        BinaryToASCIIBuffer(boolean isNegative, char[] digits){
+            this.isNegative = isNegative;
+            this.decExponent  = 0;
+            this.digits = digits;
+            this.firstDigitIndex = 0;
+            this.nDigits = digits.length;
+        }
 
-    /*
-     * Make a floating double into a FDBigInt.
-     * This could also be structured as a FDBigInt
-     * constructor, but we'd have to build a lot of knowledge
-     * about floating-point representation into it, and we don't want to.
-     *
-     * AS A SIDE EFFECT, THIS METHOD WILL SET THE INSTANCE VARIABLES
-     * bigIntExp and bigIntNBits
-     *
-     */
-    private FDBigInt
-    doubleToBigInt( double dval ){
-        long lbits = Double.doubleToLongBits( dval ) & ~signMask;
-        int binexp = (int)(lbits >>> expShift);
-        lbits &= fractMask;
-        if ( binexp > 0 ){
-            lbits |= fractHOB;
-        } else {
-            assert lbits != 0L : lbits; // doubleToBigInt(0.0)
-            binexp +=1;
-            while ( (lbits & fractHOB ) == 0L){
-                lbits <<= 1;
-                binexp -= 1;
+        @Override
+        public String toJavaFormatString() {
+            int len = getChars(buffer);
+            return new String(buffer, 0, len);
+        }
+
+        @Override
+        public void appendTo(Appendable buf) {
+            int len = getChars(buffer);
+            if (buf instanceof StringBuilder) {
+                ((StringBuilder) buf).append(buffer, 0, len);
+            } else if (buf instanceof StringBuffer) {
+                ((StringBuffer) buf).append(buffer, 0, len);
+            } else {
+                assert false;
             }
         }
-        binexp -= expBias;
-        int nbits = countBits( lbits );
-        /*
-         * We now know where the high-order 1 bit is,
-         * and we know how many there are.
-         */
-        int lowOrderZeros = expShift+1-nbits;
-        lbits >>>= lowOrderZeros;
+
+        @Override
+        public int getDecimalExponent() {
+            return decExponent;
+        }
 
-        bigIntExp = binexp+1-nbits;
-        bigIntNBits = nbits;
-        return new FDBigInt( lbits );
-    }
+        @Override
+        public int getDigits(char[] digits) {
+            System.arraycopy(this.digits,firstDigitIndex,digits,0,this.nDigits);
+            return this.nDigits;
+        }
+
+        @Override
+        public boolean isNegative() {
+            return isNegative;
+        }
 
-    /*
-     * Compute a number that is the ULP of the given value,
-     * for purposes of addition/subtraction. Generally easy.
-     * More difficult if subtracting and the argument
-     * is a normalized a power of 2, as the ULP changes at these points.
-     */
-    private static double ulp( double dval, boolean subtracting ){
-        long lbits = Double.doubleToLongBits( dval ) & ~signMask;
-        int binexp = (int)(lbits >>> expShift);
-        double ulpval;
-        if ( subtracting && ( binexp >= expShift ) && ((lbits&fractMask) == 0L) ){
-            // for subtraction from normalized, powers of 2,
-            // use next-smaller exponent
-            binexp -= 1;
+        @Override
+        public boolean isExceptional() {
+            return false;
+        }
+
+        @Override
+        public boolean digitsRoundedUp() {
+            return decimalDigitsRoundedUp;
         }
-        if ( binexp > expShift ){
-            ulpval = Double.longBitsToDouble( ((long)(binexp-expShift))<<expShift );
-        } else if ( binexp == 0 ){
-            ulpval = Double.MIN_VALUE;
-        } else {
-            ulpval = Double.longBitsToDouble( 1L<<(binexp-1) );
+
+        @Override
+        public boolean decimalDigitsExact() {
+            return exactDecimalConversion;
         }
-        if ( subtracting ) ulpval = - ulpval;
 
-        return ulpval;
-    }
+        private void setSign(boolean isNegative) {
+            this.isNegative = isNegative;
+        }
 
-    /*
-     * Round a double to a float.
-     * In addition to the fraction bits of the double,
-     * look at the class instance variable roundDir,
-     * which should help us avoid double-rounding error.
-     * roundDir was set in hardValueOf if the estimate was
-     * close enough, but not exact. It tells us which direction
-     * of rounding is preferred.
-     */
-    float
-    stickyRound( double dval ){
-        long lbits = Double.doubleToLongBits( dval );
-        long binexp = lbits & expMask;
-        if ( binexp == 0L || binexp == expMask ){
-            // what we have here is special.
-            // don't worry, the right thing will happen.
-            return (float) dval;
-        }
-        lbits += (long)roundDir; // hack-o-matic.
-        return (float)Double.longBitsToDouble( lbits );
-    }
-
-
-    /*
-     * This is the easy subcase --
-     * all the significant bits, after scaling, are held in lvalue.
-     * negSign and decExponent tell us what processing and scaling
-     * has already been done. Exceptional cases have already been
-     * stripped out.
-     * In particular:
-     * lvalue is a finite number (not Inf, nor NaN)
-     * lvalue > 0L (not zero, nor negative).
-     *
-     * The only reason that we develop the digits here, rather than
-     * calling on Long.toString() is that we can do it a little faster,
-     * and besides want to treat trailing 0s specially. If Long.toString
-     * changes, we should re-evaluate this strategy!
-     */
-    private void
-    developLongDigits( int decExponent, long lvalue, long insignificant ){
-        char digits[];
-        int  ndigits;
-        int  digitno;
-        int  c;
-        //
-        // Discard non-significant low-order bits, while rounding,
-        // up to insignificant value.
-        int i;
-        for ( i = 0; insignificant >= 10L; i++ )
-            insignificant /= 10L;
-        if ( i != 0 ){
-            long pow10 = long5pow[i] << i; // 10^i == 5^i * 2^i;
-            long residue = lvalue % pow10;
-            lvalue /= pow10;
-            decExponent += i;
-            if ( residue >= (pow10>>1) ){
-                // round up based on the low-order bits we're discarding
-                lvalue++;
+        /**
+         * This is the easy subcase --
+         * all the significant bits, after scaling, are held in lvalue.
+         * negSign and decExponent tell us what processing and scaling
+         * has already been done. Exceptional cases have already been
+         * stripped out.
+         * In particular:
+         * lvalue is a finite number (not Inf, nor NaN)
+         * lvalue > 0L (not zero, nor negative).
+         *
+         * The only reason that we develop the digits here, rather than
+         * calling on Long.toString() is that we can do it a little faster,
+         * and besides want to treat trailing 0s specially. If Long.toString
+         * changes, we should re-evaluate this strategy!
+         */
+        private void developLongDigits( int decExponent, long lvalue, int insignificantDigits ){
+            if ( insignificantDigits != 0 ){
+                // Discard non-significant low-order bits, while rounding,
+                // up to insignificant value.
+                long pow10 = FDBigInteger.LONG_5_POW[insignificantDigits] << insignificantDigits; // 10^i == 5^i * 2^i;
+                long residue = lvalue % pow10;
+                lvalue /= pow10;
+                decExponent += insignificantDigits;
+                if ( residue >= (pow10>>1) ){
+                    // round up based on the low-order bits we're discarding
+                    lvalue++;
+                }
             }
-        }
-        if ( lvalue <= Integer.MAX_VALUE ){
-            assert lvalue > 0L : lvalue; // lvalue <= 0
-            // even easier subcase!
-            // can do int arithmetic rather than long!
-            int  ivalue = (int)lvalue;
-            ndigits = 10;
-            digits = perThreadBuffer.get();
-            digitno = ndigits-1;
-            c = ivalue%10;
-            ivalue /= 10;
-            while ( c == 0 ){
-                decExponent++;
+            int  digitno = digits.length -1;
+            int  c;
+            if ( lvalue <= Integer.MAX_VALUE ){
+                assert lvalue > 0L : lvalue; // lvalue <= 0
+                // even easier subcase!
+                // can do int arithmetic rather than long!
+                int  ivalue = (int)lvalue;
                 c = ivalue%10;
                 ivalue /= 10;
-            }
-            while ( ivalue != 0){
-                digits[digitno--] = (char)(c+'0');
-                decExponent++;
-                c = ivalue%10;
-                ivalue /= 10;
-            }
-            digits[digitno] = (char)(c+'0');
-        } else {
-            // same algorithm as above (same bugs, too )
-            // but using long arithmetic.
-            ndigits = 20;
-            digits = perThreadBuffer.get();
-            digitno = ndigits-1;
-            c = (int)(lvalue%10L);
-            lvalue /= 10L;
-            while ( c == 0 ){
-                decExponent++;
+                while ( c == 0 ){
+                    decExponent++;
+                    c = ivalue%10;
+                    ivalue /= 10;
+                }
+                while ( ivalue != 0){
+                    digits[digitno--] = (char)(c+'0');
+                    decExponent++;
+                    c = ivalue%10;
+                    ivalue /= 10;
+                }
+                digits[digitno] = (char)(c+'0');
+            } else {
+                // same algorithm as above (same bugs, too )
+                // but using long arithmetic.
                 c = (int)(lvalue%10L);
                 lvalue /= 10L;
-            }
-            while ( lvalue != 0L ){
-                digits[digitno--] = (char)(c+'0');
-                decExponent++;
-                c = (int)(lvalue%10L);
-                lvalue /= 10;
-            }
-            digits[digitno] = (char)(c+'0');
-        }
-        char result [];
-        ndigits -= digitno;
-        result = new char[ ndigits ];
-        System.arraycopy( digits, digitno, result, 0, ndigits );
-        this.digits = result;
-        this.decExponent = decExponent+1;
-        this.nDigits = ndigits;
-    }
-
-    //
-    // add one to the least significant digit.
-    // in the unlikely event there is a carry out,
-    // deal with it.
-    // assert that this will only happen where there
-    // is only one digit, e.g. (float)1e-44 seems to do it.
-    //
-    private void
-    roundup(){
-        int i;
-        int q = digits[ i = (nDigits-1)];
-        if ( q == '9' ){
-            while ( q == '9' && i > 0 ){
-                digits[i] = '0';
-                q = digits[--i];
-            }
-            if ( q == '9' ){
-                // carryout! High-order 1, rest 0s, larger exp.
-                decExponent += 1;
-                digits[0] = '1';
-                return;
+                while ( c == 0 ){
+                    decExponent++;
+                    c = (int)(lvalue%10L);
+                    lvalue /= 10L;
+                }
+                while ( lvalue != 0L ){
+                    digits[digitno--] = (char)(c+'0');
+                    decExponent++;
+                    c = (int)(lvalue%10L);
+                    lvalue /= 10;
+                }
+                digits[digitno] = (char)(c+'0');
             }
-            // else fall through.
-        }
-        digits[i] = (char)(q+1);
-        decimalDigitsRoundedUp = true;
-    }
-
-    public boolean digitsRoundedUp() {
-        return decimalDigitsRoundedUp;
-    }
-
-    /*
-     * FIRST IMPORTANT CONSTRUCTOR: DOUBLE
-     */
-    public FloatingDecimal( double d )
-    {
-        long    dBits = Double.doubleToLongBits( d );
-        long    fractBits;
-        int     binExp;
-        int     nSignificantBits;
-
-        // discover and delete sign
-        if ( (dBits&signMask) != 0 ){
-            isNegative = true;
-            dBits ^= signMask;
-        } else {
-            isNegative = false;
-        }
-        // Begin to unpack
-        // Discover obvious special cases of NaN and Infinity.
-        binExp = (int)( (dBits&expMask) >> expShift );
-        fractBits = dBits&fractMask;
-        if ( binExp == (int)(expMask>>expShift) ) {
-            isExceptional = true;
-            if ( fractBits == 0L ){
-                digits =  infinity;
-            } else {
-                digits = notANumber;
-                isNegative = false; // NaN has no sign!
-            }
-            nDigits = digits.length;
-            return;
-        }
-        isExceptional = false;
-        // Finish unpacking
-        // Normalize denormalized numbers.
-        // Insert assumed high-order bit for normalized numbers.
-        // Subtract exponent bias.
-        if ( binExp == 0 ){
-            if ( fractBits == 0L ){
-                // not a denorm, just a 0!
-                decExponent = 0;
-                digits = zero;
-                nDigits = 1;
-                return;
-            }
-            while ( (fractBits&fractHOB) == 0L ){
-                fractBits <<= 1;
-                binExp -= 1;
-            }
-            nSignificantBits = expShift + binExp +1; // recall binExp is  - shift count.
-            binExp += 1;
-        } else {
-            fractBits |= fractHOB;
-            nSignificantBits = expShift+1;
+            this.decExponent = decExponent+1;
+            this.firstDigitIndex = digitno;
+            this.nDigits = this.digits.length - digitno;
         }
-        binExp -= expBias;
-        // call the routine that actually does all the hard work.
-        dtoa( binExp, fractBits, nSignificantBits );
-    }
 
-    /*
-     * SECOND IMPORTANT CONSTRUCTOR: SINGLE
-     */
-    public FloatingDecimal( float f )
-    {
-        int     fBits = Float.floatToIntBits( f );
-        int     fractBits;
-        int     binExp;
-        int     nSignificantBits;
+        private void dtoa( int binExp, long fractBits, int nSignificantBits, boolean isCompatibleFormat)
+        {
+            assert fractBits > 0 ; // fractBits here can't be zero or negative
+            assert (fractBits & FRACT_HOB)!=0  ; // Hi-order bit should be set
+            // Examine number. Determine if it is an easy case,
+            // which we can do pretty trivially using float/long conversion,
+            // or whether we must do real work.
+            final int tailZeros = Long.numberOfTrailingZeros(fractBits);
+
+            // number of significant bits of fractBits;
+            final int nFractBits = EXP_SHIFT+1-tailZeros;
+
+            // reset flags to default values as dtoa() does not always set these
+            // flags and a prior call to dtoa() might have set them to incorrect
+            // values with respect to the current state.
+            decimalDigitsRoundedUp = false;
+            exactDecimalConversion = false;
 
-        // discover and delete sign
-        if ( (fBits&singleSignMask) != 0 ){
-            isNegative = true;
-            fBits ^= singleSignMask;
-        } else {
-            isNegative = false;
-        }
-        // Begin to unpack
-        // Discover obvious special cases of NaN and Infinity.
-        binExp = (fBits&singleExpMask) >> singleExpShift;
-        fractBits = fBits&singleFractMask;
-        if ( binExp == (singleExpMask>>singleExpShift) ) {
-            isExceptional = true;
-            if ( fractBits == 0L ){
-                digits =  infinity;
-            } else {
-                digits = notANumber;
-                isNegative = false; // NaN has no sign!
+            // number of significant bits to the right of the point.
+            int nTinyBits = Math.max( 0, nFractBits - binExp - 1 );
+            if ( binExp <= MAX_SMALL_BIN_EXP && binExp >= MIN_SMALL_BIN_EXP ){
+                // Look more closely at the number to decide if,
+                // with scaling by 10^nTinyBits, the result will fit in
+                // a long.
+                if ( (nTinyBits < FDBigInteger.LONG_5_POW.length) && ((nFractBits + N_5_BITS[nTinyBits]) < 64 ) ){
+                    //
+                    // We can do this:
+                    // take the fraction bits, which are normalized.
+                    // (a) nTinyBits == 0: Shift left or right appropriately
+                    //     to align the binary point at the extreme right, i.e.
+                    //     where a long int point is expected to be. The integer
+                    //     result is easily converted to a string.
+                    // (b) nTinyBits > 0: Shift right by EXP_SHIFT-nFractBits,
+                    //     which effectively converts to long and scales by
+                    //     2^nTinyBits. Then multiply by 5^nTinyBits to
+                    //     complete the scaling. We know this won't overflow
+                    //     because we just counted the number of bits necessary
+                    //     in the result. The integer you get from this can
+                    //     then be converted to a string pretty easily.
+                    //
+                    if ( nTinyBits == 0 ) {
+                        int insignificant;
+                        if ( binExp > nSignificantBits ){
+                            insignificant = insignificantDigitsForPow2(binExp-nSignificantBits-1);
+                        } else {
+                            insignificant = 0;
+                        }
+                        if ( binExp >= EXP_SHIFT ){
+                            fractBits <<= (binExp-EXP_SHIFT);
+                        } else {
+                            fractBits >>>= (EXP_SHIFT-binExp) ;
+                        }
+                        developLongDigits( 0, fractBits, insignificant );
+                        return;
+                    }
+                    //
+                    // The following causes excess digits to be printed
+                    // out in the single-float case. Our manipulation of
+                    // halfULP here is apparently not correct. If we
+                    // better understand how this works, perhaps we can
+                    // use this special case again. But for the time being,
+                    // we do not.
+                    // else {
+                    //     fractBits >>>= EXP_SHIFT+1-nFractBits;
+                    //     fractBits//= long5pow[ nTinyBits ];
+                    //     halfULP = long5pow[ nTinyBits ] >> (1+nSignificantBits-nFractBits);
+                    //     developLongDigits( -nTinyBits, fractBits, insignificantDigits(halfULP) );
+                    //     return;
+                    // }
+                    //
+                }
             }
-            nDigits = digits.length;
-            return;
-        }
-        isExceptional = false;
-        // Finish unpacking
-        // Normalize denormalized numbers.
-        // Insert assumed high-order bit for normalized numbers.
-        // Subtract exponent bias.
-        if ( binExp == 0 ){
-            if ( fractBits == 0 ){
-                // not a denorm, just a 0!
-                decExponent = 0;
-                digits = zero;
-                nDigits = 1;
-                return;
+            //
+            // This is the hard case. We are going to compute large positive
+            // integers B and S and integer decExp, s.t.
+            //      d = ( B / S )// 10^decExp
+            //      1 <= B / S < 10
+            // Obvious choices are:
+            //      decExp = floor( log10(d) )
+            //      B      = d// 2^nTinyBits// 10^max( 0, -decExp )
+            //      S      = 10^max( 0, decExp)// 2^nTinyBits
+            // (noting that nTinyBits has already been forced to non-negative)
+            // I am also going to compute a large positive integer
+            //      M      = (1/2^nSignificantBits)// 2^nTinyBits// 10^max( 0, -decExp )
+            // i.e. M is (1/2) of the ULP of d, scaled like B.
+            // When we iterate through dividing B/S and picking off the
+            // quotient bits, we will know when to stop when the remainder
+            // is <= M.
+            //
+            // We keep track of powers of 2 and powers of 5.
+            //
+            int decExp = estimateDecExp(fractBits,binExp);
+            int B2, B5; // powers of 2 and powers of 5, respectively, in B
+            int S2, S5; // powers of 2 and powers of 5, respectively, in S
+            int M2, M5; // powers of 2 and powers of 5, respectively, in M
+
+            B5 = Math.max( 0, -decExp );
+            B2 = B5 + nTinyBits + binExp;
+
+            S5 = Math.max( 0, decExp );
+            S2 = S5 + nTinyBits;
+
+            M5 = B5;
+            M2 = B2 - nSignificantBits;
+
+            //
+            // the long integer fractBits contains the (nFractBits) interesting
+            // bits from the mantissa of d ( hidden 1 added if necessary) followed
+            // by (EXP_SHIFT+1-nFractBits) zeros. In the interest of compactness,
+            // I will shift out those zeros before turning fractBits into a
+            // FDBigInteger. The resulting whole number will be
+            //      d * 2^(nFractBits-1-binExp).
+            //
+            fractBits >>>= tailZeros;
+            B2 -= nFractBits-1;
+            int common2factor = Math.min( B2, S2 );
+            B2 -= common2factor;
+            S2 -= common2factor;
+            M2 -= common2factor;
+
+            //
+            // HACK!! For exact powers of two, the next smallest number
+            // is only half as far away as we think (because the meaning of
+            // ULP changes at power-of-two bounds) for this reason, we
+            // hack M2. Hope this works.
+            //
+            if ( nFractBits == 1 ) {
+                M2 -= 1;
             }
-            while ( (fractBits&singleFractHOB) == 0 ){
-                fractBits <<= 1;
-                binExp -= 1;
+
+            if ( M2 < 0 ){
+                // oops.
+                // since we cannot scale M down far enough,
+                // we must scale the other values up.
+                B2 -= M2;
+                S2 -= M2;
+                M2 =  0;
             }
-            nSignificantBits = singleExpShift + binExp +1; // recall binExp is  - shift count.
-            binExp += 1;
-        } else {
-            fractBits |= singleFractHOB;
-            nSignificantBits = singleExpShift+1;
-        }
-        binExp -= singleExpBias;
-        // call the routine that actually does all the hard work.
-        dtoa( binExp, ((long)fractBits)<<(expShift-singleExpShift), nSignificantBits );
-    }
+            //
+            // Construct, Scale, iterate.
+            // Some day, we'll write a stopping test that takes
+            // account of the asymmetry of the spacing of floating-point
+            // numbers below perfect powers of 2
+            // 26 Sept 96 is not that day.
+            // So we use a symmetric test.
+            //
+            int ndigit = 0;
+            boolean low, high;
+            long lowDigitDifference;
+            int  q;
 
-    private void
-    dtoa( int binExp, long fractBits, int nSignificantBits )
-    {
-        int     nFractBits; // number of significant bits of fractBits;
-        int     nTinyBits;  // number of these to the right of the point.
-        int     decExp;
+            //
+            // Detect the special cases where all the numbers we are about
+            // to compute will fit in int or long integers.
+            // In these cases, we will avoid doing FDBigInteger arithmetic.
+            // We use the same algorithms, except that we "normalize"
+            // our FDBigIntegers before iterating. This is to make division easier,
+            // as it makes our fist guess (quotient of high-order words)
+            // more accurate!
+            //
+            // Some day, we'll write a stopping test that takes
+            // account of the asymmetry of the spacing of floating-point
+            // numbers below perfect powers of 2
+            // 26 Sept 96 is not that day.
+            // So we use a symmetric test.
+            //
+            // binary digits needed to represent B, approx.
+            int Bbits = nFractBits + B2 + (( B5 < N_5_BITS.length )? N_5_BITS[B5] : ( B5*3 ));
 
-        // Examine number. Determine if it is an easy case,
-        // which we can do pretty trivially using float/long conversion,
-        // or whether we must do real work.
-        nFractBits = countBits( fractBits );
-        nTinyBits = Math.max( 0, nFractBits - binExp - 1 );
-        if ( binExp <= maxSmallBinExp && binExp >= minSmallBinExp ){
-            // Look more closely at the number to decide if,
-            // with scaling by 10^nTinyBits, the result will fit in
-            // a long.
-            if ( (nTinyBits < long5pow.length) && ((nFractBits + n5bits[nTinyBits]) < 64 ) ){
-                /*
-                 * We can do this:
-                 * take the fraction bits, which are normalized.
-                 * (a) nTinyBits == 0: Shift left or right appropriately
-                 *     to align the binary point at the extreme right, i.e.
-                 *     where a long int point is expected to be. The integer
-                 *     result is easily converted to a string.
-                 * (b) nTinyBits > 0: Shift right by expShift-nFractBits,
-                 *     which effectively converts to long and scales by
-                 *     2^nTinyBits. Then multiply by 5^nTinyBits to
-                 *     complete the scaling. We know this won't overflow
-                 *     because we just counted the number of bits necessary
-                 *     in the result. The integer you get from this can
-                 *     then be converted to a string pretty easily.
-                 */
-                long halfULP;
-                if ( nTinyBits == 0 ) {
-                    if ( binExp > nSignificantBits ){
-                        halfULP = 1L << ( binExp-nSignificantBits-1);
+            // binary digits needed to represent 10*S, approx.
+            int tenSbits = S2+1 + (( (S5+1) < N_5_BITS.length )? N_5_BITS[(S5+1)] : ( (S5+1)*3 ));
+            if ( Bbits < 64 && tenSbits < 64){
+                if ( Bbits < 32 && tenSbits < 32){
+                    // wa-hoo! They're all ints!
+                    int b = ((int)fractBits * FDBigInteger.SMALL_5_POW[B5] ) << B2;
+                    int s = FDBigInteger.SMALL_5_POW[S5] << S2;
+                    int m = FDBigInteger.SMALL_5_POW[M5] << M2;
+                    int tens = s * 10;
+                    //
+                    // Unroll the first iteration. If our decExp estimate
+                    // was too high, our first quotient will be zero. In this
+                    // case, we discard it and decrement decExp.
+                    //
+                    ndigit = 0;
+                    q = b / s;
+                    b = 10 * ( b % s );
+                    m *= 10;
+                    low  = (b <  m );
+                    high = (b+m > tens );
+                    assert q < 10 : q; // excessively large digit
+                    if ( (q == 0) && ! high ){
+                        // oops. Usually ignore leading zero.
+                        decExp--;
+                    } else {
+                        digits[ndigit++] = (char)('0' + q);
+                    }
+                    //
+                    // HACK! Java spec sez that we always have at least
+                    // one digit after the . in either F- or E-form output.
+                    // Thus we will need more than one digit if we're using
+                    // E-form
+                    //
+                    if ( !isCompatibleFormat ||decExp < -3 || decExp >= 8 ){
+                        high = low = false;
+                    }
+                    while( ! low && ! high ){
+                        q = b / s;
+                        b = 10 * ( b % s );
+                        m *= 10;
+                        assert q < 10 : q; // excessively large digit
+                        if ( m > 0L ){
+                            low  = (b <  m );
+                            high = (b+m > tens );
+                        } else {
+                            // hack -- m might overflow!
+                            // in this case, it is certainly > b,
+                            // which won't
+                            // and b+m > tens, too, since that has overflowed
+                            // either!
+                            low = true;
+                            high = true;
+                        }
+                        digits[ndigit++] = (char)('0' + q);
+                    }
+                    lowDigitDifference = (b<<1) - tens;
+                    exactDecimalConversion  = (b == 0);
+                } else {
+                    // still good! they're all longs!
+                    long b = (fractBits * FDBigInteger.LONG_5_POW[B5] ) << B2;
+                    long s = FDBigInteger.LONG_5_POW[S5] << S2;
+                    long m = FDBigInteger.LONG_5_POW[M5] << M2;
+                    long tens = s * 10L;
+                    //
+                    // Unroll the first iteration. If our decExp estimate
+                    // was too high, our first quotient will be zero. In this
+                    // case, we discard it and decrement decExp.
+                    //
+                    ndigit = 0;
+                    q = (int) ( b / s );
+                    b = 10L * ( b % s );
+                    m *= 10L;
+                    low  = (b <  m );
+                    high = (b+m > tens );
+                    assert q < 10 : q; // excessively large digit
+                    if ( (q == 0) && ! high ){
+                        // oops. Usually ignore leading zero.
+                        decExp--;
                     } else {
-                        halfULP = 0L;
+                        digits[ndigit++] = (char)('0' + q);
+                    }
+                    //
+                    // HACK! Java spec sez that we always have at least
+                    // one digit after the . in either F- or E-form output.
+                    // Thus we will need more than one digit if we're using
+                    // E-form
+                    //
+                    if ( !isCompatibleFormat || decExp < -3 || decExp >= 8 ){
+                        high = low = false;
+                    }
+                    while( ! low && ! high ){
+                        q = (int) ( b / s );
+                        b = 10 * ( b % s );
+                        m *= 10;
+                        assert q < 10 : q;  // excessively large digit
+                        if ( m > 0L ){
+                            low  = (b <  m );
+                            high = (b+m > tens );
+                        } else {
+                            // hack -- m might overflow!
+                            // in this case, it is certainly > b,
+                            // which won't
+                            // and b+m > tens, too, since that has overflowed
+                            // either!
+                            low = true;
+                            high = true;
+                        }
+                        digits[ndigit++] = (char)('0' + q);
                     }
-                    if ( binExp >= expShift ){
-                        fractBits <<= (binExp-expShift);
-                    } else {
-                        fractBits >>>= (expShift-binExp) ;
+                    lowDigitDifference = (b<<1) - tens;
+                    exactDecimalConversion  = (b == 0);
+                }
+            } else {
+                //
+                // We really must do FDBigInteger arithmetic.
+                // Fist, construct our FDBigInteger initial values.
+                //
+                FDBigInteger Sval = FDBigInteger.valueOfPow52(S5, S2);
+                int shiftBias = Sval.getNormalizationBias();
+                Sval = Sval.leftShift(shiftBias); // normalize so that division works better
+
+                FDBigInteger Bval = FDBigInteger.valueOfMulPow52(fractBits, B5, B2 + shiftBias);
+                FDBigInteger Mval = FDBigInteger.valueOfPow52(M5 + 1, M2 + shiftBias + 1);
+
+                FDBigInteger tenSval = FDBigInteger.valueOfPow52(S5 + 1, S2 + shiftBias + 1); //Sval.mult( 10 );
+                //
+                // Unroll the first iteration. If our decExp estimate
+                // was too high, our first quotient will be zero. In this
+                // case, we discard it and decrement decExp.
+                //
+                ndigit = 0;
+                q = Bval.quoRemIteration( Sval );
+                low  = (Bval.cmp( Mval ) < 0);
+                high = tenSval.addAndCmp(Bval,Mval)<=0;
+
+                assert q < 10 : q; // excessively large digit
+                if ( (q == 0) && ! high ){
+                    // oops. Usually ignore leading zero.
+                    decExp--;
+                } else {
+                    digits[ndigit++] = (char)('0' + q);
+                }
+                //
+                // HACK! Java spec sez that we always have at least
+                // one digit after the . in either F- or E-form output.
+                // Thus we will need more than one digit if we're using
+                // E-form
+                //
+                if (!isCompatibleFormat || decExp < -3 || decExp >= 8 ){
+                    high = low = false;
+                }
+                while( ! low && ! high ){
+                    q = Bval.quoRemIteration( Sval );
+                    assert q < 10 : q;  // excessively large digit
+                    Mval = Mval.multBy10(); //Mval = Mval.mult( 10 );
+                    low  = (Bval.cmp( Mval ) < 0);
+                    high = tenSval.addAndCmp(Bval,Mval)<=0;
+                    digits[ndigit++] = (char)('0' + q);
+                }
+                if ( high && low ){
+                    Bval = Bval.leftShift(1);
+                    lowDigitDifference = Bval.cmp(tenSval);
+                } else {
+                    lowDigitDifference = 0L; // this here only for flow analysis!
+                }
+                exactDecimalConversion  = (Bval.cmp( FDBigInteger.ZERO ) == 0);
+            }
+            this.decExponent = decExp+1;
+            this.firstDigitIndex = 0;
+            this.nDigits = ndigit;
+            //
+            // Last digit gets rounded based on stopping condition.
+            //
+            if ( high ){
+                if ( low ){
+                    if ( lowDigitDifference == 0L ){
+                        // it's a tie!
+                        // choose based on which digits we like.
+                        if ( (digits[firstDigitIndex+nDigits-1]&1) != 0 ) {
+                            roundup();
+                        }
+                    } else if ( lowDigitDifference > 0 ){
+                        roundup();
                     }
-                    developLongDigits( 0, fractBits, halfULP );
+                } else {
+                    roundup();
+                }
+            }
+        }
+
+        // add one to the least significant digit.
+        // in the unlikely event there is a carry out, deal with it.
+        // assert that this will only happen where there
+        // is only one digit, e.g. (float)1e-44 seems to do it.
+        //
+        private void roundup() {
+            int i = (firstDigitIndex + nDigits - 1);
+            int q = digits[i];
+            if (q == '9') {
+                while (q == '9' && i > firstDigitIndex) {
+                    digits[i] = '0';
+                    q = digits[--i];
+                }
+                if (q == '9') {
+                    // carryout! High-order 1, rest 0s, larger exp.
+                    decExponent += 1;
+                    digits[firstDigitIndex] = '1';
                     return;
                 }
-                /*
-                 * The following causes excess digits to be printed
-                 * out in the single-float case. Our manipulation of
-                 * halfULP here is apparently not correct. If we
-                 * better understand how this works, perhaps we can
-                 * use this special case again. But for the time being,
-                 * we do not.
-                 * else {
-                 *     fractBits >>>= expShift+1-nFractBits;
-                 *     fractBits *= long5pow[ nTinyBits ];
-                 *     halfULP = long5pow[ nTinyBits ] >> (1+nSignificantBits-nFractBits);
-                 *     developLongDigits( -nTinyBits, fractBits, halfULP );
-                 *     return;
-                 * }
-                 */
+                // else fall through.
             }
+            digits[i] = (char) (q + 1);
+            decimalDigitsRoundedUp = true;
         }
-        /*
-         * This is the hard case. We are going to compute large positive
-         * integers B and S and integer decExp, s.t.
-         *      d = ( B / S ) * 10^decExp
-         *      1 <= B / S < 10
-         * Obvious choices are:
-         *      decExp = floor( log10(d) )
-         *      B      = d * 2^nTinyBits * 10^max( 0, -decExp )
-         *      S      = 10^max( 0, decExp) * 2^nTinyBits
-         * (noting that nTinyBits has already been forced to non-negative)
-         * I am also going to compute a large positive integer
-         *      M      = (1/2^nSignificantBits) * 2^nTinyBits * 10^max( 0, -decExp )
-         * i.e. M is (1/2) of the ULP of d, scaled like B.
-         * When we iterate through dividing B/S and picking off the
-         * quotient bits, we will know when to stop when the remainder
-         * is <= M.
-         *
-         * We keep track of powers of 2 and powers of 5.
-         */
 
-        /*
+        /**
          * Estimate decimal exponent. (If it is small-ish,
          * we could double-check.)
          *
@@ -630,324 +813,108 @@
          * and so we can estimate
          *      log10(d) ~=~ log10(d2) + binExp * log10(2)
          * take the floor and call it decExp.
-         * FIXME -- use more precise constants here. It costs no more.
          */
-        double d2 = Double.longBitsToDouble(
-            expOne | ( fractBits &~ fractHOB ) );
-        decExp = (int)Math.floor(
-            (d2-1.5D)*0.289529654D + 0.176091259 + (double)binExp * 0.301029995663981 );
-        int B2, B5; // powers of 2 and powers of 5, respectively, in B
-        int S2, S5; // powers of 2 and powers of 5, respectively, in S
-        int M2, M5; // powers of 2 and powers of 5, respectively, in M
-        int Bbits; // binary digits needed to represent B, approx.
-        int tenSbits; // binary digits needed to represent 10*S, approx.
-        FDBigInt Sval, Bval, Mval;
-
-        B5 = Math.max( 0, -decExp );
-        B2 = B5 + nTinyBits + binExp;
-
-        S5 = Math.max( 0, decExp );
-        S2 = S5 + nTinyBits;
-
-        M5 = B5;
-        M2 = B2 - nSignificantBits;
-
-        /*
-         * the long integer fractBits contains the (nFractBits) interesting
-         * bits from the mantissa of d ( hidden 1 added if necessary) followed
-         * by (expShift+1-nFractBits) zeros. In the interest of compactness,
-         * I will shift out those zeros before turning fractBits into a
-         * FDBigInt. The resulting whole number will be
-         *      d * 2^(nFractBits-1-binExp).
-         */
-        fractBits >>>= (expShift+1-nFractBits);
-        B2 -= nFractBits-1;
-        int common2factor = Math.min( B2, S2 );
-        B2 -= common2factor;
-        S2 -= common2factor;
-        M2 -= common2factor;
-
-        /*
-         * HACK!! For exact powers of two, the next smallest number
-         * is only half as far away as we think (because the meaning of
-         * ULP changes at power-of-two bounds) for this reason, we
-         * hack M2. Hope this works.
-         */
-        if ( nFractBits == 1 )
-            M2 -= 1;
-
-        if ( M2 < 0 ){
-            // oops.
-            // since we cannot scale M down far enough,
-            // we must scale the other values up.
-            B2 -= M2;
-            S2 -= M2;
-            M2 =  0;
-        }
-        /*
-         * Construct, Scale, iterate.
-         * Some day, we'll write a stopping test that takes
-         * account of the asymmetry of the spacing of floating-point
-         * numbers below perfect powers of 2
-         * 26 Sept 96 is not that day.
-         * So we use a symmetric test.
-         */
-        char digits[] = this.digits = new char[18];
-        int  ndigit = 0;
-        boolean low, high;
-        long lowDigitDifference;
-        int  q;
-
-        /*
-         * Detect the special cases where all the numbers we are about
-         * to compute will fit in int or long integers.
-         * In these cases, we will avoid doing FDBigInt arithmetic.
-         * We use the same algorithms, except that we "normalize"
-         * our FDBigInts before iterating. This is to make division easier,
-         * as it makes our fist guess (quotient of high-order words)
-         * more accurate!
-         *
-         * Some day, we'll write a stopping test that takes
-         * account of the asymmetry of the spacing of floating-point
-         * numbers below perfect powers of 2
-         * 26 Sept 96 is not that day.
-         * So we use a symmetric test.
-         */
-        Bbits = nFractBits + B2 + (( B5 < n5bits.length )? n5bits[B5] : ( B5*3 ));
-        tenSbits = S2+1 + (( (S5+1) < n5bits.length )? n5bits[(S5+1)] : ( (S5+1)*3 ));
-        if ( Bbits < 64 && tenSbits < 64){
-            if ( Bbits < 32 && tenSbits < 32){
-                // wa-hoo! They're all ints!
-                int b = ((int)fractBits * small5pow[B5] ) << B2;
-                int s = small5pow[S5] << S2;
-                int m = small5pow[M5] << M2;
-                int tens = s * 10;
-                /*
-                 * Unroll the first iteration. If our decExp estimate
-                 * was too high, our first quotient will be zero. In this
-                 * case, we discard it and decrement decExp.
-                 */
-                ndigit = 0;
-                q = b / s;
-                b = 10 * ( b % s );
-                m *= 10;
-                low  = (b <  m );
-                high = (b+m > tens );
-                assert q < 10 : q; // excessively large digit
-                if ( (q == 0) && ! high ){
-                    // oops. Usually ignore leading zero.
-                    decExp--;
-                } else {
-                    digits[ndigit++] = (char)('0' + q);
-                }
-                /*
-                 * HACK! Java spec sez that we always have at least
-                 * one digit after the . in either F- or E-form output.
-                 * Thus we will need more than one digit if we're using
-                 * E-form
-                 */
-                if ( decExp < -3 || decExp >= 8 ){
-                    high = low = false;
-                }
-                while( ! low && ! high ){
-                    q = b / s;
-                    b = 10 * ( b % s );
-                    m *= 10;
-                    assert q < 10 : q; // excessively large digit
-                    if ( m > 0L ){
-                        low  = (b <  m );
-                        high = (b+m > tens );
-                    } else {
-                        // hack -- m might overflow!
-                        // in this case, it is certainly > b,
-                        // which won't
-                        // and b+m > tens, too, since that has overflowed
-                        // either!
-                        low = true;
-                        high = true;
-                    }
-                    digits[ndigit++] = (char)('0' + q);
-                }
-                lowDigitDifference = (b<<1) - tens;
-                exactDecimalConversion  = (b == 0);
-            } else {
-                // still good! they're all longs!
-                long b = (fractBits * long5pow[B5] ) << B2;
-                long s = long5pow[S5] << S2;
-                long m = long5pow[M5] << M2;
-                long tens = s * 10L;
-                /*
-                 * Unroll the first iteration. If our decExp estimate
-                 * was too high, our first quotient will be zero. In this
-                 * case, we discard it and decrement decExp.
-                 */
-                ndigit = 0;
-                q = (int) ( b / s );
-                b = 10L * ( b % s );
-                m *= 10L;
-                low  = (b <  m );
-                high = (b+m > tens );
-                assert q < 10 : q; // excessively large digit
-                if ( (q == 0) && ! high ){
-                    // oops. Usually ignore leading zero.
-                    decExp--;
-                } else {
-                    digits[ndigit++] = (char)('0' + q);
-                }
-                /*
-                 * HACK! Java spec sez that we always have at least
-                 * one digit after the . in either F- or E-form output.
-                 * Thus we will need more than one digit if we're using
-                 * E-form
-                 */
-                if ( decExp < -3 || decExp >= 8 ){
-                    high = low = false;
-                }
-                while( ! low && ! high ){
-                    q = (int) ( b / s );
-                    b = 10 * ( b % s );
-                    m *= 10;
-                    assert q < 10 : q;  // excessively large digit
-                    if ( m > 0L ){
-                        low  = (b <  m );
-                        high = (b+m > tens );
-                    } else {
-                        // hack -- m might overflow!
-                        // in this case, it is certainly > b,
-                        // which won't
-                        // and b+m > tens, too, since that has overflowed
-                        // either!
-                        low = true;
-                        high = true;
-                    }
-                    digits[ndigit++] = (char)('0' + q);
-                }
-                lowDigitDifference = (b<<1) - tens;
-                exactDecimalConversion  = (b == 0);
-            }
-        } else {
-            FDBigInt ZeroVal = new FDBigInt(0);
-            FDBigInt tenSval;
-            int  shiftBias;
-
-            /*
-             * We really must do FDBigInt arithmetic.
-             * Fist, construct our FDBigInt initial values.
-             */
-            Bval = multPow52( new FDBigInt( fractBits  ), B5, B2 );
-            Sval = constructPow52( S5, S2 );
-            Mval = constructPow52( M5, M2 );
-
-
-            // normalize so that division works better
-            Bval.lshiftMe( shiftBias = Sval.normalizeMe() );
-            Mval.lshiftMe( shiftBias );
-            tenSval = Sval.mult( 10 );
-            /*
-             * Unroll the first iteration. If our decExp estimate
-             * was too high, our first quotient will be zero. In this
-             * case, we discard it and decrement decExp.
-             */
-            ndigit = 0;
-            q = Bval.quoRemIteration( Sval );
-            Mval = Mval.mult( 10 );
-            low  = (Bval.cmp( Mval ) < 0);
-            high = (Bval.add( Mval ).cmp( tenSval ) > 0 );
-            assert q < 10 : q; // excessively large digit
-            if ( (q == 0) && ! high ){
-                // oops. Usually ignore leading zero.
-                decExp--;
-            } else {
-                digits[ndigit++] = (char)('0' + q);
-            }
-            /*
-             * HACK! Java spec sez that we always have at least
-             * one digit after the . in either F- or E-form output.
-             * Thus we will need more than one digit if we're using
-             * E-form
-             */
-            if ( decExp < -3 || decExp >= 8 ){
-                high = low = false;
-            }
-            while( ! low && ! high ){
-                q = Bval.quoRemIteration( Sval );
-                Mval = Mval.mult( 10 );
-                assert q < 10 : q;  // excessively large digit
-                low  = (Bval.cmp( Mval ) < 0);
-                high = (Bval.add( Mval ).cmp( tenSval ) > 0 );
-                digits[ndigit++] = (char)('0' + q);
-            }
-            if ( high && low ){
-                Bval.lshiftMe(1);
-                lowDigitDifference = Bval.cmp(tenSval);
-            } else {
-                lowDigitDifference = 0L; // this here only for flow analysis!
-            }
-            exactDecimalConversion  = (Bval.cmp( ZeroVal ) == 0);
-        }
-        this.decExponent = decExp+1;
-        this.digits = digits;
-        this.nDigits = ndigit;
-        /*
-         * Last digit gets rounded based on stopping condition.
-         */
-        if ( high ){
-            if ( low ){
-                if ( lowDigitDifference == 0L ){
-                    // it's a tie!
-                    // choose based on which digits we like.
-                    if ( (digits[nDigits-1]&1) != 0 ) roundup();
-                } else if ( lowDigitDifference > 0 ){
-                    roundup();
-                }
-            } else {
-                roundup();
+        static int estimateDecExp(long fractBits, int binExp) {
+            double d2 = Double.longBitsToDouble( EXP_ONE | ( fractBits & DoubleConsts.SIGNIF_BIT_MASK ) );
+            double d = (d2-1.5D)*0.289529654D + 0.176091259 + (double)binExp * 0.301029995663981;
+            long dBits = Double.doubleToRawLongBits(d);  //can't be NaN here so use raw
+            int exponent = (int)((dBits & DoubleConsts.EXP_BIT_MASK) >> EXP_SHIFT) - DoubleConsts.EXP_BIAS;
+            boolean isNegative = (dBits & DoubleConsts.SIGN_BIT_MASK) != 0; // discover sign
+            if(exponent>=0 && exponent<52) { // hot path
+                long mask   = DoubleConsts.SIGNIF_BIT_MASK >> exponent;
+                int r = (int)(( (dBits&DoubleConsts.SIGNIF_BIT_MASK) | FRACT_HOB )>>(EXP_SHIFT-exponent));
+                return isNegative ? (((mask & dBits) == 0L ) ? -r : -r-1 ) : r;
+            } else if (exponent < 0) {
+                return (((dBits&~DoubleConsts.SIGN_BIT_MASK) == 0) ? 0 :
+                        ( (isNegative) ? -1 : 0) );
+            } else { //if (exponent >= 52)
+                return (int)d;
             }
         }
-    }
+
+        private static int insignificantDigits(int insignificant) {
+            int i;
+            for ( i = 0; insignificant >= 10L; i++ ) {
+                insignificant /= 10L;
+            }
+            return i;
+        }
 
-    public boolean decimalDigitsExact() {
-        return exactDecimalConversion;
-    }
+        /**
+         * Calculates
+         * <pre>
+         * insignificantDigitsForPow2(v) == insignificantDigits(1L<<v)
+         * </pre>
+         */
+        private static int insignificantDigitsForPow2(int p2) {
+            if(p2>1 && p2 < insignificantDigitsNumber.length) {
+                return insignificantDigitsNumber[p2];
+            }
+            return 0;
+        }
+
+        /**
+         *  If insignificant==(1L << ixd)
+         *  i = insignificantDigitsNumber[idx] is the same as:
+         *  int i;
+         *  for ( i = 0; insignificant >= 10L; i++ )
+         *         insignificant /= 10L;
+         */
+        private static int[] insignificantDigitsNumber = {
+            0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3,
+            4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7,
+            8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 11, 11, 11,
+            12, 12, 12, 12, 13, 13, 13, 14, 14, 14,
+            15, 15, 15, 15, 16, 16, 16, 17, 17, 17,
+            18, 18, 18, 19
+        };
 
-    public String
-    toString(){
-        // most brain-dead version
-        StringBuffer result = new StringBuffer( nDigits+8 );
-        if ( isNegative ){ result.append( '-' ); }
-        if ( isExceptional ){
-            result.append( digits, 0, nDigits );
-        } else {
-            result.append( "0.");
-            result.append( digits, 0, nDigits );
-            result.append('e');
-            result.append( decExponent );
-        }
-        return new String(result);
-    }
+        // approximately ceil( log2( long5pow[i] ) )
+        private static final int[] N_5_BITS = {
+                0,
+                3,
+                5,
+                7,
+                10,
+                12,
+                14,
+                17,
+                19,
+                21,
+                24,
+                26,
+                28,
+                31,
+                33,
+                35,
+                38,
+                40,
+                42,
+                45,
+                47,
+                49,
+                52,
+                54,
+                56,
+                59,
+                61,
+        };
 
-    public String toJavaFormatString() {
-        char result[] = perThreadBuffer.get();
-        int i = getChars(result);
-        return new String(result, 0, i);
-    }
-
-    private int getChars(char[] result) {
-        assert nDigits <= 19 : nDigits; // generous bound on size of nDigits
-        int i = 0;
-        if (isNegative) { result[0] = '-'; i = 1; }
-        if (isExceptional) {
-            System.arraycopy(digits, 0, result, i, nDigits);
-            i += nDigits;
-        } else {
+        private int getChars(char[] result) {
+            assert nDigits <= 19 : nDigits; // generous bound on size of nDigits
+            int i = 0;
+            if (isNegative) {
+                result[0] = '-';
+                i = 1;
+            }
             if (decExponent > 0 && decExponent < 8) {
                 // print digits.digits.
                 int charLength = Math.min(nDigits, decExponent);
-                System.arraycopy(digits, 0, result, i, charLength);
+                System.arraycopy(digits, firstDigitIndex, result, i, charLength);
                 i += charLength;
                 if (charLength < decExponent) {
-                    charLength = decExponent-charLength;
-                    System.arraycopy(zero, 0, result, i, charLength);
+                    charLength = decExponent - charLength;
+                    Arrays.fill(result,i,i+charLength,'0');
                     i += charLength;
                     result[i++] = '.';
                     result[i++] = '0';
@@ -955,27 +922,27 @@
                     result[i++] = '.';
                     if (charLength < nDigits) {
                         int t = nDigits - charLength;
-                        System.arraycopy(digits, charLength, result, i, t);
+                        System.arraycopy(digits, firstDigitIndex+charLength, result, i, t);
                         i += t;
                     } else {
                         result[i++] = '0';
                     }
                 }
-            } else if (decExponent <=0 && decExponent > -3) {
+            } else if (decExponent <= 0 && decExponent > -3) {
                 result[i++] = '0';
                 result[i++] = '.';
                 if (decExponent != 0) {
-                    System.arraycopy(zero, 0, result, i, -decExponent);
+                    Arrays.fill(result, i, i-decExponent, '0');
                     i -= decExponent;
                 }
-                System.arraycopy(digits, 0, result, i, nDigits);
+                System.arraycopy(digits, firstDigitIndex, result, i, nDigits);
                 i += nDigits;
             } else {
-                result[i++] = digits[0];
+                result[i++] = digits[firstDigitIndex];
                 result[i++] = '.';
                 if (nDigits > 1) {
-                    System.arraycopy(digits, 1, result, i, nDigits-1);
-                    i += nDigits-1;
+                    System.arraycopy(digits, firstDigitIndex+1, result, i, nDigits - 1);
+                    i += nDigits - 1;
                 } else {
                     result[i++] = '0';
                 }
@@ -983,48 +950,776 @@
                 int e;
                 if (decExponent <= 0) {
                     result[i++] = '-';
-                    e = -decExponent+1;
+                    e = -decExponent + 1;
                 } else {
-                    e = decExponent-1;
+                    e = decExponent - 1;
                 }
                 // decExponent has 1, 2, or 3, digits
                 if (e <= 9) {
-                    result[i++] = (char)(e+'0');
+                    result[i++] = (char) (e + '0');
                 } else if (e <= 99) {
-                    result[i++] = (char)(e/10 +'0');
-                    result[i++] = (char)(e%10 + '0');
+                    result[i++] = (char) (e / 10 + '0');
+                    result[i++] = (char) (e % 10 + '0');
                 } else {
-                    result[i++] = (char)(e/100+'0');
+                    result[i++] = (char) (e / 100 + '0');
                     e %= 100;
-                    result[i++] = (char)(e/10+'0');
-                    result[i++] = (char)(e%10 + '0');
+                    result[i++] = (char) (e / 10 + '0');
+                    result[i++] = (char) (e % 10 + '0');
                 }
             }
+            return i;
         }
-        return i;
+
+    }
+
+    private static final ThreadLocal<BinaryToASCIIBuffer> threadLocalBinaryToASCIIBuffer =
+            new ThreadLocal<BinaryToASCIIBuffer>() {
+                @Override
+                protected BinaryToASCIIBuffer initialValue() {
+                    return new BinaryToASCIIBuffer();
+                }
+            };
+
+    private static BinaryToASCIIBuffer getBinaryToASCIIBuffer() {
+        return threadLocalBinaryToASCIIBuffer.get();
+    }
+
+    /**
+     * A converter which can process an ASCII <code>String</code> representation
+     * of a single or double precision floating point value into a
+     * <code>float</code> or a <code>double</code>.
+     */
+    interface ASCIIToBinaryConverter {
+
+        double doubleValue();
+
+        float floatValue();
+
+    }
+
+    /**
+     * A <code>ASCIIToBinaryConverter</code> container for a <code>double</code>.
+     */
+    static class PreparedASCIIToBinaryBuffer implements ASCIIToBinaryConverter {
+        final private double doubleVal;
+        private int roundDir = 0;
+
+        public PreparedASCIIToBinaryBuffer(double doubleVal) {
+            this.doubleVal = doubleVal;
+        }
+
+        public PreparedASCIIToBinaryBuffer(double doubleVal, int roundDir) {
+            this.doubleVal = doubleVal;
+            this.roundDir = roundDir;
+        }
+
+        @Override
+        public double doubleValue() {
+            return doubleVal;
+        }
+
+        @Override
+        public float floatValue() {
+            return stickyRound(doubleVal,roundDir);
+        }
     }
 
-    // Per-thread buffer for string/stringbuffer conversion
-    private static ThreadLocal<char[]> perThreadBuffer = new ThreadLocal<char[]>() {
-            protected synchronized char[] initialValue() {
-                return new char[26];
+    static final ASCIIToBinaryConverter A2BC_POSITIVE_INFINITY = new PreparedASCIIToBinaryBuffer(Double.POSITIVE_INFINITY);
+    static final ASCIIToBinaryConverter A2BC_NEGATIVE_INFINITY = new PreparedASCIIToBinaryBuffer(Double.NEGATIVE_INFINITY);
+    static final ASCIIToBinaryConverter A2BC_NOT_A_NUMBER  = new PreparedASCIIToBinaryBuffer(Double.NaN);
+    static final ASCIIToBinaryConverter A2BC_POSITIVE_ZERO = new PreparedASCIIToBinaryBuffer(0.0d);
+    static final ASCIIToBinaryConverter A2BC_NEGATIVE_ZERO = new PreparedASCIIToBinaryBuffer(-0.0d);
+
+    /**
+     * A buffered implementation of <code>ASCIIToBinaryConverter</code>.
+     */
+    static class ASCIIToBinaryBuffer implements ASCIIToBinaryConverter {
+        boolean     isNegative;
+        int         decExponent;
+        char        digits[];
+        int         nDigits;
+        int         roundDir = 0; // set by doubleValue
+
+        ASCIIToBinaryBuffer( boolean negSign, int decExponent, char[] digits, int n)
+        {
+            this.isNegative = negSign;
+            this.decExponent = decExponent;
+            this.digits = digits;
+            this.nDigits = n;
+        }
+
+        @Override
+        public double doubleValue() {
+            return doubleValue(false);
+        }
+
+        /**
+         * Computes a number that is the ULP of the given value,
+         * for purposes of addition/subtraction. Generally easy.
+         * More difficult if subtracting and the argument
+         * is a normalized a power of 2, as the ULP changes at these points.
+         */
+        private static double ulp(double dval, boolean subtracting) {
+            long lbits = Double.doubleToLongBits(dval) & ~DoubleConsts.SIGN_BIT_MASK;
+            int binexp = (int) (lbits >>> EXP_SHIFT);
+            double ulpval;
+            if (subtracting && (binexp >= EXP_SHIFT) && ((lbits & DoubleConsts.SIGNIF_BIT_MASK) == 0L)) {
+                // for subtraction from normalized, powers of 2,
+                // use next-smaller exponent
+                binexp -= 1;
+            }
+            if (binexp > EXP_SHIFT) {
+                ulpval = Double.longBitsToDouble(((long) (binexp - EXP_SHIFT)) << EXP_SHIFT);
+            } else if (binexp == 0) {
+                ulpval = Double.MIN_VALUE;
+            } else {
+                ulpval = Double.longBitsToDouble(1L << (binexp - 1));
+            }
+            if (subtracting) {
+                ulpval = -ulpval;
+            }
+
+            return ulpval;
+        }
+
+        /**
+         * Takes a FloatingDecimal, which we presumably just scanned in,
+         * and finds out what its value is, as a double.
+         *
+         * AS A SIDE EFFECT, SET roundDir TO INDICATE PREFERRED
+         * ROUNDING DIRECTION in case the result is really destined
+         * for a single-precision float.
+         */
+        private strictfp double doubleValue(boolean mustSetRoundDir) {
+            int kDigits = Math.min(nDigits, MAX_DECIMAL_DIGITS + 1);
+            long lValue;
+            double dValue;
+            double rValue;
+
+            if (mustSetRoundDir) {
+                roundDir = 0;
+            }
+            //
+            // convert the lead kDigits to a long integer.
+            //
+            // (special performance hack: start to do it using int)
+            int iValue = (int) digits[0] - (int) '0';
+            int iDigits = Math.min(kDigits, INT_DECIMAL_DIGITS);
+            for (int i = 1; i < iDigits; i++) {
+                iValue = iValue * 10 + (int) digits[i] - (int) '0';
+            }
+            lValue = (long) iValue;
+            for (int i = iDigits; i < kDigits; i++) {
+                lValue = lValue * 10L + (long) ((int) digits[i] - (int) '0');
+            }
+            dValue = (double) lValue;
+            int exp = decExponent - kDigits;
+            //
+            // lValue now contains a long integer with the value of
+            // the first kDigits digits of the number.
+            // dValue contains the (double) of the same.
+            //
+
+            if (nDigits <= MAX_DECIMAL_DIGITS) {
+                //
+                // possibly an easy case.
+                // We know that the digits can be represented
+                // exactly. And if the exponent isn't too outrageous,
+                // the whole thing can be done with one operation,
+                // thus one rounding error.
+                // Note that all our constructors trim all leading and
+                // trailing zeros, so simple values (including zero)
+                // will always end up here
+                //
+                if (exp == 0 || dValue == 0.0) {
+                    return (isNegative) ? -dValue : dValue; // small floating integer
+                }
+                else if (exp >= 0) {
+                    if (exp <= MAX_SMALL_TEN) {
+                        //
+                        // Can get the answer with one operation,
+                        // thus one roundoff.
+                        //
+                        rValue = dValue * SMALL_10_POW[exp];
+                        if (mustSetRoundDir) {
+                            double tValue = rValue / SMALL_10_POW[exp];
+                            roundDir = (tValue == dValue) ? 0
+                                    : (tValue < dValue) ? 1
+                                    : -1;
+                        }
+                        return (isNegative) ? -rValue : rValue;
+                    }
+                    int slop = MAX_DECIMAL_DIGITS - kDigits;
+                    if (exp <= MAX_SMALL_TEN + slop) {
+                        //
+                        // We can multiply dValue by 10^(slop)
+                        // and it is still "small" and exact.
+                        // Then we can multiply by 10^(exp-slop)
+                        // with one rounding.
+                        //
+                        dValue *= SMALL_10_POW[slop];
+                        rValue = dValue * SMALL_10_POW[exp - slop];
+
+                        if (mustSetRoundDir) {
+                            double tValue = rValue / SMALL_10_POW[exp - slop];
+                            roundDir = (tValue == dValue) ? 0
+                                    : (tValue < dValue) ? 1
+                                    : -1;
+                        }
+                        return (isNegative) ? -rValue : rValue;
+                    }
+                    //
+                    // Else we have a hard case with a positive exp.
+                    //
+                } else {
+                    if (exp >= -MAX_SMALL_TEN) {
+                        //
+                        // Can get the answer in one division.
+                        //
+                        rValue = dValue / SMALL_10_POW[-exp];
+                        if (mustSetRoundDir) {
+                            double tValue = rValue * SMALL_10_POW[-exp];
+                            roundDir = (tValue == dValue) ? 0
+                                    : (tValue < dValue) ? 1
+                                    : -1;
+                        }
+                        return (isNegative) ? -rValue : rValue;
+                    }
+                    //
+                    // Else we have a hard case with a negative exp.
+                    //
+                }
+            }
+
+            //
+            // Harder cases:
+            // The sum of digits plus exponent is greater than
+            // what we think we can do with one error.
+            //
+            // Start by approximating the right answer by,
+            // naively, scaling by powers of 10.
+            //
+            if (exp > 0) {
+                if (decExponent > MAX_DECIMAL_EXPONENT + 1) {
+                    //
+                    // Lets face it. This is going to be
+                    // Infinity. Cut to the chase.
+                    //
+                    return (isNegative) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
+                }
+                if ((exp & 15) != 0) {
+                    dValue *= SMALL_10_POW[exp & 15];
+                }
+                if ((exp >>= 4) != 0) {
+                    int j;
+                    for (j = 0; exp > 1; j++, exp >>= 1) {
+                        if ((exp & 1) != 0) {
+                            dValue *= BIG_10_POW[j];
+                        }
+                    }
+                    //
+                    // The reason for the weird exp > 1 condition
+                    // in the above loop was so that the last multiply
+                    // would get unrolled. We handle it here.
+                    // It could overflow.
+                    //
+                    double t = dValue * BIG_10_POW[j];
+                    if (Double.isInfinite(t)) {
+                        //
+                        // It did overflow.
+                        // Look more closely at the result.
+                        // If the exponent is just one too large,
+                        // then use the maximum finite as our estimate
+                        // value. Else call the result infinity
+                        // and punt it.
+                        // ( I presume this could happen because
+                        // rounding forces the result here to be
+                        // an ULP or two larger than
+                        // Double.MAX_VALUE ).
+                        //
+                        t = dValue / 2.0;
+                        t *= BIG_10_POW[j];
+                        if (Double.isInfinite(t)) {
+                            return (isNegative) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
+                        }
+                        t = Double.MAX_VALUE;
+                    }
+                    dValue = t;
+                }
+            } else if (exp < 0) {
+                exp = -exp;
+                if (decExponent < MIN_DECIMAL_EXPONENT - 1) {
+                    //
+                    // Lets face it. This is going to be
+                    // zero. Cut to the chase.
+                    //
+                    return (isNegative) ? -0.0 : 0.0;
+                }
+                if ((exp & 15) != 0) {
+                    dValue /= SMALL_10_POW[exp & 15];
+                }
+                if ((exp >>= 4) != 0) {
+                    int j;
+                    for (j = 0; exp > 1; j++, exp >>= 1) {
+                        if ((exp & 1) != 0) {
+                            dValue *= TINY_10_POW[j];
+                        }
+                    }
+                    //
+                    // The reason for the weird exp > 1 condition
+                    // in the above loop was so that the last multiply
+                    // would get unrolled. We handle it here.
+                    // It could underflow.
+                    //
+                    double t = dValue * TINY_10_POW[j];
+                    if (t == 0.0) {
+                        //
+                        // It did underflow.
+                        // Look more closely at the result.
+                        // If the exponent is just one too small,
+                        // then use the minimum finite as our estimate
+                        // value. Else call the result 0.0
+                        // and punt it.
+                        // ( I presume this could happen because
+                        // rounding forces the result here to be
+                        // an ULP or two less than
+                        // Double.MIN_VALUE ).
+                        //
+                        t = dValue * 2.0;
+                        t *= TINY_10_POW[j];
+                        if (t == 0.0) {
+                            return (isNegative) ? -0.0 : 0.0;
+                        }
+                        t = Double.MIN_VALUE;
+                    }
+                    dValue = t;
+                }
             }
+
+            //
+            // dValue is now approximately the result.
+            // The hard part is adjusting it, by comparison
+            // with FDBigInteger arithmetic.
+            // Formulate the EXACT big-number result as
+            // bigD0 * 10^exp
+            //
+            FDBigInteger bigD0 = new FDBigInteger(lValue, digits, kDigits, nDigits);
+            exp = decExponent - nDigits;
+
+            final int B5 = Math.max(0, -exp); // powers of 5 in bigB, value is not modified inside correctionLoop
+            final int D5 = Math.max(0, exp); // powers of 5 in bigD, value is not modified inside correctionLoop
+            bigD0 = bigD0.multByPow52(D5, 0);
+            bigD0.makeImmutable();   // prevent bigD0 modification inside correctionLoop
+            FDBigInteger bigD = null;
+            int prevD2 = 0;
+
+            correctionLoop:
+            while (true) {
+                // here dValue can't be NaN, Infinity or zero
+                long bigBbits = Double.doubleToRawLongBits(dValue) & ~DoubleConsts.SIGN_BIT_MASK;
+                int binexp = (int) (bigBbits >>> EXP_SHIFT);
+                bigBbits &= DoubleConsts.SIGNIF_BIT_MASK;
+                if (binexp > 0) {
+                    bigBbits |= FRACT_HOB;
+                } else { // Normalize denormalized numbers.
+                    assert bigBbits != 0L : bigBbits; // doubleToBigInt(0.0)
+                    int leadingZeros = Long.numberOfLeadingZeros(bigBbits);
+                    int shift = leadingZeros - (63 - EXP_SHIFT);
+                    bigBbits <<= shift;
+                    binexp = 1 - shift;
+                }
+                binexp -= DoubleConsts.EXP_BIAS;
+                int lowOrderZeros = Long.numberOfTrailingZeros(bigBbits);
+                bigBbits >>>= lowOrderZeros;
+                final int bigIntExp = binexp - EXP_SHIFT + lowOrderZeros;
+                final int bigIntNBits = EXP_SHIFT + 1 - lowOrderZeros;
+
+                //
+                // Scale bigD, bigB appropriately for
+                // big-integer operations.
+                // Naively, we multiply by powers of ten
+                // and powers of two. What we actually do
+                // is keep track of the powers of 5 and
+                // powers of 2 we would use, then factor out
+                // common divisors before doing the work.
+                //
+                int B2 = B5; // powers of 2 in bigB
+                int D2 = D5; // powers of 2 in bigD
+                int Ulp2;   // powers of 2 in halfUlp.
+                if (bigIntExp >= 0) {
+                    B2 += bigIntExp;
+                } else {
+                    D2 -= bigIntExp;
+                }
+                Ulp2 = B2;
+                // shift bigB and bigD left by a number s. t.
+                // halfUlp is still an integer.
+                int hulpbias;
+                if (binexp <= -DoubleConsts.EXP_BIAS) {
+                    // This is going to be a denormalized number
+                    // (if not actually zero).
+                    // half an ULP is at 2^-(expBias+EXP_SHIFT+1)
+                    hulpbias = binexp + lowOrderZeros + DoubleConsts.EXP_BIAS;
+                } else {
+                    hulpbias = 1 + lowOrderZeros;
+                }
+                B2 += hulpbias;
+                D2 += hulpbias;
+                // if there are common factors of 2, we might just as well
+                // factor them out, as they add nothing useful.
+                int common2 = Math.min(B2, Math.min(D2, Ulp2));
+                B2 -= common2;
+                D2 -= common2;
+                Ulp2 -= common2;
+                // do multiplications by powers of 5 and 2
+                FDBigInteger bigB = FDBigInteger.valueOfMulPow52(bigBbits, B5, B2);
+                if (bigD == null || prevD2 != D2) {
+                    bigD = bigD0.leftShift(D2);
+                    prevD2 = D2;
+                }
+                //
+                // to recap:
+                // bigB is the scaled-big-int version of our floating-point
+                // candidate.
+                // bigD is the scaled-big-int version of the exact value
+                // as we understand it.
+                // halfUlp is 1/2 an ulp of bigB, except for special cases
+                // of exact powers of 2
+                //
+                // the plan is to compare bigB with bigD, and if the difference
+                // is less than halfUlp, then we're satisfied. Otherwise,
+                // use the ratio of difference to halfUlp to calculate a fudge
+                // factor to add to the floating value, then go 'round again.
+                //
+                FDBigInteger diff;
+                int cmpResult;
+                boolean overvalue;
+                if ((cmpResult = bigB.cmp(bigD)) > 0) {
+                    overvalue = true; // our candidate is too big.
+                    diff = bigB.leftInplaceSub(bigD); // bigB is not user further - reuse
+                    if ((bigIntNBits == 1) && (bigIntExp > -DoubleConsts.EXP_BIAS + 1)) {
+                        // candidate is a normalized exact power of 2 and
+                        // is too big (larger than Double.MIN_NORMAL). We will be subtracting.
+                        // For our purposes, ulp is the ulp of the
+                        // next smaller range.
+                        Ulp2 -= 1;
+                        if (Ulp2 < 0) {
+                            // rats. Cannot de-scale ulp this far.
+                            // must scale diff in other direction.
+                            Ulp2 = 0;
+                            diff = diff.leftShift(1);
+                        }
+                    }
+                } else if (cmpResult < 0) {
+                    overvalue = false; // our candidate is too small.
+                    diff = bigD.rightInplaceSub(bigB); // bigB is not user further - reuse
+                } else {
+                    // the candidate is exactly right!
+                    // this happens with surprising frequency
+                    break correctionLoop;
+                }
+                cmpResult = diff.cmpPow52(B5, Ulp2);
+                if ((cmpResult) < 0) {
+                    // difference is small.
+                    // this is close enough
+                    if (mustSetRoundDir) {
+                        roundDir = overvalue ? -1 : 1;
+                    }
+                    break correctionLoop;
+                } else if (cmpResult == 0) {
+                    // difference is exactly half an ULP
+                    // round to some other value maybe, then finish
+                    dValue += 0.5 * ulp(dValue, overvalue);
+                    // should check for bigIntNBits == 1 here??
+                    if (mustSetRoundDir) {
+                        roundDir = overvalue ? -1 : 1;
+                    }
+                    break correctionLoop;
+                } else {
+                    // difference is non-trivial.
+                    // could scale addend by ratio of difference to
+                    // halfUlp here, if we bothered to compute that difference.
+                    // Most of the time ( I hope ) it is about 1 anyway.
+                    dValue += ulp(dValue, overvalue);
+                    if (dValue == 0.0 || dValue == Double.POSITIVE_INFINITY) {
+                        break correctionLoop; // oops. Fell off end of range.
+                    }
+                    continue; // try again.
+                }
+
+            }
+            return (isNegative) ? -dValue : dValue;
+        }
+
+        /**
+         * Takes a FloatingDecimal, which we presumably just scanned in,
+         * and finds out what its value is, as a float.
+         * This is distinct from doubleValue() to avoid the extremely
+         * unlikely case of a double rounding error, wherein the conversion
+         * to double has one rounding error, and the conversion of that double
+         * to a float has another rounding error, IN THE WRONG DIRECTION,
+         * ( because of the preference to a zero low-order bit ).
+         */
+        @Override
+        public strictfp float floatValue() {
+            int kDigits = Math.min(nDigits, SINGLE_MAX_DECIMAL_DIGITS + 1);
+            int iValue;
+            float fValue;
+            //
+            // convert the lead kDigits to an integer.
+            //
+            iValue = (int) digits[0] - (int) '0';
+            for (int i = 1; i < kDigits; i++) {
+                iValue = iValue * 10 + (int) digits[i] - (int) '0';
+            }
+            fValue = (float) iValue;
+            int exp = decExponent - kDigits;
+            //
+            // iValue now contains an integer with the value of
+            // the first kDigits digits of the number.
+            // fValue contains the (float) of the same.
+            //
+
+            if (nDigits <= SINGLE_MAX_DECIMAL_DIGITS) {
+                //
+                // possibly an easy case.
+                // We know that the digits can be represented
+                // exactly. And if the exponent isn't too outrageous,
+                // the whole thing can be done with one operation,
+                // thus one rounding error.
+                // Note that all our constructors trim all leading and
+                // trailing zeros, so simple values (including zero)
+                // will always end up here.
+                //
+                if (exp == 0 || fValue == 0.0f) {
+                    return (isNegative) ? -fValue : fValue; // small floating integer
+                } else if (exp >= 0) {
+                    if (exp <= SINGLE_MAX_SMALL_TEN) {
+                        //
+                        // Can get the answer with one operation,
+                        // thus one roundoff.
+                        //
+                        fValue *= SINGLE_SMALL_10_POW[exp];
+                        return (isNegative) ? -fValue : fValue;
+                    }
+                    int slop = SINGLE_MAX_DECIMAL_DIGITS - kDigits;
+                    if (exp <= SINGLE_MAX_SMALL_TEN + slop) {
+                        //
+                        // We can multiply dValue by 10^(slop)
+                        // and it is still "small" and exact.
+                        // Then we can multiply by 10^(exp-slop)
+                        // with one rounding.
+                        //
+                        fValue *= SINGLE_SMALL_10_POW[slop];
+                        fValue *= SINGLE_SMALL_10_POW[exp - slop];
+                        return (isNegative) ? -fValue : fValue;
+                    }
+                    //
+                    // Else we have a hard case with a positive exp.
+                    //
+                } else {
+                    if (exp >= -SINGLE_MAX_SMALL_TEN) {
+                        //
+                        // Can get the answer in one division.
+                        //
+                        fValue /= SINGLE_SMALL_10_POW[-exp];
+                        return (isNegative) ? -fValue : fValue;
+                    }
+                    //
+                    // Else we have a hard case with a negative exp.
+                    //
+                }
+            } else if ((decExponent >= nDigits) && (nDigits + decExponent <= MAX_DECIMAL_DIGITS)) {
+                //
+                // In double-precision, this is an exact floating integer.
+                // So we can compute to double, then shorten to float
+                // with one round, and get the right answer.
+                //
+                // First, finish accumulating digits.
+                // Then convert that integer to a double, multiply
+                // by the appropriate power of ten, and convert to float.
+                //
+                long lValue = (long) iValue;
+                for (int i = kDigits; i < nDigits; i++) {
+                    lValue = lValue * 10L + (long) ((int) digits[i] - (int) '0');
+                }
+                double dValue = (double) lValue;
+                exp = decExponent - nDigits;
+                dValue *= SMALL_10_POW[exp];
+                fValue = (float) dValue;
+                return (isNegative) ? -fValue : fValue;
+
+            }
+            //
+            // Harder cases:
+            // The sum of digits plus exponent is greater than
+            // what we think we can do with one error.
+            //
+            // Start by weeding out obviously out-of-range
+            // results, then convert to double and go to
+            // common hard-case code.
+            //
+            if (decExponent > SINGLE_MAX_DECIMAL_EXPONENT + 1) {
+                //
+                // Lets face it. This is going to be
+                // Infinity. Cut to the chase.
+                //
+                return (isNegative) ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
+            } else if (decExponent < SINGLE_MIN_DECIMAL_EXPONENT - 1) {
+                //
+                // Lets face it. This is going to be
+                // zero. Cut to the chase.
+                //
+                return (isNegative) ? -0.0f : 0.0f;
+            }
+
+            //
+            // Here, we do 'way too much work, but throwing away
+            // our partial results, and going and doing the whole
+            // thing as double, then throwing away half the bits that computes
+            // when we convert back to float.
+            //
+            // The alternative is to reproduce the whole multiple-precision
+            // algorithm for float precision, or to try to parameterize it
+            // for common usage. The former will take about 400 lines of code,
+            // and the latter I tried without success. Thus the semi-hack
+            // answer here.
+            //
+            double dValue = doubleValue(true);
+            return stickyRound(dValue, roundDir);
+        }
+
+
+        /**
+         * All the positive powers of 10 that can be
+         * represented exactly in double/float.
+         */
+        private static final double[] SMALL_10_POW = {
+            1.0e0,
+            1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,
+            1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10,
+            1.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15,
+            1.0e16, 1.0e17, 1.0e18, 1.0e19, 1.0e20,
+            1.0e21, 1.0e22
         };
 
-    public void appendTo(Appendable buf) {
-          char result[] = perThreadBuffer.get();
-          int i = getChars(result);
-        if (buf instanceof StringBuilder)
-            ((StringBuilder) buf).append(result, 0, i);
-        else if (buf instanceof StringBuffer)
-            ((StringBuffer) buf).append(result, 0, i);
-        else
-            assert false;
+        private static final float[] SINGLE_SMALL_10_POW = {
+            1.0e0f,
+            1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
+            1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
+        };
+
+        private static final double[] BIG_10_POW = {
+            1e16, 1e32, 1e64, 1e128, 1e256 };
+        private static final double[] TINY_10_POW = {
+            1e-16, 1e-32, 1e-64, 1e-128, 1e-256 };
+
+        private static final int MAX_SMALL_TEN = SMALL_10_POW.length-1;
+        private static final int SINGLE_MAX_SMALL_TEN = SINGLE_SMALL_10_POW.length-1;
+
+    }
+
+    /**
+     * Returns a <code>BinaryToASCIIConverter</code> for a <code>double</code>.
+     * The returned object is a <code>ThreadLocal</code> variable of this class.
+     *
+     * @param d The double precision value to convert.
+     * @return The converter.
+     */
+    public static BinaryToASCIIConverter getBinaryToASCIIConverter(double d) {
+        return getBinaryToASCIIConverter(d, true);
+    }
+
+    /**
+     * Returns a <code>BinaryToASCIIConverter</code> for a <code>double</code>.
+     * The returned object is a <code>ThreadLocal</code> variable of this class.
+     *
+     * @param d The double precision value to convert.
+     * @param isCompatibleFormat
+     * @return The converter.
+     */
+    static BinaryToASCIIConverter getBinaryToASCIIConverter(double d, boolean isCompatibleFormat) {
+        long dBits = Double.doubleToRawLongBits(d);
+        boolean isNegative = (dBits&DoubleConsts.SIGN_BIT_MASK) != 0; // discover sign
+        long fractBits = dBits & DoubleConsts.SIGNIF_BIT_MASK;
+        int  binExp = (int)( (dBits&DoubleConsts.EXP_BIT_MASK) >> EXP_SHIFT );
+        // Discover obvious special cases of NaN and Infinity.
+        if ( binExp == (int)(DoubleConsts.EXP_BIT_MASK>>EXP_SHIFT) ) {
+            if ( fractBits == 0L ){
+                return isNegative ? B2AC_NEGATIVE_INFINITY : B2AC_POSITIVE_INFINITY;
+            } else {
+                return B2AC_NOT_A_NUMBER;
+            }
+        }
+        // Finish unpacking
+        // Normalize denormalized numbers.
+        // Insert assumed high-order bit for normalized numbers.
+        // Subtract exponent bias.
+        int  nSignificantBits;
+        if ( binExp == 0 ){
+            if ( fractBits == 0L ){
+                // not a denorm, just a 0!
+                return isNegative ? B2AC_NEGATIVE_ZERO : B2AC_POSITIVE_ZERO;
+            }
+            int leadingZeros = Long.numberOfLeadingZeros(fractBits);
+            int shift = leadingZeros-(63-EXP_SHIFT);
+            fractBits <<= shift;
+            binExp = 1 - shift;
+            nSignificantBits =  64-leadingZeros; // recall binExp is  - shift count.
+        } else {
+            fractBits |= FRACT_HOB;
+            nSignificantBits = EXP_SHIFT+1;
+        }
+        binExp -= DoubleConsts.EXP_BIAS;
+        BinaryToASCIIBuffer buf = getBinaryToASCIIBuffer();
+        buf.setSign(isNegative);
+        // call the routine that actually does all the hard work.
+        buf.dtoa(binExp, fractBits, nSignificantBits, isCompatibleFormat);
+        return buf;
+    }
+
+    private static BinaryToASCIIConverter getBinaryToASCIIConverter(float f) {
+        int fBits = Float.floatToRawIntBits( f );
+        boolean isNegative = (fBits&FloatConsts.SIGN_BIT_MASK) != 0;
+        int fractBits = fBits&FloatConsts.SIGNIF_BIT_MASK;
+        int binExp = (fBits&FloatConsts.EXP_BIT_MASK) >> SINGLE_EXP_SHIFT;
+        // Discover obvious special cases of NaN and Infinity.
+        if ( binExp == (FloatConsts.EXP_BIT_MASK>>SINGLE_EXP_SHIFT) ) {
+            if ( fractBits == 0L ){
+                return isNegative ? B2AC_NEGATIVE_INFINITY : B2AC_POSITIVE_INFINITY;
+            } else {
+                return B2AC_NOT_A_NUMBER;
+            }
+        }
+        // Finish unpacking
+        // Normalize denormalized numbers.
+        // Insert assumed high-order bit for normalized numbers.
+        // Subtract exponent bias.
+        int  nSignificantBits;
+        if ( binExp == 0 ){
+            if ( fractBits == 0 ){
+                // not a denorm, just a 0!
+                return isNegative ? B2AC_NEGATIVE_ZERO : B2AC_POSITIVE_ZERO;
+            }
+            int leadingZeros = Integer.numberOfLeadingZeros(fractBits);
+            int shift = leadingZeros-(31-SINGLE_EXP_SHIFT);
+            fractBits <<= shift;
+            binExp = 1 - shift;
+            nSignificantBits =  32 - leadingZeros; // recall binExp is  - shift count.
+        } else {
+            fractBits |= SINGLE_FRACT_HOB;
+            nSignificantBits = SINGLE_EXP_SHIFT+1;
+        }
+        binExp -= FloatConsts.EXP_BIAS;
+        BinaryToASCIIBuffer buf = getBinaryToASCIIBuffer();
+        buf.setSign(isNegative);
+        // call the routine that actually does all the hard work.
+        buf.dtoa(binExp, ((long)fractBits)<<(EXP_SHIFT-SINGLE_EXP_SHIFT), nSignificantBits, true);
+        return buf;
     }
 
     @SuppressWarnings("fallthrough")
-    public static FloatingDecimal
-    readJavaFormatString( String in ) throws NumberFormatException {
+    static ASCIIToBinaryConverter readJavaFormatString( String in ) throws NumberFormatException {
         boolean isNegative = false;
         boolean signSeen   = false;
         int     decExp;
@@ -1034,10 +1729,12 @@
         try{
             in = in.trim(); // don't fool around with white space.
                             // throws NullPointerException if null
-            int l = in.length();
-            if ( l == 0 ) throw new NumberFormatException("empty String");
+            int len = in.length();
+            if ( len == 0 ) {
+                throw new NumberFormatException("empty String");
+            }
             int i = 0;
-            switch ( c = in.charAt( i ) ){
+            switch (in.charAt(i)){
             case '-':
                 isNegative = true;
                 //FALLTHROUGH
@@ -1045,144 +1742,121 @@
                 i++;
                 signSeen = true;
             }
-
-            // Check for NaN and Infinity strings
             c = in.charAt(i);
-            if(c == 'N' || c == 'I') { // possible NaN or infinity
-                boolean potentialNaN = false;
-                char targetChars[] = null;  // char array of "NaN" or "Infinity"
-
-                if(c == 'N') {
-                    targetChars = notANumber;
-                    potentialNaN = true;
-                } else {
-                    targetChars = infinity;
+            if(c == 'N') { // Check for NaN
+                if((len-i)==NAN_LENGTH && in.indexOf(NAN_REP,i)==i) {
+                    return A2BC_NOT_A_NUMBER;
                 }
-
-                // compare Input string to "NaN" or "Infinity"
-                int j = 0;
-                while(i < l && j < targetChars.length) {
-                    if(in.charAt(i) == targetChars[j]) {
-                        i++; j++;
+                // something went wrong, throw exception
+                break parseNumber;
+            } else if(c == 'I') { // Check for Infinity strings
+                if((len-i)==INFINITY_LENGTH && in.indexOf(INFINITY_REP,i)==i) {
+                    return isNegative? A2BC_NEGATIVE_INFINITY : A2BC_POSITIVE_INFINITY;
+                }
+                // something went wrong, throw exception
+                break parseNumber;
+            } else if (c == '0')  { // check for hexadecimal floating-point number
+                if (len > i+1 ) {
+                    char ch = in.charAt(i+1);
+                    if (ch == 'x' || ch == 'X' ) { // possible hex string
+                        return parseHexString(in);
                     }
-                    else // something is amiss, throw exception
-                        break parseNumber;
-                }
-
-                // For the candidate string to be a NaN or infinity,
-                // all characters in input string and target char[]
-                // must be matched ==> j must equal targetChars.length
-                // and i must equal l
-                if( (j == targetChars.length) && (i == l) ) { // return NaN or infinity
-                    return (potentialNaN ? new FloatingDecimal(Double.NaN) // NaN has no sign
-                            : new FloatingDecimal(isNegative?
-                                                  Double.NEGATIVE_INFINITY:
-                                                  Double.POSITIVE_INFINITY)) ;
-                }
-                else { // something went wrong, throw exception
-                    break parseNumber;
-                }
-
-            } else if (c == '0')  { // check for hexadecimal floating-point number
-                if (l > i+1 ) {
-                    char ch = in.charAt(i+1);
-                    if (ch == 'x' || ch == 'X' ) // possible hex string
-                        return parseHexString(in);
                 }
             }  // look for and process decimal floating-point string
 
-            char[] digits = new char[ l ];
+            char[] digits = new char[ len ];
             int    nDigits= 0;
             boolean decSeen = false;
             int decPt = 0;
             int nLeadZero = 0;
             int nTrailZero= 0;
-        digitLoop:
-            while ( i < l ){
-                switch ( c = in.charAt( i ) ){
-                case '0':
-                    if ( nDigits > 0 ){
-                        nTrailZero += 1;
-                    } else {
-                        nLeadZero += 1;
-                    }
-                    break; // out of switch.
-                case '1':
-                case '2':
-                case '3':
-                case '4':
-                case '5':
-                case '6':
-                case '7':
-                case '8':
-                case '9':
-                    while ( nTrailZero > 0 ){
-                        digits[nDigits++] = '0';
-                        nTrailZero -= 1;
-                    }
-                    digits[nDigits++] = c;
-                    break; // out of switch.
-                case '.':
-                    if ( decSeen ){
+
+        skipLeadingZerosLoop:
+            while (i < len) {
+                c = in.charAt(i);
+                if (c == '0') {
+                    nLeadZero++;
+                } else if (c == '.') {
+                    if (decSeen) {
                         // already saw one ., this is the 2nd.
                         throw new NumberFormatException("multiple points");
                     }
                     decPt = i;
-                    if ( signSeen ){
+                    if (signSeen) {
                         decPt -= 1;
                     }
                     decSeen = true;
-                    break; // out of switch.
-                default:
+                } else {
+                    break skipLeadingZerosLoop;
+                }
+                i++;
+            }
+        digitLoop:
+            while (i < len) {
+                c = in.charAt(i);
+                if (c >= '1' && c <= '9') {
+                    digits[nDigits++] = c;
+                    nTrailZero = 0;
+                } else if (c == '0') {
+                    digits[nDigits++] = c;
+                    nTrailZero++;
+                } else if (c == '.') {
+                    if (decSeen) {
+                        // already saw one ., this is the 2nd.
+                        throw new NumberFormatException("multiple points");
+                    }
+                    decPt = i;
+                    if (signSeen) {
+                        decPt -= 1;
+                    }
+                    decSeen = true;
+                } else {
                     break digitLoop;
                 }
                 i++;
             }
-            /*
-             * At this point, we've scanned all the digits and decimal
-             * point we're going to see. Trim off leading and trailing
-             * zeros, which will just confuse us later, and adjust
-             * our initial decimal exponent accordingly.
-             * To review:
-             * we have seen i total characters.
-             * nLeadZero of them were zeros before any other digits.
-             * nTrailZero of them were zeros after any other digits.
-             * if ( decSeen ), then a . was seen after decPt characters
-             * ( including leading zeros which have been discarded )
-             * nDigits characters were neither lead nor trailing
-             * zeros, nor point
-             */
-            /*
-             * special hack: if we saw no non-zero digits, then the
-             * answer is zero!
-             * Unfortunately, we feel honor-bound to keep parsing!
-             */
-            if ( nDigits == 0 ){
-                digits = zero;
-                nDigits = 1;
-                if ( nLeadZero == 0 ){
-                    // we saw NO DIGITS AT ALL,
-                    // not even a crummy 0!
-                    // this is not allowed.
-                    break parseNumber; // go throw exception
-                }
-
+            nDigits -=nTrailZero;
+            //
+            // At this point, we've scanned all the digits and decimal
+            // point we're going to see. Trim off leading and trailing
+            // zeros, which will just confuse us later, and adjust
+            // our initial decimal exponent accordingly.
+            // To review:
+            // we have seen i total characters.
+            // nLeadZero of them were zeros before any other digits.
+            // nTrailZero of them were zeros after any other digits.
+            // if ( decSeen ), then a . was seen after decPt characters
+            // ( including leading zeros which have been discarded )
+            // nDigits characters were neither lead nor trailing
+            // zeros, nor point
+            //
+            //
+            // special hack: if we saw no non-zero digits, then the
+            // answer is zero!
+            // Unfortunately, we feel honor-bound to keep parsing!
+            //
+            boolean isZero = (nDigits == 0);
+            if ( isZero &&  nLeadZero == 0 ){
+                // we saw NO DIGITS AT ALL,
+                // not even a crummy 0!
+                // this is not allowed.
+                break parseNumber; // go throw exception
             }
-
-            /* Our initial exponent is decPt, adjusted by the number of
-             * discarded zeros. Or, if there was no decPt,
-             * then its just nDigits adjusted by discarded trailing zeros.
-             */
+            //
+            // Our initial exponent is decPt, adjusted by the number of
+            // discarded zeros. Or, if there was no decPt,
+            // then its just nDigits adjusted by discarded trailing zeros.
+            //
             if ( decSeen ){
                 decExp = decPt - nLeadZero;
             } else {
-                decExp = nDigits+nTrailZero;
+                decExp = nDigits + nTrailZero;
             }
 
-            /*
-             * Look for 'e' or 'E' and an optionally signed integer.
-             */
-            if ( (i < l) &&  (((c = in.charAt(i) )=='e') || (c == 'E') ) ){
+            //
+            // Look for 'e' or 'E' and an optionally signed integer.
+            //
+            if ( (i < len) &&  (((c = in.charAt(i) )=='e') || (c == 'E') ) ){
                 int expSign = 1;
                 int expVal  = 0;
                 int reallyBig = Integer.MAX_VALUE / 10;
@@ -1196,31 +1870,21 @@
                 }
                 int expAt = i;
             expLoop:
-                while ( i < l  ){
+                while ( i < len  ){
                     if ( expVal >= reallyBig ){
                         // the next character will cause integer
                         // overflow.
                         expOverflow = true;
                     }
-                    switch ( c = in.charAt(i++) ){
-                    case '0':
-                    case '1':
-                    case '2':
-                    case '3':
-                    case '4':
-                    case '5':
-                    case '6':
-                    case '7':
-                    case '8':
-                    case '9':
+                    c = in.charAt(i++);
+                    if(c>='0' && c<='9') {
                         expVal = expVal*10 + ( (int)c - (int)'0' );
-                        continue;
-                    default:
+                    } else {
                         i--;           // back up.
                         break expLoop; // stop parsing exponent.
                     }
                 }
-                int expLimit = bigDecimalExponent+nDigits+nTrailZero;
+                int expLimit = BIG_DECIMAL_EXPONENT+nDigits+nTrailZero;
                 if ( expOverflow || ( expVal > expLimit ) ){
                     //
                     // The intent here is to end up with
@@ -1247,1182 +1911,588 @@
                 // but then some trailing garbage, that might be ok.
                 // so we just fall through in that case.
                 // HUMBUG
-                if ( i == expAt )
+                if ( i == expAt ) {
                     break parseNumber; // certainly bad
+                }
             }
-            /*
-             * We parsed everything we could.
-             * If there are leftovers, then this is not good input!
-             */
-            if ( i < l &&
-                ((i != l - 1) ||
+            //
+            // We parsed everything we could.
+            // If there are leftovers, then this is not good input!
+            //
+            if ( i < len &&
+                ((i != len - 1) ||
                 (in.charAt(i) != 'f' &&
                  in.charAt(i) != 'F' &&
                  in.charAt(i) != 'd' &&
                  in.charAt(i) != 'D'))) {
                 break parseNumber; // go throw exception
             }
-
-            return new FloatingDecimal( isNegative, decExp, digits, nDigits,  false );
+            if(isZero) {
+                return isNegative ? A2BC_NEGATIVE_ZERO : A2BC_POSITIVE_ZERO;
+            }
+            return new ASCIIToBinaryBuffer(isNegative, decExp, digits, nDigits);
         } catch ( StringIndexOutOfBoundsException e ){ }
         throw new NumberFormatException("For input string: \"" + in + "\"");
     }
 
-    /*
-     * Take a FloatingDecimal, which we presumably just scanned in,
-     * and find out what its value is, as a double.
-     *
-     * AS A SIDE EFFECT, SET roundDir TO INDICATE PREFERRED
-     * ROUNDING DIRECTION in case the result is really destined
-     * for a single-precision float.
+    /**
+     * Rounds a double to a float.
+     * In addition to the fraction bits of the double,
+     * look at the class instance variable roundDir,
+     * which should help us avoid double-rounding error.
+     * roundDir was set in hardValueOf if the estimate was
+     * close enough, but not exact. It tells us which direction
+     * of rounding is preferred.
      */
-
-    public strictfp double doubleValue(){
-        int     kDigits = Math.min( nDigits, maxDecimalDigits+1 );
-        long    lValue;
-        double  dValue;
-        double  rValue, tValue;
-
-        // First, check for NaN and Infinity values
-        if(digits == infinity || digits == notANumber) {
-            if(digits == notANumber)
-                return Double.NaN;
-            else
-                return (isNegative?Double.NEGATIVE_INFINITY:Double.POSITIVE_INFINITY);
-        }
-        else {
-            if (mustSetRoundDir) {
-                roundDir = 0;
-            }
-            /*
-             * convert the lead kDigits to a long integer.
-             */
-            // (special performance hack: start to do it using int)
-            int iValue = (int)digits[0]-(int)'0';
-            int iDigits = Math.min( kDigits, intDecimalDigits );
-            for ( int i=1; i < iDigits; i++ ){
-                iValue = iValue*10 + (int)digits[i]-(int)'0';
-            }
-            lValue = (long)iValue;
-            for ( int i=iDigits; i < kDigits; i++ ){
-                lValue = lValue*10L + (long)((int)digits[i]-(int)'0');
-            }
-            dValue = (double)lValue;
-            int exp = decExponent-kDigits;
-            /*
-             * lValue now contains a long integer with the value of
-             * the first kDigits digits of the number.
-             * dValue contains the (double) of the same.
-             */
-
-            if ( nDigits <= maxDecimalDigits ){
-                /*
-                 * possibly an easy case.
-                 * We know that the digits can be represented
-                 * exactly. And if the exponent isn't too outrageous,
-                 * the whole thing can be done with one operation,
-                 * thus one rounding error.
-                 * Note that all our constructors trim all leading and
-                 * trailing zeros, so simple values (including zero)
-                 * will always end up here
-                 */
-                if (exp == 0 || dValue == 0.0)
-                    return (isNegative)? -dValue : dValue; // small floating integer
-                else if ( exp >= 0 ){
-                    if ( exp <= maxSmallTen ){
-                        /*
-                         * Can get the answer with one operation,
-                         * thus one roundoff.
-                         */
-                        rValue = dValue * small10pow[exp];
-                        if ( mustSetRoundDir ){
-                            tValue = rValue / small10pow[exp];
-                            roundDir = ( tValue ==  dValue ) ? 0
-                                :( tValue < dValue ) ? 1
-                                : -1;
-                        }
-                        return (isNegative)? -rValue : rValue;
-                    }
-                    int slop = maxDecimalDigits - kDigits;
-                    if ( exp <= maxSmallTen+slop ){
-                        /*
-                         * We can multiply dValue by 10^(slop)
-                         * and it is still "small" and exact.
-                         * Then we can multiply by 10^(exp-slop)
-                         * with one rounding.
-                         */
-                        dValue *= small10pow[slop];
-                        rValue = dValue * small10pow[exp-slop];
-
-                        if ( mustSetRoundDir ){
-                            tValue = rValue / small10pow[exp-slop];
-                            roundDir = ( tValue ==  dValue ) ? 0
-                                :( tValue < dValue ) ? 1
-                                : -1;
-                        }
-                        return (isNegative)? -rValue : rValue;
-                    }
-                    /*
-                     * Else we have a hard case with a positive exp.
-                     */
-                } else {
-                    if ( exp >= -maxSmallTen ){
-                        /*
-                         * Can get the answer in one division.
-                         */
-                        rValue = dValue / small10pow[-exp];
-                        tValue = rValue * small10pow[-exp];
-                        if ( mustSetRoundDir ){
-                            roundDir = ( tValue ==  dValue ) ? 0
-                                :( tValue < dValue ) ? 1
-                                : -1;
-                        }
-                        return (isNegative)? -rValue : rValue;
-                    }
-                    /*
-                     * Else we have a hard case with a negative exp.
-                     */
-                }
-            }
-
-            /*
-             * Harder cases:
-             * The sum of digits plus exponent is greater than
-             * what we think we can do with one error.
-             *
-             * Start by approximating the right answer by,
-             * naively, scaling by powers of 10.
-             */
-            if ( exp > 0 ){
-                if ( decExponent > maxDecimalExponent+1 ){
-                    /*
-                     * Lets face it. This is going to be
-                     * Infinity. Cut to the chase.
-                     */
-                    return (isNegative)? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
-                }
-                if ( (exp&15) != 0 ){
-                    dValue *= small10pow[exp&15];
-                }
-                if ( (exp>>=4) != 0 ){
-                    int j;
-                    for( j = 0; exp > 1; j++, exp>>=1 ){
-                        if ( (exp&1)!=0)
-                            dValue *= big10pow[j];
-                    }
-                    /*
-                     * The reason for the weird exp > 1 condition
-                     * in the above loop was so that the last multiply
-                     * would get unrolled. We handle it here.
-                     * It could overflow.
-                     */
-                    double t = dValue * big10pow[j];
-                    if ( Double.isInfinite( t ) ){
-                        /*
-                         * It did overflow.
-                         * Look more closely at the result.
-                         * If the exponent is just one too large,
-                         * then use the maximum finite as our estimate
-                         * value. Else call the result infinity
-                         * and punt it.
-                         * ( I presume this could happen because
-                         * rounding forces the result here to be
-                         * an ULP or two larger than
-                         * Double.MAX_VALUE ).
-                         */
-                        t = dValue / 2.0;
-                        t *= big10pow[j];
-                        if ( Double.isInfinite( t ) ){
-                            return (isNegative)? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
-                        }
-                        t = Double.MAX_VALUE;
-                    }
-                    dValue = t;
-                }
-            } else if ( exp < 0 ){
-                exp = -exp;
-                if ( decExponent < minDecimalExponent-1 ){
-                    /*
-                     * Lets face it. This is going to be
-                     * zero. Cut to the chase.
-                     */
-                    return (isNegative)? -0.0 : 0.0;
-                }
-                if ( (exp&15) != 0 ){
-                    dValue /= small10pow[exp&15];
-                }
-                if ( (exp>>=4) != 0 ){
-                    int j;
-                    for( j = 0; exp > 1; j++, exp>>=1 ){
-                        if ( (exp&1)!=0)
-                            dValue *= tiny10pow[j];
-                    }
-                    /*
-                     * The reason for the weird exp > 1 condition
-                     * in the above loop was so that the last multiply
-                     * would get unrolled. We handle it here.
-                     * It could underflow.
-                     */
-                    double t = dValue * tiny10pow[j];
-                    if ( t == 0.0 ){
-                        /*
-                         * It did underflow.
-                         * Look more closely at the result.
-                         * If the exponent is just one too small,
-                         * then use the minimum finite as our estimate
-                         * value. Else call the result 0.0
-                         * and punt it.
-                         * ( I presume this could happen because
-                         * rounding forces the result here to be
-                         * an ULP or two less than
-                         * Double.MIN_VALUE ).
-                         */
-                        t = dValue * 2.0;
-                        t *= tiny10pow[j];
-                        if ( t == 0.0 ){
-                            return (isNegative)? -0.0 : 0.0;
-                        }
-                        t = Double.MIN_VALUE;
-                    }
-                    dValue = t;
-                }
+    static float stickyRound( double dval, int roundDirection ){
+        if(roundDirection!=0) {
+            long lbits = Double.doubleToRawLongBits( dval );
+            long binexp = lbits & DoubleConsts.EXP_BIT_MASK;
+            if ( binexp == 0L || binexp == DoubleConsts.EXP_BIT_MASK ){
+                // what we have here is special.
+                // don't worry, the right thing will happen.
+                return (float) dval;
             }
-
-            /*
-             * dValue is now approximately the result.
-             * The hard part is adjusting it, by comparison
-             * with FDBigInt arithmetic.
-             * Formulate the EXACT big-number result as
-             * bigD0 * 10^exp
-             */
-            FDBigInt bigD0 = new FDBigInt( lValue, digits, kDigits, nDigits );
-            exp   = decExponent - nDigits;
-
-            correctionLoop:
-            while(true){
-                /* AS A SIDE EFFECT, THIS METHOD WILL SET THE INSTANCE VARIABLES
-                 * bigIntExp and bigIntNBits
-                 */
-                FDBigInt bigB = doubleToBigInt( dValue );
-
-                /*
-                 * Scale bigD, bigB appropriately for
-                 * big-integer operations.
-                 * Naively, we multiply by powers of ten
-                 * and powers of two. What we actually do
-                 * is keep track of the powers of 5 and
-                 * powers of 2 we would use, then factor out
-                 * common divisors before doing the work.
-                 */
-                int B2, B5; // powers of 2, 5 in bigB
-                int     D2, D5; // powers of 2, 5 in bigD
-                int Ulp2;   // powers of 2 in halfUlp.
-                if ( exp >= 0 ){
-                    B2 = B5 = 0;
-                    D2 = D5 = exp;
-                } else {
-                    B2 = B5 = -exp;
-                    D2 = D5 = 0;
-                }
-                if ( bigIntExp >= 0 ){
-                    B2 += bigIntExp;
-                } else {
-                    D2 -= bigIntExp;
-                }
-                Ulp2 = B2;
-                // shift bigB and bigD left by a number s. t.
-                // halfUlp is still an integer.
-                int hulpbias;
-                if ( bigIntExp+bigIntNBits <= -expBias+1 ){
-                    // This is going to be a denormalized number
-                    // (if not actually zero).
-                    // half an ULP is at 2^-(expBias+expShift+1)
-                    hulpbias = bigIntExp+ expBias + expShift;
-                } else {
-                    hulpbias = expShift + 2 - bigIntNBits;
-                }
-                B2 += hulpbias;
-                D2 += hulpbias;
-                // if there are common factors of 2, we might just as well
-                // factor them out, as they add nothing useful.
-                int common2 = Math.min( B2, Math.min( D2, Ulp2 ) );
-                B2 -= common2;
-                D2 -= common2;
-                Ulp2 -= common2;
-                // do multiplications by powers of 5 and 2
-                bigB = multPow52( bigB, B5, B2 );
-                FDBigInt bigD = multPow52( new FDBigInt( bigD0 ), D5, D2 );
-                //
-                // to recap:
-                // bigB is the scaled-big-int version of our floating-point
-                // candidate.
-                // bigD is the scaled-big-int version of the exact value
-                // as we understand it.
-                // halfUlp is 1/2 an ulp of bigB, except for special cases
-                // of exact powers of 2
-                //
-                // the plan is to compare bigB with bigD, and if the difference
-                // is less than halfUlp, then we're satisfied. Otherwise,
-                // use the ratio of difference to halfUlp to calculate a fudge
-                // factor to add to the floating value, then go 'round again.
-                //
-                FDBigInt diff;
-                int cmpResult;
-                boolean overvalue;
-                if ( (cmpResult = bigB.cmp( bigD ) ) > 0 ){
-                    overvalue = true; // our candidate is too big.
-                    diff = bigB.sub( bigD );
-                    if ( (bigIntNBits == 1) && (bigIntExp > -expBias+1) ){
-                        // candidate is a normalized exact power of 2 and
-                        // is too big. We will be subtracting.
-                        // For our purposes, ulp is the ulp of the
-                        // next smaller range.
-                        Ulp2 -= 1;
-                        if ( Ulp2 < 0 ){
-                            // rats. Cannot de-scale ulp this far.
-                            // must scale diff in other direction.
-                            Ulp2 = 0;
-                            diff.lshiftMe( 1 );
-                        }
-                    }
-                } else if ( cmpResult < 0 ){
-                    overvalue = false; // our candidate is too small.
-                    diff = bigD.sub( bigB );
-                } else {
-                    // the candidate is exactly right!
-                    // this happens with surprising frequency
-                    break correctionLoop;
-                }
-                FDBigInt halfUlp = constructPow52( B5, Ulp2 );
-                if ( (cmpResult = diff.cmp( halfUlp ) ) < 0 ){
-                    // difference is small.
-                    // this is close enough
-                    if (mustSetRoundDir) {
-                        roundDir = overvalue ? -1 : 1;
-                    }
-                    break correctionLoop;
-                } else if ( cmpResult == 0 ){
-                    // difference is exactly half an ULP
-                    // round to some other value maybe, then finish
-                    dValue += 0.5*ulp( dValue, overvalue );
-                    // should check for bigIntNBits == 1 here??
-                    if (mustSetRoundDir) {
-                        roundDir = overvalue ? -1 : 1;
-                    }
-                    break correctionLoop;
-                } else {
-                    // difference is non-trivial.
-                    // could scale addend by ratio of difference to
-                    // halfUlp here, if we bothered to compute that difference.
-                    // Most of the time ( I hope ) it is about 1 anyway.
-                    dValue += ulp( dValue, overvalue );
-                    if ( dValue == 0.0 || dValue == Double.POSITIVE_INFINITY )
-                        break correctionLoop; // oops. Fell off end of range.
-                    continue; // try again.
-                }
-
-            }
-            return (isNegative)? -dValue : dValue;
-        }
-    }
-
-    /*
-     * Take a FloatingDecimal, which we presumably just scanned in,
-     * and find out what its value is, as a float.
-     * This is distinct from doubleValue() to avoid the extremely
-     * unlikely case of a double rounding error, wherein the conversion
-     * to double has one rounding error, and the conversion of that double
-     * to a float has another rounding error, IN THE WRONG DIRECTION,
-     * ( because of the preference to a zero low-order bit ).
-     */
-
-    public strictfp float floatValue(){
-        int     kDigits = Math.min( nDigits, singleMaxDecimalDigits+1 );
-        int     iValue;
-        float   fValue;
-
-        // First, check for NaN and Infinity values
-        if(digits == infinity || digits == notANumber) {
-            if(digits == notANumber)
-                return Float.NaN;
-            else
-                return (isNegative?Float.NEGATIVE_INFINITY:Float.POSITIVE_INFINITY);
-        }
-        else {
-            /*
-             * convert the lead kDigits to an integer.
-             */
-            iValue = (int)digits[0]-(int)'0';
-            for ( int i=1; i < kDigits; i++ ){
-                iValue = iValue*10 + (int)digits[i]-(int)'0';
-            }
-            fValue = (float)iValue;
-            int exp = decExponent-kDigits;
-            /*
-             * iValue now contains an integer with the value of
-             * the first kDigits digits of the number.
-             * fValue contains the (float) of the same.
-             */
-
-            if ( nDigits <= singleMaxDecimalDigits ){
-                /*
-                 * possibly an easy case.
-                 * We know that the digits can be represented
-                 * exactly. And if the exponent isn't too outrageous,
-                 * the whole thing can be done with one operation,
-                 * thus one rounding error.
-                 * Note that all our constructors trim all leading and
-                 * trailing zeros, so simple values (including zero)
-                 * will always end up here.
-                 */
-                if (exp == 0 || fValue == 0.0f)
-                    return (isNegative)? -fValue : fValue; // small floating integer
-                else if ( exp >= 0 ){
-                    if ( exp <= singleMaxSmallTen ){
-                        /*
-                         * Can get the answer with one operation,
-                         * thus one roundoff.
-                         */
-                        fValue *= singleSmall10pow[exp];
-                        return (isNegative)? -fValue : fValue;
-                    }
-                    int slop = singleMaxDecimalDigits - kDigits;
-                    if ( exp <= singleMaxSmallTen+slop ){
-                        /*
-                         * We can multiply dValue by 10^(slop)
-                         * and it is still "small" and exact.
-                         * Then we can multiply by 10^(exp-slop)
-                         * with one rounding.
-                         */
-                        fValue *= singleSmall10pow[slop];
-                        fValue *= singleSmall10pow[exp-slop];
-                        return (isNegative)? -fValue : fValue;
-                    }
-                    /*
-                     * Else we have a hard case with a positive exp.
-                     */
-                } else {
-                    if ( exp >= -singleMaxSmallTen ){
-                        /*
-                         * Can get the answer in one division.
-                         */
-                        fValue /= singleSmall10pow[-exp];
-                        return (isNegative)? -fValue : fValue;
-                    }
-                    /*
-                     * Else we have a hard case with a negative exp.
-                     */
-                }
-            } else if ( (decExponent >= nDigits) && (nDigits+decExponent <= maxDecimalDigits) ){
-                /*
-                 * In double-precision, this is an exact floating integer.
-                 * So we can compute to double, then shorten to float
-                 * with one round, and get the right answer.
-                 *
-                 * First, finish accumulating digits.
-                 * Then convert that integer to a double, multiply
-                 * by the appropriate power of ten, and convert to float.
-                 */
-                long lValue = (long)iValue;
-                for ( int i=kDigits; i < nDigits; i++ ){
-                    lValue = lValue*10L + (long)((int)digits[i]-(int)'0');
-                }
-                double dValue = (double)lValue;
-                exp = decExponent-nDigits;
-                dValue *= small10pow[exp];
-                fValue = (float)dValue;
-                return (isNegative)? -fValue : fValue;
-
-            }
-            /*
-             * Harder cases:
-             * The sum of digits plus exponent is greater than
-             * what we think we can do with one error.
-             *
-             * Start by weeding out obviously out-of-range
-             * results, then convert to double and go to
-             * common hard-case code.
-             */
-            if ( decExponent > singleMaxDecimalExponent+1 ){
-                /*
-                 * Lets face it. This is going to be
-                 * Infinity. Cut to the chase.
-                 */
-                return (isNegative)? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
-            } else if ( decExponent < singleMinDecimalExponent-1 ){
-                /*
-                 * Lets face it. This is going to be
-                 * zero. Cut to the chase.
-                 */
-                return (isNegative)? -0.0f : 0.0f;
-            }
-
-            /*
-             * Here, we do 'way too much work, but throwing away
-             * our partial results, and going and doing the whole
-             * thing as double, then throwing away half the bits that computes
-             * when we convert back to float.
-             *
-             * The alternative is to reproduce the whole multiple-precision
-             * algorithm for float precision, or to try to parameterize it
-             * for common usage. The former will take about 400 lines of code,
-             * and the latter I tried without success. Thus the semi-hack
-             * answer here.
-             */
-            mustSetRoundDir = !fromHex;
-            double dValue = doubleValue();
-            return stickyRound( dValue );
+            lbits += (long)roundDirection; // hack-o-matic.
+            return (float)Double.longBitsToDouble( lbits );
+        } else {
+            return (float)dval;
         }
     }
 
 
-    /*
-     * All the positive powers of 10 that can be
-     * represented exactly in double/float.
-     */
-    private static final double small10pow[] = {
-        1.0e0,
-        1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,
-        1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10,
-        1.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15,
-        1.0e16, 1.0e17, 1.0e18, 1.0e19, 1.0e20,
-        1.0e21, 1.0e22
-    };
-
-    private static final float singleSmall10pow[] = {
-        1.0e0f,
-        1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
-        1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
-    };
-
-    private static final double big10pow[] = {
-        1e16, 1e32, 1e64, 1e128, 1e256 };
-    private static final double tiny10pow[] = {
-        1e-16, 1e-32, 1e-64, 1e-128, 1e-256 };
-
-    private static final int maxSmallTen = small10pow.length-1;
-    private static final int singleMaxSmallTen = singleSmall10pow.length-1;
-
-    private static final int small5pow[] = {
-        1,
-        5,
-        5*5,
-        5*5*5,
-        5*5*5*5,
-        5*5*5*5*5,
-        5*5*5*5*5*5,
-        5*5*5*5*5*5*5,
-        5*5*5*5*5*5*5*5,
-        5*5*5*5*5*5*5*5*5,
-        5*5*5*5*5*5*5*5*5*5,
-        5*5*5*5*5*5*5*5*5*5*5,
-        5*5*5*5*5*5*5*5*5*5*5*5,
-        5*5*5*5*5*5*5*5*5*5*5*5*5
-    };
-
-
-    private static final long long5pow[] = {
-        1L,
-        5L,
-        5L*5,
-        5L*5*5,
-        5L*5*5*5,
-        5L*5*5*5*5,
-        5L*5*5*5*5*5,
-        5L*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-    };
-
-    // approximately ceil( log2( long5pow[i] ) )
-    private static final int n5bits[] = {
-        0,
-        3,
-        5,
-        7,
-        10,
-        12,
-        14,
-        17,
-        19,
-        21,
-        24,
-        26,
-        28,
-        31,
-        33,
-        35,
-        38,
-        40,
-        42,
-        45,
-        47,
-        49,
-        52,
-        54,
-        56,
-        59,
-        61,
-    };
-
-    private static final char infinity[] = { 'I', 'n', 'f', 'i', 'n', 'i', 't', 'y' };
-    private static final char notANumber[] = { 'N', 'a', 'N' };
-    private static final char zero[] = { '0', '0', '0', '0', '0', '0', '0', '0' };
-
-
-    /*
-     * Grammar is compatible with hexadecimal floating-point constants
-     * described in section 6.4.4.2 of the C99 specification.
-     */
-    private static Pattern hexFloatPattern = null;
-    private static synchronized Pattern getHexFloatPattern() {
-        if (hexFloatPattern == null) {
-           hexFloatPattern = Pattern.compile(
+    private static class HexFloatPattern {
+        /**
+         * Grammar is compatible with hexadecimal floating-point constants
+         * described in section 6.4.4.2 of the C99 specification.
+         */
+        private static final Pattern VALUE = Pattern.compile(
                    //1           234                   56                7                   8      9
                     "([-+])?0[xX](((\\p{XDigit}+)\\.?)|((\\p{XDigit}*)\\.(\\p{XDigit}+)))[pP]([-+])?(\\p{Digit}+)[fFdD]?"
                     );
-        }
-        return hexFloatPattern;
     }
 
-    /*
-     * Convert string s to a suitable floating decimal; uses the
-     * double constructor and set the roundDir variable appropriately
+    /**
+     * Converts string s to a suitable floating decimal; uses the
+     * double constructor and sets the roundDir variable appropriately
      * in case the value is later converted to a float.
+     *
+     * @param s The <code>String</code> to parse.
      */
-   static FloatingDecimal parseHexString(String s) {
-        // Verify string is a member of the hexadecimal floating-point
-        // string language.
-        Matcher m = getHexFloatPattern().matcher(s);
-        boolean validInput = m.matches();
-
-        if (!validInput) {
-            // Input does not match pattern
-            throw new NumberFormatException("For input string: \"" + s + "\"");
-        } else { // validInput
-            /*
-             * We must isolate the sign, significand, and exponent
-             * fields.  The sign value is straightforward.  Since
-             * floating-point numbers are stored with a normalized
-             * representation, the significand and exponent are
-             * interrelated.
-             *
-             * After extracting the sign, we normalized the
-             * significand as a hexadecimal value, calculating an
-             * exponent adjust for any shifts made during
-             * normalization.  If the significand is zero, the
-             * exponent doesn't need to be examined since the output
-             * will be zero.
-             *
-             * Next the exponent in the input string is extracted.
-             * Afterwards, the significand is normalized as a *binary*
-             * value and the input value's normalized exponent can be
-             * computed.  The significand bits are copied into a
-             * double significand; if the string has more logical bits
-             * than can fit in a double, the extra bits affect the
-             * round and sticky bits which are used to round the final
-             * value.
-             */
-
-            //  Extract significand sign
-            String group1 = m.group(1);
-            double sign = (( group1 == null ) || group1.equals("+"))? 1.0 : -1.0;
-
-
-            //  Extract Significand magnitude
-            /*
-             * Based on the form of the significand, calculate how the
-             * binary exponent needs to be adjusted to create a
-             * normalized *hexadecimal* floating-point number; that
-             * is, a number where there is one nonzero hex digit to
-             * the left of the (hexa)decimal point.  Since we are
-             * adjusting a binary, not hexadecimal exponent, the
-             * exponent is adjusted by a multiple of 4.
-             *
-             * There are a number of significand scenarios to consider;
-             * letters are used in indicate nonzero digits:
-             *
-             * 1. 000xxxx       =>      x.xxx   normalized
-             *    increase exponent by (number of x's - 1)*4
-             *
-             * 2. 000xxx.yyyy =>        x.xxyyyy        normalized
-             *    increase exponent by (number of x's - 1)*4
-             *
-             * 3. .000yyy  =>   y.yy    normalized
-             *    decrease exponent by (number of zeros + 1)*4
-             *
-             * 4. 000.00000yyy => y.yy normalized
-             *    decrease exponent by (number of zeros to right of point + 1)*4
-             *
-             * If the significand is exactly zero, return a properly
-             * signed zero.
-             */
-
-            String significandString =null;
-            int signifLength = 0;
-            int exponentAdjust = 0;
-            {
-                int leftDigits  = 0; // number of meaningful digits to
-                                     // left of "decimal" point
-                                     // (leading zeros stripped)
-                int rightDigits = 0; // number of digits to right of
-                                     // "decimal" point; leading zeros
-                                     // must always be accounted for
-                /*
-                 * The significand is made up of either
-                 *
-                 * 1. group 4 entirely (integer portion only)
-                 *
-                 * OR
-                 *
-                 * 2. the fractional portion from group 7 plus any
-                 * (optional) integer portions from group 6.
-                 */
-                String group4;
-                if( (group4 = m.group(4)) != null) {  // Integer-only significand
-                    // Leading zeros never matter on the integer portion
-                    significandString = stripLeadingZeros(group4);
-                    leftDigits = significandString.length();
-                }
-                else {
-                    // Group 6 is the optional integer; leading zeros
-                    // never matter on the integer portion
-                    String group6 = stripLeadingZeros(m.group(6));
-                    leftDigits = group6.length();
-
-                    // fraction
-                    String group7 = m.group(7);
-                    rightDigits = group7.length();
-
-                    // Turn "integer.fraction" into "integer"+"fraction"
-                    significandString =
-                        ((group6 == null)?"":group6) + // is the null
-                        // check necessary?
-                        group7;
-                }
-
-                significandString = stripLeadingZeros(significandString);
-                signifLength  = significandString.length();
-
-                /*
-                 * Adjust exponent as described above
-                 */
-                if (leftDigits >= 1) {  // Cases 1 and 2
-                    exponentAdjust = 4*(leftDigits - 1);
-                } else {                // Cases 3 and 4
-                    exponentAdjust = -4*( rightDigits - signifLength + 1);
-                }
-
-                // If the significand is zero, the exponent doesn't
-                // matter; return a properly signed zero.
-
-                if (signifLength == 0) { // Only zeros in input
-                    return new FloatingDecimal(sign * 0.0);
-                }
-            }
-
-            //  Extract Exponent
-            /*
-             * Use an int to read in the exponent value; this should
-             * provide more than sufficient range for non-contrived
-             * inputs.  If reading the exponent in as an int does
-             * overflow, examine the sign of the exponent and
-             * significand to determine what to do.
-             */
-            String group8 = m.group(8);
-            boolean positiveExponent = ( group8 == null ) || group8.equals("+");
-            long unsignedRawExponent;
-            try {
-                unsignedRawExponent = Integer.parseInt(m.group(9));
-            }
-            catch (NumberFormatException e) {
-                // At this point, we know the exponent is
-                // syntactically well-formed as a sequence of
-                // digits.  Therefore, if an NumberFormatException
-                // is thrown, it must be due to overflowing int's
-                // range.  Also, at this point, we have already
-                // checked for a zero significand.  Thus the signs
-                // of the exponent and significand determine the
-                // final result:
+   static ASCIIToBinaryConverter parseHexString(String s) {
+            // Verify string is a member of the hexadecimal floating-point
+            // string language.
+            Matcher m = HexFloatPattern.VALUE.matcher(s);
+            boolean validInput = m.matches();
+            if (!validInput) {
+                // Input does not match pattern
+                throw new NumberFormatException("For input string: \"" + s + "\"");
+            } else { // validInput
+                //
+                // We must isolate the sign, significand, and exponent
+                // fields.  The sign value is straightforward.  Since
+                // floating-point numbers are stored with a normalized
+                // representation, the significand and exponent are
+                // interrelated.
                 //
-                //                      significand
-                //                      +               -
-                // exponent     +       +infinity       -infinity
-                //              -       +0.0            -0.0
-                return new FloatingDecimal(sign * (positiveExponent ?
-                                                   Double.POSITIVE_INFINITY : 0.0));
-            }
-
-            long rawExponent =
-                (positiveExponent ? 1L : -1L) * // exponent sign
-                unsignedRawExponent;            // exponent magnitude
-
-            // Calculate partially adjusted exponent
-            long exponent = rawExponent + exponentAdjust ;
-
-            // Starting copying non-zero bits into proper position in
-            // a long; copy explicit bit too; this will be masked
-            // later for normal values.
-
-            boolean round = false;
-            boolean sticky = false;
-            int bitsCopied=0;
-            int nextShift=0;
-            long significand=0L;
-            // First iteration is different, since we only copy
-            // from the leading significand bit; one more exponent
-            // adjust will be needed...
-
-            // IMPORTANT: make leadingDigit a long to avoid
-            // surprising shift semantics!
-            long leadingDigit = getHexDigit(significandString, 0);
+                // After extracting the sign, we normalized the
+                // significand as a hexadecimal value, calculating an
+                // exponent adjust for any shifts made during
+                // normalization.  If the significand is zero, the
+                // exponent doesn't need to be examined since the output
+                // will be zero.
+                //
+                // Next the exponent in the input string is extracted.
+                // Afterwards, the significand is normalized as a *binary*
+                // value and the input value's normalized exponent can be
+                // computed.  The significand bits are copied into a
+                // double significand; if the string has more logical bits
+                // than can fit in a double, the extra bits affect the
+                // round and sticky bits which are used to round the final
+                // value.
+                //
+                //  Extract significand sign
+                String group1 = m.group(1);
+                boolean isNegative = ((group1 != null) && group1.equals("-"));
 
-            /*
-             * Left shift the leading digit (53 - (bit position of
-             * leading 1 in digit)); this sets the top bit of the
-             * significand to 1.  The nextShift value is adjusted
-             * to take into account the number of bit positions of
-             * the leadingDigit actually used.  Finally, the
-             * exponent is adjusted to normalize the significand
-             * as a binary value, not just a hex value.
-             */
-            if (leadingDigit == 1) {
-                significand |= leadingDigit << 52;
-                nextShift = 52 - 4;
-                /* exponent += 0 */     }
-            else if (leadingDigit <= 3) { // [2, 3]
-                significand |= leadingDigit << 51;
-                nextShift = 52 - 5;
-                exponent += 1;
-            }
-            else if (leadingDigit <= 7) { // [4, 7]
-                significand |= leadingDigit << 50;
-                nextShift = 52 - 6;
-                exponent += 2;
-            }
-            else if (leadingDigit <= 15) { // [8, f]
-                significand |= leadingDigit << 49;
-                nextShift = 52 - 7;
-                exponent += 3;
-            } else {
-                throw new AssertionError("Result from digit conversion too large!");
-            }
-            // The preceding if-else could be replaced by a single
-            // code block based on the high-order bit set in
-            // leadingDigit.  Given leadingOnePosition,
-
-            // significand |= leadingDigit << (SIGNIFICAND_WIDTH - leadingOnePosition);
-            // nextShift = 52 - (3 + leadingOnePosition);
-            // exponent += (leadingOnePosition-1);
-
-
-            /*
-             * Now the exponent variable is equal to the normalized
-             * binary exponent.  Code below will make representation
-             * adjustments if the exponent is incremented after
-             * rounding (includes overflows to infinity) or if the
-             * result is subnormal.
-             */
-
-            // Copy digit into significand until the significand can't
-            // hold another full hex digit or there are no more input
-            // hex digits.
-            int i = 0;
-            for(i = 1;
-                i < signifLength && nextShift >= 0;
-                i++) {
-                long currentDigit = getHexDigit(significandString, i);
-                significand |= (currentDigit << nextShift);
-                nextShift-=4;
-            }
-
-            // After the above loop, the bulk of the string is copied.
-            // Now, we must copy any partial hex digits into the
-            // significand AND compute the round bit and start computing
-            // sticky bit.
-
-            if ( i < signifLength ) { // at least one hex input digit exists
-                long currentDigit = getHexDigit(significandString, i);
-
-                // from nextShift, figure out how many bits need
-                // to be copied, if any
-                switch(nextShift) { // must be negative
-                case -1:
-                    // three bits need to be copied in; can
-                    // set round bit
-                    significand |= ((currentDigit & 0xEL) >> 1);
-                    round = (currentDigit & 0x1L)  != 0L;
-                    break;
-
-                case -2:
-                    // two bits need to be copied in; can
-                    // set round and start sticky
-                    significand |= ((currentDigit & 0xCL) >> 2);
-                    round = (currentDigit &0x2L)  != 0L;
-                    sticky = (currentDigit & 0x1L) != 0;
-                    break;
-
-                case -3:
-                    // one bit needs to be copied in
-                    significand |= ((currentDigit & 0x8L)>>3);
-                    // Now set round and start sticky, if possible
-                    round = (currentDigit &0x4L)  != 0L;
-                    sticky = (currentDigit & 0x3L) != 0;
-                    break;
+                //  Extract Significand magnitude
+                //
+                // Based on the form of the significand, calculate how the
+                // binary exponent needs to be adjusted to create a
+                // normalized//hexadecimal* floating-point number; that
+                // is, a number where there is one nonzero hex digit to
+                // the left of the (hexa)decimal point.  Since we are
+                // adjusting a binary, not hexadecimal exponent, the
+                // exponent is adjusted by a multiple of 4.
+                //
+                // There are a number of significand scenarios to consider;
+                // letters are used in indicate nonzero digits:
+                //
+                // 1. 000xxxx       =>      x.xxx   normalized
+                //    increase exponent by (number of x's - 1)*4
+                //
+                // 2. 000xxx.yyyy =>        x.xxyyyy        normalized
+                //    increase exponent by (number of x's - 1)*4
+                //
+                // 3. .000yyy  =>   y.yy    normalized
+                //    decrease exponent by (number of zeros + 1)*4
+                //
+                // 4. 000.00000yyy => y.yy normalized
+                //    decrease exponent by (number of zeros to right of point + 1)*4
+                //
+                // If the significand is exactly zero, return a properly
+                // signed zero.
+                //
 
-                case -4:
-                    // all bits copied into significand; set
-                    // round and start sticky
-                    round = ((currentDigit & 0x8L) != 0);  // is top bit set?
-                    // nonzeros in three low order bits?
-                    sticky = (currentDigit & 0x7L) != 0;
-                    break;
-
-                default:
-                    throw new AssertionError("Unexpected shift distance remainder.");
-                    // break;
-                }
-
-                // Round is set; sticky might be set.
-
-                // For the sticky bit, it suffices to check the
-                // current digit and test for any nonzero digits in
-                // the remaining unprocessed input.
-                i++;
-                while(i < signifLength && !sticky) {
-                    currentDigit =  getHexDigit(significandString,i);
-                    sticky = sticky || (currentDigit != 0);
-                    i++;
-                }
-
-            }
-            // else all of string was seen, round and sticky are
-            // correct as false.
-
-
-            // Check for overflow and update exponent accordingly.
-
-            if (exponent > DoubleConsts.MAX_EXPONENT) {         // Infinite result
-                // overflow to properly signed infinity
-                return new FloatingDecimal(sign * Double.POSITIVE_INFINITY);
-            } else {  // Finite return value
-                if (exponent <= DoubleConsts.MAX_EXPONENT && // (Usually) normal result
-                    exponent >= DoubleConsts.MIN_EXPONENT) {
-
-                    // The result returned in this block cannot be a
-                    // zero or subnormal; however after the
-                    // significand is adjusted from rounding, we could
-                    // still overflow in infinity.
-
-                    // AND exponent bits into significand; if the
-                    // significand is incremented and overflows from
-                    // rounding, this combination will update the
-                    // exponent correctly, even in the case of
-                    // Double.MAX_VALUE overflowing to infinity.
+                String significandString = null;
+                int signifLength = 0;
+                int exponentAdjust = 0;
+                {
+                    int leftDigits = 0; // number of meaningful digits to
+                    // left of "decimal" point
+                    // (leading zeros stripped)
+                    int rightDigits = 0; // number of digits to right of
+                    // "decimal" point; leading zeros
+                    // must always be accounted for
+                    //
+                    // The significand is made up of either
+                    //
+                    // 1. group 4 entirely (integer portion only)
+                    //
+                    // OR
+                    //
+                    // 2. the fractional portion from group 7 plus any
+                    // (optional) integer portions from group 6.
+                    //
+                    String group4;
+                    if ((group4 = m.group(4)) != null) {  // Integer-only significand
+                        // Leading zeros never matter on the integer portion
+                        significandString = stripLeadingZeros(group4);
+                        leftDigits = significandString.length();
+                    } else {
+                        // Group 6 is the optional integer; leading zeros
+                        // never matter on the integer portion
+                        String group6 = stripLeadingZeros(m.group(6));
+                        leftDigits = group6.length();
 
-                    significand = (( (exponent +
-                                     (long)DoubleConsts.EXP_BIAS) <<
-                                     (DoubleConsts.SIGNIFICAND_WIDTH-1))
-                                   & DoubleConsts.EXP_BIT_MASK) |
-                        (DoubleConsts.SIGNIF_BIT_MASK & significand);
-
-                }  else  {  // Subnormal or zero
-                    // (exponent < DoubleConsts.MIN_EXPONENT)
+                        // fraction
+                        String group7 = m.group(7);
+                        rightDigits = group7.length();
 
-                    if (exponent < (DoubleConsts.MIN_SUB_EXPONENT -1 )) {
-                        // No way to round back to nonzero value
-                        // regardless of significand if the exponent is
-                        // less than -1075.
-                        return new FloatingDecimal(sign * 0.0);
-                    } else { //  -1075 <= exponent <= MIN_EXPONENT -1 = -1023
-                        /*
-                         * Find bit position to round to; recompute
-                         * round and sticky bits, and shift
-                         * significand right appropriately.
-                         */
+                        // Turn "integer.fraction" into "integer"+"fraction"
+                        significandString =
+                                ((group6 == null) ? "" : group6) + // is the null
+                                        // check necessary?
+                                        group7;
+                    }
 
-                        sticky = sticky || round;
-                        round = false;
+                    significandString = stripLeadingZeros(significandString);
+                    signifLength = significandString.length();
 
-                        // Number of bits of significand to preserve is
-                        // exponent - abs_min_exp +1
-                        // check:
-                        // -1075 +1074 + 1 = 0
-                        // -1023 +1074 + 1 = 52
-
-                        int bitsDiscarded = 53 -
-                            ((int)exponent - DoubleConsts.MIN_SUB_EXPONENT + 1);
-                        assert bitsDiscarded >= 1 && bitsDiscarded <= 53;
+                    //
+                    // Adjust exponent as described above
+                    //
+                    if (leftDigits >= 1) {  // Cases 1 and 2
+                        exponentAdjust = 4 * (leftDigits - 1);
+                    } else {                // Cases 3 and 4
+                        exponentAdjust = -4 * (rightDigits - signifLength + 1);
+                    }
 
-                        // What to do here:
-                        // First, isolate the new round bit
-                        round = (significand & (1L << (bitsDiscarded -1))) != 0L;
-                        if (bitsDiscarded > 1) {
-                            // create mask to update sticky bits; low
-                            // order bitsDiscarded bits should be 1
-                            long mask = ~((~0L) << (bitsDiscarded -1));
-                            sticky = sticky || ((significand & mask) != 0L ) ;
-                        }
+                    // If the significand is zero, the exponent doesn't
+                    // matter; return a properly signed zero.
 
-                        // Now, discard the bits
-                        significand = significand >> bitsDiscarded;
-
-                        significand = (( ((long)(DoubleConsts.MIN_EXPONENT -1) + // subnorm exp.
-                                          (long)DoubleConsts.EXP_BIAS) <<
-                                         (DoubleConsts.SIGNIFICAND_WIDTH-1))
-                                       & DoubleConsts.EXP_BIT_MASK) |
-                            (DoubleConsts.SIGNIF_BIT_MASK & significand);
+                    if (signifLength == 0) { // Only zeros in input
+                        return isNegative ? A2BC_NEGATIVE_ZERO : A2BC_POSITIVE_ZERO;
                     }
                 }
 
-                // The significand variable now contains the currently
-                // appropriate exponent bits too.
+                //  Extract Exponent
+                //
+                // Use an int to read in the exponent value; this should
+                // provide more than sufficient range for non-contrived
+                // inputs.  If reading the exponent in as an int does
+                // overflow, examine the sign of the exponent and
+                // significand to determine what to do.
+                //
+                String group8 = m.group(8);
+                boolean positiveExponent = (group8 == null) || group8.equals("+");
+                long unsignedRawExponent;
+                try {
+                    unsignedRawExponent = Integer.parseInt(m.group(9));
+                }
+                catch (NumberFormatException e) {
+                    // At this point, we know the exponent is
+                    // syntactically well-formed as a sequence of
+                    // digits.  Therefore, if an NumberFormatException
+                    // is thrown, it must be due to overflowing int's
+                    // range.  Also, at this point, we have already
+                    // checked for a zero significand.  Thus the signs
+                    // of the exponent and significand determine the
+                    // final result:
+                    //
+                    //                      significand
+                    //                      +               -
+                    // exponent     +       +infinity       -infinity
+                    //              -       +0.0            -0.0
+                    return isNegative ?
+                              (positiveExponent ? A2BC_NEGATIVE_INFINITY : A2BC_NEGATIVE_ZERO)
+                            : (positiveExponent ? A2BC_POSITIVE_INFINITY : A2BC_POSITIVE_ZERO);
+
+                }
+
+                long rawExponent =
+                        (positiveExponent ? 1L : -1L) * // exponent sign
+                                unsignedRawExponent;            // exponent magnitude
+
+                // Calculate partially adjusted exponent
+                long exponent = rawExponent + exponentAdjust;
+
+                // Starting copying non-zero bits into proper position in
+                // a long; copy explicit bit too; this will be masked
+                // later for normal values.
+
+                boolean round = false;
+                boolean sticky = false;
+                int nextShift = 0;
+                long significand = 0L;
+                // First iteration is different, since we only copy
+                // from the leading significand bit; one more exponent
+                // adjust will be needed...
 
-                /*
-                 * Determine if significand should be incremented;
-                 * making this determination depends on the least
-                 * significant bit and the round and sticky bits.
-                 *
-                 * Round to nearest even rounding table, adapted from
-                 * table 4.7 in "Computer Arithmetic" by IsraelKoren.
-                 * The digit to the left of the "decimal" point is the
-                 * least significant bit, the digits to the right of
-                 * the point are the round and sticky bits
-                 *
-                 * Number       Round(x)
-                 * x0.00        x0.
-                 * x0.01        x0.
-                 * x0.10        x0.
-                 * x0.11        x1. = x0. +1
-                 * x1.00        x1.
-                 * x1.01        x1.
-                 * x1.10        x1. + 1
-                 * x1.11        x1. + 1
-                 */
-                boolean incremented = false;
-                boolean leastZero  = ((significand & 1L) == 0L);
-                if( (  leastZero  && round && sticky ) ||
-                    ((!leastZero) && round )) {
-                    incremented = true;
-                    significand++;
+                // IMPORTANT: make leadingDigit a long to avoid
+                // surprising shift semantics!
+                long leadingDigit = getHexDigit(significandString, 0);
+
+                //
+                // Left shift the leading digit (53 - (bit position of
+                // leading 1 in digit)); this sets the top bit of the
+                // significand to 1.  The nextShift value is adjusted
+                // to take into account the number of bit positions of
+                // the leadingDigit actually used.  Finally, the
+                // exponent is adjusted to normalize the significand
+                // as a binary value, not just a hex value.
+                //
+                if (leadingDigit == 1) {
+                    significand |= leadingDigit << 52;
+                    nextShift = 52 - 4;
+                    // exponent += 0
+                } else if (leadingDigit <= 3) { // [2, 3]
+                    significand |= leadingDigit << 51;
+                    nextShift = 52 - 5;
+                    exponent += 1;
+                } else if (leadingDigit <= 7) { // [4, 7]
+                    significand |= leadingDigit << 50;
+                    nextShift = 52 - 6;
+                    exponent += 2;
+                } else if (leadingDigit <= 15) { // [8, f]
+                    significand |= leadingDigit << 49;
+                    nextShift = 52 - 7;
+                    exponent += 3;
+                } else {
+                    throw new AssertionError("Result from digit conversion too large!");
+                }
+                // The preceding if-else could be replaced by a single
+                // code block based on the high-order bit set in
+                // leadingDigit.  Given leadingOnePosition,
+
+                // significand |= leadingDigit << (SIGNIFICAND_WIDTH - leadingOnePosition);
+                // nextShift = 52 - (3 + leadingOnePosition);
+                // exponent += (leadingOnePosition-1);
+
+                //
+                // Now the exponent variable is equal to the normalized
+                // binary exponent.  Code below will make representation
+                // adjustments if the exponent is incremented after
+                // rounding (includes overflows to infinity) or if the
+                // result is subnormal.
+                //
+
+                // Copy digit into significand until the significand can't
+                // hold another full hex digit or there are no more input
+                // hex digits.
+                int i = 0;
+                for (i = 1;
+                     i < signifLength && nextShift >= 0;
+                     i++) {
+                    long currentDigit = getHexDigit(significandString, i);
+                    significand |= (currentDigit << nextShift);
+                    nextShift -= 4;
                 }
 
-                FloatingDecimal fd = new FloatingDecimal(Math.copySign(
-                                                              Double.longBitsToDouble(significand),
-                                                              sign));
+                // After the above loop, the bulk of the string is copied.
+                // Now, we must copy any partial hex digits into the
+                // significand AND compute the round bit and start computing
+                // sticky bit.
+
+                if (i < signifLength) { // at least one hex input digit exists
+                    long currentDigit = getHexDigit(significandString, i);
+
+                    // from nextShift, figure out how many bits need
+                    // to be copied, if any
+                    switch (nextShift) { // must be negative
+                        case -1:
+                            // three bits need to be copied in; can
+                            // set round bit
+                            significand |= ((currentDigit & 0xEL) >> 1);
+                            round = (currentDigit & 0x1L) != 0L;
+                            break;
+
+                        case -2:
+                            // two bits need to be copied in; can
+                            // set round and start sticky
+                            significand |= ((currentDigit & 0xCL) >> 2);
+                            round = (currentDigit & 0x2L) != 0L;
+                            sticky = (currentDigit & 0x1L) != 0;
+                            break;
+
+                        case -3:
+                            // one bit needs to be copied in
+                            significand |= ((currentDigit & 0x8L) >> 3);
+                            // Now set round and start sticky, if possible
+                            round = (currentDigit & 0x4L) != 0L;
+                            sticky = (currentDigit & 0x3L) != 0;
+                            break;
+
+                        case -4:
+                            // all bits copied into significand; set
+                            // round and start sticky
+                            round = ((currentDigit & 0x8L) != 0);  // is top bit set?
+                            // nonzeros in three low order bits?
+                            sticky = (currentDigit & 0x7L) != 0;
+                            break;
+
+                        default:
+                            throw new AssertionError("Unexpected shift distance remainder.");
+                            // break;
+                    }
+
+                    // Round is set; sticky might be set.
 
-                /*
-                 * Set roundingDir variable field of fd properly so
-                 * that the input string can be properly rounded to a
-                 * float value.  There are two cases to consider:
-                 *
-                 * 1. rounding to double discards sticky bit
-                 * information that would change the result of a float
-                 * rounding (near halfway case between two floats)
-                 *
-                 * 2. rounding to double rounds up when rounding up
-                 * would not occur when rounding to float.
-                 *
-                 * For former case only needs to be considered when
-                 * the bits rounded away when casting to float are all
-                 * zero; otherwise, float round bit is properly set
-                 * and sticky will already be true.
-                 *
-                 * The lower exponent bound for the code below is the
-                 * minimum (normalized) subnormal exponent - 1 since a
-                 * value with that exponent can round up to the
-                 * minimum subnormal value and the sticky bit
-                 * information must be preserved (i.e. case 1).
-                 */
-                if ((exponent >= FloatConsts.MIN_SUB_EXPONENT-1) &&
-                    (exponent <= FloatConsts.MAX_EXPONENT ) ){
-                    // Outside above exponent range, the float value
-                    // will be zero or infinity.
+                    // For the sticky bit, it suffices to check the
+                    // current digit and test for any nonzero digits in
+                    // the remaining unprocessed input.
+                    i++;
+                    while (i < signifLength && !sticky) {
+                        currentDigit = getHexDigit(significandString, i);
+                        sticky = sticky || (currentDigit != 0);
+                        i++;
+                    }
+
+                }
+                // else all of string was seen, round and sticky are
+                // correct as false.
+
+                // Check for overflow and update exponent accordingly.
+                if (exponent > DoubleConsts.MAX_EXPONENT) {         // Infinite result
+                    // overflow to properly signed infinity
+                    return isNegative ? A2BC_NEGATIVE_INFINITY : A2BC_POSITIVE_INFINITY;
+                } else {  // Finite return value
+                    if (exponent <= DoubleConsts.MAX_EXPONENT && // (Usually) normal result
+                            exponent >= DoubleConsts.MIN_EXPONENT) {
+
+                        // The result returned in this block cannot be a
+                        // zero or subnormal; however after the
+                        // significand is adjusted from rounding, we could
+                        // still overflow in infinity.
+
+                        // AND exponent bits into significand; if the
+                        // significand is incremented and overflows from
+                        // rounding, this combination will update the
+                        // exponent correctly, even in the case of
+                        // Double.MAX_VALUE overflowing to infinity.
+
+                        significand = ((( exponent +
+                                (long) DoubleConsts.EXP_BIAS) <<
+                                (DoubleConsts.SIGNIFICAND_WIDTH - 1))
+                                & DoubleConsts.EXP_BIT_MASK) |
+                                (DoubleConsts.SIGNIF_BIT_MASK & significand);
+
+                    } else {  // Subnormal or zero
+                        // (exponent < DoubleConsts.MIN_EXPONENT)
+
+                        if (exponent < (DoubleConsts.MIN_SUB_EXPONENT - 1)) {
+                            // No way to round back to nonzero value
+                            // regardless of significand if the exponent is
+                            // less than -1075.
+                            return isNegative ? A2BC_NEGATIVE_ZERO : A2BC_POSITIVE_ZERO;
+                        } else { //  -1075 <= exponent <= MIN_EXPONENT -1 = -1023
+                            //
+                            // Find bit position to round to; recompute
+                            // round and sticky bits, and shift
+                            // significand right appropriately.
+                            //
+
+                            sticky = sticky || round;
+                            round = false;
+
+                            // Number of bits of significand to preserve is
+                            // exponent - abs_min_exp +1
+                            // check:
+                            // -1075 +1074 + 1 = 0
+                            // -1023 +1074 + 1 = 52
+
+                            int bitsDiscarded = 53 -
+                                    ((int) exponent - DoubleConsts.MIN_SUB_EXPONENT + 1);
+                            assert bitsDiscarded >= 1 && bitsDiscarded <= 53;
 
-                    /*
-                     * If the low-order 28 bits of a rounded double
-                     * significand are 0, the double could be a
-                     * half-way case for a rounding to float.  If the
-                     * double value is a half-way case, the double
-                     * significand may have to be modified to round
-                     * the the right float value (see the stickyRound
-                     * method).  If the rounding to double has lost
-                     * what would be float sticky bit information, the
-                     * double significand must be incremented.  If the
-                     * double value's significand was itself
-                     * incremented, the float value may end up too
-                     * large so the increment should be undone.
-                     */
-                    if ((significand & 0xfffffffL) ==  0x0L) {
-                        // For negative values, the sign of the
-                        // roundDir is the same as for positive values
-                        // since adding 1 increasing the significand's
-                        // magnitude and subtracting 1 decreases the
-                        // significand's magnitude.  If neither round
-                        // nor sticky is true, the double value is
-                        // exact and no adjustment is required for a
-                        // proper float rounding.
-                        if( round || sticky) {
-                            if (leastZero) { // prerounding lsb is 0
-                                // If round and sticky were both true,
-                                // and the least significant
-                                // significand bit were 0, the rounded
-                                // significand would not have its
-                                // low-order bits be zero.  Therefore,
-                                // we only need to adjust the
-                                // significand if round XOR sticky is
-                                // true.
-                                if (round ^ sticky) {
-                                    fd.roundDir =  1;
+                            // What to do here:
+                            // First, isolate the new round bit
+                            round = (significand & (1L << (bitsDiscarded - 1))) != 0L;
+                            if (bitsDiscarded > 1) {
+                                // create mask to update sticky bits; low
+                                // order bitsDiscarded bits should be 1
+                                long mask = ~((~0L) << (bitsDiscarded - 1));
+                                sticky = sticky || ((significand & mask) != 0L);
+                            }
+
+                            // Now, discard the bits
+                            significand = significand >> bitsDiscarded;
+
+                            significand = ((((long) (DoubleConsts.MIN_EXPONENT - 1) + // subnorm exp.
+                                    (long) DoubleConsts.EXP_BIAS) <<
+                                    (DoubleConsts.SIGNIFICAND_WIDTH - 1))
+                                    & DoubleConsts.EXP_BIT_MASK) |
+                                    (DoubleConsts.SIGNIF_BIT_MASK & significand);
+                        }
+                    }
+
+                    // The significand variable now contains the currently
+                    // appropriate exponent bits too.
+
+                    //
+                    // Determine if significand should be incremented;
+                    // making this determination depends on the least
+                    // significant bit and the round and sticky bits.
+                    //
+                    // Round to nearest even rounding table, adapted from
+                    // table 4.7 in "Computer Arithmetic" by IsraelKoren.
+                    // The digit to the left of the "decimal" point is the
+                    // least significant bit, the digits to the right of
+                    // the point are the round and sticky bits
+                    //
+                    // Number       Round(x)
+                    // x0.00        x0.
+                    // x0.01        x0.
+                    // x0.10        x0.
+                    // x0.11        x1. = x0. +1
+                    // x1.00        x1.
+                    // x1.01        x1.
+                    // x1.10        x1. + 1
+                    // x1.11        x1. + 1
+                    //
+                    boolean leastZero = ((significand & 1L) == 0L);
+                    if ((leastZero && round && sticky) ||
+                            ((!leastZero) && round)) {
+                        significand++;
+                    }
+
+                    double value = isNegative ?
+                            Double.longBitsToDouble(significand | DoubleConsts.SIGN_BIT_MASK) :
+                            Double.longBitsToDouble(significand );
+
+                    int roundDir = 0;
+                    //
+                    // Set roundingDir variable field of fd properly so
+                    // that the input string can be properly rounded to a
+                    // float value.  There are two cases to consider:
+                    //
+                    // 1. rounding to double discards sticky bit
+                    // information that would change the result of a float
+                    // rounding (near halfway case between two floats)
+                    //
+                    // 2. rounding to double rounds up when rounding up
+                    // would not occur when rounding to float.
+                    //
+                    // For former case only needs to be considered when
+                    // the bits rounded away when casting to float are all
+                    // zero; otherwise, float round bit is properly set
+                    // and sticky will already be true.
+                    //
+                    // The lower exponent bound for the code below is the
+                    // minimum (normalized) subnormal exponent - 1 since a
+                    // value with that exponent can round up to the
+                    // minimum subnormal value and the sticky bit
+                    // information must be preserved (i.e. case 1).
+                    //
+                    if ((exponent >= FloatConsts.MIN_SUB_EXPONENT - 1) &&
+                            (exponent <= FloatConsts.MAX_EXPONENT)) {
+                        // Outside above exponent range, the float value
+                        // will be zero or infinity.
+
+                        //
+                        // If the low-order 28 bits of a rounded double
+                        // significand are 0, the double could be a
+                        // half-way case for a rounding to float.  If the
+                        // double value is a half-way case, the double
+                        // significand may have to be modified to round
+                        // the the right float value (see the stickyRound
+                        // method).  If the rounding to double has lost
+                        // what would be float sticky bit information, the
+                        // double significand must be incremented.  If the
+                        // double value's significand was itself
+                        // incremented, the float value may end up too
+                        // large so the increment should be undone.
+                        //
+                        if ((significand & 0xfffffffL) == 0x0L) {
+                            // For negative values, the sign of the
+                            // roundDir is the same as for positive values
+                            // since adding 1 increasing the significand's
+                            // magnitude and subtracting 1 decreases the
+                            // significand's magnitude.  If neither round
+                            // nor sticky is true, the double value is
+                            // exact and no adjustment is required for a
+                            // proper float rounding.
+                            if (round || sticky) {
+                                if (leastZero) { // prerounding lsb is 0
+                                    // If round and sticky were both true,
+                                    // and the least significant
+                                    // significand bit were 0, the rounded
+                                    // significand would not have its
+                                    // low-order bits be zero.  Therefore,
+                                    // we only need to adjust the
+                                    // significand if round XOR sticky is
+                                    // true.
+                                    if (round ^ sticky) {
+                                        roundDir = 1;
+                                    }
+                                } else { // prerounding lsb is 1
+                                    // If the prerounding lsb is 1 and the
+                                    // resulting significand has its
+                                    // low-order bits zero, the significand
+                                    // was incremented.  Here, we undo the
+                                    // increment, which will ensure the
+                                    // right guard and sticky bits for the
+                                    // float rounding.
+                                    if (round) {
+                                        roundDir = -1;
+                                    }
                                 }
                             }
-                            else { // prerounding lsb is 1
-                                // If the prerounding lsb is 1 and the
-                                // resulting significand has its
-                                // low-order bits zero, the significand
-                                // was incremented.  Here, we undo the
-                                // increment, which will ensure the
-                                // right guard and sticky bits for the
-                                // float rounding.
-                                if (round)
-                                    fd.roundDir =  -1;
-                            }
                         }
                     }
+                    return new PreparedASCIIToBinaryBuffer(value,roundDir);
                 }
-
-                fd.fromHex = true;
-                return fd;
             }
-        }
     }
 
     /**
-     * Return <code>s</code> with any leading zeros removed.
+     * Returns <code>s</code> with any leading zeros removed.
      */
     static String stripLeadingZeros(String s) {
-        return  s.replaceFirst("^0+", "");
+//        return  s.replaceFirst("^0+", "");
+        if(!s.isEmpty() && s.charAt(0)=='0') {
+            for(int i=1; i<s.length(); i++) {
+                if(s.charAt(i)!='0') {
+                    return s.substring(i);
+                }
+            }
+            return "";
+        }
+        return s;
     }
 
     /**
-     * Extract a hexadecimal digit from position <code>position</code>
+     * Extracts a hexadecimal digit from position <code>position</code>
      * of string <code>s</code>.
      */
     static int getHexDigit(String s, int position) {
@@ -2433,6 +2503,4 @@
         }
         return value;
     }
-
-
 }
--- a/jdk/src/share/classes/sun/misc/FormattedFloatingDecimal.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/misc/FormattedFloatingDecimal.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,422 +25,118 @@
 
 package sun.misc;
 
-import sun.misc.DoubleConsts;
-import sun.misc.FloatConsts;
-import java.util.regex.*;
+import java.util.Arrays;
 
 public class FormattedFloatingDecimal{
-    boolean     isExceptional;
-    boolean     isNegative;
-    int         decExponent;  // value set at construction, then immutable
-    int         decExponentRounded;
-    char        digits[];
-    int         nDigits;
-    int         bigIntExp;
-    int         bigIntNBits;
-    boolean     mustSetRoundDir = false;
-    boolean     fromHex = false;
-    int         roundDir = 0; // set by doubleValue
-    int         precision;    // number of digits to the right of decimal
 
     public enum Form { SCIENTIFIC, COMPATIBLE, DECIMAL_FLOAT, GENERAL };
 
-    private Form form;
+
+    public static FormattedFloatingDecimal valueOf(double d, int precision, Form form){
+        FloatingDecimal.BinaryToASCIIConverter fdConverter =
+                FloatingDecimal.getBinaryToASCIIConverter(d, form == Form.COMPATIBLE);
+        return new FormattedFloatingDecimal(precision,form, fdConverter);
+    }
+
+    private int decExponentRounded;
+    private char[] mantissa;
+    private char[] exponent;
 
-    private     FormattedFloatingDecimal( boolean negSign, int decExponent, char []digits, int n, boolean e, int precision, Form form )
-    {
-        isNegative = negSign;
-        isExceptional = e;
-        this.decExponent = decExponent;
-        this.digits = digits;
-        this.nDigits = n;
-        this.precision = precision;
-        this.form = form;
+    private static final ThreadLocal<Object> threadLocalCharBuffer =
+            new ThreadLocal<Object>() {
+                @Override
+                protected Object initialValue() {
+                    return new char[20];
+                }
+            };
+
+    private static char[] getBuffer(){
+        return (char[]) threadLocalCharBuffer.get();
     }
 
-    /*
-     * Constants of the implementation
-     * Most are IEEE-754 related.
-     * (There are more really boring constants at the end.)
-     */
-    static final long   signMask = 0x8000000000000000L;
-    static final long   expMask  = 0x7ff0000000000000L;
-    static final long   fractMask= ~(signMask|expMask);
-    static final int    expShift = 52;
-    static final int    expBias  = 1023;
-    static final long   fractHOB = ( 1L<<expShift ); // assumed High-Order bit
-    static final long   expOne   = ((long)expBias)<<expShift; // exponent of 1.0
-    static final int    maxSmallBinExp = 62;
-    static final int    minSmallBinExp = -( 63 / 3 );
-    static final int    maxDecimalDigits = 15;
-    static final int    maxDecimalExponent = 308;
-    static final int    minDecimalExponent = -324;
-    static final int    bigDecimalExponent = 324; // i.e. abs(minDecimalExponent)
-
-    static final long   highbyte = 0xff00000000000000L;
-    static final long   highbit  = 0x8000000000000000L;
-    static final long   lowbytes = ~highbyte;
-
-    static final int    singleSignMask =    0x80000000;
-    static final int    singleExpMask  =    0x7f800000;
-    static final int    singleFractMask =   ~(singleSignMask|singleExpMask);
-    static final int    singleExpShift  =   23;
-    static final int    singleFractHOB  =   1<<singleExpShift;
-    static final int    singleExpBias   =   127;
-    static final int    singleMaxDecimalDigits = 7;
-    static final int    singleMaxDecimalExponent = 38;
-    static final int    singleMinDecimalExponent = -45;
-
-    static final int    intDecimalDigits = 9;
-
-
-    /*
-     * count number of bits from high-order 1 bit to low-order 1 bit,
-     * inclusive.
-     */
-    private static int
-    countBits( long v ){
-        //
-        // the strategy is to shift until we get a non-zero sign bit
-        // then shift until we have no bits left, counting the difference.
-        // we do byte shifting as a hack. Hope it helps.
-        //
-        if ( v == 0L ) return 0;
-
-        while ( ( v & highbyte ) == 0L ){
-            v <<= 8;
-        }
-        while ( v > 0L ) { // i.e. while ((v&highbit) == 0L )
-            v <<= 1;
+    private FormattedFloatingDecimal(int precision, Form form, FloatingDecimal.BinaryToASCIIConverter fdConverter) {
+        if (fdConverter.isExceptional()) {
+            this.mantissa = fdConverter.toJavaFormatString().toCharArray();
+            this.exponent = null;
+            return;
         }
-
-        int n = 0;
-        while (( v & lowbytes ) != 0L ){
-            v <<= 8;
-            n += 8;
-        }
-        while ( v != 0L ){
-            v <<= 1;
-            n += 1;
-        }
-        return n;
-    }
-
-    /*
-     * Keep big powers of 5 handy for future reference.
-     */
-    private static FDBigInt b5p[];
-
-    private static synchronized FDBigInt
-    big5pow( int p ){
-        assert p >= 0 : p; // negative power of 5
-        if ( b5p == null ){
-            b5p = new FDBigInt[ p+1 ];
-        }else if (b5p.length <= p ){
-            FDBigInt t[] = new FDBigInt[ p+1 ];
-            System.arraycopy( b5p, 0, t, 0, b5p.length );
-            b5p = t;
-        }
-        if ( b5p[p] != null )
-            return b5p[p];
-        else if ( p < small5pow.length )
-            return b5p[p] = new FDBigInt( small5pow[p] );
-        else if ( p < long5pow.length )
-            return b5p[p] = new FDBigInt( long5pow[p] );
-        else {
-            // construct the value.
-            // recursively.
-            int q, r;
-            // in order to compute 5^p,
-            // compute its square root, 5^(p/2) and square.
-            // or, let q = p / 2, r = p -q, then
-            // 5^p = 5^(q+r) = 5^q * 5^r
-            q = p >> 1;
-            r = p - q;
-            FDBigInt bigq =  b5p[q];
-            if ( bigq == null )
-                bigq = big5pow ( q );
-            if ( r < small5pow.length ){
-                return (b5p[p] = bigq.mult( small5pow[r] ) );
-            }else{
-                FDBigInt bigr = b5p[ r ];
-                if ( bigr == null )
-                    bigr = big5pow( r );
-                return (b5p[p] = bigq.mult( bigr ) );
-            }
+        char[] digits = getBuffer();
+        int nDigits = fdConverter.getDigits(digits);
+        int decExp = fdConverter.getDecimalExponent();
+        int exp;
+        boolean isNegative = fdConverter.isNegative();
+        switch (form) {
+            case COMPATIBLE:
+                exp = decExp;
+                this.decExponentRounded = exp;
+                fillCompatible(precision, digits, nDigits, exp, isNegative);
+                break;
+            case DECIMAL_FLOAT:
+                exp = applyPrecision(decExp, digits, nDigits, decExp + precision);
+                fillDecimal(precision, digits, nDigits, exp, isNegative);
+                this.decExponentRounded = exp;
+                break;
+            case SCIENTIFIC:
+                exp = applyPrecision(decExp, digits, nDigits, precision + 1);
+                fillScientific(precision, digits, nDigits, exp, isNegative);
+                this.decExponentRounded = exp;
+                break;
+            case GENERAL:
+                exp = applyPrecision(decExp, digits, nDigits, precision);
+                // adjust precision to be the number of digits to right of decimal
+                // the real exponent to be output is actually exp - 1, not exp
+                if (exp - 1 < -4 || exp - 1 >= precision) {
+                    // form = Form.SCIENTIFIC;
+                    precision--;
+                    fillScientific(precision, digits, nDigits, exp, isNegative);
+                } else {
+                    // form = Form.DECIMAL_FLOAT;
+                    precision = precision - exp;
+                    fillDecimal(precision, digits, nDigits, exp, isNegative);
+                }
+                this.decExponentRounded = exp;
+                break;
+            default:
+                assert false;
         }
     }
 
-    //
-    // a common operation
-    //
-    private static FDBigInt
-    multPow52( FDBigInt v, int p5, int p2 ){
-        if ( p5 != 0 ){
-            if ( p5 < small5pow.length ){
-                v = v.mult( small5pow[p5] );
-            } else {
-                v = v.mult( big5pow( p5 ) );
-            }
-        }
-        if ( p2 != 0 ){
-            v.lshiftMe( p2 );
-        }
-        return v;
-    }
-
-    //
-    // another common operation
-    //
-    private static FDBigInt
-    constructPow52( int p5, int p2 ){
-        FDBigInt v = new FDBigInt( big5pow( p5 ) );
-        if ( p2 != 0 ){
-            v.lshiftMe( p2 );
-        }
-        return v;
+    // returns the exponent after rounding has been done by applyPrecision
+    public int getExponentRounded() {
+        return decExponentRounded - 1;
     }
 
-    /*
-     * Make a floating double into a FDBigInt.
-     * This could also be structured as a FDBigInt
-     * constructor, but we'd have to build a lot of knowledge
-     * about floating-point representation into it, and we don't want to.
-     *
-     * AS A SIDE EFFECT, THIS METHOD WILL SET THE INSTANCE VARIABLES
-     * bigIntExp and bigIntNBits
-     *
-     */
-    private FDBigInt
-    doubleToBigInt( double dval ){
-        long lbits = Double.doubleToLongBits( dval ) & ~signMask;
-        int binexp = (int)(lbits >>> expShift);
-        lbits &= fractMask;
-        if ( binexp > 0 ){
-            lbits |= fractHOB;
-        } else {
-            assert lbits != 0L : lbits; // doubleToBigInt(0.0)
-            binexp +=1;
-            while ( (lbits & fractHOB ) == 0L){
-                lbits <<= 1;
-                binexp -= 1;
-            }
-        }
-        binexp -= expBias;
-        int nbits = countBits( lbits );
-        /*
-         * We now know where the high-order 1 bit is,
-         * and we know how many there are.
-         */
-        int lowOrderZeros = expShift+1-nbits;
-        lbits >>>= lowOrderZeros;
-
-        bigIntExp = binexp+1-nbits;
-        bigIntNBits = nbits;
-        return new FDBigInt( lbits );
-    }
-
-    /*
-     * Compute a number that is the ULP of the given value,
-     * for purposes of addition/subtraction. Generally easy.
-     * More difficult if subtracting and the argument
-     * is a normalized a power of 2, as the ULP changes at these points.
-     */
-    private static double ulp( double dval, boolean subtracting ){
-        long lbits = Double.doubleToLongBits( dval ) & ~signMask;
-        int binexp = (int)(lbits >>> expShift);
-        double ulpval;
-        if ( subtracting && ( binexp >= expShift ) && ((lbits&fractMask) == 0L) ){
-            // for subtraction from normalized, powers of 2,
-            // use next-smaller exponent
-            binexp -= 1;
-        }
-        if ( binexp > expShift ){
-            ulpval = Double.longBitsToDouble( ((long)(binexp-expShift))<<expShift );
-        } else if ( binexp == 0 ){
-            ulpval = Double.MIN_VALUE;
-        } else {
-            ulpval = Double.longBitsToDouble( 1L<<(binexp-1) );
-        }
-        if ( subtracting ) ulpval = - ulpval;
-
-        return ulpval;
-    }
-
-    /*
-     * Round a double to a float.
-     * In addition to the fraction bits of the double,
-     * look at the class instance variable roundDir,
-     * which should help us avoid double-rounding error.
-     * roundDir was set in hardValueOf if the estimate was
-     * close enough, but not exact. It tells us which direction
-     * of rounding is preferred.
-     */
-    float
-    stickyRound( double dval ){
-        long lbits = Double.doubleToLongBits( dval );
-        long binexp = lbits & expMask;
-        if ( binexp == 0L || binexp == expMask ){
-            // what we have here is special.
-            // don't worry, the right thing will happen.
-            return (float) dval;
-        }
-        lbits += (long)roundDir; // hack-o-matic.
-        return (float)Double.longBitsToDouble( lbits );
+    public char[] getMantissa(){
+        return mantissa;
     }
 
-
-    /*
-     * This is the easy subcase --
-     * all the significant bits, after scaling, are held in lvalue.
-     * negSign and decExponent tell us what processing and scaling
-     * has already been done. Exceptional cases have already been
-     * stripped out.
-     * In particular:
-     * lvalue is a finite number (not Inf, nor NaN)
-     * lvalue > 0L (not zero, nor negative).
-     *
-     * The only reason that we develop the digits here, rather than
-     * calling on Long.toString() is that we can do it a little faster,
-     * and besides want to treat trailing 0s specially. If Long.toString
-     * changes, we should re-evaluate this strategy!
-     */
-    private void
-    developLongDigits( int decExponent, long lvalue, long insignificant ){
-        char digits[];
-        int  ndigits;
-        int  digitno;
-        int  c;
-        //
-        // Discard non-significant low-order bits, while rounding,
-        // up to insignificant value.
-        int i;
-        for ( i = 0; insignificant >= 10L; i++ )
-            insignificant /= 10L;
-        if ( i != 0 ){
-            long pow10 = long5pow[i] << i; // 10^i == 5^i * 2^i;
-            long residue = lvalue % pow10;
-            lvalue /= pow10;
-            decExponent += i;
-            if ( residue >= (pow10>>1) ){
-                // round up based on the low-order bits we're discarding
-                lvalue++;
-            }
-        }
-        if ( lvalue <= Integer.MAX_VALUE ){
-            assert lvalue > 0L : lvalue; // lvalue <= 0
-            // even easier subcase!
-            // can do int arithmetic rather than long!
-            int  ivalue = (int)lvalue;
-            ndigits = 10;
-            digits = perThreadBuffer.get();
-            digitno = ndigits-1;
-            c = ivalue%10;
-            ivalue /= 10;
-            while ( c == 0 ){
-                decExponent++;
-                c = ivalue%10;
-                ivalue /= 10;
-            }
-            while ( ivalue != 0){
-                digits[digitno--] = (char)(c+'0');
-                decExponent++;
-                c = ivalue%10;
-                ivalue /= 10;
-            }
-            digits[digitno] = (char)(c+'0');
-        } else {
-            // same algorithm as above (same bugs, too )
-            // but using long arithmetic.
-            ndigits = 20;
-            digits = perThreadBuffer.get();
-            digitno = ndigits-1;
-            c = (int)(lvalue%10L);
-            lvalue /= 10L;
-            while ( c == 0 ){
-                decExponent++;
-                c = (int)(lvalue%10L);
-                lvalue /= 10L;
-            }
-            while ( lvalue != 0L ){
-                digits[digitno--] = (char)(c+'0');
-                decExponent++;
-                c = (int)(lvalue%10L);
-                lvalue /= 10;
-            }
-            digits[digitno] = (char)(c+'0');
-        }
-        char result [];
-        ndigits -= digitno;
-        result = new char[ ndigits ];
-        System.arraycopy( digits, digitno, result, 0, ndigits );
-        this.digits = result;
-        this.decExponent = decExponent+1;
-        this.nDigits = ndigits;
+    public char[] getExponent(){
+        return exponent;
     }
 
-    //
-    // add one to the least significant digit.
-    // in the unlikely event there is a carry out,
-    // deal with it.
-    // assert that this will only happen where there
-    // is only one digit, e.g. (float)1e-44 seems to do it.
-    //
-    private void
-    roundup(){
-        int i;
-        int q = digits[ i = (nDigits-1)];
-        if ( q == '9' ){
-            while ( q == '9' && i > 0 ){
-                digits[i] = '0';
-                q = digits[--i];
-            }
-            if ( q == '9' ){
-                // carryout! High-order 1, rest 0s, larger exp.
-                decExponent += 1;
-                digits[0] = '1';
-                return;
-            }
-            // else fall through.
+    /**
+     * Returns new decExp in case of overflow.
+     */
+    private static int applyPrecision(int decExp, char[] digits, int nDigits, int prec) {
+        if (prec >= nDigits || prec < 0) {
+            // no rounding necessary
+            return decExp;
         }
-        digits[i] = (char)(q+1);
-    }
-
-    // Given the desired number of digits predict the result's exponent.
-    private int checkExponent(int length) {
-        if (length >= nDigits || length < 0)
-            return decExponent;
-
-        for (int i = 0; i < length; i++)
-            if (digits[i] != '9')
-                // a '9' anywhere in digits will absorb the round
-                return decExponent;
-        return decExponent + (digits[length] >= '5' ? 1 : 0);
-    }
-
-    // Unlike roundup(), this method does not modify digits.  It also
-    // rounds at a particular precision.
-    private char [] applyPrecision(int length) {
-        char [] result = new char[nDigits];
-        for (int i = 0; i < result.length; i++) result[i] = '0';
-
-        if (length >= nDigits || length < 0) {
-            // no rounding necessary
-            System.arraycopy(digits, 0, result, 0, nDigits);
-            return result;
-        }
-        if (length == 0) {
+        if (prec == 0) {
             // only one digit (0 or 1) is returned because the precision
             // excludes all significant digits
             if (digits[0] >= '5') {
-                result[0] = '1';
+                digits[0] = '1';
+                Arrays.fill(digits, 1, nDigits, '0');
+                return decExp + 1;
+            } else {
+                Arrays.fill(digits, 0, nDigits, '0');
+                return decExp;
             }
-            return result;
         }
-
-        int i = length;
-        int q = digits[i];
-        if (q >= '5' && i > 0) {
+        int q = digits[prec];
+        if (q >= '5') {
+            int i = prec;
             q = digits[--i];
             if ( q == '9' ) {
                 while ( q == '9' && i > 0 ){
@@ -448,1319 +144,206 @@
                 }
                 if ( q == '9' ){
                     // carryout! High-order 1, rest 0s, larger exp.
-                    result[0] = '1';
-                    return result;
+                    digits[0] = '1';
+                    Arrays.fill(digits, 1, nDigits, '0');
+                    return decExp+1;
                 }
             }
-            result[i] = (char)(q + 1);
-        }
-        while (--i >= 0) {
-            result[i] = digits[i];
-        }
-        return result;
-    }
-
-    /*
-     * FIRST IMPORTANT CONSTRUCTOR: DOUBLE
-     */
-    public FormattedFloatingDecimal( double d )
-    {
-        this(d, Integer.MAX_VALUE, Form.COMPATIBLE);
-    }
-
-    public FormattedFloatingDecimal( double d, int precision, Form form )
-    {
-        long    dBits = Double.doubleToLongBits( d );
-        long    fractBits;
-        int     binExp;
-        int     nSignificantBits;
-
-        this.precision = precision;
-        this.form      = form;
-
-        // discover and delete sign
-        if ( (dBits&signMask) != 0 ){
-            isNegative = true;
-            dBits ^= signMask;
+            digits[i] = (char)(q + 1);
+            Arrays.fill(digits, i+1, nDigits, '0');
         } else {
-            isNegative = false;
-        }
-        // Begin to unpack
-        // Discover obvious special cases of NaN and Infinity.
-        binExp = (int)( (dBits&expMask) >> expShift );
-        fractBits = dBits&fractMask;
-        if ( binExp == (int)(expMask>>expShift) ) {
-            isExceptional = true;
-            if ( fractBits == 0L ){
-                digits =  infinity;
-            } else {
-                digits = notANumber;
-                isNegative = false; // NaN has no sign!
-            }
-            nDigits = digits.length;
-            return;
-        }
-        isExceptional = false;
-        // Finish unpacking
-        // Normalize denormalized numbers.
-        // Insert assumed high-order bit for normalized numbers.
-        // Subtract exponent bias.
-        if ( binExp == 0 ){
-            if ( fractBits == 0L ){
-                // not a denorm, just a 0!
-                decExponent = 0;
-                digits = zero;
-                nDigits = 1;
-                return;
-            }
-            while ( (fractBits&fractHOB) == 0L ){
-                fractBits <<= 1;
-                binExp -= 1;
-            }
-            nSignificantBits = expShift + binExp +1; // recall binExp is  - shift count.
-            binExp += 1;
-        } else {
-            fractBits |= fractHOB;
-            nSignificantBits = expShift+1;
+            Arrays.fill(digits, prec, nDigits, '0');
         }
-        binExp -= expBias;
-        // call the routine that actually does all the hard work.
-        dtoa( binExp, fractBits, nSignificantBits );
-    }
-
-    /*
-     * SECOND IMPORTANT CONSTRUCTOR: SINGLE
-     */
-    public FormattedFloatingDecimal( float f )
-    {
-        this(f, Integer.MAX_VALUE, Form.COMPATIBLE);
-    }
-    public FormattedFloatingDecimal( float f, int precision, Form form )
-    {
-        int     fBits = Float.floatToIntBits( f );
-        int     fractBits;
-        int     binExp;
-        int     nSignificantBits;
-
-        this.precision = precision;
-        this.form      = form;
-
-        // discover and delete sign
-        if ( (fBits&singleSignMask) != 0 ){
-            isNegative = true;
-            fBits ^= singleSignMask;
-        } else {
-            isNegative = false;
-        }
-        // Begin to unpack
-        // Discover obvious special cases of NaN and Infinity.
-        binExp = (fBits&singleExpMask) >> singleExpShift;
-        fractBits = fBits&singleFractMask;
-        if ( binExp == (singleExpMask>>singleExpShift) ) {
-            isExceptional = true;
-            if ( fractBits == 0L ){
-                digits =  infinity;
-            } else {
-                digits = notANumber;
-                isNegative = false; // NaN has no sign!
-            }
-            nDigits = digits.length;
-            return;
-        }
-        isExceptional = false;
-        // Finish unpacking
-        // Normalize denormalized numbers.
-        // Insert assumed high-order bit for normalized numbers.
-        // Subtract exponent bias.
-        if ( binExp == 0 ){
-            if ( fractBits == 0 ){
-                // not a denorm, just a 0!
-                decExponent = 0;
-                digits = zero;
-                nDigits = 1;
-                return;
-            }
-            while ( (fractBits&singleFractHOB) == 0 ){
-                fractBits <<= 1;
-                binExp -= 1;
-            }
-            nSignificantBits = singleExpShift + binExp +1; // recall binExp is  - shift count.
-            binExp += 1;
-        } else {
-            fractBits |= singleFractHOB;
-            nSignificantBits = singleExpShift+1;
-        }
-        binExp -= singleExpBias;
-        // call the routine that actually does all the hard work.
-        dtoa( binExp, ((long)fractBits)<<(expShift-singleExpShift), nSignificantBits );
+        return decExp;
     }
 
-    private void
-    dtoa( int binExp, long fractBits, int nSignificantBits )
-    {
-        int     nFractBits; // number of significant bits of fractBits;
-        int     nTinyBits;  // number of these to the right of the point.
-        int     decExp;
-
-        // Examine number. Determine if it is an easy case,
-        // which we can do pretty trivially using float/long conversion,
-        // or whether we must do real work.
-        nFractBits = countBits( fractBits );
-        nTinyBits = Math.max( 0, nFractBits - binExp - 1 );
-        if ( binExp <= maxSmallBinExp && binExp >= minSmallBinExp ){
-            // Look more closely at the number to decide if,
-            // with scaling by 10^nTinyBits, the result will fit in
-            // a long.
-            if ( (nTinyBits < long5pow.length) && ((nFractBits + n5bits[nTinyBits]) < 64 ) ){
-                /*
-                 * We can do this:
-                 * take the fraction bits, which are normalized.
-                 * (a) nTinyBits == 0: Shift left or right appropriately
-                 *     to align the binary point at the extreme right, i.e.
-                 *     where a long int point is expected to be. The integer
-                 *     result is easily converted to a string.
-                 * (b) nTinyBits > 0: Shift right by expShift-nFractBits,
-                 *     which effectively converts to long and scales by
-                 *     2^nTinyBits. Then multiply by 5^nTinyBits to
-                 *     complete the scaling. We know this won't overflow
-                 *     because we just counted the number of bits necessary
-                 *     in the result. The integer you get from this can
-                 *     then be converted to a string pretty easily.
-                 */
-                long halfULP;
-                if ( nTinyBits == 0 ) {
-                    if ( binExp > nSignificantBits ){
-                        halfULP = 1L << ( binExp-nSignificantBits-1);
-                    } else {
-                        halfULP = 0L;
-                    }
-                    if ( binExp >= expShift ){
-                        fractBits <<= (binExp-expShift);
-                    } else {
-                        fractBits >>>= (expShift-binExp) ;
-                    }
-                    developLongDigits( 0, fractBits, halfULP );
-                    return;
-                }
-                /*
-                 * The following causes excess digits to be printed
-                 * out in the single-float case. Our manipulation of
-                 * halfULP here is apparently not correct. If we
-                 * better understand how this works, perhaps we can
-                 * use this special case again. But for the time being,
-                 * we do not.
-                 * else {
-                 *     fractBits >>>= expShift+1-nFractBits;
-                 *     fractBits *= long5pow[ nTinyBits ];
-                 *     halfULP = long5pow[ nTinyBits ] >> (1+nSignificantBits-nFractBits);
-                 *     developLongDigits( -nTinyBits, fractBits, halfULP );
-                 *     return;
-                 * }
-                 */
+    /**
+     * Fills mantissa and exponent char arrays for compatible format.
+     */
+    private void fillCompatible(int precision, char[] digits, int nDigits, int exp, boolean isNegative) {
+        int startIndex = isNegative ? 1 : 0;
+        if (exp > 0 && exp < 8) {
+            // print digits.digits.
+            if (nDigits < exp) {
+                int extraZeros = exp - nDigits;
+                mantissa = create(isNegative, nDigits + extraZeros + 2);
+                System.arraycopy(digits, 0, mantissa, startIndex, nDigits);
+                Arrays.fill(mantissa, startIndex + nDigits, startIndex + nDigits + extraZeros, '0');
+                mantissa[startIndex + nDigits + extraZeros] = '.';
+                mantissa[startIndex + nDigits + extraZeros+1] = '0';
+            } else if (exp < nDigits) {
+                int t = Math.min(nDigits - exp, precision);
+                mantissa = create(isNegative, exp + 1 + t);
+                System.arraycopy(digits, 0, mantissa, startIndex, exp);
+                mantissa[startIndex + exp ] = '.';
+                System.arraycopy(digits, exp, mantissa, startIndex+exp+1, t);
+            } else { // exp == digits.length
+                mantissa = create(isNegative, nDigits + 2);
+                System.arraycopy(digits, 0, mantissa, startIndex, nDigits);
+                mantissa[startIndex + nDigits ] = '.';
+                mantissa[startIndex + nDigits +1] = '0';
             }
-        }
-        /*
-         * This is the hard case. We are going to compute large positive
-         * integers B and S and integer decExp, s.t.
-         *      d = ( B / S ) * 10^decExp
-         *      1 <= B / S < 10
-         * Obvious choices are:
-         *      decExp = floor( log10(d) )
-         *      B      = d * 2^nTinyBits * 10^max( 0, -decExp )
-         *      S      = 10^max( 0, decExp) * 2^nTinyBits
-         * (noting that nTinyBits has already been forced to non-negative)
-         * I am also going to compute a large positive integer
-         *      M      = (1/2^nSignificantBits) * 2^nTinyBits * 10^max( 0, -decExp )
-         * i.e. M is (1/2) of the ULP of d, scaled like B.
-         * When we iterate through dividing B/S and picking off the
-         * quotient bits, we will know when to stop when the remainder
-         * is <= M.
-         *
-         * We keep track of powers of 2 and powers of 5.
-         */
-
-        /*
-         * Estimate decimal exponent. (If it is small-ish,
-         * we could double-check.)
-         *
-         * First, scale the mantissa bits such that 1 <= d2 < 2.
-         * We are then going to estimate
-         *          log10(d2) ~=~  (d2-1.5)/1.5 + log(1.5)
-         * and so we can estimate
-         *      log10(d) ~=~ log10(d2) + binExp * log10(2)
-         * take the floor and call it decExp.
-         * FIXME -- use more precise constants here. It costs no more.
-         */
-        double d2 = Double.longBitsToDouble(
-            expOne | ( fractBits &~ fractHOB ) );
-        decExp = (int)Math.floor(
-            (d2-1.5D)*0.289529654D + 0.176091259 + (double)binExp * 0.301029995663981 );
-        int B2, B5; // powers of 2 and powers of 5, respectively, in B
-        int S2, S5; // powers of 2 and powers of 5, respectively, in S
-        int M2, M5; // powers of 2 and powers of 5, respectively, in M
-        int Bbits; // binary digits needed to represent B, approx.
-        int tenSbits; // binary digits needed to represent 10*S, approx.
-        FDBigInt Sval, Bval, Mval;
-
-        B5 = Math.max( 0, -decExp );
-        B2 = B5 + nTinyBits + binExp;
-
-        S5 = Math.max( 0, decExp );
-        S2 = S5 + nTinyBits;
-
-        M5 = B5;
-        M2 = B2 - nSignificantBits;
-
-        /*
-         * the long integer fractBits contains the (nFractBits) interesting
-         * bits from the mantissa of d ( hidden 1 added if necessary) followed
-         * by (expShift+1-nFractBits) zeros. In the interest of compactness,
-         * I will shift out those zeros before turning fractBits into a
-         * FDBigInt. The resulting whole number will be
-         *      d * 2^(nFractBits-1-binExp).
-         */
-        fractBits >>>= (expShift+1-nFractBits);
-        B2 -= nFractBits-1;
-        int common2factor = Math.min( B2, S2 );
-        B2 -= common2factor;
-        S2 -= common2factor;
-        M2 -= common2factor;
-
-        /*
-         * HACK!! For exact powers of two, the next smallest number
-         * is only half as far away as we think (because the meaning of
-         * ULP changes at power-of-two bounds) for this reason, we
-         * hack M2. Hope this works.
-         */
-        if ( nFractBits == 1 )
-            M2 -= 1;
-
-        if ( M2 < 0 ){
-            // oops.
-            // since we cannot scale M down far enough,
-            // we must scale the other values up.
-            B2 -= M2;
-            S2 -= M2;
-            M2 =  0;
-        }
-        /*
-         * Construct, Scale, iterate.
-         * Some day, we'll write a stopping test that takes
-         * account of the assymetry of the spacing of floating-point
-         * numbers below perfect powers of 2
-         * 26 Sept 96 is not that day.
-         * So we use a symmetric test.
-         */
-        char digits[] = this.digits = new char[18];
-        int  ndigit = 0;
-        boolean low, high;
-        long lowDigitDifference;
-        int  q;
-
-        /*
-         * Detect the special cases where all the numbers we are about
-         * to compute will fit in int or long integers.
-         * In these cases, we will avoid doing FDBigInt arithmetic.
-         * We use the same algorithms, except that we "normalize"
-         * our FDBigInts before iterating. This is to make division easier,
-         * as it makes our fist guess (quotient of high-order words)
-         * more accurate!
-         *
-         * Some day, we'll write a stopping test that takes
-         * account of the assymetry of the spacing of floating-point
-         * numbers below perfect powers of 2
-         * 26 Sept 96 is not that day.
-         * So we use a symmetric test.
-         */
-        Bbits = nFractBits + B2 + (( B5 < n5bits.length )? n5bits[B5] : ( B5*3 ));
-        tenSbits = S2+1 + (( (S5+1) < n5bits.length )? n5bits[(S5+1)] : ( (S5+1)*3 ));
-        if ( Bbits < 64 && tenSbits < 64){
-            if ( Bbits < 32 && tenSbits < 32){
-                // wa-hoo! They're all ints!
-                int b = ((int)fractBits * small5pow[B5] ) << B2;
-                int s = small5pow[S5] << S2;
-                int m = small5pow[M5] << M2;
-                int tens = s * 10;
-                /*
-                 * Unroll the first iteration. If our decExp estimate
-                 * was too high, our first quotient will be zero. In this
-                 * case, we discard it and decrement decExp.
-                 */
-                ndigit = 0;
-                q = b / s;
-                b = 10 * ( b % s );
-                m *= 10;
-                low  = (b <  m );
-                high = (b+m > tens );
-                assert q < 10 : q; // excessively large digit
-                if ( (q == 0) && ! high ){
-                    // oops. Usually ignore leading zero.
-                    decExp--;
-                } else {
-                    digits[ndigit++] = (char)('0' + q);
+        } else if (exp <= 0 && exp > -3) {
+            int zeros = Math.max(0, Math.min(-exp, precision));
+            int t = Math.max(0, Math.min(nDigits, precision + exp));
+            // write '0' s before the significant digits
+            if (zeros > 0) {
+                mantissa = create(isNegative, zeros + 2 + t);
+                mantissa[startIndex] = '0';
+                mantissa[startIndex+1] = '.';
+                Arrays.fill(mantissa, startIndex + 2, startIndex + 2 + zeros, '0');
+                if (t > 0) {
+                    // copy only when significant digits are within the precision
+                    System.arraycopy(digits, 0, mantissa, startIndex + 2 + zeros, t);
                 }
-                /*
-                 * HACK! Java spec sez that we always have at least
-                 * one digit after the . in either F- or E-form output.
-                 * Thus we will need more than one digit if we're using
-                 * E-form
-                 */
-                if (! (form == Form.COMPATIBLE && -3 < decExp && decExp < 8)) {
-                    high = low = false;
-                }
-                while( ! low && ! high ){
-                    q = b / s;
-                    b = 10 * ( b % s );
-                    m *= 10;
-                    assert q < 10 : q; // excessively large digit
-                    if ( m > 0L ){
-                        low  = (b <  m );
-                        high = (b+m > tens );
-                    } else {
-                        // hack -- m might overflow!
-                        // in this case, it is certainly > b,
-                        // which won't
-                        // and b+m > tens, too, since that has overflowed
-                        // either!
-                        low = true;
-                        high = true;
-                    }
-                    digits[ndigit++] = (char)('0' + q);
-                }
-                lowDigitDifference = (b<<1) - tens;
+            } else if (t > 0) {
+                mantissa = create(isNegative, zeros + 2 + t);
+                mantissa[startIndex] = '0';
+                mantissa[startIndex + 1] = '.';
+                // copy only when significant digits are within the precision
+                System.arraycopy(digits, 0, mantissa, startIndex + 2, t);
             } else {
-                // still good! they're all longs!
-                long b = (fractBits * long5pow[B5] ) << B2;
-                long s = long5pow[S5] << S2;
-                long m = long5pow[M5] << M2;
-                long tens = s * 10L;
-                /*
-                 * Unroll the first iteration. If our decExp estimate
-                 * was too high, our first quotient will be zero. In this
-                 * case, we discard it and decrement decExp.
-                 */
-                ndigit = 0;
-                q = (int) ( b / s );
-                b = 10L * ( b % s );
-                m *= 10L;
-                low  = (b <  m );
-                high = (b+m > tens );
-                assert q < 10 : q; // excessively large digit
-                if ( (q == 0) && ! high ){
-                    // oops. Usually ignore leading zero.
-                    decExp--;
-                } else {
-                    digits[ndigit++] = (char)('0' + q);
-                }
-                /*
-                 * HACK! Java spec sez that we always have at least
-                 * one digit after the . in either F- or E-form output.
-                 * Thus we will need more than one digit if we're using
-                 * E-form
-                 */
-                if (! (form == Form.COMPATIBLE && -3 < decExp && decExp < 8)) {
-                    high = low = false;
-                }
-                while( ! low && ! high ){
-                    q = (int) ( b / s );
-                    b = 10 * ( b % s );
-                    m *= 10;
-                    assert q < 10 : q;  // excessively large digit
-                    if ( m > 0L ){
-                        low  = (b <  m );
-                        high = (b+m > tens );
-                    } else {
-                        // hack -- m might overflow!
-                        // in this case, it is certainly > b,
-                        // which won't
-                        // and b+m > tens, too, since that has overflowed
-                        // either!
-                        low = true;
-                        high = true;
-                    }
-                    digits[ndigit++] = (char)('0' + q);
-                }
-                lowDigitDifference = (b<<1) - tens;
+                this.mantissa = create(isNegative, 1);
+                this.mantissa[startIndex] = '0';
             }
         } else {
-            FDBigInt tenSval;
-            int  shiftBias;
-
-            /*
-             * We really must do FDBigInt arithmetic.
-             * Fist, construct our FDBigInt initial values.
-             */
-            Bval = multPow52( new FDBigInt( fractBits  ), B5, B2 );
-            Sval = constructPow52( S5, S2 );
-            Mval = constructPow52( M5, M2 );
-
-
-            // normalize so that division works better
-            Bval.lshiftMe( shiftBias = Sval.normalizeMe() );
-            Mval.lshiftMe( shiftBias );
-            tenSval = Sval.mult( 10 );
-            /*
-             * Unroll the first iteration. If our decExp estimate
-             * was too high, our first quotient will be zero. In this
-             * case, we discard it and decrement decExp.
-             */
-            ndigit = 0;
-            q = Bval.quoRemIteration( Sval );
-            Mval = Mval.mult( 10 );
-            low  = (Bval.cmp( Mval ) < 0);
-            high = (Bval.add( Mval ).cmp( tenSval ) > 0 );
-            assert q < 10 : q; // excessively large digit
-            if ( (q == 0) && ! high ){
-                // oops. Usually ignore leading zero.
-                decExp--;
+            if (nDigits > 1) {
+                mantissa = create(isNegative, nDigits + 1);
+                mantissa[startIndex] = digits[0];
+                mantissa[startIndex + 1] = '.';
+                System.arraycopy(digits, 1, mantissa, startIndex + 2, nDigits - 1);
             } else {
-                digits[ndigit++] = (char)('0' + q);
+                mantissa = create(isNegative, 3);
+                mantissa[startIndex] = digits[0];
+                mantissa[startIndex + 1] = '.';
+                mantissa[startIndex + 2] = '0';
             }
-            /*
-             * HACK! Java spec sez that we always have at least
-             * one digit after the . in either F- or E-form output.
-             * Thus we will need more than one digit if we're using
-             * E-form
-             */
-            if (! (form == Form.COMPATIBLE && -3 < decExp && decExp < 8)) {
-                high = low = false;
-            }
-            while( ! low && ! high ){
-                q = Bval.quoRemIteration( Sval );
-                Mval = Mval.mult( 10 );
-                assert q < 10 : q;  // excessively large digit
-                low  = (Bval.cmp( Mval ) < 0);
-                high = (Bval.add( Mval ).cmp( tenSval ) > 0 );
-                digits[ndigit++] = (char)('0' + q);
+            int e, expStartIntex;
+            boolean isNegExp = (exp <= 0);
+            if (isNegExp) {
+                e = -exp + 1;
+                expStartIntex = 1;
+            } else {
+                e = exp - 1;
+                expStartIntex = 0;
             }
-            if ( high && low ){
-                Bval.lshiftMe(1);
-                lowDigitDifference = Bval.cmp(tenSval);
-            } else
-                lowDigitDifference = 0L; // this here only for flow analysis!
-        }
-        this.decExponent = decExp+1;
-        this.digits = digits;
-        this.nDigits = ndigit;
-        /*
-         * Last digit gets rounded based on stopping condition.
-         */
-        if ( high ){
-            if ( low ){
-                if ( lowDigitDifference == 0L ){
-                    // it's a tie!
-                    // choose based on which digits we like.
-                    if ( (digits[nDigits-1]&1) != 0 ) roundup();
-                } else if ( lowDigitDifference > 0 ){
-                    roundup();
-                }
+            // decExponent has 1, 2, or 3, digits
+            if (e <= 9) {
+                exponent = create(isNegExp,1);
+                exponent[expStartIntex] = (char) (e + '0');
+            } else if (e <= 99) {
+                exponent = create(isNegExp,2);
+                exponent[expStartIntex] = (char) (e / 10 + '0');
+                exponent[expStartIntex+1] = (char) (e % 10 + '0');
             } else {
-                roundup();
+                exponent = create(isNegExp,3);
+                exponent[expStartIntex] = (char) (e / 100 + '0');
+                e %= 100;
+                exponent[expStartIntex+1] = (char) (e / 10 + '0');
+                exponent[expStartIntex+2] = (char) (e % 10 + '0');
             }
         }
     }
 
-    public String
-    toString(){
-        // most brain-dead version
-        StringBuffer result = new StringBuffer( nDigits+8 );
-        if ( isNegative ){ result.append( '-' ); }
-        if ( isExceptional ){
-            result.append( digits, 0, nDigits );
-        } else {
-            result.append( "0.");
-            result.append( digits, 0, nDigits );
-            result.append('e');
-            result.append( decExponent );
-        }
-        return new String(result);
-    }
-
-    // returns the exponent before rounding
-    public int getExponent() {
-        return decExponent - 1;
-    }
-
-    // returns the exponent after rounding has been done by applyPrecision
-    public int getExponentRounded() {
-        return decExponentRounded - 1;
-    }
-
-    public int getChars(char[] result) {
-        assert nDigits <= 19 : nDigits; // generous bound on size of nDigits
-        int i = 0;
-        if (isNegative) { result[0] = '-'; i = 1; }
-        if (isExceptional) {
-            System.arraycopy(digits, 0, result, i, nDigits);
-            i += nDigits;
+    private static char[] create(boolean isNegative, int size) {
+        if(isNegative) {
+            char[] r = new char[size +1];
+            r[0] = '-';
+            return r;
         } else {
-            char digits [] = this.digits;
-            int exp = decExponent;
-            switch (form) {
-            case COMPATIBLE:
-                break;
-            case DECIMAL_FLOAT:
-                exp = checkExponent(decExponent + precision);
-                digits = applyPrecision(decExponent + precision);
-                break;
-            case SCIENTIFIC:
-                exp = checkExponent(precision + 1);
-                digits = applyPrecision(precision + 1);
-                break;
-            case GENERAL:
-                exp = checkExponent(precision);
-                digits = applyPrecision(precision);
-                // adjust precision to be the number of digits to right of decimal
-                // the real exponent to be output is actually exp - 1, not exp
-                if (exp - 1 < -4 || exp - 1 >= precision) {
-                    form = Form.SCIENTIFIC;
-                    precision--;
-                } else {
-                    form = Form.DECIMAL_FLOAT;
-                    precision = precision - exp;
-                }
-                break;
-            default:
-                assert false;
-            }
-            decExponentRounded = exp;
-
-            if (exp > 0
-                && ((form == Form.COMPATIBLE && (exp < 8))
-                    || (form == Form.DECIMAL_FLOAT)))
-            {
-                // print digits.digits.
-                int charLength = Math.min(nDigits, exp);
-                System.arraycopy(digits, 0, result, i, charLength);
-                i += charLength;
-                if (charLength < exp) {
-                    charLength = exp-charLength;
-                    for (int nz = 0; nz < charLength; nz++)
-                        result[i++] = '0';
-                    // Do not append ".0" for formatted floats since the user
-                    // may request that it be omitted. It is added as necessary
-                    // by the Formatter.
-                    if (form == Form.COMPATIBLE) {
-                        result[i++] = '.';
-                        result[i++] = '0';
-                    }
-                } else {
-                    // Do not append ".0" for formatted floats since the user
-                    // may request that it be omitted. It is added as necessary
-                    // by the Formatter.
-                    if (form == Form.COMPATIBLE) {
-                        result[i++] = '.';
-                        if (charLength < nDigits) {
-                            int t = Math.min(nDigits - charLength, precision);
-                            System.arraycopy(digits, charLength, result, i, t);
-                            i += t;
-                        } else {
-                            result[i++] = '0';
-                        }
-                    } else {
-                        int t = Math.min(nDigits - charLength, precision);
-                        if (t > 0) {
-                            result[i++] = '.';
-                            System.arraycopy(digits, charLength, result, i, t);
-                            i += t;
-                        }
-                    }
-                }
-            } else if (exp <= 0
-                       && ((form == Form.COMPATIBLE && exp > -3)
-                       || (form == Form.DECIMAL_FLOAT)))
-            {
-                // print 0.0* digits
-                result[i++] = '0';
-                if (exp != 0) {
-                    // write '0' s before the significant digits
-                    int t = Math.min(-exp, precision);
-                    if (t > 0) {
-                        result[i++] = '.';
-                        for (int nz = 0; nz < t; nz++)
-                            result[i++] = '0';
-                    }
-                }
-                int t = Math.min(digits.length, precision + exp);
-                if (t > 0) {
-                    if (i == 1)
-                        result[i++] = '.';
-                    // copy only when significant digits are within the precision
-                    System.arraycopy(digits, 0, result, i, t);
-                    i += t;
-                }
-            } else {
-                result[i++] = digits[0];
-                if (form == Form.COMPATIBLE) {
-                    result[i++] = '.';
-                    if (nDigits > 1) {
-                        System.arraycopy(digits, 1, result, i, nDigits-1);
-                        i += nDigits-1;
-                    } else {
-                        result[i++] = '0';
-                    }
-                    result[i++] = 'E';
-                } else {
-                    if (nDigits > 1) {
-                        int t = Math.min(nDigits -1, precision);
-                        if (t > 0) {
-                            result[i++] = '.';
-                            System.arraycopy(digits, 1, result, i, t);
-                            i += t;
-                        }
-                    }
-                    result[i++] = 'e';
-                }
-                int e;
-                if (exp <= 0) {
-                    result[i++] = '-';
-                    e = -exp+1;
-                } else {
-                    if (form != Form.COMPATIBLE)
-                        result[i++] = '+';
-                    e = exp-1;
-                }
-                // decExponent has 1, 2, or 3, digits
-                if (e <= 9) {
-                    if (form != Form.COMPATIBLE)
-                        result[i++] = '0';
-                    result[i++] = (char)(e+'0');
-                } else if (e <= 99) {
-                    result[i++] = (char)(e/10 +'0');
-                    result[i++] = (char)(e%10 + '0');
-                } else {
-                    result[i++] = (char)(e/100+'0');
-                    e %= 100;
-                    result[i++] = (char)(e/10+'0');
-                    result[i++] = (char)(e%10 + '0');
-                }
-            }
-        }
-        return i;
-    }
-
-    // Per-thread buffer for string/stringbuffer conversion
-    private static ThreadLocal<char[]> perThreadBuffer = new ThreadLocal<char[]>() {
-            protected synchronized char[] initialValue() {
-                return new char[26];
-            }
-        };
-
-    /*
-     * Take a FormattedFloatingDecimal, which we presumably just scanned in,
-     * and find out what its value is, as a double.
-     *
-     * AS A SIDE EFFECT, SET roundDir TO INDICATE PREFERRED
-     * ROUNDING DIRECTION in case the result is really destined
-     * for a single-precision float.
-     */
-
-    public strictfp double doubleValue(){
-        int     kDigits = Math.min( nDigits, maxDecimalDigits+1 );
-        long    lValue;
-        double  dValue;
-        double  rValue, tValue;
-
-        // First, check for NaN and Infinity values
-        if(digits == infinity || digits == notANumber) {
-            if(digits == notANumber)
-                return Double.NaN;
-            else
-                return (isNegative?Double.NEGATIVE_INFINITY:Double.POSITIVE_INFINITY);
-        }
-        else {
-            if (mustSetRoundDir) {
-                roundDir = 0;
-            }
-            /*
-             * convert the lead kDigits to a long integer.
-             */
-            // (special performance hack: start to do it using int)
-            int iValue = (int)digits[0]-(int)'0';
-            int iDigits = Math.min( kDigits, intDecimalDigits );
-            for ( int i=1; i < iDigits; i++ ){
-                iValue = iValue*10 + (int)digits[i]-(int)'0';
-            }
-            lValue = (long)iValue;
-            for ( int i=iDigits; i < kDigits; i++ ){
-                lValue = lValue*10L + (long)((int)digits[i]-(int)'0');
-            }
-            dValue = (double)lValue;
-            int exp = decExponent-kDigits;
-            /*
-             * lValue now contains a long integer with the value of
-             * the first kDigits digits of the number.
-             * dValue contains the (double) of the same.
-             */
-
-            if ( nDigits <= maxDecimalDigits ){
-                /*
-                 * possibly an easy case.
-                 * We know that the digits can be represented
-                 * exactly. And if the exponent isn't too outrageous,
-                 * the whole thing can be done with one operation,
-                 * thus one rounding error.
-                 * Note that all our constructors trim all leading and
-                 * trailing zeros, so simple values (including zero)
-                 * will always end up here
-                 */
-                if (exp == 0 || dValue == 0.0)
-                    return (isNegative)? -dValue : dValue; // small floating integer
-                else if ( exp >= 0 ){
-                    if ( exp <= maxSmallTen ){
-                        /*
-                         * Can get the answer with one operation,
-                         * thus one roundoff.
-                         */
-                        rValue = dValue * small10pow[exp];
-                        if ( mustSetRoundDir ){
-                            tValue = rValue / small10pow[exp];
-                            roundDir = ( tValue ==  dValue ) ? 0
-                                :( tValue < dValue ) ? 1
-                                : -1;
-                        }
-                        return (isNegative)? -rValue : rValue;
-                    }
-                    int slop = maxDecimalDigits - kDigits;
-                    if ( exp <= maxSmallTen+slop ){
-                        /*
-                         * We can multiply dValue by 10^(slop)
-                         * and it is still "small" and exact.
-                         * Then we can multiply by 10^(exp-slop)
-                         * with one rounding.
-                         */
-                        dValue *= small10pow[slop];
-                        rValue = dValue * small10pow[exp-slop];
-
-                        if ( mustSetRoundDir ){
-                            tValue = rValue / small10pow[exp-slop];
-                            roundDir = ( tValue ==  dValue ) ? 0
-                                :( tValue < dValue ) ? 1
-                                : -1;
-                        }
-                        return (isNegative)? -rValue : rValue;
-                    }
-                    /*
-                     * Else we have a hard case with a positive exp.
-                     */
-                } else {
-                    if ( exp >= -maxSmallTen ){
-                        /*
-                         * Can get the answer in one division.
-                         */
-                        rValue = dValue / small10pow[-exp];
-                        tValue = rValue * small10pow[-exp];
-                        if ( mustSetRoundDir ){
-                            roundDir = ( tValue ==  dValue ) ? 0
-                                :( tValue < dValue ) ? 1
-                                : -1;
-                        }
-                        return (isNegative)? -rValue : rValue;
-                    }
-                    /*
-                     * Else we have a hard case with a negative exp.
-                     */
-                }
-            }
-
-            /*
-             * Harder cases:
-             * The sum of digits plus exponent is greater than
-             * what we think we can do with one error.
-             *
-             * Start by approximating the right answer by,
-             * naively, scaling by powers of 10.
-             */
-            if ( exp > 0 ){
-                if ( decExponent > maxDecimalExponent+1 ){
-                    /*
-                     * Lets face it. This is going to be
-                     * Infinity. Cut to the chase.
-                     */
-                    return (isNegative)? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
-                }
-                if ( (exp&15) != 0 ){
-                    dValue *= small10pow[exp&15];
-                }
-                if ( (exp>>=4) != 0 ){
-                    int j;
-                    for( j = 0; exp > 1; j++, exp>>=1 ){
-                        if ( (exp&1)!=0)
-                            dValue *= big10pow[j];
-                    }
-                    /*
-                     * The reason for the weird exp > 1 condition
-                     * in the above loop was so that the last multiply
-                     * would get unrolled. We handle it here.
-                     * It could overflow.
-                     */
-                    double t = dValue * big10pow[j];
-                    if ( Double.isInfinite( t ) ){
-                        /*
-                         * It did overflow.
-                         * Look more closely at the result.
-                         * If the exponent is just one too large,
-                         * then use the maximum finite as our estimate
-                         * value. Else call the result infinity
-                         * and punt it.
-                         * ( I presume this could happen because
-                         * rounding forces the result here to be
-                         * an ULP or two larger than
-                         * Double.MAX_VALUE ).
-                         */
-                        t = dValue / 2.0;
-                        t *= big10pow[j];
-                        if ( Double.isInfinite( t ) ){
-                            return (isNegative)? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
-                        }
-                        t = Double.MAX_VALUE;
-                    }
-                    dValue = t;
-                }
-            } else if ( exp < 0 ){
-                exp = -exp;
-                if ( decExponent < minDecimalExponent-1 ){
-                    /*
-                     * Lets face it. This is going to be
-                     * zero. Cut to the chase.
-                     */
-                    return (isNegative)? -0.0 : 0.0;
-                }
-                if ( (exp&15) != 0 ){
-                    dValue /= small10pow[exp&15];
-                }
-                if ( (exp>>=4) != 0 ){
-                    int j;
-                    for( j = 0; exp > 1; j++, exp>>=1 ){
-                        if ( (exp&1)!=0)
-                            dValue *= tiny10pow[j];
-                    }
-                    /*
-                     * The reason for the weird exp > 1 condition
-                     * in the above loop was so that the last multiply
-                     * would get unrolled. We handle it here.
-                     * It could underflow.
-                     */
-                    double t = dValue * tiny10pow[j];
-                    if ( t == 0.0 ){
-                        /*
-                         * It did underflow.
-                         * Look more closely at the result.
-                         * If the exponent is just one too small,
-                         * then use the minimum finite as our estimate
-                         * value. Else call the result 0.0
-                         * and punt it.
-                         * ( I presume this could happen because
-                         * rounding forces the result here to be
-                         * an ULP or two less than
-                         * Double.MIN_VALUE ).
-                         */
-                        t = dValue * 2.0;
-                        t *= tiny10pow[j];
-                        if ( t == 0.0 ){
-                            return (isNegative)? -0.0 : 0.0;
-                        }
-                        t = Double.MIN_VALUE;
-                    }
-                    dValue = t;
-                }
-            }
-
-            /*
-             * dValue is now approximately the result.
-             * The hard part is adjusting it, by comparison
-             * with FDBigInt arithmetic.
-             * Formulate the EXACT big-number result as
-             * bigD0 * 10^exp
-             */
-            FDBigInt bigD0 = new FDBigInt( lValue, digits, kDigits, nDigits );
-            exp   = decExponent - nDigits;
-
-            correctionLoop:
-            while(true){
-                /* AS A SIDE EFFECT, THIS METHOD WILL SET THE INSTANCE VARIABLES
-                 * bigIntExp and bigIntNBits
-                 */
-                FDBigInt bigB = doubleToBigInt( dValue );
-
-                /*
-                 * Scale bigD, bigB appropriately for
-                 * big-integer operations.
-                 * Naively, we multipy by powers of ten
-                 * and powers of two. What we actually do
-                 * is keep track of the powers of 5 and
-                 * powers of 2 we would use, then factor out
-                 * common divisors before doing the work.
-                 */
-                int B2, B5; // powers of 2, 5 in bigB
-                int     D2, D5; // powers of 2, 5 in bigD
-                int Ulp2;   // powers of 2 in halfUlp.
-                if ( exp >= 0 ){
-                    B2 = B5 = 0;
-                    D2 = D5 = exp;
-                } else {
-                    B2 = B5 = -exp;
-                    D2 = D5 = 0;
-                }
-                if ( bigIntExp >= 0 ){
-                    B2 += bigIntExp;
-                } else {
-                    D2 -= bigIntExp;
-                }
-                Ulp2 = B2;
-                // shift bigB and bigD left by a number s. t.
-                // halfUlp is still an integer.
-                int hulpbias;
-                if ( bigIntExp+bigIntNBits <= -expBias+1 ){
-                    // This is going to be a denormalized number
-                    // (if not actually zero).
-                    // half an ULP is at 2^-(expBias+expShift+1)
-                    hulpbias = bigIntExp+ expBias + expShift;
-                } else {
-                    hulpbias = expShift + 2 - bigIntNBits;
-                }
-                B2 += hulpbias;
-                D2 += hulpbias;
-                // if there are common factors of 2, we might just as well
-                // factor them out, as they add nothing useful.
-                int common2 = Math.min( B2, Math.min( D2, Ulp2 ) );
-                B2 -= common2;
-                D2 -= common2;
-                Ulp2 -= common2;
-                // do multiplications by powers of 5 and 2
-                bigB = multPow52( bigB, B5, B2 );
-                FDBigInt bigD = multPow52( new FDBigInt( bigD0 ), D5, D2 );
-                //
-                // to recap:
-                // bigB is the scaled-big-int version of our floating-point
-                // candidate.
-                // bigD is the scaled-big-int version of the exact value
-                // as we understand it.
-                // halfUlp is 1/2 an ulp of bigB, except for special cases
-                // of exact powers of 2
-                //
-                // the plan is to compare bigB with bigD, and if the difference
-                // is less than halfUlp, then we're satisfied. Otherwise,
-                // use the ratio of difference to halfUlp to calculate a fudge
-                // factor to add to the floating value, then go 'round again.
-                //
-                FDBigInt diff;
-                int cmpResult;
-                boolean overvalue;
-                if ( (cmpResult = bigB.cmp( bigD ) ) > 0 ){
-                    overvalue = true; // our candidate is too big.
-                    diff = bigB.sub( bigD );
-                    if ( (bigIntNBits == 1) && (bigIntExp > -expBias) ){
-                        // candidate is a normalized exact power of 2 and
-                        // is too big. We will be subtracting.
-                        // For our purposes, ulp is the ulp of the
-                        // next smaller range.
-                        Ulp2 -= 1;
-                        if ( Ulp2 < 0 ){
-                            // rats. Cannot de-scale ulp this far.
-                            // must scale diff in other direction.
-                            Ulp2 = 0;
-                            diff.lshiftMe( 1 );
-                        }
-                    }
-                } else if ( cmpResult < 0 ){
-                    overvalue = false; // our candidate is too small.
-                    diff = bigD.sub( bigB );
-                } else {
-                    // the candidate is exactly right!
-                    // this happens with surprising fequency
-                    break correctionLoop;
-                }
-                FDBigInt halfUlp = constructPow52( B5, Ulp2 );
-                if ( (cmpResult = diff.cmp( halfUlp ) ) < 0 ){
-                    // difference is small.
-                    // this is close enough
-                    if (mustSetRoundDir) {
-                        roundDir = overvalue ? -1 : 1;
-                    }
-                    break correctionLoop;
-                } else if ( cmpResult == 0 ){
-                    // difference is exactly half an ULP
-                    // round to some other value maybe, then finish
-                    dValue += 0.5*ulp( dValue, overvalue );
-                    // should check for bigIntNBits == 1 here??
-                    if (mustSetRoundDir) {
-                        roundDir = overvalue ? -1 : 1;
-                    }
-                    break correctionLoop;
-                } else {
-                    // difference is non-trivial.
-                    // could scale addend by ratio of difference to
-                    // halfUlp here, if we bothered to compute that difference.
-                    // Most of the time ( I hope ) it is about 1 anyway.
-                    dValue += ulp( dValue, overvalue );
-                    if ( dValue == 0.0 || dValue == Double.POSITIVE_INFINITY )
-                        break correctionLoop; // oops. Fell off end of range.
-                    continue; // try again.
-                }
-
-            }
-            return (isNegative)? -dValue : dValue;
+            return new char[size];
         }
     }
 
     /*
-     * Take a FormattedFloatingDecimal, which we presumably just scanned in,
-     * and find out what its value is, as a float.
-     * This is distinct from doubleValue() to avoid the extremely
-     * unlikely case of a double rounding error, wherein the converstion
-     * to double has one rounding error, and the conversion of that double
-     * to a float has another rounding error, IN THE WRONG DIRECTION,
-     * ( because of the preference to a zero low-order bit ).
+     * Fills mantissa char arrays for DECIMAL_FLOAT format.
+     * Exponent should be equal to null.
      */
-
-    public strictfp float floatValue(){
-        int     kDigits = Math.min( nDigits, singleMaxDecimalDigits+1 );
-        int     iValue;
-        float   fValue;
-
-        // First, check for NaN and Infinity values
-        if(digits == infinity || digits == notANumber) {
-            if(digits == notANumber)
-                return Float.NaN;
-            else
-                return (isNegative?Float.NEGATIVE_INFINITY:Float.POSITIVE_INFINITY);
-        }
-        else {
-            /*
-             * convert the lead kDigits to an integer.
-             */
-            iValue = (int)digits[0]-(int)'0';
-            for ( int i=1; i < kDigits; i++ ){
-                iValue = iValue*10 + (int)digits[i]-(int)'0';
+    private void fillDecimal(int precision, char[] digits, int nDigits, int exp, boolean isNegative) {
+        int startIndex = isNegative ? 1 : 0;
+        if (exp > 0) {
+            // print digits.digits.
+            if (nDigits < exp) {
+                mantissa = create(isNegative,exp);
+                System.arraycopy(digits, 0, mantissa, startIndex, nDigits);
+                Arrays.fill(mantissa, startIndex + nDigits, startIndex + exp, '0');
+                // Do not append ".0" for formatted floats since the user
+                // may request that it be omitted. It is added as necessary
+                // by the Formatter.
+            } else {
+                int t = Math.min(nDigits - exp, precision);
+                mantissa = create(isNegative, exp + (t > 0 ? (t + 1) : 0));
+                System.arraycopy(digits, 0, mantissa, startIndex, exp);
+                // Do not append ".0" for formatted floats since the user
+                // may request that it be omitted. It is added as necessary
+                // by the Formatter.
+                if (t > 0) {
+                    mantissa[startIndex + exp] = '.';
+                    System.arraycopy(digits, exp, mantissa, startIndex + exp + 1, t);
+                }
             }
-            fValue = (float)iValue;
-            int exp = decExponent-kDigits;
-            /*
-             * iValue now contains an integer with the value of
-             * the first kDigits digits of the number.
-             * fValue contains the (float) of the same.
-             */
-
-            if ( nDigits <= singleMaxDecimalDigits ){
-                /*
-                 * possibly an easy case.
-                 * We know that the digits can be represented
-                 * exactly. And if the exponent isn't too outrageous,
-                 * the whole thing can be done with one operation,
-                 * thus one rounding error.
-                 * Note that all our constructors trim all leading and
-                 * trailing zeros, so simple values (including zero)
-                 * will always end up here.
-                 */
-                if (exp == 0 || fValue == 0.0f)
-                    return (isNegative)? -fValue : fValue; // small floating integer
-                else if ( exp >= 0 ){
-                    if ( exp <= singleMaxSmallTen ){
-                        /*
-                         * Can get the answer with one operation,
-                         * thus one roundoff.
-                         */
-                        fValue *= singleSmall10pow[exp];
-                        return (isNegative)? -fValue : fValue;
-                    }
-                    int slop = singleMaxDecimalDigits - kDigits;
-                    if ( exp <= singleMaxSmallTen+slop ){
-                        /*
-                         * We can multiply dValue by 10^(slop)
-                         * and it is still "small" and exact.
-                         * Then we can multiply by 10^(exp-slop)
-                         * with one rounding.
-                         */
-                        fValue *= singleSmall10pow[slop];
-                        fValue *= singleSmall10pow[exp-slop];
-                        return (isNegative)? -fValue : fValue;
-                    }
-                    /*
-                     * Else we have a hard case with a positive exp.
-                     */
-                } else {
-                    if ( exp >= -singleMaxSmallTen ){
-                        /*
-                         * Can get the answer in one division.
-                         */
-                        fValue /= singleSmall10pow[-exp];
-                        return (isNegative)? -fValue : fValue;
-                    }
-                    /*
-                     * Else we have a hard case with a negative exp.
-                     */
+        } else if (exp <= 0) {
+            int zeros = Math.max(0, Math.min(-exp, precision));
+            int t = Math.max(0, Math.min(nDigits, precision + exp));
+            // write '0' s before the significant digits
+            if (zeros > 0) {
+                mantissa = create(isNegative, zeros + 2 + t);
+                mantissa[startIndex] = '0';
+                mantissa[startIndex+1] = '.';
+                Arrays.fill(mantissa, startIndex + 2, startIndex + 2 + zeros, '0');
+                if (t > 0) {
+                    // copy only when significant digits are within the precision
+                    System.arraycopy(digits, 0, mantissa, startIndex + 2 + zeros, t);
                 }
-            } else if ( (decExponent >= nDigits) && (nDigits+decExponent <= maxDecimalDigits) ){
-                /*
-                 * In double-precision, this is an exact floating integer.
-                 * So we can compute to double, then shorten to float
-                 * with one round, and get the right answer.
-                 *
-                 * First, finish accumulating digits.
-                 * Then convert that integer to a double, multiply
-                 * by the appropriate power of ten, and convert to float.
-                 */
-                long lValue = (long)iValue;
-                for ( int i=kDigits; i < nDigits; i++ ){
-                    lValue = lValue*10L + (long)((int)digits[i]-(int)'0');
-                }
-                double dValue = (double)lValue;
-                exp = decExponent-nDigits;
-                dValue *= small10pow[exp];
-                fValue = (float)dValue;
-                return (isNegative)? -fValue : fValue;
-
+            } else if (t > 0) {
+                mantissa = create(isNegative, zeros + 2 + t);
+                mantissa[startIndex] = '0';
+                mantissa[startIndex + 1] = '.';
+                // copy only when significant digits are within the precision
+                System.arraycopy(digits, 0, mantissa, startIndex + 2, t);
+            } else {
+                this.mantissa = create(isNegative, 1);
+                this.mantissa[startIndex] = '0';
             }
-            /*
-             * Harder cases:
-             * The sum of digits plus exponent is greater than
-             * what we think we can do with one error.
-             *
-             * Start by weeding out obviously out-of-range
-             * results, then convert to double and go to
-             * common hard-case code.
-             */
-            if ( decExponent > singleMaxDecimalExponent+1 ){
-                /*
-                 * Lets face it. This is going to be
-                 * Infinity. Cut to the chase.
-                 */
-                return (isNegative)? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
-            } else if ( decExponent < singleMinDecimalExponent-1 ){
-                /*
-                 * Lets face it. This is going to be
-                 * zero. Cut to the chase.
-                 */
-                return (isNegative)? -0.0f : 0.0f;
-            }
-
-            /*
-             * Here, we do 'way too much work, but throwing away
-             * our partial results, and going and doing the whole
-             * thing as double, then throwing away half the bits that computes
-             * when we convert back to float.
-             *
-             * The alternative is to reproduce the whole multiple-precision
-             * algorythm for float precision, or to try to parameterize it
-             * for common usage. The former will take about 400 lines of code,
-             * and the latter I tried without success. Thus the semi-hack
-             * answer here.
-             */
-            mustSetRoundDir = !fromHex;
-            double dValue = doubleValue();
-            return stickyRound( dValue );
         }
     }
 
-
-    /*
-     * All the positive powers of 10 that can be
-     * represented exactly in double/float.
+    /**
+     * Fills mantissa and exponent char arrays for SCIENTIFIC format.
      */
-    private static final double small10pow[] = {
-        1.0e0,
-        1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,
-        1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10,
-        1.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15,
-        1.0e16, 1.0e17, 1.0e18, 1.0e19, 1.0e20,
-        1.0e21, 1.0e22
-    };
-
-    private static final float singleSmall10pow[] = {
-        1.0e0f,
-        1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
-        1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
-    };
-
-    private static final double big10pow[] = {
-        1e16, 1e32, 1e64, 1e128, 1e256 };
-    private static final double tiny10pow[] = {
-        1e-16, 1e-32, 1e-64, 1e-128, 1e-256 };
-
-    private static final int maxSmallTen = small10pow.length-1;
-    private static final int singleMaxSmallTen = singleSmall10pow.length-1;
-
-    private static final int small5pow[] = {
-        1,
-        5,
-        5*5,
-        5*5*5,
-        5*5*5*5,
-        5*5*5*5*5,
-        5*5*5*5*5*5,
-        5*5*5*5*5*5*5,
-        5*5*5*5*5*5*5*5,
-        5*5*5*5*5*5*5*5*5,
-        5*5*5*5*5*5*5*5*5*5,
-        5*5*5*5*5*5*5*5*5*5*5,
-        5*5*5*5*5*5*5*5*5*5*5*5,
-        5*5*5*5*5*5*5*5*5*5*5*5*5
-    };
-
-
-    private static final long long5pow[] = {
-        1L,
-        5L,
-        5L*5,
-        5L*5*5,
-        5L*5*5*5,
-        5L*5*5*5*5,
-        5L*5*5*5*5*5,
-        5L*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
-    };
-
-    // approximately ceil( log2( long5pow[i] ) )
-    private static final int n5bits[] = {
-        0,
-        3,
-        5,
-        7,
-        10,
-        12,
-        14,
-        17,
-        19,
-        21,
-        24,
-        26,
-        28,
-        31,
-        33,
-        35,
-        38,
-        40,
-        42,
-        45,
-        47,
-        49,
-        52,
-        54,
-        56,
-        59,
-        61,
-    };
-
-    private static final char infinity[] = { 'I', 'n', 'f', 'i', 'n', 'i', 't', 'y' };
-    private static final char notANumber[] = { 'N', 'a', 'N' };
-    private static final char zero[] = { '0', '0', '0', '0', '0', '0', '0', '0' };
+    private void fillScientific(int precision, char[] digits, int nDigits, int exp, boolean isNegative) {
+        int startIndex = isNegative ? 1 : 0;
+        int t = Math.max(0, Math.min(nDigits - 1, precision));
+        if (t > 0) {
+            mantissa = create(isNegative, t + 2);
+            mantissa[startIndex] = digits[0];
+            mantissa[startIndex + 1] = '.';
+            System.arraycopy(digits, 1, mantissa, startIndex + 2, t);
+        } else {
+            mantissa = create(isNegative, 1);
+            mantissa[startIndex] = digits[0];
+        }
+        char expSign;
+        int e;
+        if (exp <= 0) {
+            expSign = '-';
+            e = -exp + 1;
+        } else {
+            expSign = '+' ;
+            e = exp - 1;
+        }
+        // decExponent has 1, 2, or 3, digits
+        if (e <= 9) {
+            exponent = new char[] { expSign,
+                    '0', (char) (e + '0') };
+        } else if (e <= 99) {
+            exponent = new char[] { expSign,
+                    (char) (e / 10 + '0'), (char) (e % 10 + '0') };
+        } else {
+            char hiExpChar = (char) (e / 100 + '0');
+            e %= 100;
+            exponent = new char[] { expSign,
+                    hiExpChar, (char) (e / 10 + '0'), (char) (e % 10 + '0') };
+        }
+    }
 }
--- a/jdk/src/share/classes/sun/misc/Hashing.java	Mon Jun 24 14:26:58 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,239 +0,0 @@
-/*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-package sun.misc;
-
-import java.util.concurrent.ThreadLocalRandom;
-
-/**
- * Hashing utilities.
- *
- * Little endian implementations of Murmur3 hashing.
- */
-public class Hashing {
-
-    /**
-     * Static utility methods only.
-     */
-    private Hashing() {
-        throw new Error("No instances");
-    }
-
-    public static int murmur3_32(byte[] data) {
-        return murmur3_32(0, data, 0, data.length);
-    }
-
-    public static int murmur3_32(int seed, byte[] data) {
-        return murmur3_32(seed, data, 0, data.length);
-    }
-
-    @SuppressWarnings("fallthrough")
-    public static int murmur3_32(int seed, byte[] data, int offset, int len) {
-        int h1 = seed;
-        int count = len;
-
-        // body
-        while (count >= 4) {
-            int k1 = (data[offset] & 0x0FF)
-                    | (data[offset + 1] & 0x0FF) << 8
-                    | (data[offset + 2] & 0x0FF) << 16
-                    | data[offset + 3] << 24;
-
-            count -= 4;
-            offset += 4;
-
-            k1 *= 0xcc9e2d51;
-            k1 = Integer.rotateLeft(k1, 15);
-            k1 *= 0x1b873593;
-
-            h1 ^= k1;
-            h1 = Integer.rotateLeft(h1, 13);
-            h1 = h1 * 5 + 0xe6546b64;
-        }
-
-        // tail
-
-        if (count > 0) {
-            int k1 = 0;
-
-            switch (count) {
-                case 3:
-                    k1 ^= (data[offset + 2] & 0xff) << 16;
-                // fall through
-                case 2:
-                    k1 ^= (data[offset + 1] & 0xff) << 8;
-                // fall through
-                case 1:
-                    k1 ^= (data[offset] & 0xff);
-                // fall through
-                default:
-                    k1 *= 0xcc9e2d51;
-                    k1 = Integer.rotateLeft(k1, 15);
-                    k1 *= 0x1b873593;
-                    h1 ^= k1;
-            }
-        }
-
-        // finalization
-
-        h1 ^= len;
-
-        // finalization mix force all bits of a hash block to avalanche
-        h1 ^= h1 >>> 16;
-        h1 *= 0x85ebca6b;
-        h1 ^= h1 >>> 13;
-        h1 *= 0xc2b2ae35;
-        h1 ^= h1 >>> 16;
-
-        return h1;
-    }
-
-    public static int murmur3_32(char[] data) {
-        return murmur3_32(0, data, 0, data.length);
-    }
-
-    public static int murmur3_32(int seed, char[] data) {
-        return murmur3_32(seed, data, 0, data.length);
-    }
-
-    public static int murmur3_32(int seed, char[] data, int offset, int len) {
-        int h1 = seed;
-
-        int off = offset;
-        int count = len;
-
-        // body
-        while (count >= 2) {
-            int k1 = (data[off++] & 0xFFFF) | (data[off++] << 16);
-
-            count -= 2;
-
-            k1 *= 0xcc9e2d51;
-            k1 = Integer.rotateLeft(k1, 15);
-            k1 *= 0x1b873593;
-
-            h1 ^= k1;
-            h1 = Integer.rotateLeft(h1, 13);
-            h1 = h1 * 5 + 0xe6546b64;
-        }
-
-        // tail
-
-        if (count > 0) {
-            int k1 = data[off];
-
-            k1 *= 0xcc9e2d51;
-            k1 = Integer.rotateLeft(k1, 15);
-            k1 *= 0x1b873593;
-            h1 ^= k1;
-        }
-
-        // finalization
-
-        h1 ^= len * (Character.SIZE / Byte.SIZE);
-
-        // finalization mix force all bits of a hash block to avalanche
-        h1 ^= h1 >>> 16;
-        h1 *= 0x85ebca6b;
-        h1 ^= h1 >>> 13;
-        h1 *= 0xc2b2ae35;
-        h1 ^= h1 >>> 16;
-
-        return h1;
-    }
-
-    public static int murmur3_32(int[] data) {
-        return murmur3_32(0, data, 0, data.length);
-    }
-
-    public static int murmur3_32(int seed, int[] data) {
-        return murmur3_32(seed, data, 0, data.length);
-    }
-
-    public static int murmur3_32(int seed, int[] data, int offset, int len) {
-        int h1 = seed;
-
-        int off = offset;
-        int end = offset + len;
-
-        // body
-        while (off < end) {
-            int k1 = data[off++];
-
-            k1 *= 0xcc9e2d51;
-            k1 = Integer.rotateLeft(k1, 15);
-            k1 *= 0x1b873593;
-
-            h1 ^= k1;
-            h1 = Integer.rotateLeft(h1, 13);
-            h1 = h1 * 5 + 0xe6546b64;
-        }
-
-        // tail (always empty, as body is always 32-bit chunks)
-
-        // finalization
-
-        h1 ^= len * (Integer.SIZE / Byte.SIZE);
-
-        // finalization mix force all bits of a hash block to avalanche
-        h1 ^= h1 >>> 16;
-        h1 *= 0x85ebca6b;
-        h1 ^= h1 >>> 13;
-        h1 *= 0xc2b2ae35;
-        h1 ^= h1 >>> 16;
-
-        return h1;
-    }
-
-    /**
-     * Return a non-zero 32-bit pseudo random value. The {@code instance} object
-     * may be used as part of the value.
-     *
-     * @param instance an object to use if desired in choosing value.
-     * @return a non-zero 32-bit pseudo random value.
-     */
-    public static int randomHashSeed(Object instance) {
-        int seed;
-        if (sun.misc.VM.isBooted()) {
-            seed = ThreadLocalRandom.current().nextInt();
-        } else {
-            // lower quality "random" seed value--still better than zero and not
-            // not practically reversible.
-            int hashing_seed[] = {
-                System.identityHashCode(Hashing.class),
-                System.identityHashCode(instance),
-                System.identityHashCode(Thread.currentThread()),
-                (int) Thread.currentThread().getId(),
-                (int) (System.currentTimeMillis() >>> 2), // resolution is poor
-                (int) (System.nanoTime() >>> 5), // resolution is poor
-                (int) (Runtime.getRuntime().freeMemory() >>> 4) // alloc min
-            };
-
-            seed = murmur3_32(hashing_seed);
-        }
-
-        // force to non-zero.
-        return (0 != seed) ? seed : 1;
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/misc/JavaUtilZipFileAccess.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.misc;
+
+import java.util.zip.ZipFile;
+
+public interface JavaUtilZipFileAccess {
+    public boolean startsWithLocHeader(ZipFile zip);
+}
+
--- a/jdk/src/share/classes/sun/misc/SharedSecrets.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/misc/SharedSecrets.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -52,6 +52,7 @@
     private static JavaIOFileDescriptorAccess javaIOFileDescriptorAccess;
     private static JavaSecurityProtectionDomainAccess javaSecurityProtectionDomainAccess;
     private static JavaSecurityAccess javaSecurityAccess;
+    private static JavaUtilZipFileAccess javaUtilZipFileAccess;
     private static JavaAWTAccess javaAWTAccess;
 
     public static JavaUtilJarAccess javaUtilJarAccess() {
@@ -152,6 +153,16 @@
         return javaSecurityAccess;
     }
 
+    public static JavaUtilZipFileAccess getJavaUtilZipFileAccess() {
+        if (javaUtilZipFileAccess == null)
+            unsafe.ensureClassInitialized(java.util.zip.ZipFile.class);
+        return javaUtilZipFileAccess;
+    }
+
+    public static void setJavaUtilZipFileAccess(JavaUtilZipFileAccess access) {
+        javaUtilZipFileAccess = access;
+    }
+
     public static void setJavaAWTAccess(JavaAWTAccess jaa) {
         javaAWTAccess = jaa;
     }
@@ -159,6 +170,9 @@
     public static JavaAWTAccess getJavaAWTAccess() {
         // this may return null in which case calling code needs to
         // provision for.
+        if (javaAWTAccess == null || javaAWTAccess.getContext() == null) {
+            return null;
+        }
         return javaAWTAccess;
     }
 }
--- a/jdk/src/share/classes/sun/misc/URLClassPath.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/misc/URLClassPath.java	Wed Jul 05 19:00:49 2017 +0200
@@ -64,6 +64,7 @@
     final static String USER_AGENT_JAVA_VERSION = "UA-Java-Version";
     final static String JAVA_VERSION;
     private static final boolean DEBUG;
+    private static final boolean DISABLE_JAR_CHECKING;
 
     /**
      * Used by launcher to indicate that checking of the JAR file "Profile"
@@ -76,6 +77,9 @@
             new sun.security.action.GetPropertyAction("java.version"));
         DEBUG        = (java.security.AccessController.doPrivileged(
             new sun.security.action.GetPropertyAction("sun.misc.URLClassPath.debug")) != null);
+        String p = java.security.AccessController.doPrivileged(
+            new sun.security.action.GetPropertyAction("sun.misc.URLClassPath.disableJarChecking"));
+        DISABLE_JAR_CHECKING = p != null ? p.equals("true") || p.equals("") : false;
     }
 
     /* The original search path of URLs. */
@@ -544,7 +548,7 @@
                      * in a hurry.
                      */
                     JarURLConnection juc = (JarURLConnection)uc;
-                    jarfile = juc.getJarFile();
+                    jarfile = JarLoader.checkJar(juc.getJarFile());
                 }
             } catch (Exception e) {
                 return null;
@@ -609,6 +613,8 @@
         private URLStreamHandler handler;
         private HashMap<String, Loader> lmap;
         private boolean closed = false;
+        private static final sun.misc.JavaUtilZipFileAccess zipAccess =
+                sun.misc.SharedSecrets.getJavaUtilZipFileAccess();
 
         /*
          * Creates a new JarLoader for the specified URL referring to
@@ -713,6 +719,22 @@
             }
         }
 
+        /* Throws if the given jar file is does not start with the correct LOC */
+        static JarFile checkJar(JarFile jar) throws IOException {
+            if (System.getSecurityManager() != null && !DISABLE_JAR_CHECKING
+                && !zipAccess.startsWithLocHeader(jar)) {
+                IOException x = new IOException("Invalid Jar file");
+                try {
+                    jar.close();
+                } catch (IOException ex) {
+                    x.addSuppressed(ex);
+                }
+                throw x;
+            }
+
+            return jar;
+        }
+
         private JarFile getJarFile(URL url) throws IOException {
             // Optimize case where url refers to a local jar file
             if (isOptimizable(url)) {
@@ -720,11 +742,12 @@
                 if (!p.exists()) {
                     throw new FileNotFoundException(p.getPath());
                 }
-                return new JarFile (p.getPath());
+                return checkJar(new JarFile(p.getPath()));
             }
             URLConnection uc = getBaseURL().openConnection();
             uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION);
-            return ((JarURLConnection)uc).getJarFile();
+            JarFile jarFile = ((JarURLConnection)uc).getJarFile();
+            return checkJar(jarFile);
         }
 
         /*
--- a/jdk/src/share/classes/sun/net/NetworkClient.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/net/NetworkClient.java	Wed Jul 05 19:00:49 2017 +0200
@@ -200,7 +200,13 @@
     protected InetAddress getLocalAddress() throws IOException {
         if (serverSocket == null)
             throw new IOException("not connected");
-        return serverSocket.getLocalAddress();
+        return  AccessController.doPrivileged(
+                        new PrivilegedAction<InetAddress>() {
+                            public InetAddress run() {
+                                return serverSocket.getLocalAddress();
+
+                            }
+                        });
     }
 
     /** Close an open connection to the server. */
--- a/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java	Wed Jul 05 19:00:49 2017 +0200
@@ -76,7 +76,10 @@
     private FtpReplyCode lastReplyCode = null;
     /** Welcome message from the server, if any. */
     private String welcomeMsg;
-    private boolean passiveMode = true;
+    /**
+     * Only passive mode used in JDK. See Bug 8010784.
+     */
+    private final boolean passiveMode = true;
     private TransferType type = TransferType.BINARY;
     private long restartOffset = 0;
     private long lastTransSize = -1; // -1 means 'unknown size'
@@ -427,7 +430,7 @@
             }
             response = replyBuf.toString();
             replyBuf.setLength(0);
-            if (logger.isLoggable(PlatformLogger.FINEST)) {
+            if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                 logger.finest("Server [" + serverAddr + "] --> " + response);
             }
 
@@ -469,7 +472,7 @@
     /** Sends command <i>cmd</i> to the server. */
     private void sendServer(String cmd) {
         out.print(cmd);
-        if (logger.isLoggable(PlatformLogger.FINEST)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
             logger.finest("Server [" + serverAddr + "] <-- " + cmd);
         }
     }
@@ -645,9 +648,18 @@
         } else {
             s = new Socket();
         }
+
+        InetAddress serverAddress = AccessController.doPrivileged(
+                new PrivilegedAction<InetAddress>() {
+                    @Override
+                    public InetAddress run() {
+                        return server.getLocalAddress();
+                    }
+                });
+
         // Bind the socket to the same address as the control channel. This
         // is needed in case of multi-homed systems.
-        s.bind(new InetSocketAddress(server.getLocalAddress(), 0));
+        s.bind(new InetSocketAddress(serverAddress, 0));
         if (connectTimeout >= 0) {
             s.connect(dest, connectTimeout);
         } else {
@@ -816,7 +828,9 @@
      * @see #setActiveMode()
      */
     public sun.net.ftp.FtpClient enablePassiveMode(boolean passive) {
-        passiveMode = passive;
+
+        // Only passive mode used in JDK. See Bug 8010784.
+        // passiveMode = passive;
         return this;
     }
 
--- a/jdk/src/share/classes/sun/net/httpserver/ServerImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/net/httpserver/ServerImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -34,6 +34,8 @@
 import java.util.logging.Level;
 import javax.net.ssl.*;
 import com.sun.net.httpserver.*;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 import sun.net.httpserver.HttpConnection.State;
 
 /**
@@ -244,7 +246,14 @@
     }
 
     public InetSocketAddress getAddress() {
-        return (InetSocketAddress)schan.socket().getLocalSocketAddress();
+        return AccessController.doPrivileged(
+                new PrivilegedAction<InetSocketAddress>() {
+                    public InetSocketAddress run() {
+                        return
+                            (InetSocketAddress)schan.socket()
+                                .getLocalSocketAddress();
+                    }
+                });
     }
 
     Selector getSelector () {
--- a/jdk/src/share/classes/sun/net/www/http/ChunkedOutputStream.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/net/www/http/ChunkedOutputStream.java	Wed Jul 05 19:00:49 2017 +0200
@@ -125,7 +125,7 @@
         completeHeader = getHeader(preferredChunkDataSize);
 
         /* start with an initial buffer */
-        buf = new byte[preferredChunkDataSize + 32];
+        buf = new byte[preferredChunkGrossSize];
         reset();
     }
 
--- a/jdk/src/share/classes/sun/net/www/http/HttpClient.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/net/www/http/HttpClient.java	Wed Jul 05 19:00:49 2017 +0200
@@ -125,7 +125,7 @@
 
     private static final PlatformLogger logger = HttpURLConnection.getHttpLogger();
     private static void logFinest(String msg) {
-        if (logger.isLoggable(PlatformLogger.FINEST)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
             logger.finest(msg);
         }
     }
@@ -549,9 +549,7 @@
 
     public String getURLFile() throws IOException {
 
-        String fileName = url.getFile();
-        if ((fileName == null) || (fileName.length() == 0))
-            fileName = "/";
+        String fileName;
 
         /**
          * proxyDisabled is set by subclass HttpsClient!
@@ -575,8 +573,24 @@
                 result.append(url.getQuery());
             }
 
-            fileName =  result.toString();
+            fileName = result.toString();
+        } else {
+            fileName = url.getFile();
+
+            if ((fileName == null) || (fileName.length() == 0)) {
+                fileName = "/";
+            } else if (fileName.charAt(0) == '?') {
+                /* HTTP/1.1 spec says in 5.1.2. about Request-URI:
+                 * "Note that the absolute path cannot be empty; if
+                 * none is present in the original URI, it MUST be
+                 * given as "/" (the server root)."  So if the file
+                 * name here has only a query string, the path is
+                 * empty and we also have to add a "/".
+                 */
+                fileName = "/" + fileName;
+            }
         }
+
         if (fileName.indexOf('\n') == -1)
             return fileName;
         else
--- a/jdk/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java	Wed Jul 05 19:00:49 2017 +0200
@@ -413,13 +413,13 @@
         return java.security.AccessController.doPrivileged(
             new java.security.PrivilegedAction<PasswordAuthentication>() {
                 public PasswordAuthentication run() {
-                    if (logger.isLoggable(PlatformLogger.FINEST)) {
+                    if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                         logger.finest("Requesting Authentication: host =" + host + " url = " + url);
                     }
                     PasswordAuthentication pass = Authenticator.requestPasswordAuthentication(
                         host, addr, port, protocol,
                         prompt, scheme, url, authType);
-                    if (logger.isLoggable(PlatformLogger.FINEST)) {
+                    if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                         logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null"));
                     }
                     return pass;
@@ -632,7 +632,7 @@
             if (!chunked) {
                 if (requests.findValue("Transfer-Encoding") != null) {
                     requests.remove("Transfer-Encoding");
-                    if (logger.isLoggable(PlatformLogger.WARNING)) {
+                    if (logger.isLoggable(PlatformLogger.Level.WARNING)) {
                         logger.warning(
                             "use streaming mode for chunked encoding");
                     }
@@ -645,7 +645,7 @@
 
             setRequests=true;
         }
-        if (logger.isLoggable(PlatformLogger.FINE)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINE)) {
             logger.fine(requests.toString());
         }
         http.writeRequests(requests, poster, streaming());
@@ -991,7 +991,7 @@
                         && !(cachedResponse instanceof SecureCacheResponse)) {
                         cachedResponse = null;
                     }
-                    if (logger.isLoggable(PlatformLogger.FINEST)) {
+                    if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                         logger.finest("Cache Request for " + uri + " / " + getRequestMethod());
                         logger.finest("From cache: " + (cachedResponse != null ? cachedResponse.toString() : "null"));
                     }
@@ -1032,7 +1032,7 @@
                              });
                 if (sel != null) {
                     URI uri = sun.net.www.ParseUtil.toURI(url);
-                    if (logger.isLoggable(PlatformLogger.FINEST)) {
+                    if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                         logger.finest("ProxySelector Request for " + uri);
                     }
                     Iterator<Proxy> it = sel.select(uri).iterator();
@@ -1049,7 +1049,7 @@
                                 http = getNewHttpClient(url, p, connectTimeout, false);
                                 http.setReadTimeout(readTimeout);
                             }
-                            if (logger.isLoggable(PlatformLogger.FINEST)) {
+                            if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                                 if (p != null) {
                                     logger.finest("Proxy used: " + p.toString());
                                 }
@@ -1308,14 +1308,14 @@
 
             URI uri = ParseUtil.toURI(url);
             if (uri != null) {
-                if (logger.isLoggable(PlatformLogger.FINEST)) {
+                if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                     logger.finest("CookieHandler request for " + uri);
                 }
                 Map<String, List<String>> cookies
                     = cookieHandler.get(
                         uri, requests.getHeaders(EXCLUDE_HEADERS));
                 if (!cookies.isEmpty()) {
-                    if (logger.isLoggable(PlatformLogger.FINEST)) {
+                    if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                         logger.finest("Cookies retrieved: " + cookies.toString());
                     }
                     for (Map.Entry<String, List<String>> entry :
@@ -1476,14 +1476,14 @@
                     writeRequests();
                 }
                 http.parseHTTP(responses, pi, this);
-                if (logger.isLoggable(PlatformLogger.FINE)) {
+                if (logger.isLoggable(PlatformLogger.Level.FINE)) {
                     logger.fine(responses.toString());
                 }
 
                 boolean b1 = responses.filterNTLMResponses("WWW-Authenticate");
                 boolean b2 = responses.filterNTLMResponses("Proxy-Authenticate");
                 if (b1 || b2) {
-                    if (logger.isLoggable(PlatformLogger.FINE)) {
+                    if (logger.isLoggable(PlatformLogger.Level.FINE)) {
                         logger.fine(">>>> Headers are filtered");
                         logger.fine(responses.toString());
                     }
@@ -1943,12 +1943,12 @@
                 http.parseHTTP(responses, null, this);
 
                 /* Log the response to the CONNECT */
-                if (logger.isLoggable(PlatformLogger.FINE)) {
+                if (logger.isLoggable(PlatformLogger.Level.FINE)) {
                     logger.fine(responses.toString());
                 }
 
                 if (responses.filterNTLMResponses("Proxy-Authenticate")) {
-                    if (logger.isLoggable(PlatformLogger.FINE)) {
+                    if (logger.isLoggable(PlatformLogger.Level.FINE)) {
                         logger.fine(">>>> Headers are filtered");
                         logger.fine(responses.toString());
                     }
@@ -2075,7 +2075,7 @@
         setPreemptiveProxyAuthentication(requests);
 
          /* Log the CONNECT request */
-        if (logger.isLoggable(PlatformLogger.FINE)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINE)) {
             logger.fine(requests.toString());
         }
 
@@ -2218,7 +2218,7 @@
                     ret = new NegotiateAuthentication(new HttpCallerInfo(authhdr.getHttpCallerInfo(), "Kerberos"));
                     break;
                 case UNKNOWN:
-                    if (logger.isLoggable(PlatformLogger.FINEST)) {
+                    if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                         logger.finest("Unknown/Unsupported authentication scheme: " + scheme);
                     }
                 /*fall through*/
@@ -2247,7 +2247,7 @@
                 }
             }
         }
-        if (logger.isLoggable(PlatformLogger.FINER)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINER)) {
             logger.finer("Proxy Authentication for " + authhdr.toString() +" returned " + (ret != null ? ret.toString() : "null"));
         }
         return ret;
@@ -2377,7 +2377,7 @@
                     }
                     break;
                 case UNKNOWN:
-                    if (logger.isLoggable(PlatformLogger.FINEST)) {
+                    if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                         logger.finest("Unknown/Unsupported authentication scheme: " + scheme);
                     }
                 /*fall through*/
@@ -2404,7 +2404,7 @@
                 }
             }
         }
-        if (logger.isLoggable(PlatformLogger.FINER)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINER)) {
             logger.finer("Server Authentication for " + authhdr.toString() +" returned " + (ret != null ? ret.toString() : "null"));
         }
         return ret;
@@ -2532,7 +2532,7 @@
         if (streaming()) {
             throw new HttpRetryException (RETRY_MSG3, stat, loc);
         }
-        if (logger.isLoggable(PlatformLogger.FINE)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINE)) {
             logger.fine("Redirected from " + url + " to " + locUrl);
         }
 
--- a/jdk/src/share/classes/sun/net/www/protocol/http/NTLMAuthenticationProxy.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/net/www/protocol/http/NTLMAuthenticationProxy.java	Wed Jul 05 19:00:49 2017 +0200
@@ -142,7 +142,7 @@
 
     static void finest(Exception e) {
         PlatformLogger logger = HttpURLConnection.getHttpLogger();
-        if (logger.isLoggable(PlatformLogger.FINEST)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
             logger.finest("NTLMAuthenticationProxy: " + e);
         }
     }
--- a/jdk/src/share/classes/sun/net/www/protocol/http/Negotiator.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/net/www/protocol/http/Negotiator.java	Wed Jul 05 19:00:49 2017 +0200
@@ -76,7 +76,7 @@
 
     private static void finest(Exception e) {
         PlatformLogger logger = HttpURLConnection.getHttpLogger();
-        if (logger.isLoggable(PlatformLogger.FINEST)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
             logger.finest("NegotiateAuthentication: " + e);
         }
     }
--- a/jdk/src/share/classes/sun/net/www/protocol/https/HttpsClient.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/net/www/protocol/https/HttpsClient.java	Wed Jul 05 19:00:49 2017 +0200
@@ -350,7 +350,7 @@
                         if (httpuc != null && ret.needsTunneling())
                             httpuc.setTunnelState(TUNNELING);
                         PlatformLogger logger = HttpURLConnection.getHttpLogger();
-                        if (logger.isLoggable(PlatformLogger.FINEST)) {
+                        if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                             logger.finest("KeepAlive stream retrieved from the cache, " + ret);
                         }
                     }
--- a/jdk/src/share/classes/sun/nio/ch/AsynchronousServerSocketChannelImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/nio/ch/AsynchronousServerSocketChannelImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -51,7 +51,7 @@
     protected final FileDescriptor fd;
 
     // the local address to which the channel's socket is bound
-    protected volatile SocketAddress localAddress = null;
+    protected volatile InetSocketAddress localAddress = null;
 
     // need this lock to set local address
     private final Object stateLock = new Object();
@@ -63,6 +63,8 @@
     // set true when accept operation is cancelled
     private volatile boolean acceptKilled;
 
+    // set true when exclusive binding is on and SO_REUSEADDR is emulated
+    private boolean isReuseAddress;
 
     AsynchronousServerSocketChannelImpl(AsynchronousChannelGroupImpl group) {
         super(group.provider());
@@ -171,7 +173,7 @@
     public final SocketAddress getLocalAddress() throws IOException {
         if (!isOpen())
             throw new ClosedChannelException();
-        return localAddress;
+        return Net.getRevealedLocalAddress(localAddress);
     }
 
     @Override
@@ -186,7 +188,14 @@
 
         try {
             begin();
-            Net.setSocketOption(fd, Net.UNSPEC, name, value);
+            if (name == StandardSocketOptions.SO_REUSEADDR &&
+                    Net.useExclusiveBind())
+            {
+                // SO_REUSEADDR emulated when using exclusive bind
+                isReuseAddress = (Boolean)value;
+            } else {
+                Net.setSocketOption(fd, Net.UNSPEC, name, value);
+            }
             return this;
         } finally {
             end();
@@ -203,6 +212,12 @@
 
         try {
             begin();
+            if (name == StandardSocketOptions.SO_REUSEADDR &&
+                    Net.useExclusiveBind())
+            {
+                // SO_REUSEADDR emulated when using exclusive bind
+                return (T)Boolean.valueOf(isReuseAddress);
+            }
             return (T) Net.getSocketOption(fd, Net.UNSPEC, name);
         } finally {
             end();
@@ -236,7 +251,7 @@
             if (localAddress == null) {
                 sb.append("unbound");
             } else {
-                sb.append(localAddress.toString());
+                sb.append(Net.getRevealedLocalAddressAsString(localAddress));
             }
         }
         sb.append(']');
--- a/jdk/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -53,8 +53,8 @@
     // protects state, localAddress, and remoteAddress
     protected final Object stateLock = new Object();
 
-    protected volatile SocketAddress localAddress = null;
-    protected volatile SocketAddress remoteAddress = null;
+    protected volatile InetSocketAddress localAddress = null;
+    protected volatile InetSocketAddress remoteAddress = null;
 
     // State, increases monotonically
     static final int ST_UNINITIALIZED = -1;
@@ -79,6 +79,9 @@
     private final ReadWriteLock closeLock = new ReentrantReadWriteLock();
     private volatile boolean open = true;
 
+    // set true when exclusive binding is on and SO_REUSEADDR is emulated
+    private boolean isReuseAddress;
+
     AsynchronousSocketChannelImpl(AsynchronousChannelGroupImpl group)
         throws IOException
     {
@@ -439,7 +442,7 @@
     public final SocketAddress getLocalAddress() throws IOException {
         if (!isOpen())
             throw new ClosedChannelException();
-        return localAddress;
+         return Net.getRevealedLocalAddress(localAddress);
     }
 
     @Override
@@ -455,7 +458,14 @@
             begin();
             if (writeShutdown)
                 throw new IOException("Connection has been shutdown for writing");
-            Net.setSocketOption(fd, Net.UNSPEC, name, value);
+            if (name == StandardSocketOptions.SO_REUSEADDR &&
+                    Net.useExclusiveBind())
+            {
+                // SO_REUSEADDR emulated when using exclusive bind
+                isReuseAddress = (Boolean)value;
+            } else {
+                Net.setSocketOption(fd, Net.UNSPEC, name, value);
+            }
             return this;
         } finally {
             end();
@@ -472,6 +482,12 @@
 
         try {
             begin();
+            if (name == StandardSocketOptions.SO_REUSEADDR &&
+                    Net.useExclusiveBind())
+            {
+                // SO_REUSEADDR emulated when using exclusive bind
+                return (T)Boolean.valueOf(isReuseAddress);
+            }
             return (T) Net.getSocketOption(fd, Net.UNSPEC, name);
         } finally {
             end();
@@ -566,7 +582,8 @@
                 }
                 if (localAddress != null) {
                     sb.append(" local=");
-                    sb.append(localAddress.toString());
+                    sb.append(
+                            Net.getRevealedLocalAddressAsString(localAddress));
                 }
                 if (remoteAddress != null) {
                     sb.append(" remote=");
--- a/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -85,8 +85,8 @@
     private int state = ST_UNINITIALIZED;
 
     // Binding
-    private SocketAddress localAddress;
-    private SocketAddress remoteAddress;
+    private InetSocketAddress localAddress;
+    private InetSocketAddress remoteAddress;
 
     // Our socket adaptor, if any
     private DatagramSocket socket;
@@ -94,6 +94,12 @@
     // Multicast support
     private MembershipRegistry registry;
 
+    // set true when socket is bound and SO_REUSEADDRESS is emulated
+    private boolean reuseAddressEmulated;
+
+    // set true/false when socket is already bound and SO_REUSEADDR is emulated
+    private boolean isReuseAddress;
+
     // -- End of fields protected by stateLock
 
 
@@ -162,7 +168,8 @@
         synchronized (stateLock) {
             if (!isOpen())
                 throw new ClosedChannelException();
-            return localAddress;
+            // Perform security check before returning address
+            return Net.getRevealedLocalAddress(localAddress);
         }
     }
 
@@ -222,6 +229,12 @@
                 }
                 return this;
             }
+            if (name == StandardSocketOptions.SO_REUSEADDR &&
+                    Net.useExclusiveBind() && localAddress != null)
+            {
+                reuseAddressEmulated = true;
+                this.isReuseAddress = (Boolean)value;
+            }
 
             // remaining options don't need any special handling
             Net.setSocketOption(fd, Net.UNSPEC, name, value);
@@ -280,6 +293,12 @@
                 }
             }
 
+            if (name == StandardSocketOptions.SO_REUSEADDR &&
+                    reuseAddressEmulated)
+            {
+                return (T)Boolean.valueOf(isReuseAddress);
+            }
+
             // no special handling
             return (T) Net.getSocketOption(fd, Net.UNSPEC, name);
         }
@@ -703,6 +722,7 @@
         }
     }
 
+    @Override
     public DatagramChannel connect(SocketAddress sa) throws IOException {
         int localPort = 0;
 
@@ -724,7 +744,7 @@
 
                     // Connection succeeded; disallow further invocation
                     state = ST_CONNECTED;
-                    remoteAddress = sa;
+                    remoteAddress = isa;
                     sender = isa;
                     cachedSenderInetAddress = isa.getAddress();
                     cachedSenderPort = isa.getPort();
@@ -743,7 +763,7 @@
                 synchronized (stateLock) {
                     if (!isConnected() || !isOpen())
                         return this;
-                    InetSocketAddress isa = (InetSocketAddress)remoteAddress;
+                    InetSocketAddress isa = remoteAddress;
                     SecurityManager sm = System.getSecurityManager();
                     if (sm != null)
                         sm.checkConnect(isa.getAddress().getHostAddress(),
--- a/jdk/src/share/classes/sun/nio/ch/Net.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/nio/ch/Net.java	Wed Jul 05 19:00:49 2017 +0200
@@ -31,6 +31,7 @@
 import java.util.*;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import java.security.PrivilegedExceptionAction;
 
 
 public class Net {
@@ -44,6 +45,34 @@
         }
     };
 
+    // set to true if exclusive binding is on for Windows
+    private static final boolean exclusiveBind;
+
+    static {
+        int availLevel = isExclusiveBindAvailable();
+        if (availLevel >= 0) {
+            String exclBindProp =
+                java.security.AccessController.doPrivileged(
+                    new PrivilegedAction<String>() {
+                        @Override
+                        public String run() {
+                            return System.getProperty(
+                                    "sun.net.useExclusiveBind");
+                        }
+                    });
+            if (exclBindProp != null) {
+                exclusiveBind = exclBindProp.length() == 0 ?
+                        true : Boolean.parseBoolean(exclBindProp);
+            } else if (availLevel == 1) {
+                exclusiveBind = true;
+            } else {
+                exclusiveBind = false;
+            }
+        } else {
+            exclusiveBind = false;
+        }
+    }
+
     // -- Miscellaneous utilities --
 
     private static volatile boolean checkedIPv6 = false;
@@ -61,6 +90,13 @@
     }
 
     /**
+     * Returns true if exclusive binding is on
+     */
+    static boolean useExclusiveBind() {
+        return exclusiveBind;
+    }
+
+    /**
      * Tells whether IPv6 sockets can join IPv4 multicast groups
      */
     static boolean canIPv6SocketJoinIPv4Group() {
@@ -148,6 +184,34 @@
     }
 
     /**
+     * Returns the local address after performing a SecurityManager#checkConnect.
+     */
+    static InetSocketAddress getRevealedLocalAddress(InetSocketAddress addr) {
+        SecurityManager sm = System.getSecurityManager();
+        if (addr == null || sm == null)
+            return addr;
+
+        try{
+            sm.checkConnect(addr.getAddress().getHostAddress(), -1);
+            // Security check passed
+        } catch (SecurityException e) {
+            // Return loopback address only if security check fails
+            addr = getLoopbackAddress(addr.getPort());
+        }
+        return addr;
+    }
+
+    static String getRevealedLocalAddressAsString(InetSocketAddress addr) {
+        return System.getSecurityManager() == null ? addr.toString() :
+                getLoopbackAddress(addr.getPort()).toString();
+    }
+
+    private static InetSocketAddress getLoopbackAddress(int port) {
+        return new InetSocketAddress(InetAddress.getLoopbackAddress(),
+                                     port);
+    }
+
+    /**
      * Returns any IPv4 address of the given network interface, or
      * null if the interface does not have any IPv4 addresses.
      */
@@ -308,6 +372,12 @@
 
     private static native boolean isIPv6Available0();
 
+    /*
+     * Returns 1 for Windows versions that support exclusive binding by default, 0
+     * for those that do not, and -1 for Solaris/Linux/Mac OS
+     */
+    private static native int isExclusiveBindAvailable();
+
     private static native boolean canIPv6SocketJoinIPv4Group0();
 
     private static native boolean canJoin6WithIPv4Group0();
@@ -341,11 +411,12 @@
     {
         boolean preferIPv6 = isIPv6Available() &&
             (family != StandardProtocolFamily.INET);
-        bind0(preferIPv6, fd, addr, port);
+        bind0(fd, preferIPv6, exclusiveBind, addr, port);
     }
 
-    private static native void bind0(boolean preferIPv6, FileDescriptor fd,
-                                     InetAddress addr, int port)
+    private static native void bind0(FileDescriptor fd, boolean preferIPv6,
+                                     boolean useExclBind, InetAddress addr,
+                                     int port)
         throws IOException;
 
     static native void listen(FileDescriptor fd, int backlog) throws IOException;
--- a/jdk/src/share/classes/sun/nio/ch/ServerSocketAdaptor.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/nio/ch/ServerSocketAdaptor.java	Wed Jul 05 19:00:49 2017 +0200
@@ -80,7 +80,8 @@
     public InetAddress getInetAddress() {
         if (!ssc.isBound())
             return null;
-        return Net.asInetSocketAddress(ssc.localAddress()).getAddress();
+        return Net.getRevealedLocalAddress(ssc.localAddress()).getAddress();
+
     }
 
     public int getLocalPort() {
--- a/jdk/src/share/classes/sun/nio/ch/ServerSocketChannelImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/nio/ch/ServerSocketChannelImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -72,7 +72,10 @@
     private int state = ST_UNINITIALIZED;
 
     // Binding
-    private SocketAddress localAddress; // null => unbound
+    private InetSocketAddress localAddress; // null => unbound
+
+    // set true when exclusive binding is on and SO_REUSEADDR is emulated
+    private boolean isReuseAddress;
 
     // Our socket adaptor, if any
     ServerSocket socket;
@@ -113,7 +116,9 @@
         synchronized (stateLock) {
             if (!isOpen())
                 throw new ClosedChannelException();
-            return localAddress;
+            return localAddress == null ? localAddress
+                    : Net.getRevealedLocalAddress(
+                          Net.asInetSocketAddress(localAddress));
         }
     }
 
@@ -125,13 +130,18 @@
             throw new NullPointerException();
         if (!supportedOptions().contains(name))
             throw new UnsupportedOperationException("'" + name + "' not supported");
-
         synchronized (stateLock) {
             if (!isOpen())
                 throw new ClosedChannelException();
-
-            // no options that require special handling
-            Net.setSocketOption(fd, Net.UNSPEC, name, value);
+            if (name == StandardSocketOptions.SO_REUSEADDR &&
+                    Net.useExclusiveBind())
+            {
+                // SO_REUSEADDR emulated when using exclusive bind
+                isReuseAddress = (Boolean)value;
+            } else {
+                // no options that require special handling
+                Net.setSocketOption(fd, Net.UNSPEC, name, value);
+            }
             return this;
         }
     }
@@ -149,7 +159,12 @@
         synchronized (stateLock) {
             if (!isOpen())
                 throw new ClosedChannelException();
-
+            if (name == StandardSocketOptions.SO_REUSEADDR &&
+                    Net.useExclusiveBind())
+            {
+                // SO_REUSEADDR emulated when using exclusive bind
+                return (T)Boolean.valueOf(isReuseAddress);
+            }
             // no options that require special handling
             return (T) Net.getSocketOption(fd, Net.UNSPEC, name);
         }
@@ -177,7 +192,7 @@
         }
     }
 
-    public SocketAddress localAddress() {
+    public InetSocketAddress localAddress() {
         synchronized (stateLock) {
             return localAddress;
         }
@@ -371,14 +386,15 @@
         StringBuffer sb = new StringBuffer();
         sb.append(this.getClass().getName());
         sb.append('[');
-        if (!isOpen())
+        if (!isOpen()) {
             sb.append("closed");
-        else {
+        } else {
             synchronized (stateLock) {
-                if (localAddress() == null) {
+                InetSocketAddress addr = localAddress();
+                if (addr == null) {
                     sb.append("unbound");
                 } else {
-                    sb.append(localAddress().toString());
+                    sb.append(Net.getRevealedLocalAddressAsString(addr));
                 }
             }
         }
--- a/jdk/src/share/classes/sun/nio/ch/SocketAdaptor.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/nio/ch/SocketAdaptor.java	Wed Jul 05 19:00:49 2017 +0200
@@ -149,9 +149,10 @@
 
     public InetAddress getLocalAddress() {
         if (sc.isOpen()) {
-            SocketAddress local = sc.localAddress();
-            if (local != null)
-                return ((InetSocketAddress)local).getAddress();
+            InetSocketAddress local = sc.localAddress();
+            if (local != null) {
+                return Net.getRevealedLocalAddress(local).getAddress();
+            }
         }
         return new InetSocketAddress(0).getAddress();
     }
--- a/jdk/src/share/classes/sun/nio/ch/SocketChannelImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/nio/ch/SocketChannelImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -70,6 +70,9 @@
 
     // -- The following fields are protected by stateLock
 
+    // set true when exclusive binding is on and SO_REUSEADDR is emulated
+    private boolean isReuseAddress;
+
     // State, increases monotonically
     private static final int ST_UNINITIALIZED = -1;
     private static final int ST_UNCONNECTED = 0;
@@ -80,8 +83,8 @@
     private int state = ST_UNINITIALIZED;
 
     // Binding
-    private SocketAddress localAddress;
-    private SocketAddress remoteAddress;
+    private InetSocketAddress localAddress;
+    private InetSocketAddress remoteAddress;
 
     // Input/Output open
     private boolean isInputOpen = true;
@@ -143,7 +146,7 @@
         synchronized (stateLock) {
             if (!isOpen())
                 throw new ClosedChannelException();
-            return localAddress;
+            return  Net.getRevealedLocalAddress(localAddress);
         }
     }
 
@@ -174,6 +177,12 @@
                 if (!Net.isIPv6Available())
                     Net.setSocketOption(fd, StandardProtocolFamily.INET, name, value);
                 return this;
+            } else if (name == StandardSocketOptions.SO_REUSEADDR &&
+                           Net.useExclusiveBind())
+            {
+                // SO_REUSEADDR emulated when using exclusive bind
+                isReuseAddress = (Boolean)value;
+                return this;
             }
 
             // no options that require special handling
@@ -196,6 +205,13 @@
             if (!isOpen())
                 throw new ClosedChannelException();
 
+            if (name == StandardSocketOptions.SO_REUSEADDR &&
+                    Net.useExclusiveBind())
+            {
+                // SO_REUSEADDR emulated when using exclusive bind
+                return (T)Boolean.valueOf(isReuseAddress);
+            }
+
             // special handling for IP_TOS: always return 0 when IPv6
             if (name == StandardSocketOptions.IP_TOS) {
                 return (Net.isIPv6Available()) ? (T) Integer.valueOf(0) :
@@ -531,7 +547,7 @@
         IOUtil.configureBlocking(fd, block);
     }
 
-    public SocketAddress localAddress() {
+    public InetSocketAddress localAddress() {
         synchronized (stateLock) {
             return localAddress;
         }
@@ -958,6 +974,7 @@
         return fdVal;
     }
 
+    @Override
     public String toString() {
         StringBuffer sb = new StringBuffer();
         sb.append(this.getClass().getSuperclass().getName());
@@ -981,9 +998,10 @@
                         sb.append(" oshut");
                     break;
                 }
-                if (localAddress() != null) {
+                InetSocketAddress addr = localAddress();
+                if (addr != null) {
                     sb.append(" local=");
-                    sb.append(localAddress().toString());
+                    sb.append(Net.getRevealedLocalAddressAsString(addr));
                 }
                 if (remoteAddress() != null) {
                     sb.append(" remote=");
--- a/jdk/src/share/classes/sun/reflect/CallerSensitive.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/reflect/CallerSensitive.java	Wed Jul 05 19:00:49 2017 +0200
@@ -36,6 +36,6 @@
  * @author John R. Rose
  */
 @Retention(RetentionPolicy.RUNTIME)
-@Target({CONSTRUCTOR, METHOD})
+@Target({METHOD})
 public @interface CallerSensitive {
 }
--- a/jdk/src/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -337,12 +337,15 @@
         try {
             annotationType = AnnotationType.getInstance(type);
         } catch(IllegalArgumentException e) {
-            // Class is no longer an annotation type; all bets are off
-            return;
+            // Class is no longer an annotation type; time to punch out
+            throw new java.io.InvalidObjectException("Non-annotation type in annotation serial stream");
         }
 
         Map<String, Class<?>> memberTypes = annotationType.memberTypes();
 
+
+        // If there are annotation members without values, that
+        // situation is handled by the invoke method.
         for (Map.Entry<String, Object> memberValue : memberValues.entrySet()) {
             String name = memberValue.getKey();
             Class<?> memberType = memberTypes.get(name);
--- a/jdk/src/share/classes/sun/reflect/generics/repository/ClassRepository.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/reflect/generics/repository/ClassRepository.java	Wed Jul 05 19:00:49 2017 +0200
@@ -40,6 +40,8 @@
  */
 public class ClassRepository extends GenericDeclRepository<ClassSignature> {
 
+    public static final ClassRepository NONE = ClassRepository.make("Ljava/lang/Object;", null);
+
     private Type superclass; // caches the generic superclass info
     private Type[] superInterfaces; // caches the generic superinterface info
 
--- a/jdk/src/share/classes/sun/reflect/misc/ReflectUtil.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/reflect/misc/ReflectUtil.java	Wed Jul 05 19:00:49 2017 +0200
@@ -27,6 +27,7 @@
 package sun.reflect.misc;
 
 import java.lang.reflect.Modifier;
+import java.lang.reflect.Proxy;
 import sun.reflect.Reflection;
 
 public final class ReflectUtil {
@@ -114,11 +115,26 @@
         return false;
     }
 
-
+    /**
+     * Checks package access on the given class.
+     *
+     * If it is a {@link Proxy#isProxyClass(java.lang.Class)} that implements
+     * a non-public interface (i.e. may be in a non-restricted package),
+     * also check the package access on the proxy interfaces.
+     */
     public static void checkPackageAccess(Class<?> clazz) {
         checkPackageAccess(clazz.getName());
+        if (isNonPublicProxyClass(clazz)) {
+            checkProxyPackageAccess(clazz);
+        }
     }
 
+    /**
+     * Checks package access on the given classname.
+     * This method is typically called when the Class instance is not
+     * available and the caller attempts to load a class on behalf
+     * the true caller (application).
+     */
     public static void checkPackageAccess(String name) {
         SecurityManager s = System.getSecurityManager();
         if (s != null) {
@@ -180,13 +196,30 @@
     }
 
     /**
+     * Check package access on the proxy interfaces that the given proxy class
+     * implements.
+     *
+     * @param clazz Proxy class object
+     */
+    public static void checkProxyPackageAccess(Class<?> clazz) {
+        SecurityManager s = System.getSecurityManager();
+        if (s != null) {
+            // check proxy interfaces if the given class is a proxy class
+            if (Proxy.isProxyClass(clazz)) {
+                for (Class<?> intf : clazz.getInterfaces()) {
+                    checkPackageAccess(intf);
+                }
+            }
+        }
+    }
+
+    /**
      * Access check on the interfaces that a proxy class implements and throw
-     * {@code SecurityException} if it accesses a restricted package.
+     * {@code SecurityException} if it accesses a restricted package from
+     * the caller's class loader.
      *
      * @param ccl the caller's class loader
      * @param interfaces the list of interfaces that a proxy class implements
-     *
-     * @see Proxy#checkProxyAccess
      */
     public static void checkProxyPackageAccess(ClassLoader ccl,
                                                Class<?>... interfaces)
@@ -205,4 +238,16 @@
     // Note that bytecode instrumentation tools may exclude 'sun.*'
     // classes but not generated proxy classes and so keep it in com.sun.*
     public static final String PROXY_PACKAGE = "com.sun.proxy";
+
+    /**
+     * Test if the given class is a proxy class that implements
+     * non-public interface.  Such proxy class may be in a non-restricted
+     * package that bypasses checkPackageAccess.
+     */
+    public static boolean isNonPublicProxyClass(Class<?> cls) {
+        String name = cls.getName();
+        int i = name.lastIndexOf('.');
+        String pkg = (i != -1) ? name.substring(0, i) : "";
+        return Proxy.isProxyClass(cls) && !pkg.equals(PROXY_PACKAGE);
+    }
 }
--- a/jdk/src/share/classes/sun/rmi/rmic/Main.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/rmi/rmic/Main.java	Wed Jul 05 19:00:49 2017 +0200
@@ -879,9 +879,9 @@
         }
 
         String[] args = new String[3];
-        args[0] = (arg0 != null ? arg0.toString() : "null");
-        args[1] = (arg1 != null ? arg1.toString() : "null");
-        args[2] = (arg2 != null ? arg2.toString() : "null");
+        args[0] = (arg0 != null ? arg0 : "null");
+        args[1] = (arg1 != null ? arg1 : "null");
+        args[2] = (arg2 != null ? arg2 : "null");
 
         return java.text.MessageFormat.format(format, (Object[]) args);
     }
--- a/jdk/src/share/classes/sun/rmi/server/Activation.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/rmi/server/Activation.java	Wed Jul 05 19:00:49 2017 +0200
@@ -2230,7 +2230,13 @@
         }
 
         public InetAddress getInetAddress() {
-            return serverSocket.getInetAddress();
+            return AccessController.doPrivileged(
+                new PrivilegedAction<InetAddress>() {
+                    @Override
+                    public InetAddress run() {
+                        return serverSocket.getInetAddress();
+                    }
+                });
         }
 
         public int getLocalPort() {
@@ -2238,7 +2244,13 @@
         }
 
         public SocketAddress getLocalSocketAddress() {
-            return serverSocket.getLocalSocketAddress();
+            return AccessController.doPrivileged(
+                new PrivilegedAction<SocketAddress>() {
+                    @Override
+                    public SocketAddress run() {
+                        return serverSocket.getLocalSocketAddress();
+                    }
+                });
         }
 
         /**
--- a/jdk/src/share/classes/sun/rmi/server/LoaderHandler.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/rmi/server/LoaderHandler.java	Wed Jul 05 19:00:49 2017 +0200
@@ -55,6 +55,7 @@
 import java.util.Map;
 import java.util.StringTokenizer;
 import java.util.WeakHashMap;
+import sun.reflect.misc.ReflectUtil;
 import sun.rmi.runtime.Log;
 import sun.security.action.GetPropertyAction;
 
@@ -170,7 +171,7 @@
 
         if (defaultLoader != null) {
             try {
-                Class<?> c = Class.forName(name, false, defaultLoader);
+                Class<?> c = loadClassForName(name, false, defaultLoader);
                 if (loaderLog.isLoggable(Log.VERBOSE)) {
                     loaderLog.log(Log.VERBOSE,
                         "class \"" + name + "\" found via defaultLoader, " +
@@ -422,7 +423,7 @@
                  * resolved without the security-offending codebase anyway;
                  * if so, return successfully (see bugids 4191926 & 4349670).
                  */
-                Class<?> c = Class.forName(name, false, parent);
+                Class<?> c = loadClassForName(name, false, parent);
                 if (loaderLog.isLoggable(Log.VERBOSE)) {
                     loaderLog.log(Log.VERBOSE,
                         "class \"" + name + "\" found via " +
@@ -448,7 +449,7 @@
         }
 
         try {
-            Class<?> c = Class.forName(name, false, loader);
+            Class<?> c = loadClassForName(name, false, loader);
             if (loaderLog.isLoggable(Log.VERBOSE)) {
                 loaderLog.log(Log.VERBOSE,
                     "class \"" + name + "\" " + "found via codebase, " +
@@ -726,7 +727,7 @@
 
         for (int i = 0; i < interfaces.length; i++) {
             Class<?> cl =
-                (classObjs[i] = Class.forName(interfaces[i], false, loader));
+                (classObjs[i] = loadClassForName(interfaces[i], false, loader));
 
             if (!Modifier.isPublic(cl.getModifiers())) {
                 ClassLoader current = cl.getClassLoader();
@@ -1195,5 +1196,28 @@
         public String toString() {
             return super.toString() + "[\"" + annotation + "\"]";
         }
+
+        @Override
+        protected Class<?> loadClass(String name, boolean resolve)
+                throws ClassNotFoundException {
+            if (parent == null) {
+                ReflectUtil.checkPackageAccess(name);
+            }
+            return super.loadClass(name, resolve);
+        }
+
+
     }
+
+    private static Class<?> loadClassForName(String name,
+                                              boolean initialize,
+                                              ClassLoader loader)
+            throws ClassNotFoundException
+    {
+        if (loader == null) {
+            ReflectUtil.checkPackageAccess(name);
+        }
+        return Class.forName(name, initialize, loader);
+    }
+
 }
--- a/jdk/src/share/classes/sun/rmi/transport/proxy/WrappedSocket.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/rmi/transport/proxy/WrappedSocket.java	Wed Jul 05 19:00:49 2017 +0200
@@ -28,6 +28,8 @@
 import java.net.InetAddress;
 import java.net.Socket;
 import java.net.SocketException;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 
 /**
  * The WrappedSocket class provides a general wrapper for providing an
@@ -78,7 +80,14 @@
      * Get the local address to which the socket is bound.
      */
     public InetAddress getLocalAddress() {
-        return socket.getLocalAddress();
+        return  AccessController.doPrivileged(
+                        new PrivilegedAction<InetAddress>() {
+                            @Override
+                            public InetAddress run() {
+                                return socket.getLocalAddress();
+
+                            }
+                        });
     }
 
     /**
--- a/jdk/src/share/classes/sun/security/krb5/Config.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/Config.java	Wed Jul 05 19:00:49 2017 +0200
@@ -761,22 +761,23 @@
     }
 
     /**
-     * Returns the default encryption types.
-     *
+     * Returns all etypes specified in krb5.conf for the given configName,
+     * or all the builtin defaults. This result is always non-empty.
+     * If no etypes are found, an exception is thrown.
      */
-    public int[] defaultEtype(String enctypes) {
+    public int[] defaultEtype(String configName) throws KrbException {
         String default_enctypes;
-        default_enctypes = get("libdefaults", enctypes);
-        String delim = " ";
-        StringTokenizer st;
+        default_enctypes = get("libdefaults", configName);
         int[] etype;
         if (default_enctypes == null) {
             if (DEBUG) {
                 System.out.println("Using builtin default etypes for " +
-                    enctypes);
+                    configName);
             }
             etype = EType.getBuiltInDefaults();
         } else {
+            String delim = " ";
+            StringTokenizer st;
             for (int j = 0; j < default_enctypes.length(); j++) {
                 if (default_enctypes.substring(j, j + 1).equals(",")) {
                     // only two delimiters are allowed to use
@@ -791,17 +792,13 @@
             int type;
             for (int i = 0; i < len; i++) {
                 type = Config.getType(st.nextToken());
-                if ((type != -1) &&
-                    (EType.isSupported(type))) {
+                if (type != -1 && EType.isSupported(type)) {
                     ls.add(type);
                 }
             }
             if (ls.isEmpty()) {
-                if (DEBUG) {
-                    System.out.println(
-                        "no supported default etypes for " + enctypes);
-                }
-                return null;
+                throw new KrbException("no supported default etypes for "
+                        + configName);
             } else {
                 etype = new int[ls.size()];
                 for (int i = 0; i < etype.length; i++) {
@@ -811,7 +808,7 @@
         }
 
         if (DEBUG) {
-            System.out.print("default etypes for " + enctypes + ":");
+            System.out.print("default etypes for " + configName + ":");
             for (int i = 0; i < etype.length; i++) {
                 System.out.print(" " + etype[i]);
             }
--- a/jdk/src/share/classes/sun/security/krb5/EncryptionKey.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/EncryptionKey.java	Wed Jul 05 19:00:49 2017 +0200
@@ -98,36 +98,6 @@
     }
 
     /**
-     * Obtains the latest version of the secret key of
-     * the principal from a keytab.
-     *
-     * @param princ the principal whose secret key is desired
-     * @param keytab the path to the keytab file. A value of null
-     * will be accepted to indicate that the default path should be
-     * searched.
-     * @returns the secret key or null if none was found.
-     */
-    /*
-    // Replaced by acquireSecretKeys
-    public static EncryptionKey acquireSecretKey(PrincipalName princ,
-                                                 String keytab)
-        throws KrbException, IOException {
-
-        if (princ == null) {
-            throw new IllegalArgumentException(
-                "Cannot have null pricipal name to look in keytab.");
-        }
-
-        KeyTab ktab = KeyTab.getInstance(keytab);
-
-        if (ktab == null)
-            return null;
-
-        return ktab.readServiceKey(princ);
-    }
-    */
-
-    /**
      * Obtains all versions of the secret key of the principal from a
      * keytab.
      *
@@ -208,9 +178,6 @@
             String salt) throws KrbException {
 
         int[] etypes = EType.getDefaults("default_tkt_enctypes");
-        if (etypes == null) {
-            etypes = EType.getBuiltInDefaults();
-        }
 
         EncryptionKey[] encKeys = new EncryptionKey[etypes.length];
         for (int i = 0; i < etypes.length; i++) {
--- a/jdk/src/share/classes/sun/security/krb5/KrbApReq.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/KrbApReq.java	Wed Jul 05 19:00:49 2017 +0200
@@ -490,10 +490,6 @@
      // Check that key is one of the permitted types
      private static void checkPermittedEType(int target) throws KrbException {
         int[] etypes = EType.getDefaults("permitted_enctypes");
-        if (etypes == null) {
-            throw new KrbException(
-                "No supported encryption types listed in permitted_enctypes");
-        }
         if (!EType.isSupported(target, etypes)) {
             throw new KrbException(EType.toString(target) +
                 " encryption type not in permitted_enctypes list");
--- a/jdk/src/share/classes/sun/security/krb5/KrbTgsReq.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/KrbTgsReq.java	Wed Jul 05 19:00:49 2017 +0200
@@ -291,8 +291,7 @@
                          Ticket[] additionalTickets,
                          EncryptionKey subKey,
                          PAData extraPA)
-        throws Asn1Exception, IOException, KdcErrException, KrbApErrException,
-               UnknownHostException, KrbCryptoException {
+        throws IOException, KrbException, UnknownHostException {
         KerberosTime req_till = null;
         if (till == null) {
             req_till = new KerberosTime(0);
@@ -314,10 +313,6 @@
         int[] req_eTypes = null;
         if (eTypes == null) {
             req_eTypes = EType.getDefaults("default_tgs_enctypes");
-            if (req_eTypes == null) {
-                throw new KrbCryptoException(
-            "No supported encryption types listed in default_tgs_enctypes");
-            }
         } else {
             req_eTypes = eTypes;
         }
--- a/jdk/src/share/classes/sun/security/krb5/internal/crypto/EType.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/internal/crypto/EType.java	Wed Jul 05 19:00:49 2017 +0200
@@ -230,11 +230,14 @@
     /**
      * Retrieves the default etypes from the configuration file, or
      * if that's not available, return the built-in list of default etypes.
+     * This result is always non-empty. If no etypes are found,
+     * an exception is thrown.
      */
-    // used in KrbAsReq, KeyTab
-    public static int[] getDefaults(String configName) {
+    public static int[] getDefaults(String configName)
+            throws KrbException {
+        Config config = null;
         try {
-            return Config.getInstance().defaultEtype(configName);
+            config = Config.getInstance();
         } catch (KrbException exc) {
             if (DEBUG) {
                 System.out.println("Exception while getting " +
@@ -243,6 +246,7 @@
             }
             return getBuiltInDefaults();
         }
+        return config.defaultEtype(configName);
     }
 
     /**
@@ -254,12 +258,8 @@
      * we have keys.
      */
     public static int[] getDefaults(String configName, EncryptionKey[] keys)
-        throws KrbException {
+            throws KrbException {
         int[] answer = getDefaults(configName);
-        if (answer == null) {
-            throw new KrbException("No supported encryption types listed in "
-                + configName);
-        }
 
         List<Integer> list = new ArrayList<>(answer.length);
         for (int i = 0; i < answer.length; i++) {
--- a/jdk/src/share/classes/sun/security/krb5/internal/ktab/KeyTab.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/krb5/internal/ktab/KeyTab.java	Wed Jul 05 19:00:49 2017 +0200
@@ -279,8 +279,7 @@
 
     /**
      * Reads all keys for a service from the keytab file that have
-     * etypes that have been configured for use. If there are multiple
-     * keys with same etype, the one with the highest kvno is returned.
+     * etypes that have been configured for use.
      * @param service the PrincipalName of the requested service
      * @return an array containing all the service keys, never null
      */
@@ -313,35 +312,12 @@
         size = keys.size();
         EncryptionKey[] retVal = keys.toArray(new EncryptionKey[size]);
 
-        // Sort keys according to default_tkt_enctypes
-        if (DEBUG) {
-            System.out.println("Ordering keys wrt default_tkt_enctypes list");
-        }
-
-        final int[] etypes = EType.getDefaults("default_tkt_enctypes");
-
-        // Sort the keys, k1 is preferred than k2 if:
-        // 1. k1's etype appears earlier in etypes than k2's
-        // 2. If same, k1's KVNO is higher
+        // Sort the keys by kvno. Sometimes we must choose a single key (say,
+        // generate encrypted timestamp in AS-REQ). A key with a higher KVNO
+        // sounds like a newer one.
         Arrays.sort(retVal, new Comparator<EncryptionKey>() {
             @Override
             public int compare(EncryptionKey o1, EncryptionKey o2) {
-                if (etypes != null) {
-                    int o1EType = o1.getEType();
-                    int o2EType = o2.getEType();
-                    if (o1EType != o2EType) {
-                        for (int i=0; i<etypes.length; i++) {
-                            if (etypes[i] == o1EType) {
-                                return -1;
-                            } else if (etypes[i] == o2EType) {
-                                return 1;
-                            }
-                        }
-                        // Neither o1EType nor o2EType in default_tkt_enctypes,
-                        // therefore won't be used in AS-REQ. We do not care
-                        // about their order, use kvno is OK.
-                    }
-                }
                 return o2.getKeyVersionNumber().intValue()
                         - o1.getKeyVersionNumber().intValue();
             }
--- a/jdk/src/share/classes/sun/security/pkcs/SignerInfo.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/pkcs/SignerInfo.java	Wed Jul 05 19:00:49 2017 +0200
@@ -34,6 +34,7 @@
 import java.security.cert.X509Certificate;
 import java.security.*;
 import java.util.ArrayList;
+import java.util.Arrays;
 
 import sun.security.timestamp.TimestampToken;
 import sun.security.util.*;
@@ -57,6 +58,7 @@
     byte[] encryptedDigest;
     Timestamp timestamp;
     private boolean hasTimestamp = true;
+    private static final Debug debug = Debug.getInstance("jar");
 
     PKCS9Attributes authenticatedAttributes;
     PKCS9Attributes unauthenticatedAttributes;
@@ -499,11 +501,40 @@
         CertPath tsaChain = cf.generateCertPath(chain);
         // Create a timestamp token info object
         TimestampToken tsTokenInfo = new TimestampToken(encTsTokenInfo);
+        // Check that the signature timestamp applies to this signature
+        verifyTimestamp(tsTokenInfo);
         // Create a timestamp object
         timestamp = new Timestamp(tsTokenInfo.getDate(), tsaChain);
         return timestamp;
     }
 
+    /*
+     * Check that the signature timestamp applies to this signature.
+     * Match the hash present in the signature timestamp token against the hash
+     * of this signature.
+     */
+    private void verifyTimestamp(TimestampToken token)
+        throws NoSuchAlgorithmException, SignatureException {
+
+        MessageDigest md =
+            MessageDigest.getInstance(token.getHashAlgorithm().getName());
+
+        if (!Arrays.equals(token.getHashedMessage(),
+            md.digest(encryptedDigest))) {
+
+            throw new SignatureException("Signature timestamp (#" +
+                token.getSerialNumber() + ") generated on " + token.getDate() +
+                " is inapplicable");
+        }
+
+        if (debug != null) {
+            debug.println();
+            debug.println("Detected signature timestamp (#" +
+                token.getSerialNumber() + ") generated on " + token.getDate());
+            debug.println();
+        }
+    }
+
     public String toString() {
         HexDumpEncoder hexDump = new HexDumpEncoder();
 
--- a/jdk/src/share/classes/sun/security/ssl/Handshaker.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/ssl/Handshaker.java	Wed Jul 05 19:00:49 2017 +0200
@@ -186,6 +186,16 @@
     static final boolean allowLegacyHelloMessages = Debug.getBooleanProperty(
                     "sun.security.ssl.allowLegacyHelloMessages", true);
 
+    // To prevent the TLS renegotiation issues, by setting system property
+    // "jdk.tls.rejectClientInitializedRenego" to true, applications in server
+    // side can disable all client initiated SSL renegotiations regardless
+    // of the support of TLS protocols.
+    //
+    // By default, allow client initiated renegotiations.
+    static final boolean rejectClientInitiatedRenego =
+            Debug.getBooleanProperty(
+                "jdk.tls.rejectClientInitializedRenego", false);
+
     // need to dispose the object when it is invalidated
     boolean invalidated;
 
--- a/jdk/src/share/classes/sun/security/ssl/ServerHandshaker.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/ssl/ServerHandshaker.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -279,6 +279,15 @@
             mesg.print(System.out);
         }
 
+        // Reject client initiated renegotiation?
+        //
+        // Should not have any impact on server initiated renegotiation.
+        if (rejectClientInitiatedRenego && !isInitialHandshake &&
+                state != HandshakeMessage.ht_hello_request) {
+            fatalSE(Alerts.alert_handshake_failure,
+                "Client initiated renegotiation is not allowed");
+        }
+
         // check the server name indication if required
         ServerNameExtension clientHelloSNIExt = (ServerNameExtension)
                     mesg.extensions.get(ExtensionType.EXT_SERVER_NAME);
@@ -369,7 +378,7 @@
             } else if (!allowUnsafeRenegotiation) {
                 // abort the handshake
                 if (activeProtocolVersion.v >= ProtocolVersion.TLS10.v) {
-                    // response with a no_renegotiation warning,
+                    // respond with a no_renegotiation warning
                     warningSE(Alerts.alert_no_renegotiation);
 
                     // invalidate the handshake so that the caller can
--- a/jdk/src/share/classes/sun/security/timestamp/TimestampToken.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/timestamp/TimestampToken.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -119,6 +119,10 @@
         return policy.toString();
     }
 
+    public BigInteger getSerialNumber() {
+        return serialNumber;
+    }
+
     /*
      * Parses the timestamp token info.
      *
--- a/jdk/src/share/classes/sun/security/util/AuthResources_zh_CN.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/util/AuthResources_zh_CN.java	Wed Jul 05 19:00:49 2017 +0200
@@ -99,7 +99,7 @@
         /***    EVERYTHING BELOW IS DEPRECATED  ***/
 
         // com.sun.security.auth.PolicyFile
-        {".error.parsing.", ": \u8FDB\u884C\u8BED\u6CD5\u5206\u6790\u65F6\u51FA\u9519 "},
+        {".error.parsing.", ": \u89E3\u6790\u65F6\u51FA\u9519 "},
         {"COLON", ": "},
         {".error.adding.Permission.", ": \u6DFB\u52A0\u6743\u9650\u65F6\u51FA\u9519 "},
         {"SPACE", " "},
--- a/jdk/src/share/classes/sun/security/util/Resources_de.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/util/Resources_de.java	Wed Jul 05 19:00:49 2017 +0200
@@ -127,6 +127,8 @@
         {"multiple.Codebase.expressions",
                 "mehrere Codebase-Ausdr\u00FCcke"},
         {"multiple.SignedBy.expressions","mehrere SignedBy-Ausdr\u00FCcke"},
+        {"duplicate.keystore.domain.name","Keystore-Domainname doppelt vorhanden: {0}"},
+        {"duplicate.keystore.name","Keystore-Name doppelt vorhanden: {0}"},
         {"SignedBy.has.empty.alias","Leerer Alias in SignedBy"},
         {"can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name",
                 "Principal kann nicht mit einer Platzhalterklasse ohne Platzhalternamen angegeben werden"},
--- a/jdk/src/share/classes/sun/security/util/Resources_es.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/util/Resources_es.java	Wed Jul 05 19:00:49 2017 +0200
@@ -127,6 +127,8 @@
         {"multiple.Codebase.expressions",
                 "expresiones m\u00FAltiples de CodeBase"},
         {"multiple.SignedBy.expressions","expresiones m\u00FAltiples de SignedBy"},
+        {"duplicate.keystore.domain.name","nombre de dominio de almac\u00E9n de claves duplicado: {0}"},
+        {"duplicate.keystore.name","nombre de almac\u00E9n de claves duplicado: {0}"},
         {"SignedBy.has.empty.alias","SignedBy tiene un alias vac\u00EDo"},
         {"can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name",
                 "no se puede especificar Principal con una clase de comod\u00EDn sin un nombre de comod\u00EDn"},
--- a/jdk/src/share/classes/sun/security/util/Resources_fr.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/util/Resources_fr.java	Wed Jul 05 19:00:49 2017 +0200
@@ -127,6 +127,8 @@
         {"multiple.Codebase.expressions",
                 "expressions Codebase multiples"},
         {"multiple.SignedBy.expressions","expressions SignedBy multiples"},
+        {"duplicate.keystore.domain.name","nom de domaine de fichier de cl\u00E9s en double : {0}"},
+        {"duplicate.keystore.name","nom de fichier de cl\u00E9s en double : {0}"},
         {"SignedBy.has.empty.alias","SignedBy poss\u00E8de un alias vide"},
         {"can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name",
                 "impossible de sp\u00E9cifier le principal avec une classe g\u00E9n\u00E9rique sans nom g\u00E9n\u00E9rique"},
--- a/jdk/src/share/classes/sun/security/util/Resources_it.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/util/Resources_it.java	Wed Jul 05 19:00:49 2017 +0200
@@ -127,6 +127,8 @@
         {"multiple.Codebase.expressions",
                 "espressioni Codebase multiple"},
         {"multiple.SignedBy.expressions","espressioni SignedBy multiple"},
+        {"duplicate.keystore.domain.name","nome dominio keystore duplicato: {0}"},
+        {"duplicate.keystore.name","nome keystore duplicato: {0}"},
         {"SignedBy.has.empty.alias","SignedBy presenta un alias vuoto"},
         {"can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name",
                 "impossibile specificare un principal con una classe carattere jolly senza un nome carattere jolly"},
--- a/jdk/src/share/classes/sun/security/util/Resources_ja.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/util/Resources_ja.java	Wed Jul 05 19:00:49 2017 +0200
@@ -127,6 +127,8 @@
         {"multiple.Codebase.expressions",
                 "\u8907\u6570\u306ECodebase\u5F0F"},
         {"multiple.SignedBy.expressions","\u8907\u6570\u306ESignedBy\u5F0F"},
+        {"duplicate.keystore.domain.name","\u91CD\u8907\u3059\u308B\u30AD\u30FC\u30B9\u30C8\u30A2\u30FB\u30C9\u30E1\u30A4\u30F3\u540D: {0}"},
+        {"duplicate.keystore.name","\u91CD\u8907\u3059\u308B\u30AD\u30FC\u30B9\u30C8\u30A2\u540D: {0}"},
         {"SignedBy.has.empty.alias","SignedBy\u306F\u7A7A\u306E\u5225\u540D\u3092\u4FDD\u6301\u3057\u307E\u3059"},
         {"can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name",
                 "\u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9\u540D\u306E\u306A\u3044\u30EF\u30A4\u30EB\u30C9\u30AB\u30FC\u30C9\u30FB\u30AF\u30E9\u30B9\u3092\u4F7F\u7528\u3057\u3066\u3001\u30D7\u30EA\u30F3\u30B7\u30D1\u30EB\u3092\u6307\u5B9A\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093"},
--- a/jdk/src/share/classes/sun/security/util/Resources_ko.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/util/Resources_ko.java	Wed Jul 05 19:00:49 2017 +0200
@@ -127,6 +127,8 @@
         {"multiple.Codebase.expressions",
                 "Codebase \uD45C\uD604\uC2DD\uC774 \uC5EC\uB7EC \uAC1C\uC785\uB2C8\uB2E4."},
         {"multiple.SignedBy.expressions","SignedBy \uD45C\uD604\uC2DD\uC774 \uC5EC\uB7EC \uAC1C\uC785\uB2C8\uB2E4."},
+        {"duplicate.keystore.domain.name","\uC911\uBCF5\uB41C \uD0A4 \uC800\uC7A5\uC18C \uB3C4\uBA54\uC778 \uC774\uB984: {0}"},
+        {"duplicate.keystore.name","\uC911\uBCF5\uB41C \uD0A4 \uC800\uC7A5\uC18C \uC774\uB984: {0}"},
         {"SignedBy.has.empty.alias","SignedBy\uC758 \uBCC4\uCE6D\uC774 \uBE44\uC5B4 \uC788\uC2B5\uB2C8\uB2E4."},
         {"can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name",
                 "\uC640\uC77C\uB4DC \uCE74\uB4DC \uBB38\uC790 \uC774\uB984 \uC5C6\uC774 \uC640\uC77C\uB4DC \uCE74\uB4DC \uBB38\uC790 \uD074\uB798\uC2A4\uB97C \uC0AC\uC6A9\uD558\uB294 \uC8FC\uCCB4\uB97C \uC9C0\uC815\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4."},
--- a/jdk/src/share/classes/sun/security/util/Resources_pt_BR.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/util/Resources_pt_BR.java	Wed Jul 05 19:00:49 2017 +0200
@@ -127,6 +127,8 @@
         {"multiple.Codebase.expressions",
                 "v\u00E1rias express\u00F5es CodeBase"},
         {"multiple.SignedBy.expressions","v\u00E1rias express\u00F5es SignedBy"},
+        {"duplicate.keystore.domain.name","nome do dom\u00EDnio da \u00E1rea de armazenamento de teclas duplicado: {0}"},
+        {"duplicate.keystore.name","nome da \u00E1rea de armazenamento de chaves duplicado: {0}"},
         {"SignedBy.has.empty.alias","SignedBy tem alias vazio"},
         {"can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name",
                 "n\u00E3o \u00E9 poss\u00EDvel especificar um principal com uma classe curinga sem um nome curinga"},
--- a/jdk/src/share/classes/sun/security/util/Resources_sv.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/util/Resources_sv.java	Wed Jul 05 19:00:49 2017 +0200
@@ -127,6 +127,8 @@
         {"multiple.Codebase.expressions",
                 "flera CodeBase-uttryck"},
         {"multiple.SignedBy.expressions","flera SignedBy-uttryck"},
+        {"duplicate.keystore.domain.name","dom\u00E4nnamn f\u00F6r dubbelt nyckellager: {0}"},
+        {"duplicate.keystore.name","namn f\u00F6r dubbelt nyckellager: {0}"},
         {"SignedBy.has.empty.alias","SignedBy har ett tomt alias"},
         {"can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name",
                 "kan inte ange identitetshavare med en jokerteckenklass utan ett jokerteckennamn"},
--- a/jdk/src/share/classes/sun/security/util/Resources_zh_CN.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/util/Resources_zh_CN.java	Wed Jul 05 19:00:49 2017 +0200
@@ -105,7 +105,7 @@
         // sun.security.provider.PolicyFile
 
         {"java.security.policy.error.parsing.policy.message",
-                "java.security.policy: \u5BF9{0}\u8FDB\u884C\u8BED\u6CD5\u5206\u6790\u65F6\u51FA\u9519:\n\t{1}"},
+                "java.security.policy: \u89E3\u6790{0}\u65F6\u51FA\u9519:\n\t{1}"},
         {"java.security.policy.error.adding.Permission.perm.message",
                 "java.security.policy: \u6DFB\u52A0\u6743\u9650{0}\u65F6\u51FA\u9519:\n\t{1}"},
         {"java.security.policy.error.adding.Entry.message",
@@ -127,6 +127,8 @@
         {"multiple.Codebase.expressions",
                 "\u591A\u4E2A\u4EE3\u7801\u5E93\u8868\u8FBE\u5F0F"},
         {"multiple.SignedBy.expressions","\u591A\u4E2A SignedBy \u8868\u8FBE\u5F0F"},
+        {"duplicate.keystore.domain.name","\u5BC6\u94A5\u5E93\u57DF\u540D\u91CD\u590D: {0}"},
+        {"duplicate.keystore.name","\u5BC6\u94A5\u5E93\u540D\u79F0\u91CD\u590D: {0}"},
         {"SignedBy.has.empty.alias","SignedBy \u6709\u7A7A\u522B\u540D"},
         {"can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name",
                 "\u6CA1\u6709\u901A\u914D\u7B26\u540D\u79F0, \u65E0\u6CD5\u4F7F\u7528\u901A\u914D\u7B26\u7C7B\u6307\u5B9A\u4E3B\u7528\u6237"},
--- a/jdk/src/share/classes/sun/security/util/Resources_zh_TW.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/security/util/Resources_zh_TW.java	Wed Jul 05 19:00:49 2017 +0200
@@ -127,6 +127,8 @@
         {"multiple.Codebase.expressions",
                 "\u591A\u91CD Codebase \u8868\u793A\u5F0F"},
         {"multiple.SignedBy.expressions","\u591A\u91CD SignedBy \u8868\u793A\u5F0F"},
+        {"duplicate.keystore.domain.name","\u91CD\u8907\u7684\u91D1\u9470\u5132\u5B58\u5EAB\u7DB2\u57DF\u540D\u7A31: {0}"},
+        {"duplicate.keystore.name","\u91CD\u8907\u7684\u91D1\u9470\u5132\u5B58\u5EAB\u540D\u7A31: {0}"},
         {"SignedBy.has.empty.alias","SignedBy \u6709\u7A7A\u5225\u540D"},
         {"can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name",
                 "\u6C92\u6709\u842C\u7528\u5B57\u5143\u540D\u7A31\uFF0C\u7121\u6CD5\u6307\u5B9A\u542B\u6709\u842C\u7528\u5B57\u5143\u985E\u5225\u7684 Principal"},
--- a/jdk/src/share/classes/sun/swing/SwingUtilities2.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/swing/SwingUtilities2.java	Wed Jul 05 19:00:49 2017 +0200
@@ -33,18 +33,19 @@
 import java.awt.font.*;
 import java.awt.geom.*;
 import java.awt.print.PrinterGraphics;
-import java.text.Bidi;
 import java.text.AttributedCharacterIterator;
 import java.text.AttributedString;
 
 import javax.swing.*;
-import javax.swing.plaf.*;
+import javax.swing.event.TreeModelEvent;
 import javax.swing.text.Highlighter;
 import javax.swing.text.JTextComponent;
 import javax.swing.text.DefaultHighlighter;
 import javax.swing.text.DefaultCaret;
 import javax.swing.table.TableCellRenderer;
 import javax.swing.table.TableColumnModel;
+import javax.swing.tree.TreeModel;
+import javax.swing.tree.TreePath;
 
 import sun.swing.PrintColorUIResource;
 import sun.swing.ImageIconUIResource;
@@ -1887,4 +1888,22 @@
         }
         return InputEvent.ALT_MASK;
     }
+
+    /**
+     * Returns the {@link TreePath} that identifies the changed nodes.
+     *
+     * @param event  changes in a tree model
+     * @param model  corresponing tree model
+     * @return  the path to the changed nodes
+     */
+    public static TreePath getTreePath(TreeModelEvent event, TreeModel model) {
+        TreePath path = event.getTreePath();
+        if ((path == null) && (model != null)) {
+            Object root = model.getRoot();
+            if (root != null) {
+                path = new TreePath(root);
+            }
+        }
+        return path;
+    }
 }
--- a/jdk/src/share/classes/sun/text/resources/pt/FormatData_pt.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/text/resources/pt/FormatData_pt.java	Wed Jul 05 19:00:49 2017 +0200
@@ -103,18 +103,18 @@
             },
             { "MonthAbbreviations",
                 new String[] {
-                    "Jan", // abb january
-                    "Fev", // abb february
-                    "Mar", // abb march
-                    "Abr", // abb april
-                    "Mai", // abb may
-                    "Jun", // abb june
-                    "Jul", // abb july
-                    "Ago", // abb august
-                    "Set", // abb september
-                    "Out", // abb october
-                    "Nov", // abb november
-                    "Dez", // abb december
+                    "jan", // abb january
+                    "fev", // abb february
+                    "mar", // abb march
+                    "abr", // abb april
+                    "mai", // abb may
+                    "jun", // abb june
+                    "jul", // abb july
+                    "ago", // abb august
+                    "set", // abb september
+                    "out", // abb october
+                    "nov", // abb november
+                    "dez", // abb december
                     "" // abb month 13 if applicable
                 }
             },
--- a/jdk/src/share/classes/sun/tools/jar/resources/jar_de.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jar/resources/jar_de.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -29,6 +29,7 @@
 error.bad.cflag=Kennzeichen "c" erfordert Angabe von Manifest oder Eingabedateien.
 error.bad.uflag=Kennzeichen "u" erfordert Angabe von Manifest, Kennzeichen "e" oder Eingabedateien.
 error.bad.eflag=Kennzeichen "e" und Manifest mit dem Attribut "Main-Class" k\u00F6nnen nicht zusammen angegeben\nwerden.
+error.bad.pvalue=ung\u00FCltiger Wert f\u00FCr Attribut "Profil": {0}
 error.nosuch.fileordir={0}: Datei oder Verzeichnis nicht vorhanden
 error.write.file=Fehler beim Schreiben in vorhandener JAR-Datei
 error.create.dir={0}: Verzeichnis konnte nicht erstellt werden
@@ -44,4 +45,4 @@
 out.inflated=\ \\vergr\u00F6\u00DFert: {0}
 out.size=(ein = {0}) (aus = {1})
 
-usage=Verwendung: jar-Dateien {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] ...\nOptionen:\n    -c  Neues Archiv erstellen\n    -t  Inhaltsverzeichnis f\u00FCr Archiv auflisten\n    -x  Genannte (oder alle) Dateien aus Archiv extrahieren\n    -u  Vorhandenes Archiv aktualisieren\n    -v  Verbose-Ausgabe f\u00FCr Standardausgabe generieren\n    -f  Namen der Archivdatei angeben\n    -m  Manifest-Informationen von angegebener Manifest-Datei einschlie\u00DFen\n    -e  Anwendungs-Einstiegspunkt f\u00FCr die \n        in einer ausf\u00FChrbaren JAR-Datei geb\u00FCndelte Standalone-Anwendung angeben\n    -0  Nur speichern (keine ZIP-Komprimierung)\n    -M  Keine Manifest-Datei f\u00FCr die Eintr\u00E4ge erstellen\n    -i  Indexinformationen f\u00FCr angegebenen JAR-Dateien erstellen\n    -C  zum angegebenen Verzeichnis wechseln und folgende Datei einschlie\u00DFen\nFalls eine Datei ein Verzeichnis ist, wird dieses rekursiv verarbeitet.\nDer Name der Manifest-Datei, der Name der Archivdatei und der Name des Einstiegspunkts werden\nin derselben Reihenfolge wie die Kennzeichen "m", "f" und "e" angegeben.\n\nBeispiel 1: Archivieren Sie zwei Klassendateien in ein Archiv mit Namen "classes.jar": \n       jar cvf classes.jar Foo.class Bar.class \nBeispiel 2: Verwenden Sie die vorhandenen Manifest-Datei "mymanifest", und archivieren Sie\n           alle Dateien im Verzeichnis foo/ in "classes.jar": \n       jar cvfm classes.jar mymanifest -C foo/ .\n
+usage=Verwendung: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] Dateien...\nOptionen:\n    -c  Neues Archiv erstellen\n    -t  Inhaltsverzeichnis f\u00FCr Archiv auflisten\n    -x  Genannte (oder alle) Dateien aus Archiv extrahieren\n    -u  Vorhandenes Archiv aktualisieren\n    -v  Verbose-Ausgabe f\u00FCr Standardausgabe generieren\n    -f  Namen der Archivdatei angeben\n    -m  Manifestinformationen von angegebener Manifestdatei einschlie\u00DFen\n    -e  Anwendungseinstiegspunkt f\u00FCr die \n        in einer ausf\u00FChrbaren JAR-Datei geb\u00FCndelte Standalone-Anwendung angeben\n    -p  Profilnamen angeben\n    -0  Nur speichern (keine ZIP-Komprimierung)\n    -M  Keine Manifest-Datei f\u00FCr die Eintr\u00E4ge erstellen\n    -i  Indexinformationen f\u00FCr angegebene JAR-Dateien erstellen\n    -C  zum angegebenen Verzeichnis wechseln und folgende Datei einschlie\u00DFen\nFalls eine Datei ein Verzeichnis ist, wird dieses rekursiv verarbeitet.\nDer Name der Manifestdatei, der Name der Archivdatei und der Name des Einstiegspunkts werden\nin derselben Reihenfolge wie die Kennzeichen "m", "f" und "e" angegeben.\n\nBeispiel 1: Archivieren Sie zwei Klassendateien in ein Archiv mit dem Namen "classes.jar": \n       jar cvf classes.jar Foo.class Bar.class \nBeispiel 2: Verwenden Sie die vorhandenen Manifestdatei "mymanifest", und archivieren Sie\n           alle Dateien im Verzeichnis foo/ in "classes.jar": \n       jar cvfm classes.jar mymanifest -C foo/ .\n
--- a/jdk/src/share/classes/sun/tools/jar/resources/jar_es.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jar/resources/jar_es.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -29,6 +29,7 @@
 error.bad.cflag=El indicador 'c' necesita la especificaci\u00F3n de archivos de manifiesto o de entrada.
 error.bad.uflag=El indicador 'u' necesita la especificaci\u00F3n de archivos de manifiesto, de entrada o indicador 'e'.
 error.bad.eflag=El indicador 'e' y el manifiesto con el atributo 'Main-Class' no pueden especificarse \na la vez.
+error.bad.pvalue=valor err\u00F3neo para el atributo ''Profile'': {0}
 error.nosuch.fileordir={0} : no existe tal archivo o directorio
 error.write.file=Error al escribir un archivo jar existente
 error.create.dir={0} : no se ha podido crear el directorio
@@ -44,4 +45,4 @@
 out.inflated=\ \\inflado: {0}
 out.size=(entrada = {0}) (salida = {1})
 
-usage=Sintaxis: jar {ctxui}[vfm0Me] [archive-jar] [archive-manifiesto] [punto-entrada] [-C dir] archivos...\nOpciones:\n    -c  crear nuevo archivo\n    -t  crear la tabla de contenido del archivo\n    -x extraer el archive mencionado (o todos) del archivo\n    -u  actualizar archive existente\n    -v  generar salida detallada de los datos de salida est\u00E1ndar\n    -f  especificar nombre de archive de almacenamiento\n    -m  incluir informaci\u00F3n de manifiesto del archive de manifiesto especificado\n    -e  especificar punto de entrada de la aplicaci\u00F3n para la aplicaci\u00F3n aut\u00F3noma \n        que se incluye dentro de un archive jar ejecutable\n    -0  s\u00F3lo almacenar; no utilizar compresi\u00F3n ZIP\n    -M  no crear un archive de manifiesto para las entradas\n    -i  generar informaci\u00F3n de \u00EDndice para los archives jar especificados\n    -C  cambiar al directorio especificado e incluir el archivo siguiente\nSi alg\u00FAn archivo es un directorio, se procesar\u00E1 de forma recurrente.\nEl nombre del archivo de manifiesto, el nombre del archivo de almacenamiento y el nombre del punto de entrada se\nespecifican en el mismo orden que los indicadores 'm', 'f' y 'e'.\n\nEjemplo 1: para archivar archivos de dos clases en un archivo llamado classes.jar: \n       jar cvf classes.jar Foo.class Bar.class \nEjemplo 2: utilice un archivo de manifiesto existente 'mymanifest' y archive todos los\n           archivos del directorio foo/ en 'classes.jar': \n       jar cvfm classes.jar mymanifest -C foo/ .\n
+usage=Sintaxis: archivos jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] ...\nOpciones:\n    -c  crear nuevo archivo\n    -t  mostrar la tabla de contenido del archivo\n    -x  extraer los archivos mencionados (o todos) del archivo\n    -u  actualizar archivo existente\n    -v  generar salida detallada de los datos de salida est\u00E1ndar\n    -f  especificar nombre de archivo de almacenamiento\n    -m  incluir informaci\u00F3n de manifiesto del archivo de manifiesto especificado\n    -e  especificar punto de entrada de la aplicaci\u00F3n para la aplicaci\u00F3n aut\u00F3noma \n        que se incluye dentro de un archivo jar ejecutable\n    -p  especificar nombre de perfil\n    -0  solo almacenar; no utilizar compresi\u00F3n ZIP\n    -M  no crear un archivo de manifiesto para las entradas\n    -i  generar informaci\u00F3n de \u00EDndice para los archivos jar especificados\n    -C  cambiar al directorio especificado e incluir el archivo siguiente\nSi alg\u00FAn archivo es un directorio, se procesar\u00E1 de forma recurrente.\nEl nombre del archivo de manifiesto, el nombre del archivo de almacenamiento y el nombre del punto de entrada se\nespecifican en el mismo orden que los indicadores 'm', 'f' y 'e'.\n\nEjemplo 1: para archivar archivos de dos clases en un archivo llamado classes.jar: \n       jar cvf classes.jar Foo.class Bar.class \nEjemplo 2: utilice un archivo de manifiesto existente 'mymanifest' y archive todos los\narchivos del directorio foo/ en'classes.jar': \n       jar cvfm classes.jar mymanifest -C foo/ .\n
--- a/jdk/src/share/classes/sun/tools/jar/resources/jar_fr.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jar/resources/jar_fr.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -29,6 +29,7 @@
 error.bad.cflag=L'indicateur c requiert la sp\u00E9cification d'un fichier manifeste ou d'un fichier d'entr\u00E9e.
 error.bad.uflag=L'indicateur u requiert la sp\u00E9cification d'un fichier manifeste, d'un fichier d'entr\u00E9e ou d'un indicateur e.
 error.bad.eflag=L'indicateur e et le fichier manifeste portant l'attribut Main-Class ne peuvent pas \u00EAtre sp\u00E9cifi\u00E9s \nensemble.
+error.bad.pvalue=valeur incorrecte pour l''attribut ''Profile'' : {0}
 error.nosuch.fileordir={0} : fichier ou r\u00E9pertoire introuvable
 error.write.file=Erreur lors de l'\u00E9criture d'un fichier JAR existant
 error.create.dir={0} : impossible de cr\u00E9er le r\u00E9pertoire
@@ -44,4 +45,4 @@
 out.inflated=\ \\d\u00E9compress\u00E9 : {0}
 out.size=(entr\u00E9e = {0}) (sortie = {1})
 
-usage=Syntaxe : jar {ctxui}[vfm0Me] [fichier-jar] [fichier-manifeste] [point-entr\u00E9e] [-C r\u00E9p] fichiers...\nOptions :\n    -c  cr\u00E9e une archive\n    -t  affiche la table des mati\u00E8res de l'archive\n    -x  extrait les fichiers nomm\u00E9s (ou tous les fichiers) de l'archive\n    -u  met \u00E0 jour l'archive existante\n    -v  g\u00E9n\u00E8re une version d\u00E9taill\u00E9e d'une sortie standard\n    -f  sp\u00E9cifie le nom du fichier archive\n    -m  inclut les informations de manifeste \u00E0 partir du fichier de manifeste sp\u00E9cifi\u00E9\n    -e  sp\u00E9cifie le point d'entr\u00E9e d'une application en mode autonome \n        int\u00E9gr\u00E9e \u00E0 un fichier JAR ex\u00E9cutable\n    -0  stockage uniquement, pas de compression ZIP\n    -M  ne cr\u00E9e pas de fichier manifeste pour les entr\u00E9es\n    -i  g\u00E9n\u00E8re les informations d'index des fichiers JAR sp\u00E9cifi\u00E9s\n    -C  passe au r\u00E9pertoire sp\u00E9cifi\u00E9 et inclut le fichier suivant\nSi l'un des fichiers est un r\u00E9pertoire, celui-ci est trait\u00E9 r\u00E9cursivement.\nLes noms du fichier manifeste, du fichier archive et du point d'entr\u00E9e sont\nsp\u00E9cifi\u00E9s dans le m\u00EAme ordre que celui des indicateurs m, f et e.\n\nExemple 1 : pour archiver deux fichiers de classe dans une archive intitul\u00E9e classes.jar : \n       jar cvf classes.jar Foo.class Bar.class \nExemple 2 : pour utiliser un fichier manifeste existant 'monmanifeste', puis archiver tous les\n           fichiers du r\u00E9pertoire foo/ dans 'classes.jar' : \n       jar cvfm classes.jar monmanifeste -C foo/ .\n
+usage=Syntaxe : jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...\nOptions :\n    -c  cr\u00E9e une archive\n    -t  affiche la table des mati\u00E8res de l'archive\n    -x  extrait les fichiers nomm\u00E9s (ou tous les fichiers) de l'archive\n    -u  met \u00E0 jour l'archive existante\n    -v  g\u00E9n\u00E8re une sortie en mode verbose d'une sortie standard\n    -f  sp\u00E9cifie le nom du fichier d'archive\n    -m  inclut les informations de manifest \u00E0 partir du fichier manifest sp\u00E9cifi\u00E9\n    -e  sp\u00E9cifie le point d'entr\u00E9e d'une application en mode autonome \n        int\u00E9gr\u00E9e \u00E0 un fichier JAR ex\u00E9cutable\n    -p  indique le nom de profil\n    -0  stockage uniquement, pas de compression ZIP\n    -M  ne cr\u00E9e pas de fichier manifest pour les entr\u00E9es\n    -i  g\u00E9n\u00E8re les informations d'index des fichiers JAR sp\u00E9cifi\u00E9s\n    -C  passe au r\u00E9pertoire sp\u00E9cifi\u00E9 et inclut le fichier suivant\nSi l'un des fichiers est un r\u00E9pertoire, celui-ci est trait\u00E9 r\u00E9cursivement.\nLes noms du fichier manifest, du fichier d'archive et du point d'entr\u00E9e sont\nsp\u00E9cifi\u00E9s dans le m\u00EAme ordre que celui des indicateurs m, f et e.\n\nExemple 1 : pour archiver deux fichiers de classe dans une archive intitul\u00E9e classes.jar : \n       jar cvf classes.jar Foo.class Bar.class \nExemple 2 : pour utiliser un fichier manifest existant 'mymanifest', puis archiver tous les\n           fichiers du r\u00E9pertoire foo/ dans 'classes.jar' : \n       jar cvfm classes.jar mymanifest -C foo/ .\n
--- a/jdk/src/share/classes/sun/tools/jar/resources/jar_it.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jar/resources/jar_it.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -29,6 +29,7 @@
 error.bad.cflag=Per il flag 'c' \u00E8 necessario specificare file manifest o di input.
 error.bad.uflag=Per il flag 'u' \u00E8 necessario specificare il flag 'e' oppure file manifest o di input.
 error.bad.eflag=Il flag 'e' e il manifest con l'attributo 'Main-Class' non possono essere specificati\ninsieme.
+error.bad.pvalue=valore non valido per l''attributo ''Profile'': {0}
 error.nosuch.fileordir={0} : file o directory inesistente
 error.write.file=Errore durante la scrittura del file jar esistente
 error.create.dir={0} : impossibile creare la directory
@@ -44,4 +45,4 @@
 out.inflated=\ \\decompresso: {0}
 out.size=(in = {0}) (out = {1})
 
-usage=Uso: jar {ctxui}[vfm0Me] [file-jar] [file-manifest] [punto di ingresso] [-C dir] file ...\nOpzioni:\n    -c  crea un nuovo archivio\n    -t  visualizza l'indice dell'archivio\n    -x  estrae i file con nome (o tutti i file) dall'archivio\n    -u  aggiorna l'archivio esistente\n    -v  genera output commentato dall'output standard\n    -f  specifica il nome file dell'archivio\n    -m  include informazioni manifest dal file manifest specificato\n    -e  specifica il punto di ingresso per l'applicazione stand-alone \n        inclusa nel file jar eseguibile\n    -0  solo memorizzazione; senza compressione ZIP\n    -M  consente di non creare un file manifest per le voci\n    -i  genera informazioni sull'indice per i file jar specificati\n    -C  imposta la directory specificata e include il file seguente\nSe un file \u00E8 una directory, verr\u00E0 elaborato in modo ricorsivo.\nIl nome del file manifest, del file di archivio e del punto di ingresso devono\nessere specificati nello stesso ordine dei flag 'm', 'f' ed 'e'.\n\nEsempio 1: archiviazione di due file di classe in un archivio con il nome classes.jar: \n       jar cvf classes.jar Foo.class Bar.class \nEsempio 2: utilizzo del file manifest esistente 'mymanifest' e archiviazione di tutti i\n           file della directory foo/ in 'classes.jar': \n       jar cvfm classes.jar mymanifest -C foo/.\n
+usage=Uso: jar {ctxui}[vfm0Me] [jar-file] [file manifest] [punto di accesso] [-C dir] file ...\nOpzioni:\n    -c  crea un nuovo archivio\n    -t  visualizza il sommario dell'archivio\n    -x  estrae i file specificati (o tutti i file) dall'archivio\n    -u  aggiorna un archivio esistente\n    -v  genera un output descrittivo dall'output standard\n    -f  specifica il nome file dell'archivio\n    -m  include le informazioni manifest dal file manifest specificato\n    -e  specifica il punto di accesso per l'applicazione standalone \n        inclusa in un file JAR eseguibile\n    -p  specifica il nome del profilo\n    -0  esegue solo la memorizzazione; non utilizza la compressione ZIP\n    -M  non crea un file manifest per le voci\n    -i  genera le informazioni di indice per i file JAR specificati\n    -C  passa alla directory specificata e include il file seguente\nSe un file qualsiasi \u00E8 una directory, viene elaborato in modo ricorsivo.\nIl nome del file manifest, del file di archivio e del punto di accesso devono\nessere specificati nello stesso ordine dei flag 'm', 'f' e 'e'.\n\nEsempio 1: archiviazione di due file di classe nell'archivio denominato classes.jar: \n       jar cvf classes.jar Foo.class Bar.class \nEsempio 2: uso del file manifest esistente 'mymanifest' e archiviazione di tutti i\n           file della directory foo/ in 'classes.jar': \n       jar cvfm classes.jar mymanifest -C foo/.\n
--- a/jdk/src/share/classes/sun/tools/jar/resources/jar_ja.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jar/resources/jar_ja.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -29,6 +29,7 @@
 error.bad.cflag=\u30D5\u30E9\u30B0'c'\u3067\u306F\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u307E\u305F\u306F\u5165\u529B\u30D5\u30A1\u30A4\u30EB\u306E\u6307\u5B9A\u304C\u5FC5\u8981\u3067\u3059\u3002
 error.bad.uflag=\u30D5\u30E9\u30B0'u'\u3067\u306F\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u304B'e'\u30D5\u30E9\u30B0\u3001\u307E\u305F\u306F\u5165\u529B\u30D5\u30A1\u30A4\u30EB\u306E\u6307\u5B9A\u304C\u5FC5\u8981\u3067\u3059\u3002
 error.bad.eflag='e'\u30D5\u30E9\u30B0\u3068'Main-Class'\u5C5E\u6027\u3092\u6301\u3064\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u306F\u540C\u6642\u306B\n\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002
+error.bad.pvalue=''Profile''\u5C5E\u6027\u306E\u5024\u304C\u4E0D\u6B63\u3067\u3059: {0}
 error.nosuch.fileordir={0}\u3068\u3044\u3046\u30D5\u30A1\u30A4\u30EB\u307E\u305F\u306F\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306F\u3042\u308A\u307E\u305B\u3093
 error.write.file=\u65E2\u5B58jar\u30D5\u30A1\u30A4\u30EB\u306E\u66F8\u8FBC\u307F\u4E2D\u306B\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F
 error.create.dir=\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA{0}\u3092\u4F5C\u6210\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F
@@ -44,4 +45,4 @@
 out.inflated=\ \\{0}\u304C\u5C55\u958B\u3055\u308C\u307E\u3057\u305F
 out.size=(\u5165={0})(\u51FA={1})
 
-usage=\u4F7F\u7528\u65B9\u6CD5: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...\n\u30AA\u30D7\u30B7\u30E7\u30F3:\n   -c \u30A2\u30FC\u30AB\u30A4\u30D6\u3092\u65B0\u898F\u4F5C\u6210\u3059\u308B\n   -t \u30A2\u30FC\u30AB\u30A4\u30D6\u306E\u5185\u5BB9\u3092\u4E00\u89A7\u8868\u793A\u3059\u308B\n   -x \u6307\u5B9A\u306E(\u307E\u305F\u306F\u3059\u3079\u3066\u306E)\u30D5\u30A1\u30A4\u30EB\u3092\u30A2\u30FC\u30AB\u30A4\u30D6\u304B\u3089\u62BD\u51FA\u3059\u308B\n   -u \u65E2\u5B58\u30A2\u30FC\u30AB\u30A4\u30D6\u3092\u66F4\u65B0\u3059\u308B\n   -v \u6A19\u6E96\u51FA\u529B\u306B\u8A73\u7D30\u306A\u51FA\u529B\u3092\u751F\u6210\u3059\u308B\n   -f \u30A2\u30FC\u30AB\u30A4\u30D6\u30FB\u30D5\u30A1\u30A4\u30EB\u540D\u3092\u6307\u5B9A\u3059\u308B\n   -m \u6307\u5B9A\u306E\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u30FB\u30D5\u30A1\u30A4\u30EB\u304B\u3089\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u60C5\u5831\u3092\u53D6\u308A\u8FBC\u3080\n   -e \u5B9F\u884C\u53EF\u80FDjar\u30D5\u30A1\u30A4\u30EB\u306B\u30D0\u30F3\u30C9\u30EB\u3055\u308C\u305F\u30B9\u30BF\u30F3\u30C9\u30A2\u30ED\u30F3\u30FB\u30A2\u30D7\u30EA\u30B1\u30FC\u30B7\u30E7\u30F3\u306E\n      \u30A8\u30F3\u30C8\u30EA\u30FB\u30DD\u30A4\u30F3\u30C8\u3092\u6307\u5B9A\u3059\u308B\n   -0 \u683C\u7D0D\u306E\u307F\u3002ZIP\u5727\u7E2E\u3092\u4F7F\u7528\u3057\u306A\u3044\n   -M \u30A8\u30F3\u30C8\u30EA\u306E\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u4F5C\u6210\u3057\u306A\u3044\n   -i \u6307\u5B9A\u306Ejar\u30D5\u30A1\u30A4\u30EB\u306E\u7D22\u5F15\u60C5\u5831\u3092\u751F\u6210\u3059\u308B\n   -C \u6307\u5B9A\u306E\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306B\u5909\u66F4\u3057\u3001\u4EE5\u4E0B\u306E\u30D5\u30A1\u30A4\u30EB\u3092\u53D6\u308A\u8FBC\u3080\n\u30D5\u30A1\u30A4\u30EB\u304C\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306E\u5834\u5408\u306F\u518D\u5E30\u7684\u306B\u51E6\u7406\u3055\u308C\u307E\u3059\u3002\n\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u30FB\u30D5\u30A1\u30A4\u30EB\u540D\u3001\u30A2\u30FC\u30AB\u30A4\u30D6\u30FB\u30D5\u30A1\u30A4\u30EB\u540D\u304A\u3088\u3073\u30A8\u30F3\u30C8\u30EA\u30FB\u30DD\u30A4\u30F3\u30C8\u540D\u306F\u3001\n\u30D5\u30E9\u30B0'm'\u3001'f'\u3001'e'\u306E\u6307\u5B9A\u3068\u540C\u3058\u9806\u756A\u3067\u6307\u5B9A\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002\n\n\u4F8B1: 2\u3064\u306E\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u30A2\u30FC\u30AB\u30A4\u30D6classes.jar\u306B\u4FDD\u5B58\u3059\u308B:\n     jar cvf classes.jar Foo.class Bar.class\n\u4F8B2: \u65E2\u5B58\u306E\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u30FB\u30D5\u30A1\u30A4\u30EB'mymanifest'\u3092\u4F7F\u7528\u3057\u3001foo/\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306E\n    \u5168\u30D5\u30A1\u30A4\u30EB\u3092'classes.jar'\u306B\u30A2\u30FC\u30AB\u30A4\u30D6\u3059\u308B:\n     jar cvfm classes.jar mymanifest -C foo/ \n
+usage=\u4F7F\u7528\u65B9\u6CD5: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...\n\u30AA\u30D7\u30B7\u30E7\u30F3:\n   -c \u30A2\u30FC\u30AB\u30A4\u30D6\u3092\u65B0\u898F\u4F5C\u6210\u3059\u308B\n   -t \u30A2\u30FC\u30AB\u30A4\u30D6\u306E\u5185\u5BB9\u3092\u4E00\u89A7\u8868\u793A\u3059\u308B\n   -x \u6307\u5B9A\u306E(\u307E\u305F\u306F\u3059\u3079\u3066\u306E)\u30D5\u30A1\u30A4\u30EB\u3092\u30A2\u30FC\u30AB\u30A4\u30D6\u304B\u3089\u62BD\u51FA\u3059\u308B\n   -u \u65E2\u5B58\u30A2\u30FC\u30AB\u30A4\u30D6\u3092\u66F4\u65B0\u3059\u308B\n   -v \u6A19\u6E96\u51FA\u529B\u306B\u8A73\u7D30\u306A\u51FA\u529B\u3092\u751F\u6210\u3059\u308B\n   -f \u30A2\u30FC\u30AB\u30A4\u30D6\u30FB\u30D5\u30A1\u30A4\u30EB\u540D\u3092\u6307\u5B9A\u3059\u308B\n   -m \u6307\u5B9A\u306E\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u30FB\u30D5\u30A1\u30A4\u30EB\u304B\u3089\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u60C5\u5831\u3092\u53D6\u308A\u8FBC\u3080\n   -e \u5B9F\u884C\u53EF\u80FDjar\u30D5\u30A1\u30A4\u30EB\u306B\u30D0\u30F3\u30C9\u30EB\u3055\u308C\u305F\u30B9\u30BF\u30F3\u30C9\u30A2\u30ED\u30F3\u30FB\u30A2\u30D7\u30EA\u30B1\u30FC\u30B7\u30E7\u30F3\u306E\n      \u30A8\u30F3\u30C8\u30EA\u30FB\u30DD\u30A4\u30F3\u30C8\u3092\u6307\u5B9A\u3059\u308B\n   -p  \u30D7\u30ED\u30D5\u30A1\u30A4\u30EB\u540D\u3092\u6307\u5B9A\u3059\u308B\n   -0 \u683C\u7D0D\u306E\u307F\u3002ZIP\u5727\u7E2E\u3092\u4F7F\u7528\u3057\u306A\u3044\n   -M \u30A8\u30F3\u30C8\u30EA\u306E\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u4F5C\u6210\u3057\u306A\u3044\n   -i \u6307\u5B9A\u306Ejar\u30D5\u30A1\u30A4\u30EB\u306E\u7D22\u5F15\u60C5\u5831\u3092\u751F\u6210\u3059\u308B\n   -C \u6307\u5B9A\u306E\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306B\u5909\u66F4\u3057\u3001\u4EE5\u4E0B\u306E\u30D5\u30A1\u30A4\u30EB\u3092\u53D6\u308A\u8FBC\u3080\n\u30D5\u30A1\u30A4\u30EB\u304C\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306E\u5834\u5408\u306F\u518D\u5E30\u7684\u306B\u51E6\u7406\u3055\u308C\u307E\u3059\u3002\n\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u30FB\u30D5\u30A1\u30A4\u30EB\u540D\u3001\u30A2\u30FC\u30AB\u30A4\u30D6\u30FB\u30D5\u30A1\u30A4\u30EB\u540D\u304A\u3088\u3073\u30A8\u30F3\u30C8\u30EA\u30FB\u30DD\u30A4\u30F3\u30C8\u540D\u306F\u3001\n\u30D5\u30E9\u30B0'm'\u3001'f'\u3001'e'\u3068\u540C\u3058\u9806\u5E8F\u3067\u6307\u5B9A\u3057\u307E\u3059\u3002\n\n\u4F8B1: 2\u3064\u306E\u30AF\u30E9\u30B9\u30FB\u30D5\u30A1\u30A4\u30EB\u3092\u30A2\u30FC\u30AB\u30A4\u30D6classes.jar\u306B\u4FDD\u5B58\u3059\u308B:\n     jar cvf classes.jar Foo.class Bar.class\n\u4F8B2: \u65E2\u5B58\u306E\u30DE\u30CB\u30D5\u30A7\u30B9\u30C8\u30FB\u30D5\u30A1\u30A4\u30EB'mymanifest'\u3092\u4F7F\u7528\u3057\u3001foo/\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306E\n    \u5168\u30D5\u30A1\u30A4\u30EB\u3092'classes.jar'\u306B\u30A2\u30FC\u30AB\u30A4\u30D6\u3059\u308B:\n     jar cvfm classes.jar mymanifest -C foo/ \n
--- a/jdk/src/share/classes/sun/tools/jar/resources/jar_ko.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jar/resources/jar_ko.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -29,6 +29,7 @@
 error.bad.cflag='c' \uD50C\uB798\uADF8\uB97C \uC0AC\uC6A9\uD558\uB824\uBA74 Manifest \uB610\uB294 \uC785\uB825 \uD30C\uC77C\uC744 \uC9C0\uC815\uD574\uC57C \uD569\uB2C8\uB2E4!
 error.bad.uflag='u' \uD50C\uB798\uADF8\uB97C \uC0AC\uC6A9\uD558\uB824\uBA74 Manifest, 'e' \uD50C\uB798\uADF8 \uB610\uB294 \uC785\uB825 \uD30C\uC77C\uC744 \uC9C0\uC815\uD574\uC57C \uD569\uB2C8\uB2E4!
 error.bad.eflag='e' \uD50C\uB798\uADF8 \uBC0F Manifest\uB97C 'Main-Class' \uC18D\uC131\uACFC \uD568\uAED8 \uC9C0\uC815\uD560 \uC218\n\uC5C6\uC2B5\uB2C8\uB2E4!
+error.bad.pvalue=''Profile'' \uC18D\uC131\uC5D0 \uB300\uD574 \uC798\uBABB\uB41C \uAC12: {0}
 error.nosuch.fileordir={0}: \uD574\uB2F9 \uD30C\uC77C \uB610\uB294 \uB514\uB809\uD1A0\uB9AC\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4.
 error.write.file=\uAE30\uC874 jar \uD30C\uC77C\uC5D0 \uC4F0\uB294 \uC911 \uC624\uB958\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4.
 error.create.dir={0}: \uB514\uB809\uD1A0\uB9AC\uB97C \uC0DD\uC131\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
@@ -44,4 +45,4 @@
 out.inflated=\ \\\uC99D\uAC00\uB428: {0}
 out.size=(\uC785\uB825 = {0}) (\uCD9C\uB825 = {1})
 
-usage=\uC0AC\uC6A9\uBC95: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...\n\uC635\uC158:\n    -c  \uC0C8 \uC544\uCE74\uC774\uBE0C\uB97C \uC0DD\uC131\uD569\uB2C8\uB2E4.\n    -t  \uC544\uCE74\uC774\uBE0C\uC5D0 \uB300\uD55C \uBAA9\uCC28\uB97C \uB098\uC5F4\uD569\uB2C8\uB2E4.\n    -x  \uBA85\uBA85\uB41C(\uB610\uB294 \uBAA8\uB4E0) \uD30C\uC77C\uC744 \uC544\uCE74\uC774\uBE0C\uC5D0\uC11C \uCD94\uCD9C\uD569\uB2C8\uB2E4.\n    -u  \uAE30\uC874 \uC544\uCE74\uC774\uBE0C\uB97C \uAC31\uC2E0\uD569\uB2C8\uB2E4.\n    -v  \uD45C\uC900 \uCD9C\uB825\uC5D0 \uC0C1\uC138 \uC815\uBCF4 \uCD9C\uB825\uC744 \uC0DD\uC131\uD569\uB2C8\uB2E4.\n    -f  \uC544\uCE74\uC774\uBE0C \uD30C\uC77C \uC774\uB984\uC744 \uC9C0\uC815\uD569\uB2C8\uB2E4.\n    -m  \uC9C0\uC815\uB41C Manifest \uD30C\uC77C\uC758 Manifest \uC815\uBCF4\uB97C \uD3EC\uD568\uD569\uB2C8\uB2E4.\n    -e  jar \uC2E4\uD589 \uD30C\uC77C\uC5D0 \uBC88\uB4E4\uB85C \uC81C\uACF5\uB41C \uB3C5\uB9BD\uD615 \uC751\uC6A9 \uD504\uB85C\uADF8\uB7A8\uC758 \n        \uC751\uC6A9 \uD504\uB85C\uADF8\uB7A8 \uC2DC\uC791 \uC9C0\uC810\uC744 \uC9C0\uC815\uD569\uB2C8\uB2E4.\n    -0  \uC800\uC7A5 \uC804\uC6A9: ZIP \uC555\uCD95\uC744 \uC0AC\uC6A9\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.\n    -M  \uD56D\uBAA9\uC5D0 \uB300\uD574 Manifest \uD30C\uC77C\uC744 \uC0DD\uC131\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.\n    -i  \uC9C0\uC815\uB41C jar \uD30C\uC77C\uC5D0 \uB300\uD55C \uC778\uB371\uC2A4 \uC815\uBCF4\uB97C \uC0DD\uC131\uD569\uB2C8\uB2E4.\n    -C  \uC9C0\uC815\uB41C \uB514\uB809\uD1A0\uB9AC\uB85C \uBCC0\uACBD\uD558\uACE0 \uB2E4\uC74C \uD30C\uC77C\uC744 \uD3EC\uD568\uD569\uB2C8\uB2E4.\n\uD2B9\uC815 \uD30C\uC77C\uC774 \uB514\uB809\uD1A0\uB9AC\uC77C \uACBD\uC6B0 \uC21C\uD658\uC801\uC73C\uB85C \uCC98\uB9AC\uB429\uB2C8\uB2E4.\nManifest \uD30C\uC77C \uC774\uB984, \uC544\uCE74\uC774\uBE0C \uD30C\uC77C \uC774\uB984 \uBC0F \uC2DC\uC791 \uC9C0\uC810 \uC774\uB984\uC740\n'm', 'f' \uBC0F 'e' \uD50C\uB798\uADF8\uC640 \uB3D9\uC77C\uD55C \uC21C\uC11C\uB85C \uC9C0\uC815\uB429\uB2C8\uB2E4.\n\n\uC608 1: classes.jar\uB77C\uB294 \uC544\uCE74\uC774\uBE0C\uC5D0 \uB450 \uD074\uB798\uC2A4 \uD30C\uC77C\uC744 \uC544\uCE74\uC774\uBE0C\uD558\uB294 \uBC29\uBC95: \n       jar cvf classes.jar Foo.class Bar.class \n\uC608 2: \uAE30\uC874 Manifest \uD30C\uC77C 'mymanifest'\uB97C \uC0AC\uC6A9\uD558\uC5EC\n           foo/ \uB514\uB809\uD1A0\uB9AC\uC758 \uBAA8\uB4E0 \uD30C\uC77C\uC744 'classes.jar'\uB85C \uC544\uCE74\uC774\uBE0C\uD558\uB294 \uBC29\uBC95: \n       jar cvfm classes.jar mymanifest -C foo/ .\n
+usage=\uC0AC\uC6A9\uBC95: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...\n\uC635\uC158:\n    -c  \uC0C8 \uC544\uCE74\uC774\uBE0C\uB97C \uC0DD\uC131\uD569\uB2C8\uB2E4.\n    -t  \uC544\uCE74\uC774\uBE0C\uC5D0 \uB300\uD55C \uBAA9\uCC28\uB97C \uB098\uC5F4\uD569\uB2C8\uB2E4.\n    -x  \uBA85\uBA85\uB41C(\uB610\uB294 \uBAA8\uB4E0) \uD30C\uC77C\uC744 \uC544\uCE74\uC774\uBE0C\uC5D0\uC11C \uCD94\uCD9C\uD569\uB2C8\uB2E4.\n    -u  \uAE30\uC874 \uC544\uCE74\uC774\uBE0C\uB97C \uC5C5\uB370\uC774\uD2B8\uD569\uB2C8\uB2E4.\n    -v  \uD45C\uC900 \uCD9C\uB825\uC5D0 \uC0C1\uC138 \uC815\uBCF4 \uCD9C\uB825\uC744 \uC0DD\uC131\uD569\uB2C8\uB2E4.\n    -f  \uC544\uCE74\uC774\uBE0C \uD30C\uC77C \uC774\uB984\uC744 \uC9C0\uC815\uD569\uB2C8\uB2E4.\n    -m  \uC9C0\uC815\uB41C Manifest \uD30C\uC77C\uC758 Manifest \uC815\uBCF4\uB97C \uD3EC\uD568\uD569\uB2C8\uB2E4.\n    -e  jar \uC2E4\uD589 \uD30C\uC77C\uC5D0 \uBC88\uB4E4\uB85C \uC81C\uACF5\uB41C \uB3C5\uB9BD\uD615 \uC751\uC6A9 \uD504\uB85C\uADF8\uB7A8\uC758 \n        \uC751\uC6A9 \uD504\uB85C\uADF8\uB7A8 \uC2DC\uC791 \uC9C0\uC810\uC744 \uC9C0\uC815\uD569\uB2C8\uB2E4.\n    -p  \uD504\uB85C\uD30C\uC77C \uC774\uB984\uC744 \uC9C0\uC815\uD569\uB2C8\uB2E4.\n    -0  \uC800\uC7A5 \uC804\uC6A9: ZIP \uC555\uCD95\uC744 \uC0AC\uC6A9\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.\n    -M  \uD56D\uBAA9\uC5D0 \uB300\uD574 Manifest \uD30C\uC77C\uC744 \uC0DD\uC131\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.\n    -i  \uC9C0\uC815\uB41C jar \uD30C\uC77C\uC5D0 \uB300\uD55C \uC778\uB371\uC2A4 \uC815\uBCF4\uB97C \uC0DD\uC131\uD569\uB2C8\uB2E4.\n    -C  \uC9C0\uC815\uB41C \uB514\uB809\uD1A0\uB9AC\uB85C \uBCC0\uACBD\uD558\uACE0 \uB2E4\uC74C \uD30C\uC77C\uC744 \uD3EC\uD568\uD569\uB2C8\uB2E4.\n\uD2B9\uC815 \uD30C\uC77C\uC774 \uB514\uB809\uD1A0\uB9AC\uC77C \uACBD\uC6B0 \uC21C\uD658\uC801\uC73C\uB85C \uCC98\uB9AC\uB429\uB2C8\uB2E4.\nManifest \uD30C\uC77C \uC774\uB984, \uC544\uCE74\uC774\uBE0C \uD30C\uC77C \uC774\uB984 \uBC0F \uC2DC\uC791 \uC9C0\uC810 \uC774\uB984\uC740\n'm', 'f' \uBC0F 'e' \uD50C\uB798\uADF8\uC640 \uB3D9\uC77C\uD55C \uC21C\uC11C\uB85C \uC9C0\uC815\uB429\uB2C8\uB2E4.\n\n\uC608 1: classes.jar\uB77C\uB294 \uC544\uCE74\uC774\uBE0C\uC5D0 \uB450 \uD074\uB798\uC2A4 \uD30C\uC77C\uC744 \uC544\uCE74\uC774\uBE0C\uD558\uB294 \uBC29\uBC95: \n       jar cvf classes.jar Foo.class Bar.class \n\uC608 2: \uAE30\uC874 Manifest \uD30C\uC77C 'mymanifest'\uB97C \uC0AC\uC6A9\uD558\uC5EC\n           foo/ \uB514\uB809\uD1A0\uB9AC\uC758 \uBAA8\uB4E0 \uD30C\uC77C\uC744 'classes.jar'\uB85C \uC544\uCE74\uC774\uBE0C\uD558\uB294 \uBC29\uBC95: \n       jar cvfm classes.jar mymanifest -C foo/\n
--- a/jdk/src/share/classes/sun/tools/jar/resources/jar_pt_BR.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jar/resources/jar_pt_BR.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -29,6 +29,7 @@
 error.bad.cflag=flag 'c' requer que os arquivos de manifesto ou entrada sejam especificados!
 error.bad.uflag=o flag 'u' requer que arquivos de manifesto, o flag 'e' ou arquivos de entrada sejam especificados!
 error.bad.eflag=o flag 'e' e manifesto com o atributo 'Main-Class' n\u00E3o podem ser especificados \njuntos!
+error.bad.pvalue=valor inv\u00E1lido do atributo de ''Perfil'': {0}
 error.nosuch.fileordir={0} : n\u00E3o h\u00E1 tal arquivo ou diret\u00F3rio
 error.write.file=Erro ao gravar o arquivo jar existente
 error.create.dir={0} : n\u00E3o foi poss\u00EDvel criar o diret\u00F3rio
@@ -44,4 +45,4 @@
 out.inflated=\ \\cheio: {0}
 out.size=(dentro = {0}) (fora= {1})
 
-usage=Uso: arquivos jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] ...\nOp\u00E7\u00F5es:\n    -c  cria novo arquivo compactado\n    -t  lista o sum\u00E1rio do arquivo compactado\n    -x  extrai arquivos com o nome (ou todos) do arquivo compactado\n    -u  atualizar o arquivo compactado existente\n    -v  gera sa\u00EDda detalhada na sa\u00EDda padr\u00E3o\n    -f  especifica o nome do arquivo do arquivo compactado\n    -m  inclui as informa\u00E7\u00F5es do manifesto do arquivo de manifesto especificado\n    -e  especifica o ponto de entrada da aplica\u00E7\u00E3o para aplica\u00E7\u00E3o independente \n        empacotando em um arquivo jar execut\u00E1vel\n    -0  armazena somente; n\u00E3o usa compacta\u00E7\u00E3o ZIP\n    -M  n\u00E3o cria um arquivo de manifesto para as entradas\n    -i  gera informa\u00E7\u00F5es de \u00EDndice para os arquivos especificados\n    -C  altera para o diret\u00F3rio e inclui o arquivo seguinte\nSe nenhum arquivo for um diret\u00F3rio, ent\u00E3o ser\u00E1 processado repetidamente.\nO nome do arquivo de manifesto, o nome do arquivo compactado e o nome do ponto de entrada s\u00E3o\nespecificados na mesma ordem dos flags  'm', 'f' e 'e'.\n\nExemplo 1: para arquivar dois arquivos de classe em um arquivo compactado com o nome classes.jar: \n       jar cvf classes.jar Foo.class Bar.class \nExemplo 2: use um arquivo de manifesto existente 'mymanifest' e arquive todos os\n           arquivos no diret\u00F3rio foo/ na 'classes.jar': \n       jar cvfm classes.jar mymanifest -C foo/ .\n
+usage=Uso: arquivos jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] ...\nOp\u00E7\u00F5es:\n    -c  cria novo arquivo compactado\n    -t  lista o sum\u00E1rio do arquivo compactado\n    -x  extrai arquivos com o nome (ou todos) do arquivo compactado\n    -u  atualizar o arquivo compactado existente\n    -v  gera sa\u00EDda detalhada na sa\u00EDda padr\u00E3o\n    -f  especifica o nome do arquivo do arquivo compactado\n    -m  inclui as informa\u00E7\u00F5es do manifesto do arquivo de manifesto especificado\n    -e  especifica o ponto de entrada da aplica\u00E7\u00E3o para aplica\u00E7\u00E3o independente \n        empacotado em um arquivo jar execut\u00E1vel\n    -p  especifca o nome do perfil\n    -0  armazena somente; n\u00E3o usa compacta\u00E7\u00E3o ZIP\n    -M  n\u00E3o cria um arquivo de manifesto para as entradas\n    -i  gera informa\u00E7\u00F5es de \u00EDndice para os arquivos especificados\n    -C  altera para o diret\u00F3rio e inclui o arquivo seguinte\nSe nenhum arquivo for um diret\u00F3rio, ent\u00E3o ser\u00E1 processado repetidamente.\nO nome do arquivo de manifesto, o nome do arquivo compactado e o nome do ponto de entrada s\u00E3o\nespecificados na mesma ordem dos flags  'm', 'f' e 'e'.\n\nExemplo 1: para arquivar dois arquivos de classe em um arquivo compactado com o nome classes.jar: \n       jar cvf classes.jar Foo.class Bar.class \nExemplo 2: use um arquivo de manifesto existente 'mymanifest' e arquive todos os\n           arquivos no diret\u00F3rio foo/ na 'classes.jar': \n       jar cvfm classes.jar mymanifest -C foo/ .\n
--- a/jdk/src/share/classes/sun/tools/jar/resources/jar_sv.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jar/resources/jar_sv.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -29,6 +29,7 @@
 error.bad.cflag=f\u00F6r c-flaggan m\u00E5ste manifest- eller indatafiler anges.
 error.bad.uflag=f\u00F6r u-flaggan m\u00E5ste manifest-, e-flagg- eller indatafiler anges.
 error.bad.eflag=e-flaggan och manifest med attributet Main-Class kan inte anges \ntillsammans.
+error.bad.pvalue=felaktigt v\u00E4rde f\u00F6r ''Profile''-attribut: {0}
 error.nosuch.fileordir={0} : det finns ingen s\u00E5dan fil eller katalog
 error.write.file=Det uppstod ett fel vid skrivning till befintlig jar-fil.
 error.create.dir={0} : kunde inte skapa n\u00E5gon katalog
@@ -44,4 +45,4 @@
 out.inflated=\ uppackat: {0}
 out.size=(in = {0}) (ut = {1})
 
-usage=Syntax: jar-filer {ctxui}[vfm0Me] [jar-fil] [manifestfil] [startpunkt] [-C-katalog] ...\nAlternativ:\n    -c  skapa nytt arkiv\n    -t  lista inneh\u00E5llsf\u00F6rteckning f\u00F6r arkiv\n    -x  extrahera namngivna (eller alla) filer fr\u00E5n arkiv\n    -u  uppdatera befintligt arkiv\n    -v  generera utf\u00F6rliga utdata vid standardutmatning\n    -f  ange arkivfilens namn\n    -m  inkludera manifestinformation fr\u00E5n angivet manifest\n    -e  ange programstartpunkt f\u00F6r frist\u00E5ende applikation \n        som medf\u00F6ljer i en jar-programfil\n    -0  endast lagra  (ingen zip-komprimering)\n    -M  skapa inte n\u00E5gon manifestfil f\u00F6r posterna\n    -i  generera indexinformation f\u00F6r de angivna jar-filerna\n    -C  \u00E4ndra till den angivna katalogen och inkludera f\u00F6ljande fil\nOm en fil \u00E4r en katalog bearbetas den rekursivt.\nNamnen p\u00E5 manifestfilen, arkivfilen och startpunkten anges i samma\nordning som m-, f- och e-flaggorna.\n\nExempel 1: S\u00E5 h\u00E4r arkiverar du tv\u00E5 klassfiler i ett arkiv med namnet classes.jar: \n       jar cvf classes.jar Foo.class Bar.class \nExempel 2: Anv\u00E4nd en befintlig manifestfil (mymanifest) och arkivera alla\n           filer fr\u00E5n katalogen foo/ i classes.jar: \n       jar cvfm classes.jar mymanifest -C foo/ .\n
+usage=Syntax: jar {ctxui}[vfm0Me] [jar-fil] [manifestfil] [startpunkt] [-C katalog] filer ...\nAlternativ:\n    -c  skapa nytt arkiv\n    -t  lista inneh\u00E5llsf\u00F6rteckning f\u00F6r arkiv\n    -x  extrahera namngivna (eller alla) filer fr\u00E5n arkiv\n    -u  uppdatera befintligt arkiv\n    -v  generera utf\u00F6rliga utdata vid standardutmatning\n    -f  ange arkivfilens namn\n    -m  inkludera manifestinformation fr\u00E5n angivet manifest\n    -e  ange programstartpunkt f\u00F6r frist\u00E5ende applikation \n        som medf\u00F6ljer i en jar-programfil\n    -p  ange profilnamn\n    -0  endast lagra  (ingen zip-komprimering)\n    -M  skapa inte n\u00E5gon manifestfil f\u00F6r posterna\n    -i  generera indexinformation f\u00F6r de angivna jar-filerna\n    -C  \u00E4ndra till den angivna katalogen och inkludera f\u00F6ljande fil\nOm en fil \u00E4r en katalog bearbetas den rekursivt.\nNamnen p\u00E5 manifestfilen, arkivfilen och startpunkten anges\ni samma ordning som m-, f- och e-flaggorna.\n\nExempel 1: S\u00E5 h\u00E4r arkiverar du tv\u00E5 klassfiler i ett arkiv med namnet classes.jar: \n       jar cvf classes.jar Foo.class Bar.class \nExempel 2: Anv\u00E4nd en befintlig manifestfil (mymanifest) och arkivera alla\n           filer fr\u00E5n katalogen foo/ i classes.jar: \n       jar cvfm classes.jar mymanifest -C foo/ .\n
--- a/jdk/src/share/classes/sun/tools/jar/resources/jar_zh_CN.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jar/resources/jar_zh_CN.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -29,6 +29,7 @@
 error.bad.cflag='c' \u6807\u8BB0\u8981\u6C42\u6307\u5B9A\u6E05\u5355\u6216\u8F93\u5165\u6587\u4EF6!
 error.bad.uflag='u' \u6807\u8BB0\u8981\u6C42\u6307\u5B9A\u6E05\u5355, 'e' \u6807\u8BB0\u6216\u8F93\u5165\u6587\u4EF6!
 error.bad.eflag=\u4E0D\u80FD\u540C\u65F6\u6307\u5B9A 'e' \u6807\u8BB0\u548C\u5177\u6709 'Main-Class' \u5C5E\u6027\u7684\n\u6E05\u5355!
+error.bad.pvalue=''Profile'' \u5C5E\u6027\u7684\u503C\u9519\u8BEF: {0}
 error.nosuch.fileordir={0}: \u6CA1\u6709\u8FD9\u4E2A\u6587\u4EF6\u6216\u76EE\u5F55
 error.write.file=\u5199\u5165\u73B0\u6709\u7684 jar \u6587\u4EF6\u65F6\u51FA\u9519
 error.create.dir={0}: \u65E0\u6CD5\u521B\u5EFA\u76EE\u5F55
@@ -44,4 +45,4 @@
 out.inflated=\  \u5DF2\u89E3\u538B: {0}
 out.size=(\u8F93\u5165 = {0}) (\u8F93\u51FA = {1})
 
-usage=\u7528\u6CD5: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...\n\u9009\u9879\u5305\u62EC: \n    -c  \u521B\u5EFA\u65B0\u7684\u5F52\u6863\u6587\u4EF6\n    -t  \u5217\u51FA\u5F52\u6863\u76EE\u5F55\n    -x  \u4ECE\u6863\u6848\u4E2D\u63D0\u53D6\u6307\u5B9A\u7684 (\u6216\u6240\u6709) \u6587\u4EF6\n    -u  \u66F4\u65B0\u73B0\u6709\u7684\u5F52\u6863\u6587\u4EF6\n    -v  \u5728\u6807\u51C6\u8F93\u51FA\u4E2D\u751F\u6210\u8BE6\u7EC6\u8F93\u51FA\n    -f  \u6307\u5B9A\u5F52\u6863\u6587\u4EF6\u540D\n    -m  \u5305\u542B\u6307\u5B9A\u6E05\u5355\u6587\u4EF6\u4E2D\u7684\u6E05\u5355\u4FE1\u606F\n    -e  \u4E3A\u6346\u7ED1\u5230\u53EF\u6267\u884C jar \u6587\u4EF6\u7684\u72EC\u7ACB\u5E94\u7528\u7A0B\u5E8F\n        \u6307\u5B9A\u5E94\u7528\u7A0B\u5E8F\u5165\u53E3\u70B9\n    -0  \u4EC5\u5B58\u50A8; \u4E0D\u4F7F\u7528\u60C5\u51B5\u4EFB\u4F55 ZIP \u538B\u7F29\n    -M  \u4E0D\u521B\u5EFA\u6761\u76EE\u7684\u6E05\u5355\u6587\u4EF6\n    -i  \u4E3A\u6307\u5B9A\u7684 jar \u6587\u4EF6\u751F\u6210\u7D22\u5F15\u4FE1\u606F\n    -C  \u66F4\u6539\u4E3A\u6307\u5B9A\u7684\u76EE\u5F55\u5E76\u5305\u542B\u5176\u4E2D\u7684\u6587\u4EF6\n\u5982\u679C\u6709\u4EFB\u4F55\u76EE\u5F55\u6587\u4EF6, \u5219\u5BF9\u5176\u8FDB\u884C\u9012\u5F52\u5904\u7406\u3002\n\u6E05\u5355\u6587\u4EF6\u540D, \u5F52\u6863\u6587\u4EF6\u540D\u548C\u5165\u53E3\u70B9\u540D\u79F0\u7684\u6307\u5B9A\u987A\u5E8F\n\u4E0E 'm', 'f' \u548C 'e' \u6807\u8BB0\u7684\u6307\u5B9A\u987A\u5E8F\u76F8\u540C\u3002\n\n\u793A\u4F8B 1: \u5C06\u4E24\u4E2A\u7C7B\u6587\u4EF6\u5F52\u6863\u5230\u4E00\u4E2A\u540D\u4E3A classes.jar \u7684\u5F52\u6863\u6587\u4EF6\u4E2D: \n       jar cvf classes.jar Foo.class Bar.class \n\u793A\u4F8B 2: \u4F7F\u7528\u73B0\u6709\u7684\u6E05\u5355\u6587\u4EF6 'mymanifest' \u5E76\n           \u5C06 foo/ \u76EE\u5F55\u4E2D\u7684\u6240\u6709\u6587\u4EF6\u5F52\u6863\u5230 'classes.jar' \u4E2D: \n       jar cvfm classes.jar mymanifest -C foo/\u3002\n
+usage=\u7528\u6CD5: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...\n\u9009\u9879:\n    -c  \u521B\u5EFA\u65B0\u6863\u6848\n    -t  \u5217\u51FA\u6863\u6848\u76EE\u5F55\n    -x  \u4ECE\u6863\u6848\u4E2D\u63D0\u53D6\u6307\u5B9A\u7684 (\u6216\u6240\u6709) \u6587\u4EF6\n    -u  \u66F4\u65B0\u73B0\u6709\u6863\u6848\n    -v  \u5728\u6807\u51C6\u8F93\u51FA\u4E2D\u751F\u6210\u8BE6\u7EC6\u8F93\u51FA\n    -f  \u6307\u5B9A\u6863\u6848\u6587\u4EF6\u540D\n    -m  \u5305\u542B\u6307\u5B9A\u6E05\u5355\u6587\u4EF6\u4E2D\u7684\u6E05\u5355\u4FE1\u606F\n    -e  \u4E3A\u7ED1\u5B9A\u5230\u53EF\u6267\u884C jar \u6587\u4EF6\u7684\u72EC\u7ACB\u5E94\u7528\u7A0B\u5E8F\n        \u6307\u5B9A\u5E94\u7528\u7A0B\u5E8F\u5165\u53E3\u70B9\n    -p  \u6307\u5B9A\u914D\u7F6E\u6587\u4EF6\u540D\u79F0\n    -0  \u4EC5\u5B58\u50A8; \u4E0D\u4F7F\u7528\u4EFB\u4F55 ZIP \u538B\u7F29\n    -M  \u4E0D\u521B\u5EFA\u6761\u76EE\u7684\u6E05\u5355\u6587\u4EF6\n    -i  \u4E3A\u6307\u5B9A\u7684 jar \u6587\u4EF6\u751F\u6210\u7D22\u5F15\u4FE1\u606F\n    -C  \u66F4\u6539\u4E3A\u6307\u5B9A\u7684\u76EE\u5F55\u5E76\u5305\u542B\u4EE5\u4E0B\u6587\u4EF6\n\u5982\u679C\u6587\u4EF6\u4E3A\u76EE\u5F55, \u5219\u5BF9\u5176\u8FDB\u884C\u9012\u5F52\u5904\u7406\u3002\n\u6E05\u5355\u6587\u4EF6\u540D, \u6863\u6848\u6587\u4EF6\u540D\u548C\u5165\u53E3\u70B9\u540D\u79F0\u7684\u6307\u5B9A\u987A\u5E8F\n\u4E0E 'm', 'f' \u548C 'e' \u6807\u8BB0\u7684\u6307\u5B9A\u987A\u5E8F\u76F8\u540C\u3002\n\n\u793A\u4F8B 1: \u5C06\u4E24\u4E2A\u7C7B\u6587\u4EF6\u5F52\u6863\u5230\u4E00\u4E2A\u540D\u4E3A classes.jar \u7684\u6863\u6848\u4E2D: \n       jar cvf classes.jar Foo.class Bar.class \n\u793A\u4F8B 2: \u4F7F\u7528\u73B0\u6709\u7684\u6E05\u5355\u6587\u4EF6 'mymanifest' \u5E76\n           \u5C06 foo/ \u76EE\u5F55\u4E2D\u7684\u6240\u6709\u6587\u4EF6\u5F52\u6863\u5230 'classes.jar' \u4E2D: \n       jar cvfm classes.jar mymanifest -C foo/\u3002\n
--- a/jdk/src/share/classes/sun/tools/jar/resources/jar_zh_TW.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jar/resources/jar_zh_TW.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -29,6 +29,7 @@
 error.bad.cflag='c' \u65D7\u6A19\u8981\u6C42\u6307\u5B9A\u8CC7\u8A0A\u6E05\u55AE\u6216\u8F38\u5165\u6A94\u6848\uFF01
 error.bad.uflag='u' \u65D7\u6A19\u8981\u6C42\u6307\u5B9A\u8CC7\u8A0A\u6E05\u55AE\u3001'e' \u65D7\u6A19\u6216\u8F38\u5165\u6A94\u6848\uFF01
 error.bad.eflag=\u7121\u6CD5\u540C\u6642\u6307\u5B9A 'e' \u65D7\u6A19\u548C\u5177\u6709 'Main-Class' \u5C6C\u6027\u7684\n\u8CC7\u8A0A\u6E05\u55AE\uFF01
+error.bad.pvalue=''Profile'' \u5C6C\u6027\u503C\u7121\u6548: {0}
 error.nosuch.fileordir={0} : \u6C92\u6709\u9019\u985E\u6A94\u6848\u6216\u76EE\u9304
 error.write.file=\u5BEB\u5165\u73FE\u6709\u7684 jar \u6A94\u6848\u6642\u767C\u751F\u932F\u8AA4
 error.create.dir={0} : \u7121\u6CD5\u5EFA\u7ACB\u76EE\u9304
@@ -44,4 +45,4 @@
 out.inflated=\ \\\u64F4\u5C55: {0}
 out.size=\ (\u8B80={0})(\u5BEB={1})
 
-usage=\u7528\u6CD5: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] \u6A94\u6848 ...\n\u9078\u9805:\n    -c  \u5EFA\u7ACB\u65B0\u7684\u6B78\u6A94\n    -t  \u5217\u51FA\u6B78\u6A94\u7684\u76EE\u9304\n    -x  \u5F9E\u6B78\u6A94\u4E2D\u64F7\u53D6\u5DF2\u547D\u540D\u7684 (\u6216\u6240\u6709) \u6A94\u6848\n    -u  \u66F4\u65B0\u73FE\u6709\u6B78\u6A94\n    -v  \u5728\u6A19\u6E96\u8F38\u51FA\u4E2D\u7522\u751F\u8A73\u7D30\u8F38\u51FA\n    -f  \u6307\u5B9A\u6B78\u6A94\u6A94\u6848\u540D\u7A31\n    -m  \u5305\u542B\u6307\u5B9A\u8CC7\u8A0A\u6E05\u55AE\u4E2D\u7684\u8CC7\u8A0A\u6E05\u55AE\u8CC7\u8A0A\n    -e  \u70BA\u7368\u7ACB\u61C9\u7528\u7A0B\u5F0F\u6307\u5B9A\u61C9\u7528\u7A0B\u5F0F\u9032\u5165\u9EDE\n        \u5DF2\u96A8\u9644\u65BC\u53EF\u57F7\u884C jar \u6A94\u6848\u4E2D\n    -0  \u50C5\u5132\u5B58; \u4E0D\u4F7F\u7528 ZIP \u58D3\u7E2E\u65B9\u5F0F\n    -M  \u4E0D\u70BA\u9805\u76EE\u5EFA\u7ACB\u8CC7\u8A0A\u6E05\u55AE\u6A94\u6848\n    -i  \u70BA\u6307\u5B9A\u7684 jar \u6A94\u6848\u7522\u751F\u7D22\u5F15\u8CC7\u8A0A\n    -C  \u8B8A\u66F4\u81F3\u6307\u5B9A\u76EE\u9304\u4E26\u5305\u542B\u5F8C\u9762\u6240\u5217\u7684\u6A94\u6848\n\u5982\u679C\u6709\u4EFB\u4F55\u6A94\u6848\u662F\u76EE\u9304\uFF0C\u5247\u6703\u5C0D\u5176\u9032\u884C\u905E\u8FF4\u8655\u7406\u3002\n\u6E05\u55AE\u6A94\u6848\u540D\u7A31\u3001\u6B78\u6A94\u6A94\u6848\u540D\u7A31\u548C\u9032\u5165\u9EDE\u540D\u7A31\n\u7684\u6307\u5B9A\u9806\u5E8F\u8207\u6307\u5B9A 'm' \u65D7\u6A19\u3001'f' \u65D7\u6A19\u548C 'e' \u65D7\u6A19\u7684\u9806\u5E8F\u76F8\u540C\u3002\n\n\u7BC4\u4F8B 1: \u5C07\u5169\u500B\u985E\u5225\u6A94\u6848\u6B78\u6A94\u81F3\u540D\u70BA classes.jar \u7684\u6B78\u6A94\u4E2D: \n       jar cvf classes.jar Foo.class Bar.class\n\u7BC4\u4F8B 2: \u4F7F\u7528\u73FE\u6709\u8CC7\u8A0A\u6E05\u55AE\u6A94\u6848 'mymanifest' \u4E26\u5C07\n           foo/ \u76EE\u9304\u4E2D\u7684\u6240\u6709\u6A94\u6848\u6B78\u6A94\u81F3 'classes.jar' \u4E2D: \n       jar cvfm classes.jar mymanifest -C foo/ .\n
+usage=\u7528\u6CD5: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...\n\u9078\u9805:\n    -c  \u5EFA\u7ACB\u65B0\u7684\u5B58\u6A94\n    -t  \u5217\u51FA\u5B58\u6A94\u7684\u76EE\u9304\n    -x  \u5F9E\u5B58\u6A94\u4E2D\u64F7\u53D6\u6307\u5B9A\u7684 (\u6216\u6240\u6709) \u6A94\u6848\n    -u  \u66F4\u65B0\u73FE\u6709\u5B58\u6A94\n    -v  \u5728\u6A19\u6E96\u8F38\u51FA\u7522\u751F\u8A73\u7D30\u8F38\u51FA\n    -f  \u6307\u5B9A\u5B58\u6A94\u6A94\u6848\u540D\u7A31\n    -m  \u5305\u542B\u6307\u5B9A\u4E4B\u8CC7\u8A0A\u6E05\u55AE\u6A94\u6848\u4E2D\u7684\u8CC7\u8A0A\u6E05\u55AE\u8CC7\u8A0A\n    -e  \u6307\u5B9A\u7368\u7ACB\u61C9\u7528\u7A0B\u5F0F\u7684\u61C9\u7528\u7A0B\u5F0F\u9032\u5165\u9EDE \n        \u5DF2\u96A8\u9644\u65BC\u53EF\u57F7\u884C jar \u6A94\u6848\u4E2D\n    -p  \u6307\u5B9A\u8A2D\u5B9A\u6A94\u540D\u7A31\n    -0  \u53EA\u5132\u5B58; \u4E0D\u4F7F\u7528 ZIP \u58D3\u7E2E\u65B9\u5F0F\n    -M  \u4E0D\u66FF\u9805\u76EE\u5EFA\u7ACB\u8CC7\u8A0A\u6E05\u55AE\u6A94\u6848\n    -i  \u7522\u751F\u6307\u5B9A\u4E4B jar \u6A94\u6848\u7684\u7D22\u5F15\u8CC7\u8A0A\n    -C  \u8B8A\u66F4\u81F3\u6307\u5B9A\u7684\u76EE\u9304\u4E26\u5305\u542B\u4E0B\u5217\u6A94\u6848\n\u5982\u679C\u6709\u4EFB\u4F55\u6A94\u6848\u662F\u76EE\u9304\uFF0C\u5247\u6703\u905E\u8FF4\u5730\u8655\u7406\u6A94\u6848\u3002\n\u8CC7\u8A0A\u6E05\u55AE\u6A94\u6848\u540D\u7A31\u3001\u5B58\u6A94\u6A94\u6848\u540D\u7A31\u4EE5\u53CA\u9032\u5165\u9EDE\u540D\u7A31\u7684\n\u6307\u5B9A\u9806\u5E8F\u8207 'm' \u65D7\u6A19\u3001'f' \u65D7\u6A19\u548C 'e' \u65D7\u6A19\u7684\u9806\u5E8F\u76F8\u540C\u3002\n\n\u7BC4\u4F8B 1: \u5C07\u5169\u500B\u985E\u5225\u6A94\u6848\u5B58\u6A94\u81F3\u540D\u70BA classes.jar \u7684\u5B58\u6A94\u4E2D: \n       jar cvf classes.jar Foo.class Bar.class \n\u7BC4\u4F8B 2: \u4F7F\u7528\u73FE\u6709\u8CC7\u8A0A\u6E05\u55AE\u6A94\u6848 'mymanifest'\uFF0C\u5C07 foo/ \u76EE\u9304\n           \u4E2D\u7684\u6240\u6709\u6A94\u6848\u5B58\u6A94\u81F3 'classes.jar' \u4E2D: \n       jar cvfm classes.jar mymanifest -C foo/ \n
--- a/jdk/src/share/classes/sun/tools/java/ClassDeclaration.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/java/ClassDeclaration.java	Wed Jul 05 19:00:49 2017 +0200
@@ -230,12 +230,17 @@
      * Equality
      */
     public boolean equals(Object obj) {
-        if ((obj != null) && (obj instanceof ClassDeclaration)) {
+        if (obj instanceof ClassDeclaration) {
             return type.equals(((ClassDeclaration)obj).type);
         }
         return false;
     }
 
+    @Override
+    public int hashCode() {
+        return type.hashCode();
+    }
+
     /**
      * toString
      */
--- a/jdk/src/share/classes/sun/tools/java/MemberDefinition.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/java/MemberDefinition.java	Wed Jul 05 19:00:49 2017 +0200
@@ -256,8 +256,8 @@
         }
         String name = this.name.toString();
         return name.startsWith(prefixVal)
-            || name.toString().startsWith(prefixLoc)
-            || name.toString().startsWith(prefixThis);
+            || name.startsWith(prefixLoc)
+            || name.startsWith(prefixThis);
     }
 
     public boolean isAccessMethod() {
--- a/jdk/src/share/classes/sun/tools/jconsole/Messages.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jconsole/Messages.java	Wed Jul 05 19:00:49 2017 +0200
@@ -156,6 +156,7 @@
     public static String IMPACT;
     public static String INFO;
     public static String INFO_CAPITALIZED;
+    public static String INSECURE;
     public static String INVALID_PLUGIN_PATH;
     public static String INVALID_URL;
     public static String IS;
@@ -303,6 +304,8 @@
     public static String WRITABLE;
     public static String CONNECTION_FAILED1;
     public static String CONNECTION_FAILED2;
+    public static String CONNECTION_FAILED_SSL1;
+    public static String CONNECTION_FAILED_SSL2;
     public static String CONNECTION_LOST1;
     public static String CONNECTING_TO1;
     public static String CONNECTING_TO2;
--- a/jdk/src/share/classes/sun/tools/jconsole/ProxyClient.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jconsole/ProxyClient.java	Wed Jul 05 19:00:49 2017 +0200
@@ -307,10 +307,10 @@
         }
     }
 
-    void connect() {
+    void connect(boolean requireSSL) {
         setConnectionState(ConnectionState.CONNECTING);
         try {
-            tryConnect();
+            tryConnect(requireSSL);
             setConnectionState(ConnectionState.CONNECTED);
         } catch (Exception e) {
             if (JConsole.isDebug()) {
@@ -320,7 +320,7 @@
         }
     }
 
-    private void tryConnect() throws IOException {
+    private void tryConnect(boolean requireRemoteSSL) throws IOException {
         if (jmxUrl == null && "localhost".equals(hostName) && port == 0) {
             // Monitor self
             this.jmxc = null;
@@ -340,6 +340,10 @@
                     this.jmxUrl = new JMXServiceURL(lvm.connectorAddress());
                 }
             }
+            Map<String, Object> env = new HashMap<String, Object>();
+            if (requireRemoteSSL) {
+                env.put("jmx.remote.x.check.stub", "true");
+            }
             // Need to pass in credentials ?
             if (userName == null && password == null) {
                 if (isVmConnector()) {
@@ -348,12 +352,11 @@
                         checkSslConfig();
                     }
                     this.jmxc = new RMIConnector(stub, null);
-                    jmxc.connect();
+                    jmxc.connect(env);
                 } else {
-                    this.jmxc = JMXConnectorFactory.connect(jmxUrl);
+                    this.jmxc = JMXConnectorFactory.connect(jmxUrl, env);
                 }
             } else {
-                Map<String, String[]> env = new HashMap<String, String[]>();
                 env.put(JMXConnector.CREDENTIALS,
                         new String[] {userName, password});
                 if (isVmConnector()) {
--- a/jdk/src/share/classes/sun/tools/jconsole/VMPanel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jconsole/VMPanel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -56,6 +56,7 @@
     private static ArrayList<TabInfo> tabInfos = new ArrayList<TabInfo>();
     private boolean wasConnected = false;
     private boolean userDisconnected = false;
+    private boolean shouldUseSSL = true;
 
     // The everConnected flag keeps track of whether the window can be
     // closed if the user clicks Cancel after a failed connection attempt.
@@ -288,7 +289,7 @@
             new Thread("VMPanel.connect") {
 
                 public void run() {
-                    proxyClient.connect();
+                    proxyClient.connect(shouldUseSSL);
                 }
             }.start();
         }
@@ -467,8 +468,12 @@
             msgTitle = Messages.CONNECTION_LOST1;
             msgExplanation = Resources.format(Messages.CONNECTING_TO2, getConnectionName());
             buttonStr = Messages.RECONNECT;
+        } else if (shouldUseSSL) {
+            msgTitle = Messages.CONNECTION_FAILED_SSL1;
+            msgExplanation = Resources.format(Messages.CONNECTION_FAILED_SSL2, getConnectionName());
+            buttonStr = Messages.INSECURE;
         } else {
-            msgTitle =Messages.CONNECTION_FAILED1;
+            msgTitle = Messages.CONNECTION_FAILED1;
             msgExplanation = Resources.format(Messages.CONNECTION_FAILED2, getConnectionName());
             buttonStr = Messages.CONNECT;
         }
@@ -490,6 +495,9 @@
 
                     if (value == Messages.RECONNECT || value == Messages.CONNECT) {
                         connect();
+                    } else if (value == Messages.INSECURE) {
+                        shouldUseSSL = false;
+                        connect();
                     } else if (!everConnected) {
                         try {
                             getFrame().setClosed(true);
--- a/jdk/src/share/classes/sun/tools/jconsole/inspector/Utils.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jconsole/inspector/Utils.java	Wed Jul 05 19:00:49 2017 +0200
@@ -352,7 +352,7 @@
             result = new Character(value.charAt(0));
         } else if (Number.class.isAssignableFrom(Utils.getClass(type))) {
             result = createNumberFromStringValue(value);
-        } else if (value == null || value.toString().equals("null")) {
+        } else if (value == null || value.equals("null")) {
             // hack for null value
             result = null;
         } else {
--- a/jdk/src/share/classes/sun/tools/jconsole/inspector/XObject.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jconsole/inspector/XObject.java	Wed Jul 05 19:00:49 2017 +0200
@@ -27,6 +27,7 @@
 
 // java import
 import javax.swing.*;
+import java.util.Objects;
 
 /**
  * This provides a wrapper to the Object class to allow it to be
@@ -48,18 +49,17 @@
     }
 
     public boolean equals(Object o) {
-        try {
-            if (o instanceof XObject) {
-                return object.equals(((XObject)o).getObject());
-            }
-        }
-        catch (Throwable t) {
-            System.out.println("Error comparing XObjects"+
-                               t.getMessage());
+        if (o instanceof XObject) {
+            return Objects.equals(object, ((XObject)o).getObject());
         }
         return false;
     }
 
+    @Override
+    public int hashCode() {
+        return object.hashCode();
+    }
+
 
     public Object getObject() {
         return object;
--- a/jdk/src/share/classes/sun/tools/jconsole/resources/messages.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/jconsole/resources/messages.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -114,6 +114,7 @@
 IMPACT=Impact
 INFO=Info
 INFO_CAPITALIZED=INFO
+INSECURE=Insecure connection
 INVALID_PLUGIN_PATH=Warning: Invalid plugin path: {0}
 INVALID_URL=Invalid URL: {0}
 IS=Is
@@ -261,6 +262,8 @@
 WRITABLE=Writable
 CONNECTION_FAILED1=Connection Failed: Retry?
 CONNECTION_FAILED2=The connection to {0} did not succeed.<br>Would you like to try again?
+CONNECTION_FAILED_SSL1=Secure connection failed. Retry insecurely?
+CONNECTION_FAILED_SSL2=The connection to {0} could not be made using SSL.<br>Would you like to try without SSL?<br>(Username and password will be sent in plain text.)
 CONNECTION_LOST1=Connection Lost: Reconnect?
 CONNECTING_TO1=Connecting to {0}
 CONNECTING_TO2=You are currently being connected to {0}.<br>This will take a few moments.
--- a/jdk/src/share/classes/sun/tools/serialver/serialver_zh_CN.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tools/serialver/serialver_zh_CN.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -6,7 +6,7 @@
 SerialVersion=\u5E8F\u5217\u7248\u672C:
 NotSerializable=\u7C7B{0}\u65E0\u6CD5\u5E8F\u5217\u5316\u3002
 ClassNotFound=\u627E\u4E0D\u5230\u7C7B{0}\u3002
-error.parsing.classpath=\u5BF9\u7C7B\u8DEF\u5F84 {0} \u8FDB\u884C\u8BED\u6CD5\u5206\u6790\u65F6\u51FA\u9519\u3002
+error.parsing.classpath=\u89E3\u6790\u7C7B\u8DEF\u5F84 {0} \u65F6\u51FA\u9519\u3002
 error.missing.classpath=\u7F3A\u5C11 -classpath \u9009\u9879\u7684\u53C2\u6570
 invalid.flag=\u65E0\u6548\u6807\u8BB0{0}\u3002
 ignoring.classes=\u65E0\u6CD5\u4F7F\u7528 -show \u9009\u9879\u6307\u5B9A\u7C7B\u53C2\u6570
--- a/jdk/src/share/classes/sun/tracing/ProviderSkeleton.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tracing/ProviderSkeleton.java	Wed Jul 05 19:00:49 2017 +0200
@@ -154,20 +154,25 @@
      * @return always null, if the method is a user-defined probe
      */
     public Object invoke(Object proxy, Method method, Object[] args) {
-        if (method.getDeclaringClass() != providerType) {
+        Class declaringClass = method.getDeclaringClass();
+        // not a provider subtype's own method
+        if (declaringClass != providerType) {
             try {
-                return method.invoke(this, args);
+                // delegate only to methods declared by
+                // com.sun.tracing.Provider or java.lang.Object
+                if (declaringClass == Provider.class ||
+                    declaringClass == Object.class) {
+                    return method.invoke(this, args);
+                } else {
+                    assert false;
+                }
             } catch (IllegalAccessException e) {
                 assert false;
             } catch (InvocationTargetException e) {
                 assert false;
             }
-        } else if (active) {
-            ProbeSkeleton p = probes.get(method);
-            if (p != null) {
-                // Skips argument check -- already done by javac
-                p.uncheckedTrigger(args);
-            }
+        } else {
+            triggerProbe(method, args);
         }
         return null;
     }
@@ -252,4 +257,14 @@
         }
         return ret;
     }
+
+    protected void triggerProbe(Method method, Object[] args) {
+        if (active) {
+            ProbeSkeleton p = probes.get(method);
+            if (p != null) {
+                // Skips argument check -- already done by javac
+                p.uncheckedTrigger(args);
+            }
+        }
+    }
 }
--- a/jdk/src/share/classes/sun/tracing/dtrace/DTraceProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/tracing/dtrace/DTraceProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -151,19 +151,8 @@
     // directly.  So this method should never get invoked.  We also wire up the
     // DTraceProbe.uncheckedTrigger() method to call the proxy method instead
     // of doing the work itself.
-    public Object invoke(Object proxy, Method method, Object[] args) {
-        if (method.getDeclaringClass() != providerType) {
-            try {
-                return method.invoke(this, args);
-            } catch (IllegalAccessException e) {
-                assert false;
-            } catch (InvocationTargetException e) {
-                assert false;
-            }
-        } else if (active) {
-            assert false : "This method should have been overridden by the JVM";
-        }
-        return null;
+    protected void triggerProbe(Method method, Object[] args) {
+        assert false : "This method should have been overridden by the JVM";
     }
 
     public String getProviderName() {
--- a/jdk/src/share/classes/sun/util/logging/resources/logging_de.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/util/logging/resources/logging_de.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -27,20 +27,20 @@
 # these are the same as the non-localized level name.
 
 # The following ALL CAPS words should be translated.
-ALL=Alle
+ALL=ALL
 # The following ALL CAPS words should be translated.
-SEVERE=Schwerwiegend
+SEVERE=SEVERE
 # The following ALL CAPS words should be translated.
-WARNING=Warnung
+WARNING=WARNING
 # The following ALL CAPS words should be translated.
-INFO=Information
+INFO=INFO
 # The following ALL CAPS words should be translated.
-CONFIG= Konfiguration
+CONFIG= CONFIG
 # The following ALL CAPS words should be translated.
-FINE=Fein
+FINE=FINE
 # The following ALL CAPS words should be translated.
-FINER=Feiner
+FINER=FINER
 # The following ALL CAPS words should be translated.
-FINEST=Am feinsten
+FINEST=FINEST
 # The following ALL CAPS words should be translated.
-OFF=Deaktiviert
+OFF=OFF
--- a/jdk/src/share/classes/sun/util/logging/resources/logging_es.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/util/logging/resources/logging_es.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -27,20 +27,20 @@
 # these are the same as the non-localized level name.
 
 # The following ALL CAPS words should be translated.
-ALL=Todo
+ALL=ALL
 # The following ALL CAPS words should be translated.
-SEVERE=Grave
+SEVERE=SEVERE
 # The following ALL CAPS words should be translated.
-WARNING=Advertencia
+WARNING=WARNING
 # The following ALL CAPS words should be translated.
-INFO=Informaci\u00F3n
+INFO=INFO
 # The following ALL CAPS words should be translated.
-CONFIG= Configurar
+CONFIG= CONFIG
 # The following ALL CAPS words should be translated.
-FINE=Detallado
+FINE=FINE
 # The following ALL CAPS words should be translated.
-FINER=Muy Detallado
+FINER=FINER
 # The following ALL CAPS words should be translated.
-FINEST=M\u00E1s Detallado
+FINEST=FINEST
 # The following ALL CAPS words should be translated.
-OFF=Desactivado
+OFF=OFF
--- a/jdk/src/share/classes/sun/util/logging/resources/logging_fr.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/util/logging/resources/logging_fr.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -27,20 +27,20 @@
 # these are the same as the non-localized level name.
 
 # The following ALL CAPS words should be translated.
-ALL=Tout
+ALL=ALL
 # The following ALL CAPS words should be translated.
-SEVERE=Grave
+SEVERE=SEVERE
 # The following ALL CAPS words should be translated.
-WARNING=Avertissement
+WARNING=WARNING
 # The following ALL CAPS words should be translated.
-INFO=Infos
+INFO=INFO
 # The following ALL CAPS words should be translated.
-CONFIG= Config
+CONFIG= CONFIG
 # The following ALL CAPS words should be translated.
-FINE=Pr\u00E9cis
+FINE=FINE
 # The following ALL CAPS words should be translated.
-FINER=Plus pr\u00E9cis
+FINER=FINER
 # The following ALL CAPS words should be translated.
-FINEST=Le plus pr\u00E9cis
+FINEST=FINEST
 # The following ALL CAPS words should be translated.
-OFF=D\u00E9sactiv\u00E9
+OFF=OFF
--- a/jdk/src/share/classes/sun/util/logging/resources/logging_it.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/util/logging/resources/logging_it.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -27,20 +27,20 @@
 # these are the same as the non-localized level name.
 
 # The following ALL CAPS words should be translated.
-ALL=Tutto
+ALL=ALL
 # The following ALL CAPS words should be translated.
-SEVERE=Grave
+SEVERE=SEVERE
 # The following ALL CAPS words should be translated.
-WARNING=Avvertenza
+WARNING=WARNING
 # The following ALL CAPS words should be translated.
-INFO=Informazioni
+INFO=INFO
 # The following ALL CAPS words should be translated.
-CONFIG= Configurazione
+CONFIG= CONFIG
 # The following ALL CAPS words should be translated.
-FINE=Buono
+FINE=FINE
 # The following ALL CAPS words should be translated.
-FINER=Migliore
+FINER=FINER
 # The following ALL CAPS words should be translated.
-FINEST=Ottimale
+FINEST=FINEST
 # The following ALL CAPS words should be translated.
-OFF=Non attivo
+OFF=OFF
--- a/jdk/src/share/classes/sun/util/logging/resources/logging_ja.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/util/logging/resources/logging_ja.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -29,18 +29,18 @@
 # The following ALL CAPS words should be translated.
 ALL=\u3059\u3079\u3066
 # The following ALL CAPS words should be translated.
-SEVERE=\u91CD\u5927
+SEVERE=SEVERE
 # The following ALL CAPS words should be translated.
-WARNING=\u8B66\u544A
+WARNING=WARNING
 # The following ALL CAPS words should be translated.
 INFO=\u60C5\u5831
 # The following ALL CAPS words should be translated.
-CONFIG= \u69CB\u6210
+CONFIG= CONFIG
 # The following ALL CAPS words should be translated.
-FINE=\u666E\u901A
+FINE=\u8A73\u7D30\u30EC\u30D9\u30EB(\u4F4E)
 # The following ALL CAPS words should be translated.
-FINER=\u8A73\u7D30
+FINER=FINER
 # The following ALL CAPS words should be translated.
-FINEST=\u6700\u3082\u8A73\u7D30
+FINEST=FINEST
 # The following ALL CAPS words should be translated.
 OFF=\u30AA\u30D5
--- a/jdk/src/share/classes/sun/util/logging/resources/logging_ko.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/util/logging/resources/logging_ko.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -27,20 +27,20 @@
 # these are the same as the non-localized level name.
 
 # The following ALL CAPS words should be translated.
-ALL=\uBAA8\uB450
+ALL=ALL
 # The following ALL CAPS words should be translated.
-SEVERE=\uC2EC\uAC01
+SEVERE=SEVERE
 # The following ALL CAPS words should be translated.
-WARNING=\uACBD\uACE0
+WARNING=WARNING
 # The following ALL CAPS words should be translated.
-INFO=\uC815\uBCF4
+INFO=INFO
 # The following ALL CAPS words should be translated.
-CONFIG= \uAD6C\uC131
+CONFIG= CONFIG
 # The following ALL CAPS words should be translated.
-FINE=\uBBF8\uC138
+FINE=FINE
 # The following ALL CAPS words should be translated.
-FINER=\uBCF4\uB2E4 \uBBF8\uC138
+FINER=FINER
 # The following ALL CAPS words should be translated.
-FINEST=\uAC00\uC7A5 \uBBF8\uC138
+FINEST=FINEST
 # The following ALL CAPS words should be translated.
-OFF=\uD574\uC81C
+OFF=OFF
--- a/jdk/src/share/classes/sun/util/logging/resources/logging_pt_BR.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/util/logging/resources/logging_pt_BR.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -27,20 +27,20 @@
 # these are the same as the non-localized level name.
 
 # The following ALL CAPS words should be translated.
-ALL=Tudo
+ALL=ALL
 # The following ALL CAPS words should be translated.
-SEVERE=Grave
+SEVERE=SEVERE
 # The following ALL CAPS words should be translated.
-WARNING=Advert\u00EAncia
+WARNING=WARNING
 # The following ALL CAPS words should be translated.
-INFO=Informa\u00E7\u00F5es
+INFO=INFO
 # The following ALL CAPS words should be translated.
-CONFIG= Configura\u00E7\u00E3o
+CONFIG= CONFIG
 # The following ALL CAPS words should be translated.
-FINE=Detalhado
+FINE=FINE
 # The following ALL CAPS words should be translated.
-FINER=Mais Detalhado
+FINER=FINER
 # The following ALL CAPS words should be translated.
-FINEST=O Mais Detalhado
+FINEST=FINEST
 # The following ALL CAPS words should be translated.
-OFF=Desativado
+OFF=OFF
--- a/jdk/src/share/classes/sun/util/logging/resources/logging_sv.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/util/logging/resources/logging_sv.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -27,20 +27,20 @@
 # these are the same as the non-localized level name.
 
 # The following ALL CAPS words should be translated.
-ALL=Alla
+ALL=ALLA
 # The following ALL CAPS words should be translated.
-SEVERE=Allvarlig
+SEVERE=SEVERE
 # The following ALL CAPS words should be translated.
-WARNING=Varning
+WARNING=WARNING
 # The following ALL CAPS words should be translated.
-INFO=Info
+INFO=INFO
 # The following ALL CAPS words should be translated.
-CONFIG= Konfig
+CONFIG= CONFIG
 # The following ALL CAPS words should be translated.
-FINE=Fin
+FINE=FINE
 # The following ALL CAPS words should be translated.
-FINER=Finare
+FINER=FINER
 # The following ALL CAPS words should be translated.
-FINEST=Finaste
+FINEST=FINEST
 # The following ALL CAPS words should be translated.
-OFF=Av
+OFF=OFF
--- a/jdk/src/share/classes/sun/util/logging/resources/logging_zh_CN.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/util/logging/resources/logging_zh_CN.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -27,20 +27,20 @@
 # these are the same as the non-localized level name.
 
 # The following ALL CAPS words should be translated.
-ALL=\u5168\u90E8
+ALL=ALL
 # The following ALL CAPS words should be translated.
-SEVERE=\u4E25\u91CD
+SEVERE=SEVERE
 # The following ALL CAPS words should be translated.
-WARNING=\u8B66\u544A
+WARNING=WARNING
 # The following ALL CAPS words should be translated.
-INFO=\u4FE1\u606F
+INFO=INFO
 # The following ALL CAPS words should be translated.
-CONFIG= \u914D\u7F6E
+CONFIG= CONFIG
 # The following ALL CAPS words should be translated.
-FINE=\u8BE6\u7EC6
+FINE=FINE
 # The following ALL CAPS words should be translated.
-FINER=\u8F83\u8BE6\u7EC6
+FINER=FINER
 # The following ALL CAPS words should be translated.
-FINEST=\u975E\u5E38\u8BE6\u7EC6
+FINEST=FINEST
 # The following ALL CAPS words should be translated.
-OFF=\u7981\u7528
+OFF=OFF
--- a/jdk/src/share/classes/sun/util/logging/resources/logging_zh_TW.properties	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/classes/sun/util/logging/resources/logging_zh_TW.properties	Wed Jul 05 19:00:49 2017 +0200
@@ -27,20 +27,20 @@
 # these are the same as the non-localized level name.
 
 # The following ALL CAPS words should be translated.
-ALL=\u5168\u90E8
+ALL=\u6240\u6709
 # The following ALL CAPS words should be translated.
-SEVERE=\u56B4\u91CD
+SEVERE=SEVERE
 # The following ALL CAPS words should be translated.
-WARNING=\u8B66\u544A
+WARNING=WARNING
 # The following ALL CAPS words should be translated.
 INFO=\u8CC7\u8A0A
 # The following ALL CAPS words should be translated.
-CONFIG= \u7D44\u614B
+CONFIG= CONFIG
 # The following ALL CAPS words should be translated.
 FINE=\u8A73\u7D30
 # The following ALL CAPS words should be translated.
-FINER=\u8F03\u8A73\u7D30
+FINER=FINER
 # The following ALL CAPS words should be translated.
-FINEST=\u6700\u8A73\u7D30
+FINEST=FINEST
 # The following ALL CAPS words should be translated.
 OFF=\u95DC\u9589
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1940,7 +1940,6 @@
             if (elen64 != 0) {
                 elen64 += 4;                 // header and data sz 4 bytes
             }
-
             while (eoff + 4 < elen) {
                 int tag = SH(extra, eoff);
                 int sz = SH(extra, eoff + 2);
@@ -1995,7 +1994,6 @@
                     writeLong(os, locoff);
             }
             if (elenNTFS != 0) {
-                // System.out.println("writing NTFS:" + elenNTFS);
                 writeShort(os, EXTID_NTFS);
                 writeShort(os, elenNTFS - 4);
                 writeInt(os, 0);            // reserved
@@ -2197,7 +2195,7 @@
             if (extra != null) {
                 writeBytes(os, extra);
             }
-            return LOCHDR + name.length + elen + elen64 + elenEXTT;
+            return LOCHDR + name.length + elen + elen64 + elenNTFS + elenEXTT;
         }
 
         // Data Descriptior
--- a/jdk/src/share/javavm/export/jvm.h	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/javavm/export/jvm.h	Wed Jul 05 19:00:49 2017 +0200
@@ -441,9 +441,6 @@
 JNIEXPORT jobject JNICALL
 JVM_GetProtectionDomain(JNIEnv *env, jclass cls);
 
-JNIEXPORT void JNICALL
-JVM_SetProtectionDomain(JNIEnv *env, jclass cls, jobject protection_domain);
-
 JNIEXPORT jboolean JNICALL
 JVM_IsArrayClass(JNIEnv *env, jclass cls);
 
--- a/jdk/src/share/lib/security/java.security-linux	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/lib/security/java.security-linux	Wed Jul 05 19:00:49 2017 +0200
@@ -177,6 +177,7 @@
 # corresponding RuntimePermission ("accessClassInPackage."+package) has
 # been granted.
 package.access=sun.,\
+               com.sun.corba.se.impl.,\
                com.sun.xml.internal.,\
                com.sun.imageio.,\
                com.sun.istack.internal.,\
@@ -197,12 +198,14 @@
                com.sun.org.apache.xalan.internal.xsltc.trax.,\
                com.sun.org.apache.xalan.internal.xsltc.util.,\
                com.sun.org.apache.xml.internal.res.,\
+               com.sun.org.apache.xml.internal.security.,\
                com.sun.org.apache.xml.internal.serializer.utils.,\
                com.sun.org.apache.xml.internal.utils.,\
                com.sun.org.glassfish.,\
                com.oracle.xmlns.internal.,\
                com.oracle.webservices.internal.,\
 	       oracle.jrockit.jfr.,\
+               org.jcp.xml.dsig.internal.,\
                jdk.internal.,\
                jdk.nashorn.internal.,\
                jdk.nashorn.tools.
@@ -219,6 +222,7 @@
 # checkPackageDefinition.
 #
 package.definition=sun.,\
+                   com.sun.corba.se.impl.,\
                    com.sun.xml.internal.,\
                    com.sun.imageio.,\
                    com.sun.istack.internal.,\
@@ -239,12 +243,14 @@
                    com.sun.org.apache.xalan.internal.xsltc.trax.,\
                    com.sun.org.apache.xalan.internal.xsltc.util.,\
                    com.sun.org.apache.xml.internal.res.,\
+                   com.sun.org.apache.xml.internal.security.,\
                    com.sun.org.apache.xml.internal.serializer.utils.,\
                    com.sun.org.apache.xml.internal.utils.,\
                    com.sun.org.glassfish.,\
                    com.oracle.xmlns.internal.,\
                    com.oracle.webservices.internal.,\
 		   oracle.jrockit.jfr.,\
+                   org.jcp.xml.dsig.internal.,\
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
                    jdk.nashorn.tools.
--- a/jdk/src/share/lib/security/java.security-macosx	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/lib/security/java.security-macosx	Wed Jul 05 19:00:49 2017 +0200
@@ -178,6 +178,7 @@
 # corresponding RuntimePermission ("accessClassInPackage."+package) has
 # been granted.
 package.access=sun.,\
+               com.sun.corba.se.impl.,\
                com.sun.xml.internal.,\
                com.sun.imageio.,\
                com.sun.istack.internal.,\
@@ -198,11 +199,13 @@
                com.sun.org.apache.xalan.internal.xsltc.trax.,\
                com.sun.org.apache.xalan.internal.xsltc.util.,\
                com.sun.org.apache.xml.internal.res.,\
+               com.sun.org.apache.xml.internal.security.,\
                com.sun.org.apache.xml.internal.serializer.utils.,\
                com.sun.org.apache.xml.internal.utils.,\
                com.sun.org.glassfish.,\
                com.oracle.xmlns.internal.,\
                com.oracle.webservices.internal.,\
+               org.jcp.xml.dsig.internal.,\
                jdk.internal.,\
                jdk.nashorn.internal.,\
                jdk.nashorn.tools.,\
@@ -220,6 +223,7 @@
 # checkPackageDefinition.
 #
 package.definition=sun.,\
+                   com.sun.corba.se.impl.,\
                    com.sun.xml.internal.,\
                    com.sun.imageio.,\
                    com.sun.istack.internal.,\
@@ -240,11 +244,13 @@
                    com.sun.org.apache.xalan.internal.xsltc.trax.,\
                    com.sun.org.apache.xalan.internal.xsltc.util.,\
                    com.sun.org.apache.xml.internal.res.,\
+                   com.sun.org.apache.xml.internal.security.,\
                    com.sun.org.apache.xml.internal.serializer.utils.,\
                    com.sun.org.apache.xml.internal.utils.,\
                    com.sun.org.glassfish.,\
                    com.oracle.xmlns.internal.,\
                    com.oracle.webservices.internal.,\
+                   org.jcp.xml.dsig.internal.,\
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
                    jdk.nashorn.tools.,\
--- a/jdk/src/share/lib/security/java.security-solaris	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/lib/security/java.security-solaris	Wed Jul 05 19:00:49 2017 +0200
@@ -179,6 +179,7 @@
 # corresponding RuntimePermission ("accessClassInPackage."+package) has
 # been granted.
 package.access=sun.,\
+               com.sun.corba.se.impl.,\
                com.sun.xml.internal.,\
                com.sun.imageio.,\
                com.sun.istack.internal.,\
@@ -199,12 +200,14 @@
                com.sun.org.apache.xalan.internal.xsltc.trax.,\
                com.sun.org.apache.xalan.internal.xsltc.util.,\
                com.sun.org.apache.xml.internal.res.,\
+               com.sun.org.apache.xml.internal.security.,\
                com.sun.org.apache.xml.internal.serializer.utils.,\
                com.sun.org.apache.xml.internal.utils.,\
                com.sun.org.glassfish.,\
                com.oracle.xmlns.internal.,\
                com.oracle.webservices.internal.,\
 	       oracle.jrockit.jfr.,\
+               org.jcp.xml.dsig.internal.,\
                jdk.internal.,\
                jdk.nashorn.internal.,\
                jdk.nashorn.tools.
@@ -220,6 +223,7 @@
 # checkPackageDefinition.
 #
 package.definition=sun.,\
+                   com.sun.corba.se.impl.,\
                    com.sun.xml.internal.,\
                    com.sun.imageio.,\
                    com.sun.istack.internal.,\
@@ -240,12 +244,14 @@
                    com.sun.org.apache.xalan.internal.xsltc.trax.,\
                    com.sun.org.apache.xalan.internal.xsltc.util.,\
                    com.sun.org.apache.xml.internal.res.,\
+                   com.sun.org.apache.xml.internal.security.,\
                    com.sun.org.apache.xml.internal.serializer.utils.,\
                    com.sun.org.apache.xml.internal.utils.,\
                    com.sun.org.glassfish.,\
                    com.oracle.xmlns.internal.,\
                    com.oracle.webservices.internal.,\
 		   oracle.jrockit.jfr.,\
+                   org.jcp.xml.dsig.internal.,\
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
                    jdk.nashorn.tools.
--- a/jdk/src/share/lib/security/java.security-windows	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/lib/security/java.security-windows	Wed Jul 05 19:00:49 2017 +0200
@@ -178,6 +178,7 @@
 # corresponding RuntimePermission ("accessClassInPackage."+package) has
 # been granted.
 package.access=sun.,\
+               com.sun.corba.se.impl.,\
                com.sun.xml.internal.,\
                com.sun.imageio.,\
                com.sun.istack.internal.,\
@@ -198,12 +199,14 @@
                com.sun.org.apache.xalan.internal.xsltc.trax.,\
                com.sun.org.apache.xalan.internal.xsltc.util.,\
                com.sun.org.apache.xml.internal.res.,\
+               com.sun.org.apache.xml.internal.security.,\
                com.sun.org.apache.xml.internal.serializer.utils.,\
                com.sun.org.apache.xml.internal.utils.,\
                com.sun.org.glassfish.,\
                com.oracle.xmlns.internal.,\
                com.oracle.webservices.internal.,\
 	       oracle.jrockit.jfr.,\
+               org.jcp.xml.dsig.internal.,\
                jdk.internal.,\
                jdk.nashorn.internal.,\
                jdk.nashorn.tools.,\
@@ -220,6 +223,7 @@
 # checkPackageDefinition.
 #
 package.definition=sun.,\
+                   com.sun.corba.se.impl.,\
                    com.sun.xml.internal.,\
                    com.sun.imageio.,\
                    com.sun.istack.internal.,\
@@ -240,12 +244,14 @@
                    com.sun.org.apache.xalan.internal.xsltc.trax.,\
                    com.sun.org.apache.xalan.internal.xsltc.util.,\
                    com.sun.org.apache.xml.internal.res.,\
+                   com.sun.org.apache.xml.internal.security.,\
                    com.sun.org.apache.xml.internal.serializer.utils.,\
                    com.sun.org.apache.xml.internal.utils.,\
                    com.sun.org.glassfish.,\
                    com.oracle.xmlns.internal.,\
                    com.oracle.webservices.internal.,\
 		   oracle.jrockit.jfr.,\
+                   org.jcp.xml.dsig.internal.,\
                    jdk.internal.,\
                    jdk.nashorn.internal.,\
                    jdk.nashorn.tools.,\
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/native/common/sizecalc.h	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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.
+ */
+
+#ifndef SIZECALC_H
+#define SIZECALC_H
+
+/*
+ * A machinery for safe calculation of sizes used when allocating memory.
+ *
+ * All size checks are performed against the SIZE_MAX (the maximum value for
+ * size_t). All numerical arguments as well as the result of calculation must
+ * be non-negative integers less than or equal to SIZE_MAX, otherwise the
+ * calculated size is considered unsafe.
+ *
+ * If the SIZECALC_ALLOC_THROWING_BAD_ALLOC macro is defined, then _ALLOC_
+ * helper macros throw the std::bad_alloc instead of returning NULL.
+ */
+
+#include <stdint.h> /* SIZE_MAX for C99+ */
+/* http://stackoverflow.com/questions/3472311/what-is-a-portable-method-to-find-the-maximum-value-of-size-t */
+#ifndef SIZE_MAX
+#define SIZE_MAX ((size_t)-1)
+#endif
+
+#define IS_SAFE_SIZE_T(x) ((x) >= 0 && (unsigned long long)(x) <= SIZE_MAX)
+
+#define IS_SAFE_SIZE_MUL(m, n) \
+    (IS_SAFE_SIZE_T(m) && IS_SAFE_SIZE_T(n) && ((m) == 0 || (n) == 0 || (size_t)(n) <= (SIZE_MAX / (size_t)(m))))
+
+#define IS_SAFE_SIZE_ADD(a, b) \
+    (IS_SAFE_SIZE_T(a) && IS_SAFE_SIZE_T(b) && (size_t)(b) <= (SIZE_MAX - (size_t)(a)))
+
+
+
+/* Helper macros */
+
+#ifdef SIZECALC_ALLOC_THROWING_BAD_ALLOC
+#define FAILURE_RESULT throw std::bad_alloc()
+#else
+#define FAILURE_RESULT NULL
+#endif
+
+/*
+ * A helper macro to safely allocate an array of size m*n.
+ * Example usage:
+ *    int* p = (int*)SAFE_SIZE_ARRAY_ALLOC(malloc, sizeof(int), n);
+ *    if (!p) throw OutOfMemory;
+ *    // Use the allocated array...
+ */
+#define SAFE_SIZE_ARRAY_ALLOC(func, m, n) \
+    (IS_SAFE_SIZE_MUL((m), (n)) ? ((func)((m) * (n))) : FAILURE_RESULT)
+
+#define SAFE_SIZE_ARRAY_REALLOC(func, p, m, n) \
+    (IS_SAFE_SIZE_MUL((m), (n)) ? ((func)((p), (m) * (n))) : FAILURE_RESULT)
+
+/*
+ * A helper macro to safely allocate an array of type 'type' with 'n' items
+ * using the C++ new[] operator.
+ * Example usage:
+ *    MyClass* p = SAFE_SIZE_NEW_ARRAY(MyClass, n);
+ *    // Use the pointer.
+ * This macro throws the std::bad_alloc C++ exception to indicate
+ * a failure.
+ * NOTE: if 'n' is calculated, the calling code is responsible for using the
+ * IS_SAFE_... macros to check if the calculations are safe.
+ */
+#define SAFE_SIZE_NEW_ARRAY(type, n) \
+    (IS_SAFE_SIZE_MUL(sizeof(type), (n)) ? (new type[(n)]) : throw std::bad_alloc())
+
+#define SAFE_SIZE_NEW_ARRAY2(type, n, m) \
+    (IS_SAFE_SIZE_MUL((m), (n)) && IS_SAFE_SIZE_MUL(sizeof(type), (n) * (m)) ? \
+     (new type[(n) * (m)]) : throw std::bad_alloc())
+
+/*
+ * Checks if a data structure of size (a + m*n) can be safely allocated
+ * w/o producing an integer overflow when calculating its size.
+ */
+#define IS_SAFE_STRUCT_SIZE(a, m, n) \
+    ( \
+      IS_SAFE_SIZE_MUL((m), (n)) && IS_SAFE_SIZE_ADD((m) * (n), (a)) \
+    )
+
+/*
+ * A helper macro for implementing safe memory allocation for a data structure
+ * of size (a + m * n).
+ * Example usage:
+ *    void * p = SAFE_SIZE_ALLOC(malloc, header, num, itemSize);
+ *    if (!p) throw OutOfMemory;
+ *    // Use the allocated memory...
+ */
+#define SAFE_SIZE_STRUCT_ALLOC(func, a, m, n) \
+    (IS_SAFE_STRUCT_SIZE((a), (m), (n)) ? ((func)((a) + (m) * (n))) : FAILURE_RESULT)
+
+
+#endif /* SIZECALC_H */
+
--- a/jdk/src/share/native/java/lang/Class.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/java/lang/Class.c	Wed Jul 05 19:00:49 2017 +0200
@@ -55,7 +55,7 @@
 static JNINativeMethod methods[] = {
     {"getName0",         "()" STR,          (void *)&JVM_GetClassName},
     {"getSuperclass",    "()" CLS,          NULL},
-    {"getInterfaces",    "()[" CLS,         (void *)&JVM_GetClassInterfaces},
+    {"getInterfaces0",   "()[" CLS,         (void *)&JVM_GetClassInterfaces},
     {"getClassLoader0",  "()" JCL,          (void *)&JVM_GetClassLoader},
     {"isInterface",      "()Z",             (void *)&JVM_IsInterface},
     {"getSigners",       "()[" OBJ,         (void *)&JVM_GetClassSigners},
@@ -68,10 +68,9 @@
     {"getDeclaredMethods0","(Z)[" MHD,      (void *)&JVM_GetClassDeclaredMethods},
     {"getDeclaredConstructors0","(Z)[" CTR, (void *)&JVM_GetClassDeclaredConstructors},
     {"getProtectionDomain0", "()" PD,       (void *)&JVM_GetProtectionDomain},
-    {"setProtectionDomain0", "(" PD ")V",   (void *)&JVM_SetProtectionDomain},
     {"getDeclaredClasses0",  "()[" CLS,      (void *)&JVM_GetDeclaredClasses},
     {"getDeclaringClass",   "()" CLS,      (void *)&JVM_GetDeclaringClass},
-    {"getGenericSignature", "()" STR,       (void *)&JVM_GetClassSignature},
+    {"getGenericSignature0", "()" STR,      (void *)&JVM_GetClassSignature},
     {"getRawAnnotations",      "()" BA,        (void *)&JVM_GetClassAnnotations},
     {"getConstantPool",     "()" CPL,       (void *)&JVM_GetClassConstantPool},
     {"desiredAssertionStatus0","("CLS")Z",(void *)&JVM_DesiredAssertionStatus},
--- a/jdk/src/share/native/java/util/zip/ZipFile.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/java/util/zip/ZipFile.c	Wed Jul 05 19:00:49 2017 +0200
@@ -137,6 +137,14 @@
     return zip->total;
 }
 
+JNIEXPORT jboolean JNICALL
+Java_java_util_zip_ZipFile_startsWithLOC(JNIEnv *env, jclass cls, jlong zfile)
+{
+    jzfile *zip = jlong_to_ptr(zfile);
+
+    return zip->locsig;
+}
+
 JNIEXPORT void JNICALL
 Java_java_util_zip_ZipFile_close(JNIEnv *env, jclass cls, jlong zfile)
 {
--- a/jdk/src/share/native/java/util/zip/zip_util.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/java/util/zip/zip_util.c	Wed Jul 05 19:00:49 2017 +0200
@@ -831,6 +831,14 @@
         return NULL;
     }
 
+    // Assumption, zfd refers to start of file. Trivially, reuse errbuf.
+    if (readFully(zfd, errbuf, 4) != -1) {  // errors will be handled later
+        if (GETSIG(errbuf) == LOCSIG)
+            zip->locsig = JNI_TRUE;
+        else
+            zip->locsig = JNI_FALSE;
+    }
+
     len = zip->len = IO_Lseek(zfd, 0, SEEK_END);
     if (len <= 0) {
         if (len == 0) { /* zip file is empty */
--- a/jdk/src/share/native/java/util/zip/zip_util.h	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/java/util/zip/zip_util.h	Wed Jul 05 19:00:49 2017 +0200
@@ -210,6 +210,7 @@
                              start of the file. */
     jboolean usemmap;     /* if mmap is used. */
 #endif
+    jboolean locsig;      /* if zip file starts with LOCSIG */
     cencache cencache;    /* CEN header cache */
     ZFILE zfd;            /* open file descriptor */
     void *lock;           /* read lock */
--- a/jdk/src/share/native/sun/awt/image/awt_parseImage.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/awt/image/awt_parseImage.c	Wed Jul 05 19:00:49 2017 +0200
@@ -396,10 +396,39 @@
     return 1;
 }
 
+static int getColorModelType(JNIEnv *env, jobject jcmodel) {
+    int type = UNKNOWN_CM_TYPE;
+
+    if ((*env)->IsInstanceOf(env, jcmodel,
+                 (*env)->FindClass(env, "java/awt/image/IndexColorModel")))
+    {
+        type = INDEX_CM_TYPE;
+    } else if ((*env)->IsInstanceOf(env, jcmodel,
+                 (*env)->FindClass(env, "java/awt/image/PackedColorModel")))
+    {
+        if  ((*env)->IsInstanceOf(env, jcmodel,
+                (*env)->FindClass(env, "java/awt/image/DirectColorModel"))) {
+            type = DIRECT_CM_TYPE;
+        }
+        else {
+            type = PACKED_CM_TYPE;
+        }
+    }
+    else if ((*env)->IsInstanceOf(env, jcmodel,
+                 (*env)->FindClass(env, "java/awt/image/ComponentColorModel")))
+    {
+        type = COMPONENT_CM_TYPE;
+    }
+
+    return type;
+}
+
 int awt_parseColorModel (JNIEnv *env, jobject jcmodel, int imageType,
                          ColorModelS_t *cmP) {
     /*jmethodID jID;   */
     jobject jnBits;
+    jsize   nBitsLength;
+
     int i;
     static jobject s_jdefCM = NULL;
 
@@ -421,15 +450,55 @@
     cmP->transparency = (*env)->GetIntField(env, jcmodel,
                                             g_CMtransparencyID);
 
+    jnBits = (*env)->GetObjectField(env, jcmodel, g_CMnBitsID);
+    if (jnBits == NULL) {
+        JNU_ThrowNullPointerException(env, "null nBits structure in CModel");
+        return -1;
+    }
+
+    nBitsLength = (*env)->GetArrayLength(env, jnBits);
+    if (nBitsLength != cmP->numComponents) {
+        // invalid number of components?
+        return -1;
+    }
+
+    cmP->nBits = NULL;
+    if (SAFE_TO_ALLOC_2(cmP->numComponents, sizeof(jint))) {
+        cmP->nBits = (jint *)malloc(cmP->numComponents * sizeof(jint));
+    }
+
+    if (cmP->nBits == NULL){
+        JNU_ThrowOutOfMemoryError(env, "Out of memory");
+        return -1;
+    }
+    (*env)->GetIntArrayRegion(env, jnBits, 0, cmP->numComponents,
+                              cmP->nBits);
+    cmP->maxNbits = 0;
+    for (i=0; i < cmP->numComponents; i++) {
+        if (cmP->maxNbits < cmP->nBits[i]) {
+            cmP->maxNbits = cmP->nBits[i];
+        }
+    }
+
+    cmP->is_sRGB = (*env)->GetBooleanField(env, cmP->jcmodel, g_CMis_sRGBID);
+
+    cmP->csType = (*env)->GetIntField(env, cmP->jcmodel, g_CMcsTypeID);
+
+    cmP->cmType = getColorModelType(env, jcmodel);
+
+    cmP->isDefaultCM = FALSE;
+    cmP->isDefaultCompatCM = FALSE;
+
+    /* look for standard cases */
     if (imageType == java_awt_image_BufferedImage_TYPE_INT_ARGB) {
         cmP->isDefaultCM = TRUE;
         cmP->isDefaultCompatCM = TRUE;
     } else if (imageType == java_awt_image_BufferedImage_TYPE_INT_ARGB_PRE ||
-             imageType == java_awt_image_BufferedImage_TYPE_INT_RGB) {
-        cmP->isDefaultCompatCM = TRUE;
-    } else if (imageType == java_awt_image_BufferedImage_TYPE_INT_BGR ||
+               imageType == java_awt_image_BufferedImage_TYPE_INT_RGB ||
+               imageType == java_awt_image_BufferedImage_TYPE_INT_BGR ||
                imageType == java_awt_image_BufferedImage_TYPE_4BYTE_ABGR ||
-               imageType == java_awt_image_BufferedImage_TYPE_4BYTE_ABGR_PRE){
+               imageType == java_awt_image_BufferedImage_TYPE_4BYTE_ABGR_PRE)
+    {
         cmP->isDefaultCompatCM = TRUE;
     }
     else {
@@ -450,50 +519,25 @@
         cmP->isDefaultCompatCM = cmP->isDefaultCM;
     }
 
+    /* check whether image attributes correspond to default cm */
     if (cmP->isDefaultCompatCM) {
-        cmP->cmType = DIRECT_CM_TYPE;
-        cmP->nBits = (jint *) malloc(sizeof(jint)*4);
-        cmP->nBits[0] = cmP->nBits[1] = cmP->nBits[2] = cmP->nBits[3] = 8;
-        cmP->maxNbits = 8;
-        cmP->is_sRGB = TRUE;
-        cmP->csType  = java_awt_color_ColorSpace_TYPE_RGB;
-
-        return 1;
-    }
+        if (cmP->csType != java_awt_color_ColorSpace_TYPE_RGB ||
+            !cmP->is_sRGB)
+        {
+            return -1;
+        }
 
-    jnBits = (*env)->GetObjectField(env, jcmodel, g_CMnBitsID);
-    if (jnBits == NULL) {
-        JNU_ThrowNullPointerException(env, "null nBits structure in CModel");
-        return -1;
-    }
-
-    cmP->nBits = NULL;
-    if (SAFE_TO_ALLOC_2(cmP->numComponents, sizeof(jint))) {
-        cmP->nBits = (jint *)malloc(cmP->numComponents * sizeof(jint));
-    }
-    if (cmP->nBits == NULL){
-        JNU_ThrowOutOfMemoryError(env, "Out of memory");
-        return -1;
-    }
-    (*env)->GetIntArrayRegion(env, jnBits, 0, cmP->numComponents,
-                              cmP->nBits);
-    cmP->maxNbits = 0;
-    for (i=0; i < cmP->numComponents; i++) {
-        if (cmP->maxNbits < cmP->nBits[i]) {
-            cmP->maxNbits = cmP->nBits[i];
+        for (i = 0; i < cmP->numComponents; i++) {
+            if (cmP->nBits[i] != 8) {
+                return -1;
+            }
         }
     }
 
-    cmP->is_sRGB = (*env)->GetBooleanField(env, cmP->jcmodel, g_CMis_sRGBID);
-
-    cmP->csType = (*env)->GetIntField(env, cmP->jcmodel, g_CMcsTypeID);
-
-    /* Find out what type of colol model */
+    /* Get index color model attributes */
     if (imageType == java_awt_image_BufferedImage_TYPE_BYTE_INDEXED ||
-        (*env)->IsInstanceOf(env, jcmodel,
-                 (*env)->FindClass(env, "java/awt/image/IndexColorModel")))
+        cmP->cmType == INDEX_CM_TYPE)
     {
-        cmP->cmType = INDEX_CM_TYPE;
         cmP->transIdx = (*env)->GetIntField(env, jcmodel, g_ICMtransIdxID);
         cmP->mapSize = (*env)->GetIntField(env, jcmodel, g_ICMmapSizeID);
         cmP->jrgb    = (*env)->GetObjectField(env, jcmodel, g_ICMrgbID);
@@ -519,31 +563,6 @@
             }
         }
     }
-    else if ((*env)->IsInstanceOf(env, jcmodel,
-                 (*env)->FindClass(env, "java/awt/image/PackedColorModel")))
-    {
-        if  ((*env)->IsInstanceOf(env, jcmodel,
-                (*env)->FindClass(env, "java/awt/image/DirectColorModel"))){
-            cmP->cmType = DIRECT_CM_TYPE;
-        }
-        else {
-            cmP->cmType = PACKED_CM_TYPE;
-        }
-    }
-    else if ((*env)->IsInstanceOf(env, jcmodel,
-                 (*env)->FindClass(env, "java/awt/image/ComponentColorModel")))
-    {
-        cmP->cmType = COMPONENT_CM_TYPE;
-    }
-    else if ((*env)->IsInstanceOf(env, jcmodel,
-              (*env)->FindClass(env, "java/awt/image/PackedColorModel")))
-    {
-        cmP->cmType = PACKED_CM_TYPE;
-    }
-    else {
-        cmP->cmType = UNKNOWN_CM_TYPE;
-    }
-
 
     return 1;
 }
@@ -648,6 +667,13 @@
     ColorModelS_t *cmodelP = &imageP->cmodel;
     int imageType = imageP->imageType;
 
+    // check whether raster and color model are compatible
+    if (cmodelP->numComponents != rasterP->numBands) {
+        if (cmodelP->cmType != INDEX_CM_TYPE) {
+            return -1;
+        }
+    }
+
     hintP->numChans = imageP->cmodel.numComponents;
     hintP->colorOrder = NULL;
     if (SAFE_TO_ALLOC_2(hintP->numChans, sizeof(int))) {
@@ -1139,6 +1165,10 @@
     jsm = (*env)->GetObjectField(env, rasterP->jraster, g_RasterSampleModelID);
     jdatabuffer = (*env)->GetObjectField(env, rasterP->jraster,
                                          g_RasterDataBufferID);
+    if (band >= numBands) {
+        JNU_ThrowInternalError(env, "Band out of range.");
+        return -1;
+    }
     /* Here is the generic code */
     jdata = (*env)->NewIntArray(env, maxBytes*rasterP->numBands*maxLines);
     if (JNU_IsNull(env, jdata)) {
@@ -1147,11 +1177,6 @@
     }
     if (band >= 0) {
         int dOff;
-        if (band >= numBands) {
-            (*env)->DeleteLocalRef(env, jdata);
-            JNU_ThrowInternalError(env, "Band out of range.");
-            return -1;
-        }
         off = 0;
         for (y=0; y < h; y+=maxLines) {
             if (y+maxLines > h) {
--- a/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c	Wed Jul 05 19:00:49 2017 +0200
@@ -1152,22 +1152,131 @@
     return retStatus;
 }
 
+typedef struct {
+    jobject jArray;
+    jsize length;
+    unsigned char *table;
+} LookupArrayInfo;
+
+#define NLUT 8
+
+#ifdef _LITTLE_ENDIAN
+#define INDEXES    { 3, 2, 1, 0, 7, 6, 5, 4 }
+#else
+#define INDEXES    { 0, 1, 2, 3, 4, 5, 6, 7 }
+#endif
+
+static int lookupShortData(mlib_image* src, mlib_image* dst,
+    LookupArrayInfo* lookup)
+{
+    int x, y;
+    unsigned int mask = NLUT-1;
+
+    unsigned short* srcLine = (unsigned short*)src->data;
+    unsigned char* dstLine = (unsigned char*)dst->data;
+
+    static int indexes[NLUT] = INDEXES;
+
+    if (src->width != dst->width || src->height != dst->height) {
+        return 0;
+    }
+
+    for (y=0; y < src->height; y++) {
+        int nloop, nx;
+        int npix = src->width;
+
+        unsigned short* srcPixel = srcLine;
+        unsigned char* dstPixel = dstLine;
+
+#ifdef SIMPLE_LOOKUP_LOOP
+        for (x=0; status && x < width; x++) {
+            unsigned short s = *srcPixel++;
+            if (s >= lookup->length) {
+                /* we can not handle source image using
+                * byte lookup table. Fall back to processing
+                * images in java
+                */
+                return 0;
+            }
+            *dstPixel++ = lookup->table[s];
+        }
+#else
+        /* Get to 32 bit-aligned point */
+        while(((uintptr_t)dstPixel & 0x3) != 0 && npix>0) {
+            unsigned short s = *srcPixel++;
+            if (s >= lookup->length) {
+                return 0;
+            }
+            *dstPixel++ = lookup->table[s];
+            npix--;
+        }
+
+        /*
+         * Do NLUT pixels per loop iteration.
+         * Pack into ints and write out 2 at a time.
+         */
+        nloop = npix/NLUT;
+        nx = npix%NLUT;
+
+        for(x=nloop; x!=0; x--) {
+            int i = 0;
+            int* dstP = (int*)dstPixel;
+
+            for (i = 0; i < NLUT; i++) {
+                if (srcPixel[i] >= lookup->length) {
+                    return 0;
+                }
+            }
+
+            dstP[0] = (int)
+                ((lookup->table[srcPixel[indexes[0]]] << 24) |
+                 (lookup->table[srcPixel[indexes[1]]] << 16) |
+                 (lookup->table[srcPixel[indexes[2]]] << 8)  |
+                  lookup->table[srcPixel[indexes[3]]]);
+            dstP[1] = (int)
+                ((lookup->table[srcPixel[indexes[4]]] << 24) |
+                 (lookup->table[srcPixel[indexes[5]]] << 16) |
+                 (lookup->table[srcPixel[indexes[6]]] << 8)  |
+                  lookup->table[srcPixel[indexes[7]]]);
+
+
+            dstPixel += NLUT;
+            srcPixel += NLUT;
+        }
+
+        /*
+         * Complete any remaining pixels
+         */
+        for(x=nx; x!=0; x--) {
+            unsigned short s = *srcPixel++;
+            if (s >= lookup->length) {
+                return 0;
+            }
+            *dstPixel++ = lookup->table[s];
+        }
+#endif
+
+        dstLine += dst->stride;     // array of bytes, scan stride in bytes
+        srcLine += src->stride / 2; // array of shorts, scan stride in bytes
+    }
+    return 1;
+}
+
 JNIEXPORT jint JNICALL
-Java_sun_awt_image_ImagingLib_lookupByteBI(JNIEnv *env, jobject this,
+Java_sun_awt_image_ImagingLib_lookupByteBI(JNIEnv *env, jobject thisLib,
                                            jobject jsrc, jobject jdst,
                                            jobjectArray jtableArrays)
 {
     mlib_image *src;
     mlib_image *dst;
     void *sdata, *ddata;
-    unsigned char **table;
     unsigned char **tbl;
     unsigned char lut[256];
     int retStatus = 1;
     int i;
     mlib_status status;
-    int jlen;
-    jobject *jtable;
+    int lut_nbands;
+    LookupArrayInfo *jtable;
     BufImageS_t *srcImageP, *dstImageP;
     int nbands;
     int ncomponents;
@@ -1193,12 +1302,39 @@
         return 0;
     }
 
-    jlen = (*env)->GetArrayLength(env, jtableArrays);
+    nbands = setImageHints(env, srcImageP, dstImageP, FALSE, TRUE,
+                        FALSE, &hint);
+
+    if (nbands < 1 || nbands > srcImageP->cmodel.numComponents) {
+        /* Can't handle any custom images */
+        awt_freeParsedImage(srcImageP, TRUE);
+        awt_freeParsedImage(dstImageP, TRUE);
+        return 0;
+    }
 
     ncomponents = srcImageP->cmodel.isDefaultCompatCM
         ? 4
         : srcImageP->cmodel.numComponents;
 
+    /* Make sure that color order can be used for
+     * re-ordering of lookup arrays.
+     */
+    for (i = 0; i < nbands; i++) {
+        int idx = srcImageP->hints.colorOrder[i];
+
+        if (idx < 0 || idx >= ncomponents) {
+            awt_freeParsedImage(srcImageP, TRUE);
+            awt_freeParsedImage(dstImageP, TRUE);
+            return 0;
+        }
+    }
+
+    lut_nbands = (*env)->GetArrayLength(env, jtableArrays);
+
+    if (lut_nbands > ncomponents) {
+        lut_nbands = ncomponents;
+    }
+
     tbl = NULL;
     if (SAFE_TO_ALLOC_2(ncomponents, sizeof(unsigned char *))) {
         tbl = (unsigned char **)
@@ -1206,18 +1342,12 @@
     }
 
     jtable = NULL;
-    if (SAFE_TO_ALLOC_2(jlen, sizeof(jobject *))) {
-        jtable = (jobject *)malloc(jlen * sizeof (jobject *));
+    if (SAFE_TO_ALLOC_2(lut_nbands, sizeof(LookupArrayInfo))) {
+        jtable = (LookupArrayInfo *)malloc(lut_nbands * sizeof (LookupArrayInfo));
     }
 
-    table = NULL;
-    if (SAFE_TO_ALLOC_2(jlen, sizeof(unsigned char *))) {
-        table = (unsigned char **)malloc(jlen * sizeof(unsigned char *));
-    }
-
-    if (tbl == NULL || table == NULL || jtable == NULL) {
+    if (tbl == NULL || jtable == NULL) {
         if (tbl != NULL) free(tbl);
-        if (table != NULL) free(table);
         if (jtable != NULL) free(jtable);
         awt_freeParsedImage(srcImageP, TRUE);
         awt_freeParsedImage(dstImageP, TRUE);
@@ -1225,11 +1355,21 @@
         return 0;
     }
     /* Need to grab these pointers before we lock down arrays */
-    for (i=0; i < jlen; i++) {
-        jtable[i] = (*env)->GetObjectArrayElement(env, jtableArrays, i);
-        if (jtable[i] == NULL) {
+    for (i=0; i < lut_nbands; i++) {
+        jtable[i].jArray = (*env)->GetObjectArrayElement(env, jtableArrays, i);
+
+        if (jtable[i].jArray != NULL) {
+            jtable[i].length = (*env)->GetArrayLength(env, jtable[i].jArray);
+            jtable[i].table = NULL;
+
+            if (jtable[i].length < 256) {
+                /* we may read outside the table during lookup */
+                jtable[i].jArray = NULL;
+                jtable[i].length = 0;
+            }
+        }
+        if (jtable[i].jArray == NULL) {
             free(tbl);
-            free(table);
             free(jtable);
             awt_freeParsedImage(srcImageP, TRUE);
             awt_freeParsedImage(dstImageP, TRUE);
@@ -1237,23 +1377,10 @@
         }
     }
 
-    nbands = setImageHints(env, srcImageP, dstImageP, FALSE, TRUE,
-                        FALSE, &hint);
-    if (nbands < 1) {
-        /* Can't handle any custom images */
-        free(tbl);
-        free(table);
-        free(jtable);
-        awt_freeParsedImage(srcImageP, TRUE);
-        awt_freeParsedImage(dstImageP, TRUE);
-        return 0;
-    }
-
     /* Allocate the arrays */
     if (allocateArray(env, srcImageP, &src, &sdata, TRUE, FALSE, FALSE) < 0) {
         /* Must be some problem */
         free(tbl);
-        free(table);
         free(jtable);
         awt_freeParsedImage(srcImageP, TRUE);
         awt_freeParsedImage(dstImageP, TRUE);
@@ -1262,7 +1389,6 @@
     if (allocateArray(env, dstImageP, &dst, &ddata, FALSE, FALSE, FALSE) < 0) {
         /* Must be some problem */
         free(tbl);
-        free(table);
         free(jtable);
         freeArray(env, srcImageP, src, sdata, NULL, NULL, NULL);
         awt_freeParsedImage(srcImageP, TRUE);
@@ -1278,7 +1404,7 @@
      * sufficient number of lookup arrays we add references to identity
      * lookup array to make medialib happier.
      */
-    if (jlen < ncomponents) {
+    if (lut_nbands < ncomponents) {
         int j;
         /* REMIND: This should be the size of the input lut!! */
         for (j=0; j < 256; j++) {
@@ -1287,65 +1413,45 @@
         for (j=0; j < ncomponents; j++) {
             tbl[j] = lut;
         }
-
     }
 
-    for (i=0; i < jlen; i++) {
-        table[i] = (unsigned char *)
-            (*env)->GetPrimitiveArrayCritical(env, jtable[i], NULL);
-        if (table[i] == NULL) {
+    for (i=0; i < lut_nbands; i++) {
+        jtable[i].table = (unsigned char *)
+            (*env)->GetPrimitiveArrayCritical(env, jtable[i].jArray, NULL);
+        if (jtable[i].table == NULL) {
             /* Free what we've got so far. */
             int j;
             for (j = 0; j < i; j++) {
                 (*env)->ReleasePrimitiveArrayCritical(env,
-                                                      jtable[j],
-                                                      (jbyte *) table[j],
+                                                      jtable[j].jArray,
+                                                      (jbyte *) jtable[j].table,
                                                       JNI_ABORT);
             }
             free(tbl);
-            free(table);
             free(jtable);
             freeArray(env, srcImageP, src, sdata, NULL, NULL, NULL);
             awt_freeParsedImage(srcImageP, TRUE);
             awt_freeParsedImage(dstImageP, TRUE);
             return 0;
         }
-        tbl[srcImageP->hints.colorOrder[i]] = table[i];
+        tbl[srcImageP->hints.colorOrder[i]] = jtable[i].table;
     }
 
-    if (jlen == 1) {
+    if (lut_nbands == 1) {
         for (i=1; i < nbands -
                  srcImageP->cmodel.supportsAlpha; i++) {
-            tbl[srcImageP->hints.colorOrder[i]] = table[0];
+                     tbl[srcImageP->hints.colorOrder[i]] = jtable[0].table;
         }
     }
 
     /* Mlib needs 16bit lookuptable and must be signed! */
     if (src->type == MLIB_SHORT) {
-        unsigned short *sdataP = (unsigned short *) src->data;
-        unsigned short *sP;
         if (dst->type == MLIB_BYTE) {
-            unsigned char *cdataP  = (unsigned char *)  dst->data;
-            unsigned char *cP;
             if (nbands > 1) {
                 retStatus = 0;
             }
             else {
-                int x, y;
-                for (y=0; y < src->height; y++) {
-                    cP = cdataP;
-                    sP = sdataP;
-                    for (x=0; x < src->width; x++) {
-                        *cP++ = table[0][*sP++];
-                    }
-
-                    /*
-                     * 4554571: increment pointers using the scanline stride
-                     * in pixel units (not byte units)
-                     */
-                    cdataP += dstImageP->raster.scanlineStride;
-                    sdataP += srcImageP->raster.scanlineStride;
-                }
+                retStatus = lookupShortData(src, dst, &jtable[0]);
             }
         }
         /* How about ddata == null? */
@@ -1370,12 +1476,11 @@
     }
 
     /* Release the LUT */
-    for (i=0; i < jlen; i++) {
-        (*env)->ReleasePrimitiveArrayCritical(env, jtable[i],
-                                              (jbyte *) table[i], JNI_ABORT);
+    for (i=0; i < lut_nbands; i++) {
+        (*env)->ReleasePrimitiveArrayCritical(env, jtable[i].jArray,
+            (jbyte *) jtable[i].table, JNI_ABORT);
     }
     free ((void *) jtable);
-    free ((void *) table);
     free ((void *) tbl);
 
     /* Release the pinned memory */
@@ -1389,7 +1494,6 @@
     return retStatus;
 }
 
-
 JNIEXPORT jint JNICALL
 Java_sun_awt_image_ImagingLib_lookupByteRaster(JNIEnv *env,
                                                jobject this,
@@ -1403,8 +1507,8 @@
     mlib_image*    dst;
     void*          sdata;
     void*          ddata;
-    jobject        jtable[4];
-    unsigned char* table[4];
+    LookupArrayInfo jtable[4];
+    unsigned char* mlib_lookupTable[4];
     int            i;
     int            retStatus = 1;
     mlib_status    status;
@@ -1452,6 +1556,11 @@
     src_nbands = srcRasterP->numBands;
     dst_nbands = dstRasterP->numBands;
 
+    /* adjust number of lookup bands */
+    if (lut_nbands > src_nbands) {
+        lut_nbands = src_nbands;
+    }
+
     /* MediaLib can't do more than 4 bands */
     if (src_nbands <= 0 || src_nbands > 4 ||
         dst_nbands <= 0 || dst_nbands > 4 ||
@@ -1516,22 +1625,37 @@
     /* Get references to the lookup table arrays */
     /* Need to grab these pointers before we lock down arrays */
     for (i=0; i < lut_nbands; i++) {
-        jtable[i] = (*env)->GetObjectArrayElement(env, jtableArrays, i);
-        if (jtable[i] == NULL) {
+        jtable[i].jArray = (*env)->GetObjectArrayElement(env, jtableArrays, i);
+        jtable[i].table = NULL;
+        if (jtable[i].jArray != NULL) {
+            jtable[i].length = (*env)->GetArrayLength(env, jtable[i].jArray);
+            if (jtable[i].length < 256) {
+                 /* we may read outside the table during lookup */
+                jtable[i].jArray = NULL;
+            }
+        }
+
+        if (jtable[i].jArray == NULL)
+        {
+            freeDataArray(env, srcRasterP->jdata, src, sdata,
+                          dstRasterP->jdata, dst, ddata);
+
+            awt_freeParsedRaster(srcRasterP, TRUE);
+            awt_freeParsedRaster(dstRasterP, TRUE);
             return 0;
         }
     }
 
     for (i=0; i < lut_nbands; i++) {
-        table[i] = (unsigned char *)
-            (*env)->GetPrimitiveArrayCritical(env, jtable[i], NULL);
-        if (table[i] == NULL) {
+        jtable[i].table = (unsigned char *)
+            (*env)->GetPrimitiveArrayCritical(env, jtable[i].jArray, NULL);
+        if (jtable[i].table == NULL) {
             /* Free what we've got so far. */
             int j;
             for (j = 0; j < i; j++) {
                 (*env)->ReleasePrimitiveArrayCritical(env,
-                                                      jtable[j],
-                                                      (jbyte *) table[j],
+                                                      jtable[j].jArray,
+                                                      (jbyte *) jtable[j].table,
                                                       JNI_ABORT);
             }
             freeDataArray(env, srcRasterP->jdata, src, sdata,
@@ -1540,6 +1664,7 @@
             awt_freeParsedRaster(dstRasterP, TRUE);
             return 0;
         }
+        mlib_lookupTable[i] = jtable[i].table;
     }
 
     /*
@@ -1548,107 +1673,28 @@
      * contains single lookup array.
      */
     for (i = lut_nbands; i < src_nbands; i++) {
-        table[i] = table[0];
+        mlib_lookupTable[i] = jtable[0].table;
     }
 
     /*
      * Setup lookup array for "extra" channels
      */
     for ( ; i < src->channels; i++) {
-        table[i] = ilut;
+        mlib_lookupTable[i] = ilut;
     }
 
-#define NLUT 8
     /* Mlib needs 16bit lookuptable and must be signed! */
     if (src->type == MLIB_SHORT) {
-        unsigned short *sdataP = (unsigned short *) src->data;
-        unsigned short *sP;
         if (dst->type == MLIB_BYTE) {
-            unsigned char *cdataP  = (unsigned char *)  dst->data;
-            unsigned char *cP;
             if (lut_nbands > 1) {
                 retStatus = 0;
             } else {
-                int x, y;
-                unsigned int mask = NLUT-1;
-                unsigned char* pLut = table[0];
-                unsigned int endianTest = 0xff000000;
-                for (y=0; y < src->height; y++) {
-                    int nloop, nx;
-                    unsigned short* srcP;
-                    int* dstP;
-                    int npix = src->width;
-                    cP = cdataP;
-                    sP = sdataP;
-                    /* Get to 32 bit-aligned point */
-                    while(((uintptr_t)cP & 0x3) != 0 && npix>0) {
-                          *cP++ = pLut[*sP++];
-                          npix--;
-                    }
-
-                    /*
-                     * Do NLUT pixels per loop iteration.
-                     * Pack into ints and write out 2 at a time.
-                     */
-                    nloop = npix/NLUT;
-                    nx = npix%NLUT;
-                    srcP = sP;
-                    dstP = (int*)cP;
-
-                    if(((char*)(&endianTest))[0] != 0) {
-                        /* Big endian loop */
-                        for(x=nloop; x!=0; x--) {
-                            dstP[0] = (int)
-                                    ((pLut[srcP[0]] << 24) |
-                                     (pLut[srcP[1]] << 16) |
-                                     (pLut[srcP[2]] << 8)  |
-                                      pLut[srcP[3]]);
-                            dstP[1] = (int)
-                                    ((pLut[srcP[4]] << 24) |
-                                     (pLut[srcP[5]] << 16) |
-                                     (pLut[srcP[6]] << 8)  |
-                                      pLut[srcP[7]]);
-                            dstP += NLUT/4;
-                            srcP += NLUT;
-                        }
-                    } else {
-                        /* Little endian loop */
-                        for(x=nloop; x!=0; x--) {
-                            dstP[0] = (int)
-                                    ((pLut[srcP[3]] << 24) |
-                                     (pLut[srcP[2]] << 16) |
-                                     (pLut[srcP[1]] << 8)  |
-                                      pLut[srcP[0]]);
-                            dstP[1] = (int)
-                                    ((pLut[srcP[7]] << 24) |
-                                     (pLut[srcP[6]] << 16) |
-                                     (pLut[srcP[5]] << 8)  |
-                                      pLut[srcP[4]]);
-                            dstP += NLUT/4;
-                            srcP += NLUT;
-                        }
-                    }
-                    /*
-                     * Complete any remaining pixels
-                     */
-                    cP = cP + NLUT * nloop;
-                    sP = sP + NLUT * nloop;
-                    for(x=nx; x!=0; x--) {
-                        *cP++ = pLut[*sP++];
-                    }
-
-                    /*
-                     * 4554571: increment pointers using the scanline stride
-                     * in pixel units (not byte units)
-                     */
-                    cdataP += dstRasterP->scanlineStride;
-                    sdataP += srcRasterP->scanlineStride;
-                }
+                retStatus = lookupShortData(src, dst, &jtable[0]);
             }
         }
         /* How about ddata == null? */
     } else if ((status = (*sMlibFns[MLIB_LOOKUP].fptr)(dst, src,
-                                      (void **)table) != MLIB_SUCCESS)) {
+                                      (void **)mlib_lookupTable) != MLIB_SUCCESS)) {
         printMedialibError(status);
         retStatus = 0;
     }
@@ -1677,8 +1723,8 @@
 
     /* Release the LUT */
     for (i=0; i < lut_nbands; i++) {
-        (*env)->ReleasePrimitiveArrayCritical(env, jtable[i],
-                                              (jbyte *) table[i], JNI_ABORT);
+        (*env)->ReleasePrimitiveArrayCritical(env, jtable[i].jArray,
+                                              (jbyte *) jtable[i].table, JNI_ABORT);
     }
 
     /* Release the pinned memory */
@@ -2558,6 +2604,41 @@
     return 0;
 }
 
+#define ERR_BAD_IMAGE_LAYOUT (-2)
+
+#define CHECK_DST_ARRAY(start_offset, elements_per_pixel)             \
+    do {                                                              \
+        int offset = (start_offset);                                  \
+        int lastScanOffset;                                           \
+                                                                      \
+        if (!SAFE_TO_MULT(rasterP->scanlineStride,                    \
+                          (rasterP->height - 1)))                     \
+        {                                                             \
+            return ERR_BAD_IMAGE_LAYOUT;                              \
+        }                                                             \
+        lastScanOffset = rasterP->scanlineStride *                    \
+            (rasterP->height - 1);                                    \
+                                                                      \
+        if (!SAFE_TO_ADD(offset, lastScanOffset)) {                   \
+            return ERR_BAD_IMAGE_LAYOUT;                              \
+        }                                                             \
+        lastScanOffset += offset;                                     \
+                                                                      \
+        if (!SAFE_TO_MULT((elements_per_pixel), rasterP->width)) {    \
+            return ERR_BAD_IMAGE_LAYOUT;                              \
+        }                                                             \
+        offset = (elements_per_pixel) * rasterP->width;               \
+                                                                      \
+        if (!SAFE_TO_ADD(offset, lastScanOffset)) {                   \
+            return ERR_BAD_IMAGE_LAYOUT;                              \
+        }                                                             \
+        lastScanOffset += offset;                                     \
+                                                                      \
+        if (dataArrayLength < lastScanOffset) {                       \
+            return ERR_BAD_IMAGE_LAYOUT;                              \
+        }                                                             \
+    } while(0);                                                       \
+
 static int
 storeImageArray(JNIEnv *env, BufImageS_t *srcP, BufImageS_t *dstP,
                 mlib_image *mlibImP) {
@@ -2565,6 +2646,7 @@
     unsigned char *cmDataP, *dataP, *cDataP;
     HintS_t *hintP = &dstP->hints;
     RasterS_t *rasterP = &dstP->raster;
+    jsize dataArrayLength = (*env)->GetArrayLength(env, rasterP->jdata);
     int y;
 
     /* REMIND: Store mlib data type? */
@@ -2583,14 +2665,15 @@
 
     if (hintP->packing == BYTE_INTERLEAVED) {
         /* Write it back to the destination */
+        CHECK_DST_ARRAY(hintP->channelOffset, hintP->numChans);
         cmDataP = (unsigned char *) mlib_ImageGetData(mlibImP);
         mStride = mlib_ImageGetStride(mlibImP);
         dataP = (unsigned char *)(*env)->GetPrimitiveArrayCritical(env,
                                                       rasterP->jdata, NULL);
         if (dataP == NULL) return 0;
-        cDataP = dataP + hintP->dataOffset;
+        cDataP = dataP + hintP->channelOffset;
         for (y=0; y < rasterP->height;
-             y++, cmDataP += mStride, cDataP += hintP->sStride)
+             y++, cmDataP += mStride, cDataP += rasterP->scanlineStride)
         {
             memcpy(cDataP, cmDataP, rasterP->width*hintP->numChans);
         }
@@ -2601,13 +2684,14 @@
         /* Write it back to the destination */
         unsigned short *sdataP, *sDataP;
         unsigned short *smDataP = (unsigned short *)mlib_ImageGetData(mlibImP);
+        CHECK_DST_ARRAY(hintP->channelOffset, hintP->numChans);
         mStride = mlib_ImageGetStride(mlibImP);
         sdataP = (unsigned short *)(*env)->GetPrimitiveArrayCritical(env,
                                                       rasterP->jdata, NULL);
         if (sdataP == NULL) return -1;
-        sDataP = sdataP + hintP->dataOffset;
+        sDataP = sdataP + hintP->channelOffset;
         for (y=0; y < rasterP->height;
-             y++, smDataP += mStride, sDataP += hintP->sStride)
+            y++, smDataP += mStride, sDataP += rasterP->scanlineStride)
         {
             memcpy(sDataP, smDataP, rasterP->width*hintP->numChans);
         }
@@ -3400,7 +3484,8 @@
     unsigned char *inP = inDataP;
     unsigned char *lineOutP, *outP;
     jarray jOutDataP;
-    jint   *outDataP;
+    jsize dataArrayLength;
+    unsigned char *outDataP;
     int loff[MAX_NUMBANDS], roff[MAX_NUMBANDS];
 
     if (rasterP->numBands > MAX_NUMBANDS) {
@@ -3409,11 +3494,18 @@
 
     /* Grab data ptr, strides, offsets from raster */
     jOutDataP = (*env)->GetObjectField(env, rasterP->jraster, g_BCRdataID);
+    if (JNU_IsNull(env, jOutDataP)) {
+        return -1;
+    }
+
+    dataArrayLength = (*env)->GetArrayLength(env, jOutDataP);
+    CHECK_DST_ARRAY(rasterP->chanOffsets[0], 1);
+
     outDataP = (*env)->GetPrimitiveArrayCritical(env, jOutDataP, 0);
     if (outDataP == NULL) {
         return -1;
     }
-    lineOutP =  (unsigned char *)outDataP + rasterP->chanOffsets[0];
+    lineOutP = outDataP + rasterP->chanOffsets[0];
 
     if (component < 0) {
         for (c=0; c < rasterP->numBands; c++) {
@@ -3468,7 +3560,8 @@
     unsigned char *inP = inDataP;
     unsigned short *lineOutP, *outP;
     jarray jOutDataP;
-    jint   *outDataP;
+    jsize dataArrayLength;
+    unsigned short *outDataP;
     int loff[MAX_NUMBANDS], roff[MAX_NUMBANDS];
 
     if (rasterP->numBands > MAX_NUMBANDS) {
@@ -3477,11 +3570,18 @@
 
     /* Grab data ptr, strides, offsets from raster */
     jOutDataP = (*env)->GetObjectField(env, rasterP->jraster, g_SCRdataID);
+    if (JNU_IsNull(env, jOutDataP)) {
+        return -1;
+    }
+
+    dataArrayLength = (*env)->GetArrayLength(env, jOutDataP);
+    CHECK_DST_ARRAY(rasterP->chanOffsets[0], 1);
+
     outDataP = (*env)->GetPrimitiveArrayCritical(env, jOutDataP, 0);
     if (outDataP == NULL) {
         return -1;
     }
-    lineOutP =  (unsigned short *)outDataP + rasterP->chanOffsets[0];
+    lineOutP = outDataP + rasterP->chanOffsets[0];
 
     if (component < 0) {
         for (c=0; c < rasterP->numBands; c++) {
@@ -3536,7 +3636,8 @@
     unsigned char *inP = inDataP;
     unsigned int *lineOutP, *outP;
     jarray jOutDataP;
-    jint   *outDataP;
+    jsize dataArrayLength;
+    unsigned int *outDataP;
     int loff[MAX_NUMBANDS], roff[MAX_NUMBANDS];
 
     if (rasterP->numBands > MAX_NUMBANDS) {
@@ -3545,11 +3646,18 @@
 
     /* Grab data ptr, strides, offsets from raster */
     jOutDataP = (*env)->GetObjectField(env, rasterP->jraster, g_ICRdataID);
+    if (JNU_IsNull(env, jOutDataP)) {
+        return -1;
+    }
+
+    dataArrayLength = (*env)->GetArrayLength(env, jOutDataP);
+    CHECK_DST_ARRAY(rasterP->chanOffsets[0], 1);
+
     outDataP = (*env)->GetPrimitiveArrayCritical(env, jOutDataP, 0);
     if (outDataP == NULL) {
         return -1;
     }
-    lineOutP =  (unsigned int *)outDataP + rasterP->chanOffsets[0];
+    lineOutP = outDataP + rasterP->chanOffsets[0];
 
     if (component < 0) {
         for (c=0; c < rasterP->numBands; c++) {
@@ -3606,7 +3714,8 @@
     unsigned char *inP = inDataP;
     unsigned char *lineOutP, *outP;
     jarray jOutDataP;
-    jint   *outDataP;
+    jsize  dataArrayLength;
+    unsigned char *outDataP;
     int loff[MAX_NUMBANDS], roff[MAX_NUMBANDS];
     int a = rasterP->numBands - 1;
 
@@ -3616,11 +3725,18 @@
 
     /* Grab data ptr, strides, offsets from raster */
     jOutDataP = (*env)->GetObjectField(env, rasterP->jraster, g_BCRdataID);
+    if (JNU_IsNull(env, jOutDataP)) {
+        return -1;
+    }
+
+    dataArrayLength = (*env)->GetArrayLength(env, jOutDataP);
+    CHECK_DST_ARRAY(rasterP->chanOffsets[0], 1);
+
     outDataP = (*env)->GetPrimitiveArrayCritical(env, jOutDataP, 0);
     if (outDataP == NULL) {
         return -1;
     }
-    lineOutP =  (unsigned char *)outDataP + rasterP->chanOffsets[0];
+    lineOutP = outDataP + rasterP->chanOffsets[0];
 
     if (component < 0) {
         for (c=0; c < rasterP->numBands; c++) {
@@ -3696,7 +3812,8 @@
     unsigned char *inP = inDataP;
     unsigned short *lineOutP, *outP;
     jarray jOutDataP;
-    jint   *outDataP;
+    jsize dataArrayLength;
+    unsigned short *outDataP;
     int loff[MAX_NUMBANDS], roff[MAX_NUMBANDS];
     int a = rasterP->numBands - 1;
 
@@ -3706,11 +3823,17 @@
 
     /* Grab data ptr, strides, offsets from raster */
     jOutDataP = (*env)->GetObjectField(env, rasterP->jraster, g_SCRdataID);
+    if (JNU_IsNull(env, jOutDataP)) {
+        return -1;
+    }
+    dataArrayLength = (*env)->GetArrayLength(env, jOutDataP);
+    CHECK_DST_ARRAY(rasterP->chanOffsets[0], 1);
+
     outDataP = (*env)->GetPrimitiveArrayCritical(env, jOutDataP, 0);
     if (outDataP == NULL) {
         return -1;
     }
-    lineOutP =  (unsigned short *)outDataP + rasterP->chanOffsets[0];
+    lineOutP = outDataP + rasterP->chanOffsets[0];
 
     if (component < 0) {
         for (c=0; c < rasterP->numBands; c++) {
@@ -3786,7 +3909,8 @@
     unsigned char *inP = inDataP;
     unsigned int *lineOutP, *outP;
     jarray jOutDataP;
-    jint   *outDataP;
+    jsize dataArrayLength;
+    unsigned int *outDataP;
     int loff[MAX_NUMBANDS], roff[MAX_NUMBANDS];
     int a = rasterP->numBands - 1;
 
@@ -3796,11 +3920,18 @@
 
     /* Grab data ptr, strides, offsets from raster */
     jOutDataP = (*env)->GetObjectField(env, rasterP->jraster, g_ICRdataID);
+    if (JNU_IsNull(env, jOutDataP)) {
+        return -1;
+    }
+
+    dataArrayLength = (*env)->GetArrayLength(env, jOutDataP);
+    CHECK_DST_ARRAY(rasterP->chanOffsets[0], 1);
+
     outDataP = (*env)->GetPrimitiveArrayCritical(env, jOutDataP, 0);
     if (outDataP == NULL) {
         return -1;
     }
-    lineOutP =  (unsigned int *)outDataP + rasterP->chanOffsets[0];
+    lineOutP = outDataP + rasterP->chanOffsets[0];
 
     if (component < 0) {
         for (c=0; c < rasterP->numBands; c++) {
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageCreate.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageCreate.c	Wed Jul 05 19:00:49 2017 +0200
@@ -160,27 +160,46 @@
 /* Check if stride == width
    * If it is then image can be treated as a 1-D vector
  */
+
+  if (!SAFE_TO_MULT(width, channels)) {
+    return NULL;
+  }
+
+  wb = width * channels;
+
   switch (type) {
     case MLIB_DOUBLE:
-      wb = width * channels * 8;
+      if (!SAFE_TO_MULT(wb, 8)) {
+        return NULL;
+      }
+      wb *= 8;
       mask = 7;
       break;
     case MLIB_FLOAT:
     case MLIB_INT:
-      wb = width * channels * 4;
+      if (!SAFE_TO_MULT(wb, 4)) {
+        return NULL;
+      }
+      wb *= 4;
       mask = 3;
       break;
     case MLIB_USHORT:
     case MLIB_SHORT:
-      wb = width * channels * 2;
+      if (!SAFE_TO_MULT(wb, 2)) {
+        return NULL;
+      }
+      wb *= 2;
       mask = 1;
       break;
     case MLIB_BYTE:
-      wb = width * channels;
+      // wb is ready
       mask = 0;
       break;
     case MLIB_BIT:
-      wb = (width * channels + 7) / 8;
+      if (!SAFE_TO_ADD(7, wb)) {
+        return NULL;
+      }
+      wb = (wb + 7) / 8;
       mask = 0;
       break;
     default:
@@ -270,7 +289,7 @@
       break;
     case MLIB_USHORT:
     case MLIB_SHORT:
-      if (!SAFE_TO_MULT(wb, 4)) {
+      if (!SAFE_TO_MULT(wb, 2)) {
         return NULL;
       }
       wb *= 2;
--- a/jdk/src/share/native/sun/awt/splashscreen/java_awt_SplashScreen.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/awt/splashscreen/java_awt_SplashScreen.c	Wed Jul 05 19:00:49 2017 +0200
@@ -26,6 +26,7 @@
 #include "splashscreen_impl.h"
 #include <jni.h>
 #include <jlong_md.h>
+#include <sizecalc.h>
 
 JNIEXPORT jint JNICALL
 JNI_OnLoad(JavaVM * vm, void *reserved)
@@ -57,7 +58,7 @@
     if (splash->overlayData) {
         free(splash->overlayData);
     }
-    splash->overlayData = malloc(dataSize * sizeof(rgbquad_t));
+    splash->overlayData = SAFE_SIZE_ARRAY_ALLOC(malloc, dataSize, sizeof(rgbquad_t));
     if (splash->overlayData) {
         /* we need a copy anyway, so we'll be using GetIntArrayRegion */
         (*env)->GetIntArrayRegion(env, data, 0, dataSize,
--- a/jdk/src/share/native/sun/awt/splashscreen/splashscreen_gif.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/awt/splashscreen/splashscreen_gif.c	Wed Jul 05 19:00:49 2017 +0200
@@ -28,6 +28,8 @@
 
 #include <gif_lib.h>
 
+#include "sizecalc.h"
+
 #define GIF_TRANSPARENT     0x01
 #define GIF_USER_INPUT      0x02
 #define GIF_DISPOSE_MASK    0x07
@@ -120,7 +122,7 @@
     splash->height = gif->SHeight;
     splash->frameCount = gif->ImageCount;
     splash->frames = (SplashImage *)
-        malloc(sizeof(SplashImage) * gif->ImageCount);
+        SAFE_SIZE_ARRAY_ALLOC(malloc, sizeof(SplashImage), gif->ImageCount);
     if (!splash->frames) {
       free(pBitmapBits);
       free(pOldBitmapBits);
@@ -254,7 +256,7 @@
         // now dispose of the previous frame correctly
 
         splash->frames[imageIndex].bitmapBits =
-            (rgbquad_t *) malloc(bufferSize);
+            (rgbquad_t *) malloc(bufferSize); // bufferSize is safe (checked above)
         if (!splash->frames[imageIndex].bitmapBits) {
             free(pBitmapBits);
             free(pOldBitmapBits);
--- a/jdk/src/share/native/sun/font/freetypeScaler.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/freetypeScaler.c	Wed Jul 05 19:00:49 2017 +0200
@@ -1351,17 +1351,22 @@
     FTScalerInfo *scalerInfo =
              (FTScalerInfo*) jlong_to_ptr(pScaler);
 
-    glyphs = (jint*) malloc(numGlyphs*sizeof(jint));
+    glyphs = NULL;
+    if (numGlyphs > 0 && 0xffffffffu / sizeof(jint) >= numGlyphs) {
+        glyphs = (jint*) malloc(numGlyphs*sizeof(jint));
+    }
     if (glyphs == NULL) {
+        // We reach here if:
+        // 1. numGlyphs <= 0,
+        // 2. overflow check failed, or
+        // 3. malloc failed.
         gp = (*env)->NewObject(env, sunFontIDs.gpClass, sunFontIDs.gpCtrEmpty);
-        if (!isNullScalerContext(context) && scalerInfo != NULL) {
-            invalidateJavaScaler(env, scaler, scalerInfo);
-        }
         return gp;
     }
 
     (*env)->GetIntArrayRegion(env, glyphArray, 0, numGlyphs, glyphs);
 
+    gpdata.numCoords = 0;
     for (i=0; i<numGlyphs;i++) {
         if (glyphs[i] >= INVISIBLE_GLYPHS) {
             continue;
--- a/jdk/src/share/native/sun/font/layout/ContextualSubstSubtables.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/ContextualSubstSubtables.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -218,6 +218,9 @@
 
     LEGlyphID glyph = glyphIterator->getCurrGlyphID();
     le_int32 coverageIndex = getGlyphCoverage(lookupProcessor->getReference(), glyph, success);
+    if (LE_FAILURE(success)) {
+        return 0;
+    }
 
     if (coverageIndex >= 0) {
         le_uint16 srSetCount = SWAPW(subRuleSetCount);
@@ -267,6 +270,9 @@
 
     LEGlyphID glyph = glyphIterator->getCurrGlyphID();
     le_int32 coverageIndex = getGlyphCoverage(lookupProcessor->getReference(), glyph, success);
+    if (LE_FAILURE(success)) {
+        return 0;
+    }
 
     if (coverageIndex >= 0) {
         const ClassDefinitionTable *classDefinitionTable =
@@ -395,6 +401,9 @@
 
     LEGlyphID glyph = glyphIterator->getCurrGlyphID();
     le_int32 coverageIndex = getGlyphCoverage(lookupProcessor->getReference(), glyph, success);
+    if (LE_FAILURE(success)) {
+        return 0;
+    }
 
     if (coverageIndex >= 0) {
         le_uint16 srSetCount = SWAPW(chainSubRuleSetCount);
@@ -466,6 +475,9 @@
 
     LEGlyphID glyph = glyphIterator->getCurrGlyphID();
     le_int32 coverageIndex = getGlyphCoverage(lookupProcessor->getReference(), glyph, success);
+    if (LE_FAILURE(success)) {
+        return 0;
+    }
 
     if (coverageIndex >= 0) {
         const ClassDefinitionTable *backtrackClassDefinitionTable =
--- a/jdk/src/share/native/sun/font/layout/CursiveAttachmentSubtables.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/CursiveAttachmentSubtables.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -45,7 +45,7 @@
     le_int32  coverageIndex = getGlyphCoverage(base, glyphID, success);
     le_uint16 eeCount       = SWAPW(entryExitCount);
 
-    if (coverageIndex < 0 || coverageIndex >= eeCount) {
+    if (coverageIndex < 0 || coverageIndex >= eeCount || LE_FAILURE(success)) {
         glyphIterator->setCursiveGlyph();
         return 0;
     }
--- a/jdk/src/share/native/sun/font/layout/ExtensionSubtables.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/ExtensionSubtables.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -44,10 +44,10 @@
 #define READ_LONG(code) (le_uint32)((SWAPW(*(le_uint16*)&code) << 16) + SWAPW(*(((le_uint16*)&code) + 1)))
 
 // FIXME: should look at the format too... maybe have a sub-class for it?
-le_uint32 ExtensionSubtable::process(const LookupProcessor *lookupProcessor, le_uint16 lookupType,
+le_uint32 ExtensionSubtable::process(const LEReferenceTo<ExtensionSubtable> &thisRef,
+                                     const LookupProcessor *lookupProcessor, le_uint16 lookupType,
                                       GlyphIterator *glyphIterator, const LEFontInstance *fontInstance, LEErrorCode& success) const
 {
-    const LEReferenceTo<ExtensionSubtable> thisRef(lookupProcessor->getReference(), success); // create a reference to this
 
     if (LE_FAILURE(success)) {
         return 0;
@@ -57,7 +57,7 @@
 
     if (elt != lookupType) {
         le_uint32 extOffset = READ_LONG(extensionOffset);
-        LEReferenceTo<LookupSubtable> subtable(thisRef, success, extOffset);
+        LEReferenceTo<LookupSubtable> subtable(thisRef, success,  extOffset);
 
         if(LE_SUCCESS(success)) {
           return lookupProcessor->applySubtable(subtable, elt, glyphIterator, fontInstance, success);
--- a/jdk/src/share/native/sun/font/layout/ExtensionSubtables.h	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/ExtensionSubtables.h	Wed Jul 05 19:00:49 2017 +0200
@@ -52,7 +52,8 @@
     le_uint16 extensionLookupType;
     le_uint32 extensionOffset;
 
-    le_uint32 process(const LookupProcessor *lookupProcessor, le_uint16 lookupType,
+    le_uint32 process(const LEReferenceTo<ExtensionSubtable> &extRef,
+                      const LookupProcessor *lookupProcessor, le_uint16 lookupType,
                       GlyphIterator *glyphIterator, const LEFontInstance *fontInstance, LEErrorCode& success) const;
 };
 
--- a/jdk/src/share/native/sun/font/layout/GlyphPosnLookupProc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/GlyphPosnLookupProc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -168,7 +168,7 @@
     {
         LEReferenceTo<ExtensionSubtable> subtable(lookupSubtable, success);
 
-        delta = subtable->process(this, lookupType, glyphIterator, fontInstance, success);
+        delta = subtable->process(subtable, this, lookupType, glyphIterator, fontInstance, success);
         break;
     }
 
--- a/jdk/src/share/native/sun/font/layout/GlyphSubstLookupProc.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/GlyphSubstLookupProc.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -139,7 +139,7 @@
     {
         const LEReferenceTo<ExtensionSubtable> subtable(lookupSubtable, success);
 
-        delta = subtable->process(this, lookupType, glyphIterator, fontInstance, success);
+        delta = subtable->process(subtable, this, lookupType, glyphIterator, fontInstance, success);
         break;
     }
 
--- a/jdk/src/share/native/sun/font/layout/KernTable.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/KernTable.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -96,7 +96,7 @@
  * TODO: respect header flags
  */
 KernTable::KernTable(const LETableReference& base, LEErrorCode &success)
-  : pairs(), pairsSwapped(NULL), fTable(base)
+  : pairsSwapped(NULL), fTable(base)
 {
   if(LE_FAILURE(success) || (fTable.isEmpty())) {
 #if DEBUG
@@ -143,32 +143,36 @@
 #endif
 
         if(LE_SUCCESS(success) && nPairs>0) {
-          // pairs is an instance member, and table is on the stack.
-          // set 'pairs' based on table.getAlias(). This will range check it.
+          // pairsSwapped is an instance member, and table is on the stack.
+          // set 'pairsSwapped' based on table.getAlias(). This will range check it.
 
-          pairs = LEReferenceToArrayOf<PairInfo>(fTable, // based on overall table
-                                                 success,
-                                                 (const PairInfo*)table.getAlias(),  // subtable 0 + ..
-                                                 KERN_SUBTABLE_0_HEADER_SIZE,  // .. offset of header size
-                                                 nPairs); // count
-        }
-        if (LE_SUCCESS(success) && pairs.isValid()) {
-            pairsSwapped =  (PairInfo*)(malloc(nPairs*sizeof(PairInfo)));
-            PairInfo *p = (PairInfo*)pairsSwapped;
-            for (int i = 0; LE_SUCCESS(success) && i < nPairs; i++, p++) {
-              memcpy(p, pairs.getAlias(i,success), KERN_PAIRINFO_SIZE);
-              p->key = SWAPL(p->key);
+          pairsSwapped = (PairInfo*)(fTable.getFont()->getKernPairs());
+          if (pairsSwapped == NULL) {
+            LEReferenceToArrayOf<PairInfo>pairs =
+              LEReferenceToArrayOf<PairInfo>(fTable, // based on overall table
+                                             success,
+                                             (const PairInfo*)table.getAlias(),  // subtable 0 + ..
+                                             KERN_SUBTABLE_0_HEADER_SIZE,  // .. offset of header size
+                                             nPairs); // count
+            if (LE_SUCCESS(success) && pairs.isValid()) {
+              pairsSwapped =  (PairInfo*)(malloc(nPairs*sizeof(PairInfo)));
+              PairInfo *p = (PairInfo*)pairsSwapped;
+              for (int i = 0; LE_SUCCESS(success) && i < nPairs; i++, p++) {
+                memcpy(p, pairs.getAlias(i,success), KERN_PAIRINFO_SIZE);
+                p->key = SWAPL(p->key);
+              }
+              fTable.getFont()->setKernPairs((void*)pairsSwapped); // store it
             }
-            fTable.getFont()->setKernPairs((void*)pairsSwapped); // store it
+          }
         }
 
 #if 0
-        fprintf(stderr, "coverage: %0.4x nPairs: %d pairs %p\n", coverage, nPairs, pairs.getAlias());
+        fprintf(stderr, "coverage: %0.4x nPairs: %d pairs %p\n", coverage, nPairs, pairsSwapped);
         fprintf(stderr, "  searchRange: %d entrySelector: %d rangeShift: %d\n", searchRange, entrySelector, rangeShift);
         fprintf(stderr, "[[ ignored font table entries: range %d selector %d shift %d ]]\n", SWAPW(table->searchRange), SWAPW(table->entrySelector), SWAPW(table->rangeShift));
 #endif
 #if DEBUG
-        fprintf(stderr, "coverage: %0.4x nPairs: %d pairs 0x%x\n", coverage, nPairs, pairs);
+        fprintf(stderr, "coverage: %0.4x nPairs: %d pairs 0x%x\n", coverage, nPairs, pairsSwapped);
         fprintf(stderr,
           "  searchRange(pairs): %d entrySelector: %d rangeShift(pairs): %d\n",
           searchRange, entrySelector, rangeShift);
@@ -182,7 +186,7 @@
               ids[id] = (char)i;
             }
           }
-          PairInfo *p = pairs;
+          PairInfo *p = pairsSwapped;
           for (int i = 0; i < nPairs; ++i, p++) {
             le_uint32 k = p->key;
             le_uint16 left = (k >> 16) & 0xffff;
--- a/jdk/src/share/native/sun/font/layout/KernTable.h	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/KernTable.h	Wed Jul 05 19:00:49 2017 +0200
@@ -57,7 +57,6 @@
  private:
   le_uint16 coverage;
   le_uint16 nPairs;
-  LEReferenceToArrayOf<PairInfo> pairs;
   PairInfo  *pairsSwapped;
   const LETableReference &fTable;
   le_uint16 searchRange;
--- a/jdk/src/share/native/sun/font/layout/LEGlyphStorage.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/LEGlyphStorage.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -584,7 +584,7 @@
 {
     le_int32 growAmount = fInsertionList->getGrowAmount();
 
-    if (growAmount == 0) {
+    if (growAmount <= 0) {
         return fGlyphCount;
     }
 
@@ -613,7 +613,9 @@
         fAuxData = (le_uint32 *)newAuxData;
     }
 
-    fSrcIndex  = fGlyphCount - 1;
+    if (fGlyphCount > 0) {
+       fSrcIndex  = fGlyphCount - 1;
+    }
     fDestIndex = newGlyphCount - 1;
 
 #if 0
@@ -653,6 +655,10 @@
     }
 #endif
 
+    if (atPosition < 0 || fSrcIndex < 0 || fDestIndex < 0) {
+        return FALSE;
+    }
+
     if (fAuxData != NULL) {
         le_int32 src = fSrcIndex, dest = fDestIndex;
 
@@ -665,7 +671,7 @@
         }
     }
 
-    while (fSrcIndex > atPosition) {
+    while (fSrcIndex > atPosition && fSrcIndex >= 0 && fDestIndex >= 0) {
         fGlyphs[fDestIndex]      = fGlyphs[fSrcIndex];
         fCharIndices[fDestIndex] = fCharIndices[fSrcIndex];
 
@@ -673,7 +679,7 @@
         fSrcIndex  -= 1;
     }
 
-    for (le_int32 i = count - 1; i >= 0; i -= 1) {
+    for (le_int32 i = count - 1; i >= 0 && fDestIndex >= 0; i -= 1) {
         fGlyphs[fDestIndex]      = newGlyphs[i];
         fCharIndices[fDestIndex] = fCharIndices[atPosition];
 
@@ -682,7 +688,7 @@
 
     // the source glyph we're pointing at
     // just got replaced by the insertion
-    fSrcIndex -= 1;
+        fSrcIndex -= 1;
 
     return FALSE;
 }
--- a/jdk/src/share/native/sun/font/layout/LayoutEngine.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/LayoutEngine.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -569,7 +569,6 @@
 {
   if(fGlyphStorage!=NULL) {
     fGlyphStorage->reset();
-    fGlyphStorage = NULL;
   }
 }
 
--- a/jdk/src/share/native/sun/font/layout/LigatureSubstSubtables.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/LigatureSubstSubtables.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -45,6 +45,10 @@
     LEGlyphID glyph = glyphIterator->getCurrGlyphID();
     le_int32 coverageIndex = getGlyphCoverage(base, glyph, success);
 
+    if (LE_FAILURE(success)) {
+      return 0;
+    }
+
     if (coverageIndex >= 0) {
         Offset ligSetTableOffset = SWAPW(ligSetTableOffsetArray[coverageIndex]);
         const LigatureSetTable *ligSetTable = (const LigatureSetTable *) ((char *) this + ligSetTableOffset);
--- a/jdk/src/share/native/sun/font/layout/LookupProcessor.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/LookupProcessor.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -61,7 +61,7 @@
 
         delta = applySubtable(lookupSubtable, lookupType, glyphIterator, fontInstance, success);
 
-        if (delta > 0 && LE_FAILURE(success)) {
+        if (delta > 0 || LE_FAILURE(success)) {
             return 1;
         }
 
--- a/jdk/src/share/native/sun/font/layout/MarkToBasePosnSubtables.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/MarkToBasePosnSubtables.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -56,6 +56,10 @@
     LEGlyphID markGlyph = glyphIterator->getCurrGlyphID();
     le_int32 markCoverage = getGlyphCoverage(base, (LEGlyphID) markGlyph, success);
 
+    if (LE_FAILURE(success)) {
+      return 0;
+    }
+
     if (markCoverage < 0) {
         // markGlyph isn't a covered mark glyph
         return 0;
--- a/jdk/src/share/native/sun/font/layout/MarkToLigaturePosnSubtables.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/MarkToLigaturePosnSubtables.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -55,6 +55,10 @@
     LEGlyphID markGlyph = glyphIterator->getCurrGlyphID();
     le_int32 markCoverage = getGlyphCoverage(base, (LEGlyphID) markGlyph, success);
 
+    if (LE_FAILURE(success)) {
+      return 0;
+    }
+
     if (markCoverage < 0) {
         // markGlyph isn't a covered mark glyph
         return 0;
--- a/jdk/src/share/native/sun/font/layout/MarkToMarkPosnSubtables.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/MarkToMarkPosnSubtables.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -56,6 +56,10 @@
     LEGlyphID markGlyph = glyphIterator->getCurrGlyphID();
     le_int32 markCoverage = getGlyphCoverage(base, (LEGlyphID) markGlyph, success);
 
+    if (LE_FAILURE(success)) {
+        return 0;
+    }
+
     if (markCoverage < 0) {
         // markGlyph isn't a covered mark glyph
         return 0;
--- a/jdk/src/share/native/sun/font/layout/MultipleSubstSubtables.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/MultipleSubstSubtables.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -61,6 +61,10 @@
     le_int32 coverageIndex = getGlyphCoverage(base, glyph, success);
     le_uint16 seqCount = SWAPW(sequenceCount);
 
+    if (LE_FAILURE(success)) {
+        return 0;
+    }
+
     if (coverageIndex >= 0 && coverageIndex < seqCount) {
         Offset sequenceTableOffset = SWAPW(sequenceTableOffsetArray[coverageIndex]);
         const SequenceTable *sequenceTable = (const SequenceTable *) ((char *) this + sequenceTableOffset);
--- a/jdk/src/share/native/sun/font/layout/PairPositioningSubtables.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/PairPositioningSubtables.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -76,23 +76,30 @@
 {
     LEGlyphID firstGlyph = glyphIterator->getCurrGlyphID();
     le_int32 coverageIndex = getGlyphCoverage(base, firstGlyph, success);
+
+    if (LE_FAILURE(success)) {
+      return 0;
+    }
     GlyphIterator tempIterator(*glyphIterator);
 
     if (coverageIndex >= 0 && glyphIterator->next()) {
         Offset pairSetTableOffset = SWAPW(pairSetTableOffsetArray[coverageIndex]);
-        PairSetTable *pairSetTable = (PairSetTable *) ((char *) this + pairSetTableOffset);
+        LEReferenceTo<PairSetTable> pairSetTable(base, success, ((char *) this + pairSetTableOffset));
+        if (LE_FAILURE(success)) {
+          return 0;
+        }
         le_uint16 pairValueCount = SWAPW(pairSetTable->pairValueCount);
         le_int16 valueRecord1Size = ValueRecord::getSize(SWAPW(valueFormat1));
         le_int16 valueRecord2Size = ValueRecord::getSize(SWAPW(valueFormat2));
         le_int16 recordSize = sizeof(PairValueRecord) - sizeof(ValueRecord) + valueRecord1Size + valueRecord2Size;
         LEGlyphID secondGlyph = glyphIterator->getCurrGlyphID();
-        const PairValueRecord *pairValueRecord = NULL;
+        LEReferenceTo<PairValueRecord> pairValueRecord;
 
         if (pairValueCount != 0) {
-            pairValueRecord = findPairValueRecord((TTGlyphID) LE_GET_GLYPH(secondGlyph), pairSetTable->pairValueRecordArray, pairValueCount, recordSize);
+            pairValueRecord = findPairValueRecord(base, (TTGlyphID) LE_GET_GLYPH(secondGlyph), pairSetTable->pairValueRecordArray, pairValueCount, recordSize, success);
         }
 
-        if (pairValueRecord == NULL) {
+        if (pairValueRecord.isEmpty()) {
             return 0;
         }
 
@@ -119,6 +126,11 @@
 {
     LEGlyphID firstGlyph = glyphIterator->getCurrGlyphID();
     le_int32 coverageIndex = getGlyphCoverage(base, firstGlyph, success);
+
+    if (LE_FAILURE(success)) {
+        return 0;
+    }
+
     GlyphIterator tempIterator(*glyphIterator);
 
     if (coverageIndex >= 0 && glyphIterator->next()) {
@@ -154,22 +166,26 @@
     return 0;
 }
 
-const PairValueRecord *PairPositioningFormat1Subtable::findPairValueRecord(TTGlyphID glyphID, const PairValueRecord *records, le_uint16 recordCount, le_uint16 recordSize) const
+LEReferenceTo<PairValueRecord> PairPositioningFormat1Subtable::findPairValueRecord(const LETableReference &base, TTGlyphID glyphID, const PairValueRecord *records, le_uint16 recordCount, le_uint16 recordSize, LEErrorCode &success) const
 {
 #if 1
         // The OpenType spec. says that the ValueRecord table is
         // sorted by secondGlyph. Unfortunately, there are fonts
         // around that have an unsorted ValueRecord table.
-        const PairValueRecord *record = records;
+        LEReferenceTo<PairValueRecord> record(base, success, records);
+        record.verifyLength(0, recordSize, success);
 
         for(le_int32 r = 0; r < recordCount; r += 1) {
+           if (LE_FAILURE(success)) return (const PairValueRecord*)NULL;
                 if (SWAPW(record->secondGlyph) == glyphID) {
                         return record;
                 }
 
-                record = (const PairValueRecord *) ((char *) record + recordSize);
+                record =  LEReferenceTo<PairValueRecord>(base, success, ((const char*)record.getAlias())+ recordSize);
+                record.verifyLength(0, recordSize, success);
         }
 #else
+  #error dead code - not updated.
     le_uint8 bit = OpenTypeUtilities::highBit(recordCount);
     le_uint16 power = 1 << bit;
     le_uint16 extra = (recordCount - power) * recordSize;
@@ -195,7 +211,7 @@
     }
 #endif
 
-    return NULL;
+    return (const PairValueRecord*)NULL;
 }
 
 U_NAMESPACE_END
--- a/jdk/src/share/native/sun/font/layout/PairPositioningSubtables.h	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/PairPositioningSubtables.h	Wed Jul 05 19:00:49 2017 +0200
@@ -77,8 +77,9 @@
     le_uint32  process(const LEReferenceTo<PairPositioningFormat1Subtable> &base, GlyphIterator *glyphIterator, const LEFontInstance *fontInstance, LEErrorCode &success) const;
 
 private:
-    const PairValueRecord *findPairValueRecord(TTGlyphID glyphID, const PairValueRecord *records,
-        le_uint16 recordCount, le_uint16 recordSize) const;
+    LEReferenceTo<PairValueRecord> findPairValueRecord(const LETableReference &base, TTGlyphID glyphID, const PairValueRecord *records,
+        le_uint16 recordCount, le_uint16 recordSize, LEErrorCode &success) const;
+
 };
 LE_VAR_ARRAY(PairPositioningFormat1Subtable, pairSetTableOffsetArray)
 
--- a/jdk/src/share/native/sun/font/layout/SinglePositioningSubtables.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/SinglePositioningSubtables.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -70,6 +70,9 @@
 {
     LEGlyphID glyph = glyphIterator->getCurrGlyphID();
     le_int32 coverageIndex = getGlyphCoverage(base, glyph, success);
+    if (LE_FAILURE(success)) {
+        return 0;
+    }
 
     if (coverageIndex >= 0) {
         valueRecord.adjustPosition(SWAPW(valueFormat), (const char *) this, *glyphIterator, fontInstance);
@@ -84,6 +87,9 @@
 {
     LEGlyphID glyph = glyphIterator->getCurrGlyphID();
     le_int16 coverageIndex = (le_int16) getGlyphCoverage(base, glyph, success);
+    if (LE_FAILURE(success)) {
+        return 0;
+    }
 
     if (coverageIndex >= 0) {
         valueRecordArray[0].adjustPosition(coverageIndex, SWAPW(valueFormat), (const char *) this, *glyphIterator, fontInstance);
--- a/jdk/src/share/native/sun/font/layout/SingleSubstitutionSubtables.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/SingleSubstitutionSubtables.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -69,6 +69,9 @@
 {
     LEGlyphID glyph = glyphIterator->getCurrGlyphID();
     le_int32 coverageIndex = getGlyphCoverage(base, glyph, success);
+    if (LE_FAILURE(success)) {
+        return 0;
+    }
 
     if (coverageIndex >= 0) {
         TTGlyphID substitute = ((TTGlyphID) LE_GET_GLYPH(glyph)) + SWAPW(deltaGlyphID);
@@ -87,6 +90,9 @@
 {
     LEGlyphID glyph = glyphIterator->getCurrGlyphID();
     le_int32 coverageIndex = getGlyphCoverage(base, glyph, success);
+    if (LE_FAILURE(success)) {
+        return 0;
+    }
 
     if (coverageIndex >= 0) {
         TTGlyphID substitute = SWAPW(substituteArray[coverageIndex]);
--- a/jdk/src/share/native/sun/font/layout/SunLayoutEngine.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/font/layout/SunLayoutEngine.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -203,16 +203,19 @@
   getFloat(env, pt, x, y);
   jboolean rtl = (typo_flags & TYPO_RTL) != 0;
   int glyphCount = engine->layoutChars(chars, start - min, limit - start, len, rtl, x, y, success);
-  //   fprintf(stderr, "sle nl len %d -> gc: %d\n", len, glyphCount); fflush(stderr);
+    // fprintf(stderr, "sle nl len %d -> gc: %d\n", len, glyphCount); fflush(stderr);
 
   engine->getGlyphPosition(glyphCount, x, y, success);
 
-  //  fprintf(stderr, "layout glyphs: %d x: %g y: %g\n", glyphCount, x, y); fflush(stderr);
-
-  if (putGV(env, gmask, baseIndex, gvdata, engine, glyphCount)) {
-    // !!! hmmm, could use current value in positions array of GVData...
-    putFloat(env, pt, x, y);
-  }
+   // fprintf(stderr, "layout glyphs: %d x: %g y: %g\n", glyphCount, x, y); fflush(stderr);
+   if (LE_FAILURE(success)) {
+       env->SetIntField(gvdata, gvdCountFID, -1); // flag failure
+   } else {
+      if (putGV(env, gmask, baseIndex, gvdata, engine, glyphCount)) {
+        // !!! hmmm, could use current value in positions array of GVData...
+        putFloat(env, pt, x, y);
+      }
+   }
 
   if (chars != buffer) {
     free(chars);
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c	Wed Jul 05 19:00:49 2017 +0200
@@ -1021,7 +1021,7 @@
     mpe = cmsStageAllocToneCurves(ContextID, 3, LabTable);
     cmsFreeToneCurveTriple(LabTable);
 
-    if (mpe == NULL) return NULL;
+    if (mpe == NULL) return mpe;
 
     mpe ->Implements = cmsSigLabV2toV4;
     return mpe;
@@ -1426,6 +1426,8 @@
     if (lut == NULL) return NULL;
 
     NewLUT = cmsPipelineAlloc(lut ->ContextID, lut ->InputChannels, lut ->OutputChannels);
+    if (NewLUT == NULL) return NULL;
+
     for (mpe = lut ->Elements;
          mpe != NULL;
          mpe = mpe ->Next) {
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c	Wed Jul 05 19:00:49 2017 +0200
@@ -517,9 +517,9 @@
     while (v -> Allocated < n)
         GrowNamedColorList(v);
 
-    strncpy(v ->Prefix, Prefix, sizeof(v ->Prefix));
-    strncpy(v ->Suffix, Suffix, sizeof(v ->Suffix));
-    v->Prefix[32] = v->Suffix[32] = 0;
+    strncpy(v ->Prefix, Prefix, sizeof(v ->Prefix) - 1);
+    strncpy(v ->Suffix, Suffix, sizeof(v ->Suffix) - 1);
+    v->Prefix[sizeof(v ->Prefix) - 1] = v->Suffix[sizeof(v ->Suffix) - 1] = 0;
 
     v -> ColorantCount = ColorantCount;
 
@@ -577,9 +577,10 @@
     if (Name != NULL) {
 
         strncpy(NamedColorList ->List[NamedColorList ->nColors].Name, Name,
-                    sizeof(NamedColorList ->List[NamedColorList ->nColors].Name));
+                    sizeof(NamedColorList ->List[NamedColorList ->nColors].Name) - 1);
 
-        NamedColorList ->List[NamedColorList ->nColors].Name[cmsMAX_PATH-1] = 0;
+        NamedColorList ->List[NamedColorList ->nColors].
+            Name[sizeof(NamedColorList ->List[NamedColorList ->nColors].Name) - 1] = 0;
 
     }
     else
@@ -734,6 +735,10 @@
     Seq -> seq      = (cmsPSEQDESC*) _cmsCalloc(ContextID, n, sizeof(cmsPSEQDESC));
     Seq -> n        = n;
 
+    if (Seq -> seq == NULL) {
+        _cmsFree(ContextID, Seq);
+        return NULL;
+    }
 
     for (i=0; i < n; i++) {
         Seq -> seq[i].Manufacturer = NULL;
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c	Wed Jul 05 19:00:49 2017 +0200
@@ -1201,6 +1201,15 @@
     for (i=0; i < nCurves; i++) {
 
         c16->Curves[i] = _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number));
+        if (c16->Curves[i] == NULL) {
+            for (j=0; j < i; j++) {
+                _cmsFree(ContextID, c16->Curves[j]);
+            }
+            _cmsFree(ContextID, c16->Curves);
+            _cmsFree(ContextID, c16);
+
+            return NULL;
+        }
 
         if (nElements == 256) {
 
--- a/jdk/src/share/native/sun/java2d/pipe/Region.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/java2d/pipe/Region.c	Wed Jul 05 19:00:49 2017 +0200
@@ -28,6 +28,7 @@
 #include "jni_util.h"
 
 #include "Region.h"
+#include "sizecalc.h"
 
 static jfieldID endIndexID;
 static jfieldID bandsID;
@@ -260,8 +261,8 @@
         }
         Region_StartIteration(env, &clipInfo);
         numrects = Region_CountIterationRects(&clipInfo);
-        if (numrects > initialBufferSize) {
-            *pRect = (RECT_T *) malloc(numrects * sizeof(RECT_T));
+        if ((unsigned long)numrects > initialBufferSize) {
+            *pRect = (RECT_T *) SAFE_SIZE_ARRAY_ALLOC(malloc, numrects, sizeof(RECT_T));
             if (*pRect == NULL) {
                 Region_EndIteration(env, &clipInfo);
                 JNU_ThrowOutOfMemoryError(env,
--- a/jdk/src/share/native/sun/management/DiagnosticCommandImpl.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/management/DiagnosticCommandImpl.c	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c)  2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/native/sun/security/jgss/wrapper/GSSLibStub.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/share/native/sun/security/jgss/wrapper/GSSLibStub.c	Wed Jul 05 19:00:49 2017 +0200
@@ -329,6 +329,8 @@
   initGSSBuffer(env, jnameVal, &nameVal);
   nameType = newGSSOID(env, jnameType);
   if ((*env)->ExceptionCheck(env)) {
+    deleteGSSOID(nameType);
+    resetGSSBuffer(env, jnameVal, &nameVal);
     return jlong_zero;
   }
 
@@ -823,6 +825,7 @@
                                         FID_NativeGSSContext_lifetime));
   cb = getGSSCB(env, jcb);
   if ((*env)->ExceptionCheck(env)) {
+    free(cb);
     return NULL;
   }
 
@@ -927,6 +930,8 @@
   initGSSBuffer(env, jinToken, &inToken);
   cb = getGSSCB(env, jcb);
   if ((*env)->ExceptionCheck(env)) {
+    free(cb);
+    resetGSSBuffer(env, jinToken, &inToken);
     return NULL;
   }
   srcName = GSS_C_NO_NAME;
@@ -979,6 +984,7 @@
 
       /* return immediately if an exception has occurred */
       if ((*env)->ExceptionCheck(env)) {
+        resetGSSBuffer(env, jinToken, &inToken);
         return NULL;
       }
       sprintf(debugBuf, "[GSSLibStub_acceptContext] set targetName=%ld",
@@ -993,6 +999,7 @@
                                    ptr_to_jlong(srcName), jobj);
       /* return immediately if an exception has occurred */
       if ((*env)->ExceptionCheck(env)) {
+        resetGSSBuffer(env, jinToken, &inToken);
         return NULL;
       }
       sprintf(debugBuf, "[GSSLibStub_acceptContext] set srcName=%ld",
@@ -1019,6 +1026,7 @@
                                      ptr_to_jlong(delCred), jsrcName, jMech);
         /* return immediately if an exception has occurred */
         if ((*env)->ExceptionCheck(env)) {
+          resetGSSBuffer(env, jinToken, &inToken);
           return NULL;
         }
         (*env)->SetObjectField(env, jcontextSpi,
--- a/jdk/src/solaris/classes/sun/awt/X11/ListHelper.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/ListHelper.java	Wed Jul 05 19:00:49 2017 +0200
@@ -261,7 +261,7 @@
     }
 
     public int y2index(int y) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("y=" + y +", firstIdx=" + firstDisplayedIndex() +", itemHeight=" + getItemHeight()
                      + ",item_margin=" + ITEM_MARGIN);
         }
--- a/jdk/src/solaris/classes/sun/awt/X11/UnsafeXDisposerRecord.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/UnsafeXDisposerRecord.java	Wed Jul 05 19:00:49 2017 +0200
@@ -59,7 +59,7 @@
         XToolkit.awtLock();
         try {
             if (!disposed) {
-                if (XlibWrapper.isBuildInternal && "Java2D Disposer".equals(Thread.currentThread().getName()) && log.isLoggable(PlatformLogger.WARNING)) {
+                if (XlibWrapper.isBuildInternal && "Java2D Disposer".equals(Thread.currentThread().getName()) && log.isLoggable(PlatformLogger.Level.WARNING)) {
                     if (place != null) {
                         log.warning(name + " object was not disposed before finalization!", place);
                     } else {
--- a/jdk/src/solaris/classes/sun/awt/X11/XAWTXSettings.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XAWTXSettings.java	Wed Jul 05 19:00:49 2017 +0200
@@ -55,7 +55,7 @@
     }
 
     void initXSettings() {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Initializing XAWT XSettings");
         }
         settings = new XMSelection("_XSETTINGS");
@@ -68,27 +68,27 @@
     }
 
     public void ownerDeath(int screen, XMSelection sel, long deadOwner) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Owner " + deadOwner + " died for selection " + sel + " screen "+ screen);
         }
     }
 
 
     public void ownerChanged(int screen, XMSelection sel, long newOwner, long data, long timestamp) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("New Owner "+ newOwner + " for selection = " + sel + " screen " +screen );
         }
     }
 
     public void selectionChanged(int screen, XMSelection sel, long owner , XPropertyEvent event) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Selection changed on sel " + sel + " screen = " + screen + " owner = " + owner + " event = " + event);
         }
         updateXSettings(screen,owner);
     }
 
     void initPerScreenXSettings() {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Updating Per XSettings changes");
         }
 
@@ -124,7 +124,7 @@
     }
 
     private Map getUpdatedSettings(final long owner) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("owner =" + owner);
         }
         if (0 == owner) {
@@ -140,7 +140,7 @@
                 int status = getter.execute(XErrorHandler.IgnoreBadWindowHandler.getInstance());
 
                 if (status != XConstants.Success || getter.getData() == 0) {
-                    if (log.isLoggable(PlatformLogger.FINE)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("OH OH : getter failed  status = " + status );
                     }
                     settings = null;
@@ -148,7 +148,7 @@
 
                 long ptr = getter.getData();
 
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("noItems = " + getter.getNumberOfItems());
                 }
                 byte array[] = Native.toBytes(ptr,getter.getNumberOfItems());
--- a/jdk/src/solaris/classes/sun/awt/X11/XBaseMenuWindow.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XBaseMenuWindow.java	Wed Jul 05 19:00:49 2017 +0200
@@ -330,7 +330,7 @@
                 items.add(mp);
             }
         } else {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("WARNING: Attempt to add menu item without a peer");
             }
         }
@@ -351,7 +351,7 @@
             if (index < items.size()) {
                 items.remove(index);
             } else {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("WARNING: Attempt to remove non-existing menu item, index : " + index + ", item count : " + items.size());
                 }
             }
@@ -386,7 +386,7 @@
             XMenuPeer showingSubmenu = getShowingSubmenu();
             int newSelectedIndex = (item != null) ? items.indexOf(item) : -1;
             if (this.selectedIndex != newSelectedIndex) {
-                if (log.isLoggable(PlatformLogger.FINEST)) {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                     log.finest("Selected index changed, was : " + this.selectedIndex + ", new : " + newSelectedIndex);
                 }
                 this.selectedIndex = newSelectedIndex;
@@ -426,7 +426,7 @@
         try {
             synchronized(getMenuTreeLock()) {
                 if (showingSubmenu != submenuToShow) {
-                    if (log.isLoggable(PlatformLogger.FINEST)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                         log.finest("Changing showing submenu");
                     }
                     if (showingSubmenu != null) {
@@ -1122,7 +1122,7 @@
      * that grabs input focus
      */
     void doHandleJavaKeyEvent(KeyEvent event) {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer(event.toString());
         }
         if (event.getID() != KeyEvent.KEY_PRESSED) {
--- a/jdk/src/solaris/classes/sun/awt/X11/XBaseWindow.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XBaseWindow.java	Wed Jul 05 19:00:49 2017 +0200
@@ -160,7 +160,7 @@
      * with class-specific values and perform post-initialization actions.
      */
     void postInit(XCreateWindowParams params) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("WM name is " + getWMName());
         }
         updateWMName();
@@ -362,7 +362,7 @@
                     value_mask |= XConstants.CWBitGravity;
                 }
 
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("Creating window for " + this + " with the following attributes: \n" + params);
                 }
                 window = XlibWrapper.XCreateWindow(XToolkit.getDisplay(),
@@ -482,7 +482,7 @@
     }
 
     public void setSizeHints(long flags, int x, int y, int width, int height) {
-        if (insLog.isLoggable(PlatformLogger.FINER)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
             insLog.finer("Setting hints, flags " + XlibWrapper.hintsToString(flags));
         }
         XToolkit.awtLock();
@@ -545,7 +545,7 @@
             flags |= XUtilConstants.PWinGravity;
             hints.set_flags(flags);
             hints.set_win_gravity((int)XConstants.NorthWestGravity);
-            if (insLog.isLoggable(PlatformLogger.FINER)) {
+            if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
                 insLog.finer("Setting hints, resulted flags " + XlibWrapper.hintsToString(flags) +
                              ", values " + hints);
             }
@@ -599,7 +599,7 @@
     public void xRequestFocus(long time) {
         XToolkit.awtLock();
         try {
-            if (focusLog.isLoggable(PlatformLogger.FINER)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                 focusLog.finer("XSetInputFocus on " + Long.toHexString(getWindow()) + " with time " + time);
             }
             XlibWrapper.XSetInputFocus2(XToolkit.getDisplay(), getWindow(), time);
@@ -610,7 +610,7 @@
     public void xRequestFocus() {
         XToolkit.awtLock();
         try {
-            if (focusLog.isLoggable(PlatformLogger.FINER)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                 focusLog.finer("XSetInputFocus on " + Long.toHexString(getWindow()));
             }
              XlibWrapper.XSetInputFocus(XToolkit.getDisplay(), getWindow());
@@ -629,7 +629,7 @@
     }
 
     public void xSetVisible(boolean visible) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Setting visible on " + this + " to " + visible);
         }
         XToolkit.awtLock();
@@ -716,7 +716,7 @@
             insLog.warning("Attempt to resize uncreated window");
             throw new IllegalStateException("Attempt to resize uncreated window");
         }
-        if (insLog.isLoggable(PlatformLogger.FINE)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
             insLog.fine("Setting bounds on " + this + " to (" + x + ", " + y + "), " + width + "x" + height);
         }
         width = Math.max(MIN_SIZE, width);
@@ -834,7 +834,7 @@
      * The active grab overrides activated automatic grab.
      */
     public boolean grabInput() {
-        if (grabLog.isLoggable(PlatformLogger.FINE)) {
+        if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
             grabLog.fine("Grab input on {0}", this);
         }
 
@@ -899,7 +899,7 @@
         XToolkit.awtLock();
         try {
             XBaseWindow grabWindow = XAwtState.getGrabWindow();
-            if (grabLog.isLoggable(PlatformLogger.FINE)) {
+            if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
                 grabLog.fine("UnGrab input on {0}", grabWindow);
             }
             if (grabWindow != null) {
@@ -943,7 +943,7 @@
         mapped = false;
     }
     public void handleReparentNotifyEvent(XEvent xev) {
-        if (eventLog.isLoggable(PlatformLogger.FINER)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINER)) {
             XReparentEvent msg = xev.get_xreparent();
             eventLog.finer(msg.toString());
         }
@@ -953,7 +953,7 @@
         if (XPropertyCache.isCachingSupported()) {
             XPropertyCache.clearCache(window, XAtom.get(msg.get_atom()));
         }
-        if (eventLog.isLoggable(PlatformLogger.FINER)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINER)) {
             eventLog.finer("{0}", msg);
         }
     }
@@ -983,7 +983,7 @@
     }
 
     public void handleClientMessage(XEvent xev) {
-        if (eventLog.isLoggable(PlatformLogger.FINER)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINER)) {
             XClientMessageEvent msg = xev.get_xclient();
             eventLog.finer(msg.toString());
         }
@@ -1039,7 +1039,7 @@
     }
     public void handleConfigureNotifyEvent(XEvent xev) {
         XConfigureEvent xe = xev.get_xconfigure();
-        if (insLog.isLoggable(PlatformLogger.FINER)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
             insLog.finer("Configure, {0}", xe);
         }
         x = xe.get_x();
@@ -1092,7 +1092,7 @@
     }
 
     public void dispatchEvent(XEvent xev) {
-        if (eventLog.isLoggable(PlatformLogger.FINEST)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
             eventLog.finest(xev.toString());
         }
         int type = xev.get_type();
--- a/jdk/src/solaris/classes/sun/awt/X11/XCheckboxPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XCheckboxPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -172,7 +172,7 @@
             Checkbox cb = (Checkbox) e.getSource();
 
             if (cb.contains(e.getX(), e.getY())) {
-                if (log.isLoggable(PlatformLogger.FINER)) {
+                if (log.isLoggable(PlatformLogger.Level.FINER)) {
                     log.finer("mousePressed() on " + target.getName() + " : armed = " + armed + ", pressed = " + pressed
                               + ", selected = " + selected + ", enabled = " + isEnabled());
                 }
@@ -190,7 +190,7 @@
     }
 
     public void mouseReleased(MouseEvent e) {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("mouseReleased() on " + target.getName() + ": armed = " + armed + ", pressed = " + pressed
                       + ", selected = " + selected + ", enabled = " + isEnabled());
         }
@@ -215,7 +215,7 @@
     }
 
     public void mouseEntered(MouseEvent e) {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("mouseEntered() on " + target.getName() + ": armed = " + armed + ", pressed = " + pressed
                       + ", selected = " + selected + ", enabled = " + isEnabled());
         }
@@ -226,7 +226,7 @@
     }
 
     public void mouseExited(MouseEvent e) {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("mouseExited() on " + target.getName() + ": armed = " + armed + ", pressed = " + pressed
                       + ", selected = " + selected + ", enabled = " + isEnabled());
         }
--- a/jdk/src/solaris/classes/sun/awt/X11/XChoicePeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XChoicePeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -892,7 +892,7 @@
                 if (transX > 0 && transX < width &&
                     transY > 0 && transY < height) {
                     int newIdx = helper.y2index(transY);
-                    if (log.isLoggable(PlatformLogger.FINE)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("transX=" + transX + ", transY=" + transY
                                  + ",width=" + width + ", height=" + height
                                  + ", newIdx=" + newIdx + " on " + target);
--- a/jdk/src/solaris/classes/sun/awt/X11/XComponentPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XComponentPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -214,7 +214,7 @@
      * Called when component receives focus
      */
     public void focusGained(FocusEvent e) {
-        if (focusLog.isLoggable(PlatformLogger.FINE)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
             focusLog.fine("{0}", e);
         }
         bHasFocus = true;
@@ -224,7 +224,7 @@
      * Called when component loses focus
      */
     public void focusLost(FocusEvent e) {
-        if (focusLog.isLoggable(PlatformLogger.FINE)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
             focusLog.fine("{0}", e);
         }
         bHasFocus = false;
@@ -298,7 +298,7 @@
           case XKeyboardFocusManagerPeer.SNFH_SUCCESS_PROCEED:
               // Currently we just generate focus events like we deal with lightweight instead of calling
               // XSetInputFocus on native window
-              if (focusLog.isLoggable(PlatformLogger.FINER)) {
+              if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                   focusLog.finer("Proceeding with request to " +
                                  lightweightChild + " in " + target);
               }
@@ -325,7 +325,7 @@
                */
               boolean res = wpeer.requestWindowFocus(null);
 
-              if (focusLog.isLoggable(PlatformLogger.FINER)) {
+              if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                   focusLog.finer("Requested window focus: " + res);
               }
               // If parent window can be made focused and has been made focused(synchronously)
@@ -347,7 +347,7 @@
     }
 
     private boolean rejectFocusRequestHelper(String logMsg) {
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer(logMsg);
         }
         XKeyboardFocusManagerPeer.removeLastFocusRequest(target);
@@ -355,7 +355,7 @@
     }
 
     void handleJavaFocusEvent(AWTEvent e) {
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer(e.toString());
         }
         if (e.getID() == FocusEvent.FOCUS_GAINED) {
@@ -386,7 +386,7 @@
      * @see java.awt.peer.ComponentPeer
      */
     public void setEnabled(final boolean value) {
-        if (enableLog.isLoggable(PlatformLogger.FINE)) {
+        if (enableLog.isLoggable(PlatformLogger.Level.FINE)) {
             enableLog.fine("{0}ing {1}", (value ? "Enabl" : "Disabl"), this);
         }
         boolean status = value;
@@ -467,13 +467,13 @@
         if (true) {
             switch(e.getID()) {
               case PaintEvent.UPDATE:
-                  if (log.isLoggable(PlatformLogger.FINER)) {
+                  if (log.isLoggable(PlatformLogger.Level.FINER)) {
                       log.finer("XCP coalescePaintEvent : UPDATE : add : x = " +
                             r.x + ", y = " + r.y + ", width = " + r.width + ",height = " + r.height);
                   }
                   return;
               case PaintEvent.PAINT:
-                  if (log.isLoggable(PlatformLogger.FINER)) {
+                  if (log.isLoggable(PlatformLogger.Level.FINER)) {
                       log.finer("XCP coalescePaintEvent : PAINT : add : x = " +
                             r.x + ", y = " + r.y + ", width = " + r.width + ",height = " + r.height);
                   }
@@ -640,7 +640,7 @@
     }
 
     public void setBackground(Color c) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Set background to " + c);
         }
         synchronized (getStateLock()) {
@@ -651,7 +651,7 @@
     }
 
     public void setForeground(Color c) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Set foreground to " + c);
         }
         synchronized (getStateLock()) {
@@ -672,7 +672,7 @@
      * @since     JDK1.0
      */
     public FontMetrics getFontMetrics(Font font) {
-        if (fontLog.isLoggable(PlatformLogger.FINE)) {
+        if (fontLog.isLoggable(PlatformLogger.Level.FINE)) {
             fontLog.fine("Getting font metrics for " + font);
         }
         return sun.font.FontDesignMetrics.getMetrics(font);
@@ -1158,7 +1158,7 @@
     public void createBuffers(int numBuffers, BufferCapabilities caps)
       throws AWTException
     {
-        if (buffersLog.isLoggable(PlatformLogger.FINE)) {
+        if (buffersLog.isLoggable(PlatformLogger.Level.FINE)) {
             buffersLog.fine("createBuffers(" + numBuffers + ", " + caps + ")");
         }
         // set the caps first, they're used when creating the bb
@@ -1176,7 +1176,7 @@
     public void flip(int x1, int y1, int x2, int y2,
                      BufferCapabilities.FlipContents flipAction)
     {
-        if (buffersLog.isLoggable(PlatformLogger.FINE)) {
+        if (buffersLog.isLoggable(PlatformLogger.Level.FINE)) {
             buffersLog.fine("flip(" + flipAction + ")");
         }
         if (backBuffer == 0) {
@@ -1187,7 +1187,7 @@
     }
 
     public Image getBackBuffer() {
-        if (buffersLog.isLoggable(PlatformLogger.FINE)) {
+        if (buffersLog.isLoggable(PlatformLogger.Level.FINE)) {
             buffersLog.fine("getBackBuffer()");
         }
         if (backBuffer == 0) {
@@ -1197,7 +1197,7 @@
     }
 
     public void destroyBuffers() {
-        if (buffersLog.isLoggable(PlatformLogger.FINE)) {
+        if (buffersLog.isLoggable(PlatformLogger.Level.FINE)) {
             buffersLog.fine("destroyBuffers()");
         }
         graphicsConfig.destroyBackBuffer(backBuffer);
@@ -1232,7 +1232,7 @@
      * ButtonPress, ButtonRelease, KeyPress, KeyRelease, EnterNotify, LeaveNotify, MotionNotify
      */
     protected boolean isEventDisabled(XEvent e) {
-        if (enableLog.isLoggable(PlatformLogger.FINEST)) {
+        if (enableLog.isLoggable(PlatformLogger.Level.FINEST)) {
             enableLog.finest("Component is {1}, checking for disabled event {0}", e, (isEnabled()?"enabled":"disable"));
         }
         if (!isEnabled()) {
@@ -1244,7 +1244,7 @@
               case XConstants.EnterNotify:
               case XConstants.LeaveNotify:
               case XConstants.MotionNotify:
-                  if (enableLog.isLoggable(PlatformLogger.FINER)) {
+                  if (enableLog.isLoggable(PlatformLogger.Level.FINER)) {
                       enableLog.finer("Event {0} is disable", e);
                   }
                   return true;
@@ -1367,7 +1367,7 @@
      */
     public void applyShape(Region shape) {
         if (XlibUtil.isShapingSupported()) {
-            if (shapeLog.isLoggable(PlatformLogger.FINER)) {
+            if (shapeLog.isLoggable(PlatformLogger.Level.FINER)) {
                 shapeLog.finer(
                         "*** INFO: Setting shape: PEER: " + this
                         + "; WINDOW: " + getWindow()
@@ -1397,7 +1397,7 @@
                 XToolkit.awtUnlock();
             }
         } else {
-            if (shapeLog.isLoggable(PlatformLogger.FINER)) {
+            if (shapeLog.isLoggable(PlatformLogger.Level.FINER)) {
                 shapeLog.finer("*** WARNING: Shaping is NOT supported!");
             }
         }
--- a/jdk/src/solaris/classes/sun/awt/X11/XContentWindow.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XContentWindow.java	Wed Jul 05 19:00:49 2017 +0200
@@ -115,7 +115,7 @@
             if (in != null) {
                 newBounds.setLocation(-in.left, -in.top);
             }
-            if (insLog.isLoggable(PlatformLogger.FINE)) {
+            if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
                 insLog.fine("Setting content bounds {0}, old bounds {1}",
                             newBounds, getBounds());
             }
--- a/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,7 @@
 import java.awt.event.InvocationEvent;
 import java.awt.event.WindowEvent;
 
+import sun.awt.IconInfo;
 import sun.util.logging.PlatformLogger;
 
 import sun.awt.AWTAccessor;
@@ -78,7 +79,7 @@
         Rectangle bounds = (Rectangle)params.get(BOUNDS);
         dimensions = new WindowDimensions(bounds, getRealInsets(), false);
         params.put(BOUNDS, dimensions.getClientRect());
-        if (insLog.isLoggable(PlatformLogger.FINE)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
             insLog.fine("Initial dimensions {0}", dimensions);
         }
 
@@ -108,7 +109,7 @@
         focusProxy = createFocusProxy();
     }
 
-    void setIconHints(java.util.List<XIconInfo> icons) {
+    void setIconHints(java.util.List<IconInfo> icons) {
         if (!XWM.getWM().setNetWMIcon(this, icons)) {
             if (icons.size() > 0) {
                 if (iconWindow == null) {
@@ -181,7 +182,7 @@
     }
 
     public void setTitle(String title) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Title is " + title);
         }
         winAttr.title = title;
@@ -231,7 +232,7 @@
 
         // If we somehow received focus events forward it instead to proxy
         // FIXME: Shouldn't we instead check for inferrior?
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer("Received focus event on shell: " + xfe);
         }
 //         focusProxy.xRequestFocus();
@@ -275,7 +276,7 @@
             wm_set_insets = XWM.getInsetsFromProp(getWindow(), changedAtom);
         }
 
-        if (insLog.isLoggable(PlatformLogger.FINER)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
             insLog.finer("FRAME_EXTENTS: {0}", wm_set_insets);
         }
 
@@ -304,7 +305,7 @@
 
     public void handleReparentNotifyEvent(XEvent xev) {
         XReparentEvent  xe = xev.get_xreparent();
-        if (insLog.isLoggable(PlatformLogger.FINE)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
             insLog.fine(xe.toString());
         }
         reparent_serial = xe.get_serial();
@@ -345,7 +346,7 @@
                 // Check if we have insets provided by the WM
                 Insets correctWM = getWMSetInsets(null);
                 if (correctWM != null) {
-                    if (insLog.isLoggable(PlatformLogger.FINER)) {
+                    if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
                         insLog.finer("wm-provided insets {0}", correctWM);
                     }
                     // If these insets are equal to our current insets - no actions are necessary
@@ -360,7 +361,7 @@
                 } else {
                     correctWM = XWM.getWM().getInsets(this, xe.get_window(), xe.get_parent());
 
-                    if (insLog.isLoggable(PlatformLogger.FINER)) {
+                    if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
                         if (correctWM != null) {
                             insLog.finer("correctWM {0}", correctWM);
                         } else {
@@ -386,7 +387,7 @@
              * initial insets were wrong (most likely they were).
              */
             Insets correction = difference(correctWM, currentInsets);
-            if (insLog.isLoggable(PlatformLogger.FINEST)) {
+            if (insLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 insLog.finest("Corrention {0}", correction);
             }
             if (!isNull(correction)) {
@@ -398,7 +399,7 @@
                 //update minimum size hints
                 updateMinSizeHints();
             }
-            if (insLog.isLoggable(PlatformLogger.FINER)) {
+            if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
                 insLog.finer("Dimensions before reparent: " + dimensions);
             }
 
@@ -473,7 +474,7 @@
     public Insets getInsets() {
         Insets in = copy(getRealInsets());
         in.top += getMenuBarHeight();
-        if (insLog.isLoggable(PlatformLogger.FINEST)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINEST)) {
             insLog.finest("Get insets returns {0}", in);
         }
         return in;
@@ -503,7 +504,7 @@
     public void reshape(WindowDimensions newDimensions, int op,
                         boolean userReshape)
     {
-        if (insLog.isLoggable(PlatformLogger.FINE)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
             insLog.fine("Reshaping " + this + " to " + newDimensions + " op " + op + " user reshape " + userReshape);
         }
         if (userReshape) {
@@ -524,7 +525,7 @@
         XToolkit.awtLock();
         try {
             if (!isReparented() || !isVisible()) {
-                if (insLog.isLoggable(PlatformLogger.FINE)) {
+                if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
                     insLog.fine("- not reparented({0}) or not visible({1}), default reshape",
                            Boolean.valueOf(isReparented()), Boolean.valueOf(visible));
                 }
@@ -632,7 +633,7 @@
               dims.setSize(width, height);
               break;
         }
-        if (insLog.isLoggable(PlatformLogger.FINE)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
             insLog.fine("For the operation {0} new dimensions are {1}",
                         operationToString(operation), dims);
         }
@@ -665,7 +666,7 @@
     public void handleConfigureNotifyEvent(XEvent xev) {
         assert (SunToolkit.isAWTLockHeldByCurrentThread());
         XConfigureEvent xe = xev.get_xconfigure();
-        if (insLog.isLoggable(PlatformLogger.FINE)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
             insLog.fine("Configure notify {0}", xe);
         }
 
@@ -704,7 +705,7 @@
          * it!!!! or we wind up in a bogus location.
          */
         int runningWM = XWM.getWMID();
-        if (insLog.isLoggable(PlatformLogger.FINE)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
             insLog.fine("reparented={0}, visible={1}, WM={2}, decorations={3}",
                         isReparented(), isVisible(), runningWM, getDecorations());
         }
@@ -718,7 +719,7 @@
         if (!insets_corrected && getDecorations() != XWindowAttributesData.AWT_DECOR_NONE) {
             long parent = XlibUtil.getParentWindow(window);
             Insets correctWM = (parent != -1) ? XWM.getWM().getInsets(this, window, parent) : null;
-            if (insLog.isLoggable(PlatformLogger.FINER)) {
+            if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
                 if (correctWM != null) {
                     insLog.finer("Configure notify - insets : " + correctWM);
                 } else {
@@ -758,7 +759,7 @@
                 case XWM.SAWFISH_WM:
                 {
                     Point xlocation = queryXLocation();
-                    if (log.isLoggable(PlatformLogger.FINE)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("New X location: {0}", xlocation);
                     }
                     if (xlocation != null) {
@@ -777,7 +778,7 @@
                 copy(currentInsets),
                 true);
 
-        if (insLog.isLoggable(PlatformLogger.FINER)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
             insLog.finer("Insets are {0}, new dimensions {1}",
                      currentInsets, newDimensions);
         }
@@ -815,7 +816,7 @@
     }
 
     public void setShellBounds(Rectangle rec) {
-        if (insLog.isLoggable(PlatformLogger.FINE)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
             insLog.fine("Setting shell bounds on " + this + " to " + rec);
         }
         XToolkit.awtLock();
@@ -829,7 +830,7 @@
         }
     }
     public void setShellSize(Rectangle rec) {
-        if (insLog.isLoggable(PlatformLogger.FINE)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
             insLog.fine("Setting shell size on " + this + " to " + rec);
         }
         XToolkit.awtLock();
@@ -842,7 +843,7 @@
         }
     }
     public void setShellPosition(Rectangle rec) {
-        if (insLog.isLoggable(PlatformLogger.FINE)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
             insLog.fine("Setting shell position on " + this + " to " + rec);
         }
         XToolkit.awtLock();
@@ -944,7 +945,7 @@
                 return toGlobal(0,0);
             } else {
                 Point location = target.getLocation();
-                if (insLog.isLoggable(PlatformLogger.FINE)) {
+                if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
                     insLog.fine("getLocationOnScreen {0} not reparented: {1} ",
                                 this, location);
                 }
@@ -984,7 +985,7 @@
     }
 
     public void setVisible(boolean vis) {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("Setting {0} to visible {1}", this, Boolean.valueOf(vis));
         }
         if (vis && !isVisible()) {
@@ -1037,7 +1038,7 @@
     }
 
     private void handleWmTakeFocus(XClientMessageEvent cl) {
-        if (focusLog.isLoggable(PlatformLogger.FINE)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
             focusLog.fine("WM_TAKE_FOCUS on {0}", this);
         }
         requestWindowFocus(cl.get_data(1), true);
@@ -1052,11 +1053,11 @@
         // by "proxy" - invisible mapped window. When we want to set X input focus to
         // toplevel set it on proxy instead.
         if (focusProxy == null) {
-            if (focusLog.isLoggable(PlatformLogger.WARNING)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.WARNING)) {
                 focusLog.warning("Focus proxy is null for " + this);
             }
         } else {
-            if (focusLog.isLoggable(PlatformLogger.FINE)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
                 focusLog.fine("Requesting focus to proxy: " + focusProxy);
             }
             if (timeProvided) {
@@ -1150,7 +1151,7 @@
         Window focusedWindow = XKeyboardFocusManagerPeer.getInstance().getCurrentFocusedWindow();
         Window activeWindow = XWindowPeer.getDecoratedOwner(focusedWindow);
 
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer("Current window is: active={0}, focused={1}",
                        Boolean.valueOf(target == activeWindow),
                        Boolean.valueOf(target == focusedWindow));
@@ -1177,20 +1178,20 @@
                 return true;
             }
             Window realNativeFocusedWindow = XWindowPeer.getNativeFocusedWindow();
-            if (focusLog.isLoggable(PlatformLogger.FINEST)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 focusLog.finest("Real native focused window: " + realNativeFocusedWindow +
                             "\nKFM's focused window: " + focusedWindow);
             }
 
             // A workaround for Metacity. See 6522725, 6613426, 7147075.
             if (target == realNativeFocusedWindow && XWM.getWMID() == XWM.METACITY_WM) {
-                if (focusLog.isLoggable(PlatformLogger.FINE)) {
+                if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
                     focusLog.fine("The window is already natively focused.");
                 }
                 return true;
             }
         }
-        if (focusLog.isLoggable(PlatformLogger.FINE)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
             focusLog.fine("Requesting focus to " + (this == toFocus ? "this window" : toFocus));
         }
 
--- a/jdk/src/solaris/classes/sun/awt/X11/XDnDDragSourceProtocol.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XDnDDragSourceProtocol.java	Wed Jul 05 19:00:49 2017 +0200
@@ -395,7 +395,7 @@
                 return false;
             }
 
-            if (logger.isLoggable(PlatformLogger.FINEST)) {
+            if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                 logger.finest("        sourceWindow=" + sourceWindow +
                               " get_window=" + xclient.get_window() +
                               " xclient=" + xclient);
--- a/jdk/src/solaris/classes/sun/awt/X11/XDnDDropTargetProtocol.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XDnDDropTargetProtocol.java	Wed Jul 05 19:00:49 2017 +0200
@@ -993,7 +993,7 @@
             if (sourceFormats != null && sourceFormats.length > 3) {
                 data1 |= XDnDConstants.XDND_DATA_TYPES_BIT;
             }
-            if (logger.isLoggable(PlatformLogger.FINEST)) {
+            if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                 logger.finest("         "
                               + " entryVersion=" + version
                               + " sourceProtocolVersion=" +
@@ -1052,7 +1052,7 @@
 
     public boolean forwardEventToEmbedded(long embedded, long ctxt,
                                           int eventID) {
-        if (logger.isLoggable(PlatformLogger.FINEST)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
             logger.finest("        ctxt=" + ctxt +
                           " type=" + (ctxt != 0 ?
                                       getMessageType(new
@@ -1080,7 +1080,7 @@
                 long data3 = Native.getLong(ctxt + size + 2 * Native.getLongSize());
                 long data4 = Native.getLong(ctxt + size + 3 * Native.getLongSize());
 
-                if (logger.isLoggable(PlatformLogger.FINEST)) {
+                if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                     logger.finest("         1 "
                                   + " embedded=" + embedded
                                   + " source=" + xclient.get_data(0)
@@ -1114,7 +1114,7 @@
 
                                 if ((XErrorHandlerUtil.saved_error != null) &&
                                     (XErrorHandlerUtil.saved_error.get_error_code() != XConstants.Success)) {
-                                    if (logger.isLoggable(PlatformLogger.WARNING)) {
+                                    if (logger.isLoggable(PlatformLogger.Level.WARNING)) {
                                         logger.warning("Cannot set XdndTypeList on the proxy window");
                                     }
                                 }
@@ -1122,7 +1122,7 @@
                                 XToolkit.awtUnlock();
                             }
                         } else {
-                            if (logger.isLoggable(PlatformLogger.WARNING)) {
+                            if (logger.isLoggable(PlatformLogger.Level.WARNING)) {
                                 logger.warning("Cannot read XdndTypeList from the source window");
                             }
                         }
@@ -1137,7 +1137,7 @@
                 overXEmbedClient = true;
             }
 
-            if (logger.isLoggable(PlatformLogger.FINEST)) {
+            if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                 logger.finest("         2 "
                               + " embedded=" + embedded
                               + " xclient=" + xclient);
--- a/jdk/src/solaris/classes/sun/awt/X11/XDragSourceContextPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XDragSourceContextPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -542,7 +542,7 @@
             return false;
         }
 
-        if (logger.isLoggable(PlatformLogger.FINEST)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
             logger.finest("        proxyModeSourceWindow=" +
                           getProxyModeSourceWindow() +
                           " ev=" + ev);
--- a/jdk/src/solaris/classes/sun/awt/X11/XDropTargetContextPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XDropTargetContextPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -199,7 +199,7 @@
                    structure. */
                 long ctxt = getNativeDragContext();
 
-                if (logger.isLoggable(PlatformLogger.FINER)) {
+                if (logger.isLoggable(PlatformLogger.Level.FINER)) {
                     logger.finer("        processing " + event + " ctxt=" + ctxt +
                                  " consumed=" + event.isConsumed());
                 }
--- a/jdk/src/solaris/classes/sun/awt/X11/XDropTargetProtocol.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XDropTargetProtocol.java	Wed Jul 05 19:00:49 2017 +0200
@@ -116,7 +116,7 @@
                                                            XClientMessageEvent xclient) {
         EmbedderRegistryEntry entry = getEmbedderRegistryEntry(toplevel);
 
-        if (logger.isLoggable(PlatformLogger.FINEST)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
             logger.finest("        entry={0}", entry);
         }
         // Window not registered as an embedder for this protocol.
@@ -124,7 +124,7 @@
             return false;
         }
 
-        if (logger.isLoggable(PlatformLogger.FINEST)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
             logger.finest("        entry.isOverriden()={0}", entry.isOverriden());
         }
         // Window didn't have an associated drop site, so there is no need
@@ -137,7 +137,7 @@
 
         long proxy = entry.getProxy();
 
-        if (logger.isLoggable(PlatformLogger.FINEST)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
             logger.finest("        proxy={0} toplevel={1}", proxy, toplevel);
         }
         if (proxy == 0) {
--- a/jdk/src/solaris/classes/sun/awt/X11/XDropTargetRegistry.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XDropTargetRegistry.java	Wed Jul 05 19:00:49 2017 +0200
@@ -614,7 +614,7 @@
         if (info != null &&
             info.getProtocolVersion() >= XDnDConstants.XDND_MIN_PROTOCOL_VERSION) {
 
-            if (logger.isLoggable(PlatformLogger.FINE)) {
+            if (logger.isLoggable(PlatformLogger.Level.FINE)) {
                 logger.fine("        XEmbed drop site will be registered for " + Long.toHexString(clientWindow));
             }
             registerEmbeddedDropSite(canvasWindow, clientWindow);
@@ -628,14 +628,14 @@
                 dropTargetProtocol.registerEmbeddedDropSite(clientWindow);
             }
 
-            if (logger.isLoggable(PlatformLogger.FINE)) {
+            if (logger.isLoggable(PlatformLogger.Level.FINE)) {
                 logger.fine("        XEmbed drop site has been registered for " + Long.toHexString(clientWindow));
             }
         }
     }
 
     public void unregisterXEmbedClient(long canvasWindow, long clientWindow) {
-        if (logger.isLoggable(PlatformLogger.FINE)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINE)) {
             logger.fine("        XEmbed drop site will be unregistered for " + Long.toHexString(clientWindow));
         }
         Iterator dropTargetProtocols =
@@ -649,7 +649,7 @@
 
         unregisterEmbeddedDropSite(canvasWindow, clientWindow);
 
-        if (logger.isLoggable(PlatformLogger.FINE)) {
+        if (logger.isLoggable(PlatformLogger.Level.FINE)) {
             logger.fine("        XEmbed drop site has beed unregistered for " + Long.toHexString(clientWindow));
         }
     }
--- a/jdk/src/solaris/classes/sun/awt/X11/XEmbedCanvasPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbedCanvasPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -123,7 +123,7 @@
     }
 
     void initDispatching() {
-        if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
             xembedLog.fine("Init embedding for " + Long.toHexString(xembed.handle));
         }
         XToolkit.awtLock();
@@ -142,7 +142,7 @@
     }
 
     void endDispatching() {
-        if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
             xembedLog.fine("End dispatching for " + Long.toHexString(xembed.handle));
         }
         XToolkit.awtLock();
@@ -164,7 +164,7 @@
     }
 
     void childDestroyed() {
-        if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
             xembedLog.fine("Child " + Long.toHexString(xembed.handle) + " has self-destroyed.");
         }
         endDispatching();
@@ -196,10 +196,10 @@
         switch (ev.get_type()) {
           case XConstants.CreateNotify:
               XCreateWindowEvent cr = ev.get_xcreatewindow();
-              if (xembedLog.isLoggable(PlatformLogger.FINEST)) {
+              if (xembedLog.isLoggable(PlatformLogger.Level.FINEST)) {
                   xembedLog.finest("Message on embedder: " + cr);
               }
-              if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+              if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                   xembedLog.finer("Create notify for parent " + Long.toHexString(cr.get_parent()) +
                                   ", window " + Long.toHexString(cr.get_window()));
               }
@@ -207,20 +207,20 @@
               break;
           case XConstants.DestroyNotify:
               XDestroyWindowEvent dn = ev.get_xdestroywindow();
-              if (xembedLog.isLoggable(PlatformLogger.FINEST)) {
+              if (xembedLog.isLoggable(PlatformLogger.Level.FINEST)) {
                   xembedLog.finest("Message on embedder: " + dn);
               }
-              if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+              if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                   xembedLog.finer("Destroy notify for parent: " + dn);
               }
               childDestroyed();
               break;
           case XConstants.ReparentNotify:
               XReparentEvent rep = ev.get_xreparent();
-              if (xembedLog.isLoggable(PlatformLogger.FINEST)) {
+              if (xembedLog.isLoggable(PlatformLogger.Level.FINEST)) {
                   xembedLog.finest("Message on embedder: " + rep);
               }
-              if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+              if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                   xembedLog.finer("Reparent notify for parent " + Long.toHexString(rep.get_parent()) +
                                   ", window " + Long.toHexString(rep.get_window()) +
                                   ", event " + Long.toHexString(rep.get_event()));
@@ -323,7 +323,7 @@
     }
 
     void childResized() {
-        if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
             Rectangle bounds = getClientBounds();
             xembedLog.finer("Child resized: " + bounds);
             // It is not required to update embedder's size when client size changes
@@ -388,7 +388,7 @@
     }
 
     void detachChild() {
-        if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
             xembedLog.fine("Detaching child " + Long.toHexString(xembed.handle));
         }
         /**
@@ -471,7 +471,7 @@
         try {
             XKeyEvent ke = new XKeyEvent(data);
             ke.set_window(xembed.handle);
-            if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+            if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
                 xembedLog.fine("Forwarding native key event: " + ke);
             }
             XToolkit.awtLock();
@@ -504,7 +504,7 @@
         postEvent(new InvocationEvent(target, new Runnable() {
                 public void run() {
                     GrabbedKey grab = new GrabbedKey(keysym, modifiers);
-                    if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+                    if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
                         xembedLog.fine("Grabbing key: " + grab);
                     }
                     synchronized(GRAB_LOCK) {
@@ -518,7 +518,7 @@
         postEvent(new InvocationEvent(target, new Runnable() {
                 public void run() {
                     GrabbedKey grab = new GrabbedKey(keysym, modifiers);
-                    if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+                    if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
                         xembedLog.fine("UnGrabbing key: " + grab);
                     }
                     synchronized(GRAB_LOCK) {
@@ -533,7 +533,7 @@
                 public void run() {
                     AWTKeyStroke stroke = xembed.getKeyStrokeForKeySym(keysym, modifiers);
                     if (stroke != null) {
-                        if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+                        if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
                             xembedLog.fine("Registering accelerator " + accel_id + " for " + stroke);
                         }
                         synchronized(ACCEL_LOCK) {
@@ -553,7 +553,7 @@
                     synchronized(ACCEL_LOCK) {
                         stroke = accelerators.get(accel_id);
                         if (stroke != null) {
-                            if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+                            if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
                                 xembedLog.fine("Unregistering accelerator: " + accel_id);
                             }
                             accelerators.remove(accel_id);
@@ -601,7 +601,7 @@
 
         boolean result = false;
 
-        if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
             xembedLog.finer("Post-processing event " + e);
         }
 
@@ -616,7 +616,7 @@
             }
         }
         if (exists) {
-            if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+            if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
                 xembedLog.fine("Activating accelerator " + accel_id);
             }
             xembed.sendMessage(xembed.handle, XEMBED_ACTIVATE_ACCELERATOR, accel_id, 0, 0); // FIXME: How about overloaded?
@@ -630,7 +630,7 @@
             exists = grabbed_keys.contains(key);
         }
         if (exists) {
-            if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+            if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
                 xembedLog.fine("Forwarding grabbed key " + e);
             }
             forwardKeyEvent(e);
@@ -651,11 +651,11 @@
     public void handleClientMessage(XEvent xev) {
         super.handleClientMessage(xev);
         XClientMessageEvent msg = xev.get_xclient();
-        if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
             xembedLog.finer("Client message to embedder: " + msg);
         }
         if (msg.get_message_type() == xembed.XEmbed.getAtom()) {
-            if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+            if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
                 xembedLog.fine(xembed.XEmbedMessageToString(msg));
             }
         }
@@ -723,7 +723,7 @@
     }
 
     public boolean processXEmbedDnDEvent(long ctxt, int eventID) {
-        if (xembedLog.isLoggable(PlatformLogger.FINEST)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINEST)) {
             xembedLog.finest("     Drop target=" + target.getDropTarget());
         }
         if (target.getDropTarget() instanceof XEmbedDropTarget) {
@@ -758,7 +758,7 @@
                 boolean new_mapped = (flags & XEMBED_MAPPED) != 0;
                 boolean currently_mapped = XlibUtil.getWindowMapState(handle) != XConstants.IsUnmapped;
                 if (new_mapped != currently_mapped) {
-                    if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+                    if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                         xembedLog.finer("Mapping state of the client has changed, old state: " + currently_mapped + ", new state: " + new_mapped);
                     }
                     if (new_mapped) {
@@ -777,7 +777,7 @@
                         }
                     }
                 } else {
-                    if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+                    if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                         xembedLog.finer("Mapping state didn't change, mapped: " + currently_mapped);
                     }
                 }
@@ -790,7 +790,7 @@
         public void handlePropertyNotify(XEvent xev) {
             if (isXEmbedActive()) {
                 XPropertyEvent ev = xev.get_xproperty();
-                if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+                if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                     xembedLog.finer("Property change on client: " + ev);
                 }
                 if (ev.get_atom() == XAtom.XA_WM_NORMAL_HINTS) {
@@ -813,7 +813,7 @@
         void handleConfigureNotify(XEvent xev) {
             if (isXEmbedActive()) {
                 XConfigureEvent ev = xev.get_xconfigure();
-                if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+                if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                     xembedLog.finer("Bounds change on client: " + ev);
                 }
                 if (xev.get_xany().get_window() == handle) {
@@ -866,7 +866,7 @@
 
                 // We recognize only these masks
                 modifiers = ke.get_state() & (XConstants.ShiftMask | XConstants.ControlMask | XConstants.LockMask);
-                if (xembedLog.isLoggable(PlatformLogger.FINEST)) {
+                if (xembedLog.isLoggable(PlatformLogger.Level.FINEST)) {
                     xembedLog.finest("Mapped " + e + " to " + this);
                 }
             } finally {
--- a/jdk/src/solaris/classes/sun/awt/X11/XEmbedClientHelper.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbedClientHelper.java	Wed Jul 05 19:00:49 2017 +0200
@@ -53,7 +53,7 @@
     }
 
     void setClient(XEmbeddedFramePeer client) {
-        if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
             xembedLog.fine("XEmbed client: " + client);
         }
         if (embedded != null) {
@@ -67,7 +67,7 @@
     }
 
     void install() {
-        if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
             xembedLog.fine("Installing xembedder on " + embedded);
         }
         long[] info = new long[] { XEMBED_VERSION, XEMBED_MAPPED };
@@ -95,11 +95,11 @@
 
     void handleClientMessage(XEvent xev) {
         XClientMessageEvent msg = xev.get_xclient();
-        if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
             xembedLog.fine(msg.toString());
         }
         if (msg.get_message_type() == XEmbed.getAtom()) {
-            if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+            if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
                 xembedLog.fine("Embedded message: " + msgidToString((int)msg.get_data(1)));
             }
             switch ((int)msg.get_data(1)) {
--- a/jdk/src/solaris/classes/sun/awt/X11/XEmbedHelper.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbedHelper.java	Wed Jul 05 19:00:49 2017 +0200
@@ -82,13 +82,13 @@
     XEmbedHelper() {
         if (XEmbed == null) {
             XEmbed = XAtom.get("_XEMBED");
-            if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+            if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                 xembedLog.finer("Created atom " + XEmbed.toString());
             }
         }
         if (XEmbedInfo == null) {
             XEmbedInfo = XAtom.get("_XEMBED_INFO");
-            if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+            if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                 xembedLog.finer("Created atom " + XEmbedInfo.toString());
             }
         }
@@ -110,7 +110,7 @@
         msg.set_data(4, data2);
         XToolkit.awtLock();
         try {
-            if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+            if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
                 xembedLog.fine("Sending " + XEmbedMessageToString(msg));
             }
             XlibWrapper.XSendEvent(XToolkit.getDisplay(), window, false, XConstants.NoEventMask, msg.pData);
--- a/jdk/src/solaris/classes/sun/awt/X11/XEmbedServerTester.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbedServerTester.java	Wed Jul 05 19:00:49 2017 +0200
@@ -81,7 +81,7 @@
             throw new RuntimeException("Can't create robot");
         }
         initAccel();
-        if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
             xembedLog.finer("XEmbed client(tester), embedder window: " + Long.toHexString(parent));
         }
     }
@@ -91,7 +91,7 @@
     }
 
     private void dumpReceivedEvents() {
-        if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
             xembedLog.finer("Events received so far:");
             int pos = 0;
             for (Integer event : events) {
@@ -395,7 +395,7 @@
                                                      SubstructureNotifyMask | KeyPressMask)});
             window = new XBaseWindow(params);
 
-            if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+            if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                 xembedLog.finer("Created tester window: " + window);
             }
 
@@ -535,7 +535,7 @@
         synchronized(EVENT_LOCK) {
             // Check for already received events after the request
             if (checkEventList(position, event) != -1) {
-                if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+                if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                     xembedLog.finer("The event " + XEmbedHelper.msgidToString(event) + " has already been received");
                 }
                 return;
@@ -543,14 +543,14 @@
 
             if (eventReceived == event) {
                 // Already received
-                if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+                if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                     xembedLog.finer("Already received " + XEmbedHelper.msgidToString(event));
                 }
                 return;
             }
             eventReceived = -1;
             eventWaited = event;
-            if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+            if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                 xembedLog.finer("Waiting for " + XEmbedHelper.msgidToString(event) + " starting from " + position);
             }
             try {
@@ -563,7 +563,7 @@
                 dumpReceivedEvents();
                 throw new RuntimeException("Didn't receive event " + XEmbedHelper.msgidToString(event) + " but recevied " + XEmbedHelper.msgidToString(eventReceived));
             } else {
-                if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+                if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                     xembedLog.finer("Successfully recevied " + XEmbedHelper.msgidToString(event));
                 }
             }
@@ -648,7 +648,7 @@
         if (ev.get_type() == ClientMessage) {
             XClientMessageEvent msg = ev.get_xclient();
             if (msg.get_message_type() == xembed.XEmbed.getAtom()) {
-                if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+                if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
                     xembedLog.fine("Embedded message: " + XEmbedHelper.msgidToString((int)msg.get_data(1)));
                 }
                 switch ((int)msg.get_data(1)) {
@@ -675,12 +675,12 @@
                 synchronized(EVENT_LOCK) {
                     events.add((int)msg.get_data(1));
 
-                    if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+                    if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                         xembedLog.finer("Tester is waiting for " +  XEmbedHelper.msgidToString(eventWaited));
                     }
                     if ((int)msg.get_data(1) == eventWaited) {
                         eventReceived = (int)msg.get_data(1);
-                        if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+                        if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                             xembedLog.finer("Notifying waiting object for event " + System.identityHashCode(EVENT_LOCK));
                         }
                         EVENT_LOCK.notifyAll();
@@ -692,12 +692,12 @@
                 int eventID = (int)ev.get_type() | SYSTEM_EVENT_MASK;
                 events.add(eventID);
 
-                if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+                if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                     xembedLog.finer("Tester is waiting for " + XEmbedHelper.msgidToString(eventWaited) + ", but we received " + ev + "(" + XEmbedHelper.msgidToString(eventID) + ")");
                 }
                 if (eventID == eventWaited) {
                     eventReceived = eventID;
-                    if (xembedLog.isLoggable(PlatformLogger.FINER)) {
+                    if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                         xembedLog.finer("Notifying waiting object" + System.identityHashCode(EVENT_LOCK));
                     }
                     EVENT_LOCK.notifyAll();
--- a/jdk/src/solaris/classes/sun/awt/X11/XEmbeddedFramePeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbeddedFramePeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -139,7 +139,7 @@
     {
         assert (SunToolkit.isAWTLockHeldByCurrentThread());
         XConfigureEvent xe = xev.get_xconfigure();
-        if (xembedLog.isLoggable(PlatformLogger.FINE)) {
+        if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
             xembedLog.fine(xe.toString());
         }
 
--- a/jdk/src/solaris/classes/sun/awt/X11/XErrorHandlerUtil.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XErrorHandlerUtil.java	Wed Jul 05 19:00:49 2017 +0200
@@ -119,7 +119,7 @@
             // Default XErrorHandler may just terminate the process. Don't call it.
             // return XlibWrapper.CallErrorHandler(saved_error_handler, display, error.pData);
         }
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Unhandled XErrorEvent: " +
                 "id=" + error.get_resourceid() + ", " +
                 "serial=" + error.get_serial() + ", " +
--- a/jdk/src/solaris/classes/sun/awt/X11/XFileDialogPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XFileDialogPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -720,7 +720,7 @@
         }
 
         File fe = new File(dir).getAbsoluteFile();
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Current directory : " + fe);
         }
 
--- a/jdk/src/solaris/classes/sun/awt/X11/XFramePeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XFramePeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -75,7 +75,7 @@
         winAttr.isResizable = true; // target.isResizable();
         winAttr.title = target.getTitle();
         winAttr.initialResizability = target.isResizable();
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Frame''s initial attributes: decor {0}, resizable {1}, undecorated {2}, initial state {3}",
                      Integer.valueOf(winAttr.decorations), Boolean.valueOf(winAttr.initialResizability),
                      Boolean.valueOf(!winAttr.nativeDecor), Integer.valueOf(winAttr.initialState));
@@ -209,7 +209,7 @@
     }
 
     public void setMaximizedBounds(Rectangle b) {
-        if (insLog.isLoggable(PlatformLogger.FINE)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
             insLog.fine("Setting maximized bounds to " + b);
         }
         if (b == null) return;
@@ -228,7 +228,7 @@
             } else {
                 hints.set_max_height((int)XlibWrapper.DisplayHeight(XToolkit.getDisplay(), XlibWrapper.DefaultScreen(XToolkit.getDisplay())));
             }
-            if (insLog.isLoggable(PlatformLogger.FINER)) {
+            if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
                 insLog.finer("Setting hints, flags " + XlibWrapper.hintsToString(hints.get_flags()));
             }
             XlibWrapper.XSetWMNormalHints(XToolkit.getDisplay(), window, hints.pData);
@@ -258,18 +258,18 @@
         int changed = state ^ newState;
         int changeIconic = changed & Frame.ICONIFIED;
         boolean iconic = (newState & Frame.ICONIFIED) != 0;
-        if (stateLog.isLoggable(PlatformLogger.FINER)) {
+        if (stateLog.isLoggable(PlatformLogger.Level.FINER)) {
             stateLog.finer("Changing state, old state {0}, new state {1}(iconic {2})",
                        Integer.valueOf(state), Integer.valueOf(newState), Boolean.valueOf(iconic));
         }
         if (changeIconic != 0 && iconic) {
-            if (stateLog.isLoggable(PlatformLogger.FINER)) {
+            if (stateLog.isLoggable(PlatformLogger.Level.FINER)) {
                 stateLog.finer("Iconifying shell " + getShell() + ", this " + this + ", screen " + getScreenNumber());
             }
             XToolkit.awtLock();
             try {
                 int res = XlibWrapper.XIconifyWindow(XToolkit.getDisplay(), getShell(), getScreenNumber());
-                if (stateLog.isLoggable(PlatformLogger.FINER)) {
+                if (stateLog.isLoggable(PlatformLogger.Level.FINER)) {
                     stateLog.finer("XIconifyWindow returned " + res);
                 }
             }
@@ -281,7 +281,7 @@
             setExtendedState(newState);
         }
         if (changeIconic != 0 && !iconic) {
-            if (stateLog.isLoggable(PlatformLogger.FINER)) {
+            if (stateLog.isLoggable(PlatformLogger.Level.FINER)) {
                 stateLog.finer("DeIconifying " + this);
             }
             xSetVisible(true);
@@ -296,7 +296,7 @@
         super.handlePropertyNotify(xev);
         XPropertyEvent ev = xev.get_xproperty();
 
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("Property change {0}", ev);
         }
         /*
@@ -311,7 +311,7 @@
         final int newState = XWM.getWM().getState(this);
         int changed = state ^ newState;
         if (changed == 0) {
-            if (stateLog.isLoggable(PlatformLogger.FINER)) {
+            if (stateLog.isLoggable(PlatformLogger.Level.FINER)) {
                 stateLog.finer("State is the same: " + state);
             }
             return;
@@ -365,7 +365,7 @@
             XWMHints hints = getWMHints();
             hints.set_flags((int)XUtilConstants.StateHint | hints.get_flags());
             hints.set_initial_state(wm_state);
-            if (stateLog.isLoggable(PlatformLogger.FINE)) {
+            if (stateLog.isLoggable(PlatformLogger.Level.FINE)) {
                 stateLog.fine("Setting initial WM state on " + this + " to " + wm_state);
             }
             XlibWrapper.XSetWMHints(XToolkit.getDisplay(), getWindow(), hints.pData);
--- a/jdk/src/solaris/classes/sun/awt/X11/XIconInfo.java	Mon Jun 24 14:26:58 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,237 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-package sun.awt.X11;
-import java.awt.*;
-import java.awt.color.*;
-import java.awt.image.*;
-import sun.awt.image.ToolkitImage;
-import sun.awt.image.ImageRepresentation;
-import java.util.Arrays;
-
-class XIconInfo {
-    /**
-     * Representation of image as an int array
-     * It's being used for _NET_WM_ICON hint
-     * with 32-bit X data model
-     */
-    private int[] intIconData;
-    /**
-     * Representation of image as an int array
-     * It's being used for _NET_WM_ICON hint
-     * with 64-bit X data model
-     */
-    private long[] longIconData;
-    /**
-     * Icon image.
-     */
-    private Image image;
-    /**
-     * Width of icon image. Being set in constructor.
-     */
-    private final int width;
-    /**
-     * Height of icon image. Being set in constructor.
-     */
-    private final int height;
-    /**
-     * Width of scaled icon image. Can be set in setScaledDimension.
-     */
-    private int scaledWidth;
-    /**
-     * Height of scaled icon image. Can be set in setScaledDimension.
-     */
-    private int scaledHeight;
-    /**
-     * Length of raw data. Being set in constructor / setScaledDimension.
-     */
-    private int rawLength;
-
-    XIconInfo(int[] intIconData) {
-        this.intIconData =
-            (null == intIconData) ? null : Arrays.copyOf(intIconData, intIconData.length);
-        this.width = intIconData[0];
-        this.height = intIconData[1];
-        this.scaledWidth = width;
-        this.scaledHeight = height;
-        this.rawLength = width * height + 2;
-    }
-
-    XIconInfo(long[] longIconData) {
-        this.longIconData =
-        (null == longIconData) ? null : Arrays.copyOf(longIconData, longIconData.length);
-        this.width = (int)longIconData[0];
-        this.height = (int)longIconData[1];
-        this.scaledWidth = width;
-        this.scaledHeight = height;
-        this.rawLength = width * height + 2;
-    }
-
-    XIconInfo(Image image) {
-        this.image = image;
-        if (image instanceof ToolkitImage) {
-            ImageRepresentation ir = ((ToolkitImage)image).getImageRep();
-            ir.reconstruct(ImageObserver.ALLBITS);
-            this.width = ir.getWidth();
-            this.height = ir.getHeight();
-        } else {
-            this.width = image.getWidth(null);
-            this.height = image.getHeight(null);
-        }
-        this.scaledWidth = width;
-        this.scaledHeight = height;
-        this.rawLength = width * height + 2;
-    }
-
-    /*
-     * It sets size of scaled icon.
-     */
-    void setScaledSize(int width, int height) {
-        this.scaledWidth = width;
-        this.scaledHeight = height;
-        this.rawLength = width * height + 2;
-    }
-
-    boolean isValid() {
-        return (width > 0 && height > 0);
-    }
-
-    int getWidth() {
-        return width;
-    }
-
-    int getHeight() {
-        return height;
-    }
-
-    public String toString() {
-        return "XIconInfo[w=" + width + ",h=" + height + ",sw=" + scaledWidth + ",sh=" + scaledHeight + "]";
-    }
-
-    int getRawLength() {
-        return rawLength;
-    }
-
-    int[] getIntData() {
-        if (this.intIconData == null) {
-            if (this.longIconData != null) {
-                this.intIconData = longArrayToIntArray(longIconData);
-            } else if (this.image != null) {
-                this.intIconData = imageToIntArray(this.image, scaledWidth, scaledHeight);
-            }
-        }
-        return this.intIconData;
-    }
-
-    long[] getLongData() {
-        if (this.longIconData == null) {
-            if (this.intIconData != null) {
-                this.longIconData = intArrayToLongArray(this.intIconData);
-            } else if (this.image != null) {
-                int[] intIconData = imageToIntArray(this.image, scaledWidth, scaledHeight);
-                this.longIconData = intArrayToLongArray(intIconData);
-            }
-        }
-        return this.longIconData;
-    }
-
-    Image getImage() {
-        if (this.image == null) {
-            if (this.intIconData != null) {
-                this.image = intArrayToImage(this.intIconData);
-            } else if (this.longIconData != null) {
-                int[] intIconData = longArrayToIntArray(this.longIconData);
-                this.image = intArrayToImage(intIconData);
-            }
-        }
-        return this.image;
-    }
-
-    private static int[] longArrayToIntArray(long[] longData) {
-        int[] intData = new int[longData.length];
-        for (int i = 0; i < longData.length; i++) {
-            // Such a conversion is valid since the
-            // original data (see
-            // make/sun/xawt/ToBin.java) were ints
-            intData[i] = (int)longData[i];
-        }
-        return intData;
-    }
-
-    private static long[] intArrayToLongArray(int[] intData) {
-        long[] longData = new long[intData.length];
-        for (int i = 0; i < intData.length; i++) {
-            longData[i] = (int)intData[i];
-        }
-        return longData;
-    }
-
-    static Image intArrayToImage(int[] raw) {
-        ColorModel cm =
-            new DirectColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), 32,
-                                 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000,
-                                 false, DataBuffer.TYPE_INT);
-        DataBuffer buffer = new DataBufferInt(raw, raw.length-2, 2);
-        WritableRaster raster =
-            Raster.createPackedRaster(buffer, raw[0], raw[1],
-                                      raw[0],
-                                      new int[] {0x00ff0000, 0x0000ff00,
-                                                 0x000000ff, 0xff000000},
-                                      null);
-        BufferedImage im = new BufferedImage(cm, raster, false, null);
-        return im;
-    }
-
-    /*
-     * Returns array of integers which holds data for the image.
-     * It scales the image if necessary.
-     */
-    static int[] imageToIntArray(Image image, int width, int height) {
-        if (width <= 0 || height <= 0) {
-            return null;
-        }
-        ColorModel cm =
-            new DirectColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), 32,
-                                 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000,
-                                 false, DataBuffer.TYPE_INT);
-        DataBufferInt buffer = new DataBufferInt(width * height);
-        WritableRaster raster =
-            Raster.createPackedRaster(buffer, width, height,
-                                      width,
-                                      new int[] {0x00ff0000, 0x0000ff00,
-                                                 0x000000ff, 0xff000000},
-                                      null);
-        BufferedImage im = new BufferedImage(cm, raster, false, null);
-        Graphics g = im.getGraphics();
-        g.drawImage(image, 0, 0, width, height, null);
-        g.dispose();
-        int[] data = buffer.getData();
-        int[] raw = new int[width * height + 2];
-        raw[0] = width;
-        raw[1] = height;
-        System.arraycopy(data, 0, raw, 2, width * height);
-        return raw;
-    }
-
-}
--- a/jdk/src/solaris/classes/sun/awt/X11/XIconWindow.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XIconWindow.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,8 @@
 
 import java.awt.*;
 import java.awt.image.*;
-import sun.awt.X11GraphicsConfig;
+
+import sun.awt.IconInfo;
 import sun.awt.image.ToolkitImage;
 import sun.awt.image.ImageRepresentation;
 
@@ -61,7 +62,7 @@
             final long screen = adata.get_awt_visInfo().get_screen();
             final long display = XToolkit.getDisplay();
 
-            if (log.isLoggable(PlatformLogger.FINEST)) {
+            if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                 log.finest(adata.toString());
             }
 
@@ -73,13 +74,13 @@
             }
             int count = Native.getInt(XlibWrapper.iarg1);
             long sizes_ptr = Native.getLong(XlibWrapper.larg1); // XIconSize*
-            if (log.isLoggable(PlatformLogger.FINEST)) {
+            if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                 log.finest("count = {1}, sizes_ptr = {0}", Long.valueOf(sizes_ptr), Integer.valueOf(count));
             }
             XIconSize[] res = new XIconSize[count];
             for (int i = 0; i < count; i++, sizes_ptr += XIconSize.getSize()) {
                 res[i] = new XIconSize(sizes_ptr);
-                if (log.isLoggable(PlatformLogger.FINEST)) {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                     log.finest("sizes_ptr[{1}] = {0}", res[i], Integer.valueOf(i));
                 }
             }
@@ -98,7 +99,7 @@
         }
 
         XIconSize[] sizeList = getIconSizes();
-        if (log.isLoggable(PlatformLogger.FINEST)) {
+        if (log.isLoggable(PlatformLogger.Level.FINEST)) {
             log.finest("Icon sizes: {0}", (Object[]) sizeList);
         }
         if (sizeList == null) {
@@ -147,11 +148,11 @@
                 }
             }
         }
-        if (log.isLoggable(PlatformLogger.FINEST)) {
+        if (log.isLoggable(PlatformLogger.Level.FINEST)) {
             log.finest("found=" + found);
         }
         if (!found) {
-            if (log.isLoggable(PlatformLogger.FINEST)) {
+            if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                 log.finest("widthHint=" + widthHint + ", heightHint=" + heightHint
                            + ", saveWidth=" + saveWidth + ", saveHeight=" + saveHeight
                            + ", max_width=" + sizeList[0].get_max_width()
@@ -167,7 +168,7 @@
                 /* determine which way to scale */
                 int wdiff = widthHint - sizeList[0].get_max_width();
                 int hdiff = heightHint - sizeList[0].get_max_height();
-                if (log.isLoggable(PlatformLogger.FINEST)) {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                     log.finest("wdiff=" + wdiff + ", hdiff=" + hdiff);
                 }
                 if (wdiff >= hdiff) { /* need to scale width more  */
@@ -199,7 +200,7 @@
             XToolkit.awtUnlock();
         }
 
-        if (log.isLoggable(PlatformLogger.FINEST)) {
+        if (log.isLoggable(PlatformLogger.Level.FINEST)) {
             log.finest("return " + saveWidth + "x" + saveHeight);
         }
         return new Dimension(saveWidth, saveHeight);
@@ -406,12 +407,12 @@
      * Sets icon image by selecting one of the images from the list.
      * The selected image is the one having the best matching size.
      */
-    void setIconImages(java.util.List<XIconInfo> icons) {
+    void setIconImages(java.util.List<IconInfo> icons) {
         if (icons == null || icons.size() == 0) return;
 
         int minDiff = Integer.MAX_VALUE;
         Image min = null;
-        for (XIconInfo iconInfo : icons) {
+        for (IconInfo iconInfo : icons) {
             if (iconInfo.isValid()) {
                 Image image = iconInfo.getImage();
                 Dimension dim = calcIconSize(image.getWidth(null), image.getHeight(null));
@@ -426,7 +427,7 @@
             }
         }
         if (min != null) {
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("Icon: {0}x{1}", min.getWidth(null), min.getHeight(null));
             }
             setIconImage(min);
@@ -454,7 +455,7 @@
             }
             Dimension iconSize = getIconSize(width, height);
             if (iconSize != null) {
-                if (log.isLoggable(PlatformLogger.FINEST)) {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                     log.finest("Icon size: {0}", iconSize);
                 }
                 iconWidth = iconSize.width;
--- a/jdk/src/solaris/classes/sun/awt/X11/XInputMethod.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XInputMethod.java	Wed Jul 05 19:00:49 2017 +0200
@@ -102,7 +102,7 @@
     protected ComponentPeer getPeer(Component client) {
         XComponentPeer peer;
 
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Client is " + client);
         }
         peer = (XComponentPeer)XToolkit.targetToPeer(client);
@@ -110,7 +110,7 @@
             client = getParent(client);
             peer = (XComponentPeer)XToolkit.targetToPeer(client);
         }
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Peer is {0}, client is {1}", peer, client);
         }
 
--- a/jdk/src/solaris/classes/sun/awt/X11/XKeyboardFocusManagerPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XKeyboardFocusManagerPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,9 +26,11 @@
 
 import java.awt.Component;
 import java.awt.Window;
-import sun.util.logging.PlatformLogger;
+
+import sun.awt.AWTAccessor;
 import sun.awt.CausedFocusEvent;
 import sun.awt.KeyboardFocusManagerPeerImpl;
+import sun.util.logging.PlatformLogger;
 
 public class XKeyboardFocusManagerPeer extends KeyboardFocusManagerPeerImpl {
     private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.awt.X11.focus.XKeyboardFocusManagerPeer");
@@ -60,7 +62,7 @@
 
     @Override
     public void setCurrentFocusedWindow(Window win) {
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer("Setting current focused window " + win);
         }
 
@@ -68,13 +70,13 @@
 
         synchronized(this) {
             if (currentFocusedWindow != null) {
-                from = (XWindowPeer)currentFocusedWindow.getPeer();
+                from = (XWindowPeer)AWTAccessor.getComponentAccessor().getPeer(currentFocusedWindow);
             }
 
             currentFocusedWindow = win;
 
             if (currentFocusedWindow != null) {
-                to = (XWindowPeer)currentFocusedWindow.getPeer();
+                to = (XWindowPeer)AWTAccessor.getComponentAccessor().getPeer(currentFocusedWindow);
             }
         }
 
--- a/jdk/src/solaris/classes/sun/awt/X11/XListPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XListPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -575,12 +575,12 @@
     }
 
     void mousePressed(MouseEvent mouseEvent) {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer(mouseEvent.toString() + ", hsb " + hsbVis + ", vsb " + vsbVis);
         }
         if (isEnabled() && mouseEvent.getButton() == MouseEvent.BUTTON1) {
             if (inWindow(mouseEvent.getX(), mouseEvent.getY())) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("Mouse press in items area");
                 }
                 active = WINDOW;
@@ -619,7 +619,7 @@
                     currentIndex = -1;
                 }
             } else if (inVerticalScrollbar(mouseEvent.getX(), mouseEvent.getY())) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("Mouse press in vertical scrollbar");
                 }
                 active = VERSCROLLBAR;
@@ -628,7 +628,7 @@
                                      mouseEvent.getX() - (width - SCROLLBAR_WIDTH),
                                      mouseEvent.getY());
             } else if (inHorizontalScrollbar(mouseEvent.getX(), mouseEvent.getY())) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("Mouse press in horizontal scrollbar");
                 }
                 active = HORSCROLLBAR;
@@ -813,7 +813,7 @@
 
     void keyPressed(KeyEvent e) {
         int keyCode = e.getKeyCode();
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine(e.toString());
         }
         switch(keyCode) {
@@ -1000,7 +1000,7 @@
      */
     public void notifyValue(XScrollbar obj, int type, int v, boolean isAdjusting) {
 
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Notify value changed on " + obj + " to " + v);
         }
         int value = obj.getValue();
@@ -1085,7 +1085,7 @@
                 }
             }
         }
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("Adding item '" + item + "' to " + addedIndex);
         }
 
@@ -1105,7 +1105,7 @@
                 | ((vsb.needsRepaint())?(PAINT_VSCROLL):0);
 
         }
-        if (log.isLoggable(PlatformLogger.FINEST)) {
+        if (log.isLoggable(PlatformLogger.Level.FINEST)) {
             log.finest("Last visible: " + getLastVisibleItem() +
             ", hsb changed : " + (hsbWasVis ^ hsbVis) + ", items changed " + repaintItems);
         }
@@ -1123,11 +1123,11 @@
         boolean vsbWasVisible = vsbVis;
         int oldLastDisplayed = lastItemDisplayed();
 
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Deleting from " + s + " to " + e);
         }
 
-        if (log.isLoggable(PlatformLogger.FINEST)) {
+        if (log.isLoggable(PlatformLogger.Level.FINEST)) {
             log.finest("Last displayed item: " + oldLastDisplayed + ", items in window " + itemsInWindow() +
             ", size " + items.size());
         }
@@ -1197,7 +1197,7 @@
             options |= PAINT_FOCUS;
         }
 
-        if (log.isLoggable(PlatformLogger.FINEST)) {
+        if (log.isLoggable(PlatformLogger.Level.FINEST)) {
             log.finest("Multiple selections: " + multipleSelections);
         }
 
@@ -1452,7 +1452,7 @@
      * y is the number of items to scroll
      */
     void scrollVertical(int y) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Scrolling vertically by " + y);
         }
         int itemsInWin = itemsInWindow();
@@ -1494,7 +1494,7 @@
      * x is the number of pixels to scroll
      */
     void scrollHorizontal(int x) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Scrolling horizontally by " + y);
         }
         int w = getListWidth();
@@ -1732,7 +1732,7 @@
             }
 
             if (localBuffer == null) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("Creating buffer " + width + "x" + height);
                 }
                 // use GraphicsConfig.cCVI() instead of Component.cVI(),
@@ -1771,7 +1771,7 @@
 
         private void paint(Graphics listG, int firstItem, int lastItem, int options,
                            Rectangle source, Point distance) {
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("Repaint from " + firstItem + " to " + lastItem + " options " + options);
             }
             if (firstItem > lastItem) {
@@ -1862,7 +1862,7 @@
         }
 
         private void paintItems(Graphics g, int firstItem, int lastItem, int options) {
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("Painting items from " + firstItem + " to " + lastItem + ", focused " + focusIndex + ", first " + getFirstVisibleItem() + ", last " + getLastVisibleItem());
             }
 
@@ -1875,7 +1875,7 @@
             firstItem = Math.max(getFirstVisibleItem(), firstItem);
             lastItem = Math.min(lastItem, items.size()-1);
 
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("Actually painting items from " + firstItem + " to " + lastItem +
                           ", items in window " + itemsInWindow());
             }
@@ -1885,7 +1885,7 @@
         }
 
         private void paintItem(Graphics g, int index) {
-            if (log.isLoggable(PlatformLogger.FINEST)) {
+            if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                 log.finest("Painting item " + index);
             }
             // 4895367 - only paint items which are visible
@@ -1895,7 +1895,7 @@
                 int h = getItemHeight();
                 int y = getItemY(index);
                 int x = getItemX();
-                if (log.isLoggable(PlatformLogger.FINEST)) {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                     log.finest("Setting clip " + new Rectangle(x, y, w - (SPACE*2), h-(SPACE*2)));
                 }
                 g.setClip(x, y, w - (SPACE*2), h-(SPACE*2));
@@ -1903,14 +1903,14 @@
                 // Always paint the background so that focus is unpainted in
                 // multiselect mode
                 if (isSelected(index)) {
-                    if (log.isLoggable(PlatformLogger.FINEST)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                         log.finest("Painted item is selected");
                     }
                     g.setColor(getListForeground());
                 } else {
                     g.setColor(getListBackground());
                 }
-                if (log.isLoggable(PlatformLogger.FINEST)) {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                     log.finest("Filling " + new Rectangle(x, y, w, h));
                 }
                 g.fillRect(x, y, w, h);
@@ -1936,7 +1936,7 @@
         }
 
         void paintScrollBar(XScrollbar scr, Graphics g, int x, int y, int width, int height, boolean paintAll) {
-            if (log.isLoggable(PlatformLogger.FINEST)) {
+            if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                 log.finest("Painting scrollbar " + scr + " width " +
                 width + " height " + height + ", paintAll " + paintAll);
             }
@@ -1976,19 +1976,19 @@
             if (paintFocus && !hasFocus()) {
                 paintFocus = false;
             }
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("Painting focus, focus index " + getFocusIndex() + ", focus is " +
                          (isItemHidden(getFocusIndex())?("invisible"):("visible")) + ", paint focus is " + paintFocus);
             }
             Shape clip = g.getClip();
             g.setClip(0, 0, listWidth, listHeight);
-            if (log.isLoggable(PlatformLogger.FINEST)) {
+            if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                 log.finest("Setting focus clip " + new Rectangle(0, 0, listWidth, listHeight));
             }
             Rectangle rect = getFocusRect();
             if (prevFocusRect != null) {
                 // Erase focus rect
-                if (log.isLoggable(PlatformLogger.FINEST)) {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                     log.finest("Erasing previous focus rect " + prevFocusRect);
                 }
                 g.setColor(getListBackground());
@@ -1997,7 +1997,7 @@
             }
             if (paintFocus) {
                 // Paint new
-                if (log.isLoggable(PlatformLogger.FINEST)) {
+                if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                     log.finest("Painting focus rect " + rect);
                 }
                 g.setColor(getListForeground());  // Focus color is always black on Linux
--- a/jdk/src/solaris/classes/sun/awt/X11/XMSelection.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XMSelection.java	Wed Jul 05 19:00:49 2017 +0200
@@ -128,7 +128,7 @@
             long display = XToolkit.getDisplay();
             synchronized(this) {
                 setOwner(owner, screen);
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("New Selection Owner for screen " + screen + " = " + owner );
                 }
                 XlibWrapper.XSelectInput(display, owner, XConstants.StructureNotifyMask | eventMask);
@@ -150,14 +150,14 @@
         try {
             try {
                 long display = XToolkit.getDisplay();
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("Grabbing XServer");
                 }
                 XlibWrapper.XGrabServer(display);
 
                 synchronized(this) {
                     String selection_name = getName()+"_S"+screen;
-                    if (log.isLoggable(PlatformLogger.FINE)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("Screen = " + screen + " selection name = " + selection_name);
                     }
                     XAtom atom = XAtom.get(selection_name);
@@ -166,7 +166,7 @@
                     long owner = XlibWrapper.XGetSelectionOwner(display, atom.getAtom());
                     if (owner != 0) {
                         setOwner(owner, screen);
-                        if (log.isLoggable(PlatformLogger.FINE)) {
+                        if (log.isLoggable(PlatformLogger.Level.FINE)) {
                             log.fine("Selection Owner for screen " + screen + " = " + owner );
                         }
                         XlibWrapper.XSelectInput(display, owner, XConstants.StructureNotifyMask | extra_mask);
@@ -183,7 +183,7 @@
                 e.printStackTrace();
             }
             finally {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("UnGrabbing XServer");
                 }
                 XlibWrapper.XUngrabServer(XToolkit.getDisplay());
@@ -197,7 +197,7 @@
     static boolean processClientMessage(XEvent xev, int screen) {
         XClientMessageEvent xce = xev.get_xclient();
         if (xce.get_message_type() == XA_MANAGER.getAtom()) {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("client messags = " + xce);
             }
             long timestamp = xce.get_data(0);
@@ -306,7 +306,7 @@
 
 
     synchronized void dispatchSelectionChanged( XPropertyEvent ev, int screen) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Selection Changed : Screen = " + screen + "Event =" + ev);
         }
         if (listeners != null) {
@@ -319,7 +319,7 @@
     }
 
     synchronized void dispatchOwnerDeath(XDestroyWindowEvent de, int screen) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Owner dead : Screen = " + screen + "Event =" + de);
         }
         if (listeners != null) {
@@ -333,7 +333,7 @@
     }
 
     void dispatchSelectionEvent(XEvent xev, int screen) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Event =" + xev);
         }
         if (xev.get_type() == XConstants.DestroyNotify) {
--- a/jdk/src/solaris/classes/sun/awt/X11/XMenuBarPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XMenuBarPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -519,7 +519,7 @@
      */
     public void handleKeyPress(XEvent xev) {
         XKeyEvent xkey = xev.get_xkey();
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine(xkey.toString());
         }
         if (isEventDisabled(xev)) {
--- a/jdk/src/solaris/classes/sun/awt/X11/XMenuPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XMenuPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -111,7 +111,7 @@
      * for adding separators
      */
     public void addSeparator() {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("addSeparator is not implemented");
         }
     }
@@ -121,7 +121,7 @@
         if (menuWindow != null) {
             menuWindow.addItem(item);
         } else {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("Attempt to use XMenuWindowPeer without window");
             }
         }
@@ -132,7 +132,7 @@
         if (menuWindow != null) {
             menuWindow.delItem(index);
         } else {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("Attempt to use XMenuWindowPeer without window");
             }
         }
--- a/jdk/src/solaris/classes/sun/awt/X11/XMenuWindow.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XMenuWindow.java	Wed Jul 05 19:00:49 2017 +0200
@@ -399,7 +399,7 @@
         if (!isCreated()) {
             return;
         }
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("showing menu window + " + getWindow() + " at " + bounds);
         }
         XToolkit.awtLock();
--- a/jdk/src/solaris/classes/sun/awt/X11/XNETProtocol.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XNETProtocol.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * 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,8 @@
 package sun.awt.X11;
 
 import java.awt.Frame;
+
+import sun.awt.IconInfo;
 import sun.util.logging.PlatformLogger;
 
 final class XNETProtocol extends XProtocol implements XStateProtocol, XLayerProtocol
@@ -43,7 +45,7 @@
     }
 
     public void setState(XWindowPeer window, int state) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Setting state of " + window + " to " + state);
         }
         if (window.isShowing()) {
@@ -55,7 +57,7 @@
 
     private void setInitialState(XWindowPeer window, int state) {
         XAtomList old_state = window.getNETWMState();
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Current state of the window {0} is {1}", window, old_state);
         }
         if ((state & Frame.MAXIMIZED_VERT) != 0) {
@@ -68,7 +70,7 @@
         } else {
             old_state.remove(XA_NET_WM_STATE_MAXIMIZED_HORZ);
         }
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Setting initial state of the window {0} to {1}", window, old_state);
         }
         window.setNETWMState(old_state);
@@ -103,7 +105,7 @@
               default:
                   return;
             }
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("Requesting state on " + window + " for " + state);
             }
             req.set_type((int)XConstants.ClientMessage);
@@ -187,7 +189,7 @@
             req.set_data(1, state.getAtom());
             // Fix for 6735584: req.data[2] must be set to 0 when only one property is changed
             req.set_data(2, 0);
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("Setting _NET_STATE atom {0} on {1} for {2}", state, window, Boolean.valueOf(isAdd));
             }
             XToolkit.awtLock();
@@ -214,7 +216,7 @@
      * @param reset Indicates operation, 'set' if false, 'reset' if true
      */
     private void setStateHelper(XWindowPeer window, XAtom state, boolean set) {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("Window visibility is: withdrawn={0}, visible={1}, mapped={2} showing={3}",
                   Boolean.valueOf(window.isWithdrawn()), Boolean.valueOf(window.isVisible()),
                   Boolean.valueOf(window.isMapped()), Boolean.valueOf(window.isShowing()));
@@ -223,7 +225,7 @@
             requestState(window, state, set);
         } else {
             XAtomList net_wm_state = window.getNETWMState();
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("Current state on {0} is {1}", window, net_wm_state);
             }
             if (!set) {
@@ -231,7 +233,7 @@
             } else {
                 net_wm_state.add(state);
             }
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("Setting states on {0} to {1}", window, net_wm_state);
             }
             window.setNETWMState(net_wm_state);
@@ -290,7 +292,7 @@
         }
         NetWindow = checkAnchor(XA_NET_SUPPORTING_WM_CHECK, XAtom.XA_WINDOW);
         supportChecked = true;
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### " + this + " is active: " + (NetWindow != 0));
         }
     }
@@ -302,7 +304,7 @@
 
     boolean doStateProtocol() {
         boolean res = active() && checkProtocol(XA_NET_SUPPORTED, XA_NET_WM_STATE);
-        if (stateLog.isLoggable(PlatformLogger.FINER)) {
+        if (stateLog.isLoggable(PlatformLogger.Level.FINER)) {
             stateLog.finer("doStateProtocol() returns " + res);
         }
         return res;
@@ -331,7 +333,7 @@
         if (net_wm_name_string == null) {
             return false;
         }
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### WM_NAME = " + net_wm_name_string);
         }
         return net_wm_name_string.startsWith(name);
@@ -372,10 +374,10 @@
     }
 
     /**
-     * Sets _NET_WM_ICON property on the window using the List of XIconInfo
+     * Sets _NET_WM_ICON property on the window using the List of IconInfo
      * If icons is null or empty list, removes _NET_WM_ICON property
      */
-    public void setWMIcons(XWindowPeer window, java.util.List<XIconInfo> icons) {
+    public void setWMIcons(XWindowPeer window, java.util.List<IconInfo> icons) {
         if (window == null) return;
 
         XAtom iconsAtom = XAtom.get("_NET_WM_ICON");
@@ -385,7 +387,7 @@
         }
 
         int length = 0;
-        for (XIconInfo ii : icons) {
+        for (IconInfo ii : icons) {
             length += ii.getRawLength();
         }
         int cardinalSize = (XlibWrapper.dataModel == 32) ? 4 : 8;
@@ -395,7 +397,7 @@
             long buffer = XlibWrapper.unsafe.allocateMemory(bufferSize);
             try {
                 long ptr = buffer;
-                for (XIconInfo ii : icons) {
+                for (IconInfo ii : icons) {
                     int size = ii.getRawLength() * cardinalSize;
                     if (XlibWrapper.dataModel == 32) {
                         XlibWrapper.copyIntArray(ptr, ii.getIntData(), size);
--- a/jdk/src/solaris/classes/sun/awt/X11/XPopupMenuPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XPopupMenuPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -123,7 +123,7 @@
      * for adding separators
      */
     public void addSeparator() {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("addSeparator is not implemented");
         }
     }
@@ -343,7 +343,7 @@
      */
     public void handleKeyPress(XEvent xev) {
         XKeyEvent xkey = xev.get_xkey();
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine(xkey.toString());
         }
         if (isEventDisabled(xev)) {
--- a/jdk/src/solaris/classes/sun/awt/X11/XProtocol.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XProtocol.java	Wed Jul 05 19:00:49 2017 +0200
@@ -54,7 +54,7 @@
         } finally {
             if (firstCheck) {
                 firstCheck = false;
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("{0}:{1} supports {2}", this, listName, protocols);
                 }
             }
--- a/jdk/src/solaris/classes/sun/awt/X11/XScrollbar.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XScrollbar.java	Wed Jul 05 19:00:49 2017 +0200
@@ -118,7 +118,7 @@
     abstract protected void rebuildArrows();
 
     public void setSize(int width, int height) {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("Setting scroll bar " + this + " size to " + width + "x" + height);
         }
         this.width = width;
@@ -166,7 +166,7 @@
      * @param paintAll paint the whole scrollbar if true, just the thumb is false
      */
     void paint(Graphics g, Color colors[], boolean paintAll) {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("Painting scrollbar " + this);
         }
 
@@ -339,7 +339,7 @@
      * Tell the scroller to start scrolling.
      */
     void startScrolling() {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("Start scrolling on " + this);
         }
         // Make sure that we scroll at least once
@@ -361,7 +361,7 @@
      * See 6243382 for more information
      */
     void startScrollingInstance() {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("Start scrolling on " + this);
         }
         // Make sure that we scroll at least once
@@ -376,7 +376,7 @@
      * See 6243382 for more information
      */
     void stopScrollingInstance() {
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("Stop scrolling on " + this);
         }
 
@@ -464,7 +464,7 @@
             return;
         }
 
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
              String type;
              switch (id) {
                 case MouseEvent.MOUSE_PRESSED:
--- a/jdk/src/solaris/classes/sun/awt/X11/XScrollbarPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XScrollbarPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -156,7 +156,7 @@
 
     public void handleJavaKeyEvent(KeyEvent event) {
         super.handleJavaKeyEvent(event);
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("KeyEvent on scrollbar: " + event);
         }
         if (!(event.isConsumed()) && event.getID() == KeyEvent.KEY_RELEASED) {
--- a/jdk/src/solaris/classes/sun/awt/X11/XSystemTrayPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XSystemTrayPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -58,7 +58,7 @@
         long selection_owner = selection.getOwner(SCREEN);
         available = (selection_owner != XConstants.None);
 
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine(" check if system tray is available. selection owner: " + selection_owner);
         }
     }
@@ -108,7 +108,7 @@
     void addTrayIcon(XTrayIconPeer tiPeer) throws AWTException {
         long selection_owner = selection.getOwner(SCREEN);
 
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine(" send SYSTEM_TRAY_REQUEST_DOCK message to owner: " + selection_owner);
         }
 
--- a/jdk/src/solaris/classes/sun/awt/X11/XTextFieldPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XTextFieldPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -258,7 +258,7 @@
     }
 
     public void setBackground(Color c) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("target="+ target + ", old=" + background + ", new=" + c);
         }
         background = c;
--- a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java	Wed Jul 05 19:00:49 2017 +0200
@@ -266,7 +266,7 @@
                                 ((XAWTXSettings)xs).dispose();
                             }
                             freeXKB();
-                            if (log.isLoggable(PlatformLogger.FINE)) {
+                            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                                 dumpPeers();
                             }
                         }
@@ -524,7 +524,7 @@
     }
 
     static void processException(Throwable thr) {
-        if (log.isLoggable(PlatformLogger.WARNING)) {
+        if (log.isLoggable(PlatformLogger.Level.WARNING)) {
             log.warning("Exception on Toolkit thread", thr);
         }
     }
@@ -586,7 +586,7 @@
                     continue;
                 }
 
-                if (eventLog.isLoggable(PlatformLogger.FINER)) {
+                if (eventLog.isLoggable(PlatformLogger.Level.FINER)) {
                     eventLog.finer("{0}", ev);
                 }
 
@@ -602,13 +602,13 @@
                         }
                     }
                 }
-                if( keyEventLog.isLoggable(PlatformLogger.FINE) && (ev.get_type() == XConstants.KeyPress || ev.get_type() == XConstants.KeyRelease) ) {
+                if( keyEventLog.isLoggable(PlatformLogger.Level.FINE) && (ev.get_type() == XConstants.KeyPress || ev.get_type() == XConstants.KeyRelease) ) {
                     keyEventLog.fine("before XFilterEvent:"+ev);
                 }
                 if (XlibWrapper.XFilterEvent(ev.getPData(), w)) {
                     continue;
                 }
-                if( keyEventLog.isLoggable(PlatformLogger.FINE) && (ev.get_type() == XConstants.KeyPress || ev.get_type() == XConstants.KeyRelease) ) {
+                if( keyEventLog.isLoggable(PlatformLogger.Level.FINE) && (ev.get_type() == XConstants.KeyPress || ev.get_type() == XConstants.KeyRelease) ) {
                     keyEventLog.fine("after XFilterEvent:"+ev); // IS THIS CORRECT?
                 }
 
@@ -1321,7 +1321,7 @@
     }
 
     static void dumpPeers() {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Mapped windows:");
             Iterator iter = winMap.entrySet().iterator();
             while (iter.hasNext()) {
@@ -1417,7 +1417,7 @@
                 }
             } catch (InterruptedException ie) {
             // Note: the returned timeStamp can be incorrect in this case.
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("Catched exception, timeStamp may not be correct (ie = " + ie + ")");
                 }
             }
@@ -1584,7 +1584,7 @@
 
             name = "gnome." + name;
             setDesktopProperty(name, e.getValue());
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("name = " + name + " value = " + e.getValue());
             }
 
@@ -1773,7 +1773,7 @@
         } finally {
             awtUnlock();
         }
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("metaMask = " + metaMask);
             log.fine("altMask = " + altMask);
             log.fine("numLockMask = " + numLockMask);
@@ -1795,11 +1795,11 @@
         }
         awtLock();
         try {
-            if (timeoutTaskLog.isLoggable(PlatformLogger.FINER)) {
+            if (timeoutTaskLog.isLoggable(PlatformLogger.Level.FINER)) {
                 timeoutTaskLog.finer("Removing task " + task);
             }
             if (timeoutTasks == null) {
-                if (timeoutTaskLog.isLoggable(PlatformLogger.FINER)) {
+                if (timeoutTaskLog.isLoggable(PlatformLogger.Level.FINER)) {
                     timeoutTaskLog.finer("Task is not scheduled");
                 }
                 return;
@@ -1846,7 +1846,7 @@
 
         awtLock();
         try {
-            if (timeoutTaskLog.isLoggable(PlatformLogger.FINER)) {
+            if (timeoutTaskLog.isLoggable(PlatformLogger.Level.FINER)) {
                 timeoutTaskLog.finer("XToolkit.schedule(): current time={0}" +
                                      ";  interval={1}" +
                                      ";  task being added={2}" + ";  tasks before addition={3}",
@@ -1893,7 +1893,7 @@
      * Called from run() under awtLock.
      */
     private static void callTimeoutTasks() {
-        if (timeoutTaskLog.isLoggable(PlatformLogger.FINER)) {
+        if (timeoutTaskLog.isLoggable(PlatformLogger.Level.FINER)) {
             timeoutTaskLog.finer("XToolkit.callTimeoutTasks(): current time={0}" +
                                  ";  tasks={1}", Long.valueOf(System.currentTimeMillis()), timeoutTasks);
         }
@@ -1911,7 +1911,7 @@
             for (Iterator iter = tasks.iterator(); iter.hasNext();) {
                 Runnable task = (Runnable)iter.next();
 
-                if (timeoutTaskLog.isLoggable(PlatformLogger.FINER)) {
+                if (timeoutTaskLog.isLoggable(PlatformLogger.Level.FINER)) {
                     timeoutTaskLog.finer("XToolkit.callTimeoutTasks(): current time={0}" +
                                          ";  about to run task={1}", Long.valueOf(currentTime), task);
                 }
@@ -1986,7 +1986,7 @@
          */
 
         long current_time_utc = System.currentTimeMillis();
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("reset_time=" + reset_time_utc + ", current_time=" + current_time_utc
                       + ", server_offset=" + server_offset + ", wrap_time=" + WRAP_TIME_MILLIS);
         }
@@ -1995,7 +1995,7 @@
             reset_time_utc = System.currentTimeMillis() - getCurrentServerTime();
         }
 
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("result = " + (reset_time_utc + server_offset));
         }
         return reset_time_utc + server_offset;
@@ -2074,14 +2074,14 @@
 
         if (prop == null) {
             backingStoreType = XConstants.NotUseful;
-            if (backingStoreLog.isLoggable(PlatformLogger.CONFIG)) {
+            if (backingStoreLog.isLoggable(PlatformLogger.Level.CONFIG)) {
                 backingStoreLog.config("The system property sun.awt.backingStore is not set" +
                                        ", by default backingStore=NotUseful");
             }
             return;
         }
 
-        if (backingStoreLog.isLoggable(PlatformLogger.CONFIG)) {
+        if (backingStoreLog.isLoggable(PlatformLogger.Level.CONFIG)) {
             backingStoreLog.config("The system property sun.awt.backingStore is " + prop);
         }
         prop = prop.toLowerCase();
@@ -2093,7 +2093,7 @@
             backingStoreType = XConstants.NotUseful;
         }
 
-        if (backingStoreLog.isLoggable(PlatformLogger.CONFIG)) {
+        if (backingStoreLog.isLoggable(PlatformLogger.Level.CONFIG)) {
             backingStoreLog.config("backingStore(as provided by the system property)=" +
                                    ( backingStoreType == XConstants.NotUseful ? "NotUseful"
                                      : backingStoreType == XConstants.WhenMapped ?
@@ -2103,7 +2103,7 @@
         if (sun.java2d.x11.X11SurfaceData.isDgaAvailable()) {
             backingStoreType = XConstants.NotUseful;
 
-            if (backingStoreLog.isLoggable(PlatformLogger.CONFIG)) {
+            if (backingStoreLog.isLoggable(PlatformLogger.Level.CONFIG)) {
                 backingStoreLog.config("DGA is available, backingStore=NotUseful");
             }
 
@@ -2118,7 +2118,7 @@
                         == XConstants.NotUseful) {
                     backingStoreType = XConstants.NotUseful;
 
-                    if (backingStoreLog.isLoggable(PlatformLogger.CONFIG)) {
+                    if (backingStoreLog.isLoggable(PlatformLogger.Level.CONFIG)) {
                         backingStoreLog.config("Backing store is not available on the screen " +
                                                i + ", backingStore=NotUseful");
                     }
@@ -2396,7 +2396,7 @@
             // Wait for selection notify for oops on win
             long event_number = getEventNumber();
             XAtom atom = XAtom.get("WM_S0");
-            if (eventLog.isLoggable(PlatformLogger.FINER)) {
+            if (eventLog.isLoggable(PlatformLogger.Level.FINER)) {
                 eventLog.finer("WM_S0 selection owner {0}", XlibWrapper.XGetSelectionOwner(getDisplay(), atom.getAtom()));
             }
             XlibWrapper.XConvertSelection(getDisplay(), atom.getAtom(),
--- a/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -106,7 +106,7 @@
 
                     XConfigureEvent ce = ev.get_xconfigure();
 
-                    if (ctrLog.isLoggable(PlatformLogger.FINE)) {
+                    if (ctrLog.isLoggable(PlatformLogger.Level.FINE)) {
                         ctrLog.fine("ConfigureNotify on parent of {0}: {1}x{2}+{3}+{4} (old: {5}+{6})",
                                 XTrayIconPeer.this, ce.get_width(), ce.get_height(),
                                 ce.get_x(), ce.get_y(), old_x, old_y);
@@ -130,7 +130,7 @@
                         // If both the height and the width differ from the fixed size then WM
                         // must level at least one side to the fixed size. For some reason it may take
                         // a few hops (even after reparenting) and we have to skip the intermediate ones.
-                        if (ctrLog.isLoggable(PlatformLogger.FINE)) {
+                        if (ctrLog.isLoggable(PlatformLogger.Level.FINE)) {
                             ctrLog.fine("ConfigureNotify on parent of {0}. Skipping as intermediate resizing.",
                                     XTrayIconPeer.this);
                         }
@@ -138,7 +138,7 @@
 
                     } else if (ce.get_height() > TRAY_ICON_HEIGHT) {
 
-                        if (ctrLog.isLoggable(PlatformLogger.FINE)) {
+                        if (ctrLog.isLoggable(PlatformLogger.Level.FINE)) {
                             ctrLog.fine("ConfigureNotify on parent of {0}. Centering by \"Y\".",
                                     XTrayIconPeer.this);
                         }
@@ -153,7 +153,7 @@
 
                     } else if (ce.get_width() > TRAY_ICON_WIDTH) {
 
-                        if (ctrLog.isLoggable(PlatformLogger.FINE)) {
+                        if (ctrLog.isLoggable(PlatformLogger.Level.FINE)) {
                             ctrLog.fine("ConfigureNotify on parent of {0}. Centering by \"X\".",
                                     XTrayIconPeer.this);
                         }
@@ -173,7 +173,7 @@
 
                         if (ex_height != 0) {
 
-                            if (ctrLog.isLoggable(PlatformLogger.FINE)) {
+                            if (ctrLog.isLoggable(PlatformLogger.Level.FINE)) {
                                 ctrLog.fine("ConfigureNotify on parent of {0}. Move detected. Centering by \"Y\".",
                                         XTrayIconPeer.this);
                             }
@@ -184,7 +184,7 @@
 
                         } else if (ex_width != 0) {
 
-                            if (ctrLog.isLoggable(PlatformLogger.FINE)) {
+                            if (ctrLog.isLoggable(PlatformLogger.Level.FINE)) {
                                 ctrLog.fine("ConfigureNotify on parent of {0}. Move detected. Centering by \"X\".",
                                         XTrayIconPeer.this);
                             }
@@ -193,7 +193,7 @@
                                                     ce.get_x() + ex_width/2 - TRAY_ICON_WIDTH/2,
                                                     ce.get_y());
                         } else {
-                            if (ctrLog.isLoggable(PlatformLogger.FINE)) {
+                            if (ctrLog.isLoggable(PlatformLogger.Level.FINE)) {
                                 ctrLog.fine("ConfigureNotify on parent of {0}. Move detected. Skipping.",
                                         XTrayIconPeer.this);
                             }
--- a/jdk/src/solaris/classes/sun/awt/X11/XWINProtocol.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XWINProtocol.java	Wed Jul 05 19:00:49 2017 +0200
@@ -63,7 +63,7 @@
             req.set_format(32);
             req.set_data(0, (WIN_STATE_MAXIMIZED_HORIZ | WIN_STATE_MAXIMIZED_VERT));
             req.set_data(1, win_state);
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("Sending WIN_STATE to root to change the state to " + win_state);
             }
             try {
@@ -113,7 +113,7 @@
                 win_state &= ~WIN_STATE_MAXIMIZED_HORIZ;
             }
             if ((old_win_state ^ win_state) != 0) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("Setting WIN_STATE on " + window + " to change the state to " + win_state);
                 }
                 XA_WIN_STATE.setCard32Property(window, win_state);
@@ -160,7 +160,7 @@
             req.set_data(0, layer == LAYER_NORMAL ? WIN_LAYER_NORMAL : WIN_LAYER_ONTOP);
             req.set_data(1, 0);
             req.set_data(2, 0);
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("Setting layer " + layer + " by root message : " + req);
             }
             XToolkit.awtLock();
@@ -177,7 +177,7 @@
             }
             req.dispose();
         } else {
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("Setting layer property to " + layer);
             }
             XA_WIN_LAYER.setCard32Property(window, layer == LAYER_NORMAL ? WIN_LAYER_NORMAL : WIN_LAYER_ONTOP);
@@ -205,7 +205,7 @@
         }
         WinWindow = checkAnchor(XA_WIN_SUPPORTING_WM_CHECK, XAtom.XA_CARDINAL);
         supportChecked = true;
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### " + this + " is active: " + (WinWindow != 0));
         }
     }
@@ -216,7 +216,7 @@
     }
     boolean doStateProtocol() {
         boolean res = active() && checkProtocol(XA_WIN_PROTOCOLS, XA_WIN_STATE);
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### " + this + " supports state: " + res);
         }
         return res;
@@ -224,7 +224,7 @@
 
     boolean doLayerProtocol() {
         boolean res = active() && checkProtocol(XA_WIN_PROTOCOLS, XA_WIN_LAYER);
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("### " + this + " supports layer: " + res);
         }
         return res;
--- a/jdk/src/solaris/classes/sun/awt/X11/XWM.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XWM.java	Wed Jul 05 19:00:49 2017 +0200
@@ -30,6 +30,7 @@
  */
 package sun.awt.X11;
 
+import sun.awt.IconInfo;
 import sun.misc.Unsafe;
 import java.awt.Insets;
 import java.awt.Frame;
@@ -148,7 +149,7 @@
     XWM(int WMID) {
         this.WMID = WMID;
         initializeProtocols();
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Window manager: " + toString());
         }
     }
@@ -254,7 +255,7 @@
              * having a window manager running. I.e. it does not reparent
              * top level shells.
              */
-            if (insLog.isLoggable(PlatformLogger.FINER)) {
+            if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
                 insLog.finer("eXcursion means NO_WM");
             }
             return true;
@@ -272,7 +273,7 @@
             long selection_owner =
                 XlibWrapper.XGetSelectionOwner(XToolkit.getDisplay(),
                                                XAtom.get(selection_name).getAtom());
-            if (insLog.isLoggable(PlatformLogger.FINER)) {
+            if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
                 insLog.finer("selection owner of " + selection_name
                              + " is " + selection_owner);
             }
@@ -301,7 +302,7 @@
                                                     XToolkit.getDefaultRootWindow(),
                                                     XConstants.CWEventMask,
                                                     substruct.pData);
-                if (insLog.isLoggable(PlatformLogger.FINER)) {
+                if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
                     insLog.finer("It looks like there is no WM thus NO_WM");
                 }
             }
@@ -345,7 +346,7 @@
             byte[] bytes = XlibWrapper.getStringBytes(getter.getData());
             String id = new String(bytes);
 
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("ENLIGHTENMENT_COMMS is " + id);
             }
 
@@ -354,15 +355,15 @@
             try {
                 Matcher match = winIdPat.matcher(id);
                 if (match.matches()) {
-                    if (log.isLoggable(PlatformLogger.FINEST)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                         log.finest("Match group count: " + match.groupCount());
                     }
                     String longId = match.group(1);
-                    if (log.isLoggable(PlatformLogger.FINEST)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                         log.finest("Match group 1 " + longId);
                     }
                     long winid = Long.parseLong(longId, 16);
-                    if (log.isLoggable(PlatformLogger.FINER)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINER)) {
                         log.finer("Enlightenment communication window " + winid);
                     }
                     return winid;
@@ -371,7 +372,7 @@
                     return 0;
                 }
             } catch (Exception e) {
-                if (log.isLoggable(PlatformLogger.FINER)) {
+                if (log.isLoggable(PlatformLogger.Level.FINER)) {
                     e.printStackTrace();
                 }
                 return 0;
@@ -417,7 +418,7 @@
     static boolean isCDE() {
 
         if (!XA_DT_SM_WINDOW_INFO.isInterned()) {
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("{0} is not interned", XA_DT_SM_WINDOW_INFO);
             }
             return false;
@@ -450,7 +451,7 @@
 
             /* Now check that this window has _DT_SM_STATE_INFO (ignore contents) */
             if (!XA_DT_SM_STATE_INFO.isInterned()) {
-                if (log.isLoggable(PlatformLogger.FINER)) {
+                if (log.isLoggable(PlatformLogger.Level.FINER)) {
                     log.finer("{0} is not interned", XA_DT_SM_STATE_INFO);
                 }
                 return false;
@@ -624,7 +625,7 @@
          */
 
         if (!XA_ICEWM_WINOPTHINT.isInterned()) {
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("{0} is not interned", XA_ICEWM_WINOPTHINT);
             }
             return false;
@@ -660,7 +661,7 @@
      */
     static boolean isIceWM() {
         if (!XA_ICEWM_WINOPTHINT.isInterned()) {
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("{0} is not interned", XA_ICEWM_WINOPTHINT);
             }
             return false;
@@ -673,7 +674,7 @@
         try {
             int status = getter.execute();
             boolean res = (status == XConstants.Success && getter.getActualType() != 0);
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("Status getting XA_ICEWM_WINOPTHINT: " + !res);
             }
             return !res || isNetWMName("IceWM");
@@ -729,7 +730,7 @@
         return wm;
     }
     static int getWMID() {
-        if (insLog.isLoggable(PlatformLogger.FINEST)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINEST)) {
             insLog.finest("awt_wmgr = " + awt_wmgr);
         }
         /*
@@ -753,7 +754,7 @@
             // Later, WM will initialize its own version of protocol
             XNETProtocol l_net_protocol = g_net_protocol = new XNETProtocol();
             l_net_protocol.detect();
-            if (log.isLoggable(PlatformLogger.FINE) && l_net_protocol.active()) {
+            if (log.isLoggable(PlatformLogger.Level.FINE) && l_net_protocol.active()) {
                 log.fine("_NET_WM_NAME is " + l_net_protocol.getWMName());
             }
             XWINProtocol win = g_win_protocol = new XWINProtocol();
@@ -837,7 +838,7 @@
             }
 
             hints.set_flags(hints.get_flags() & ~mask);
-            if (insLog.isLoggable(PlatformLogger.FINER)) {
+            if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
                 insLog.finer("Setting hints, flags " + XlibWrapper.hintsToString(hints.get_flags()));
             }
             XlibWrapper.XSetWMNormalHints(XToolkit.getDisplay(),
@@ -896,7 +897,7 @@
 
         XAtomList decorDel = new XAtomList();
         decorations = normalizeMotifDecor(decorations);
-        if (insLog.isLoggable(PlatformLogger.FINER)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
             insLog.finer("Setting OL_DECOR to " + Integer.toBinaryString(decorations));
         }
         if ((decorations & MWMConstants.MWM_DECOR_TITLE) == 0) {
@@ -915,7 +916,7 @@
             insLog.finer("Deleting OL_DECOR");
             XA_OL_DECOR_DEL.DeleteProperty(window);
         } else {
-            if (insLog.isLoggable(PlatformLogger.FINER)) {
+            if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
                 insLog.finer("Setting OL_DECOR to " + decorDel);
             }
             XA_OL_DECOR_DEL.setAtomListProperty(window, decorDel);
@@ -945,7 +946,7 @@
         hints.set_functions(functions);
         hints.set_decorations(decorations);
 
-        if (stateLog.isLoggable(PlatformLogger.FINER)) {
+        if (stateLog.isLoggable(PlatformLogger.Level.FINER)) {
             stateLog.finer("Setting MWM_HINTS to " + hints);
         }
         window.setMWMHints(hints);
@@ -1009,7 +1010,7 @@
      * Make specified shell resizable.
      */
     static void setShellResizable(XDecoratedPeer window) {
-        if (insLog.isLoggable(PlatformLogger.FINE)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
             insLog.fine("Setting shell resizable " + window);
         }
         XToolkit.awtLock();
@@ -1041,7 +1042,7 @@
     static void setShellNotResizable(XDecoratedPeer window, WindowDimensions newDimensions, Rectangle shellBounds,
                                      boolean justChangeSize)
     {
-        if (insLog.isLoggable(PlatformLogger.FINE)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
             insLog.fine("Setting non-resizable shell " + window + ", dimensions " + newDimensions +
                         ", shellBounds " + shellBounds +", just change size: " + justChangeSize);
         }
@@ -1175,7 +1176,7 @@
             stateLog.finer("WithdrawnState");
             return false;
         } else {
-            if (stateLog.isLoggable(PlatformLogger.FINER)) {
+            if (stateLog.isLoggable(PlatformLogger.Level.FINER)) {
                 stateLog.finer("Window WM_STATE is " + wm_state);
             }
         }
@@ -1186,7 +1187,7 @@
 
         for (XStateProtocol proto : getProtocols(XStateProtocol.class)) {
             is_state_change |= proto.isStateChange(e);
-            if (stateLog.isLoggable(PlatformLogger.FINEST)) {
+            if (stateLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 stateLog.finest(proto + ": is state changed = " + is_state_change);
             }
         }
@@ -1340,7 +1341,7 @@
                   res = defaultInsets;
             }
         }
-        if (insLog.isLoggable(PlatformLogger.FINEST)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINEST)) {
             insLog.finest("WM guessed insets: " + res);
         }
         return res;
@@ -1411,7 +1412,7 @@
         XNETProtocol net_protocol = getWM().getNETProtocol();
         if (net_protocol != null && net_protocol.active()) {
             Insets insets = getInsetsFromProp(window, XA_NET_FRAME_EXTENTS);
-            if (insLog.isLoggable(PlatformLogger.FINE)) {
+            if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
                 insLog.fine("_NET_FRAME_EXTENTS: {0}", insets);
             }
 
@@ -1554,7 +1555,7 @@
          *       [mwm, e!, kwin, fvwm2 ... ]
          */
         Insets correctWM = XWM.getInsetsFromExtents(window);
-        if (insLog.isLoggable(PlatformLogger.FINER)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
             insLog.finer("Got insets from property: {0}", correctWM);
         }
 
@@ -1617,7 +1618,7 @@
                   }
                   case XWM.OTHER_WM:
                   default: {                /* this is very similar to the E! case above */
-                      if (insLog.isLoggable(PlatformLogger.FINEST)) {
+                      if (insLog.isLoggable(PlatformLogger.Level.FINEST)) {
                           insLog.finest("Getting correct insets for OTHER_WM/default, parent: {0}", parent);
                       }
                       syncTopLevelPos(parent, lwinAttr);
@@ -1646,7 +1647,7 @@
                           && lwinAttr.get_width()+2*lwinAttr.get_border_width() == pattr.get_width()
                           && lwinAttr.get_height()+2*lwinAttr.get_border_width() == pattr.get_height())
                       {
-                          if (insLog.isLoggable(PlatformLogger.FINEST)) {
+                          if (insLog.isLoggable(PlatformLogger.Level.FINEST)) {
                               insLog.finest("Double reparenting detected, pattr({2})={0}, lwinAttr({3})={1}",
                                         lwinAttr, pattr, parent, window);
                           }
@@ -1676,7 +1677,7 @@
                        * widths and inner/outer distinction, so for the time
                        * being, just ignore it.
                        */
-                      if (insLog.isLoggable(PlatformLogger.FINEST)) {
+                      if (insLog.isLoggable(PlatformLogger.Level.FINEST)) {
                           insLog.finest("Attrs before calculation: pattr({2})={0}, lwinAttr({3})={1}",
                                     lwinAttr, pattr, parent, window);
                       }
@@ -1719,7 +1720,7 @@
      *
      * @return true if hint was modified successfully, false otherwise
      */
-    public boolean setNetWMIcon(XWindowPeer window, java.util.List<XIconInfo> icons) {
+    public boolean setNetWMIcon(XWindowPeer window, java.util.List<IconInfo> icons) {
         if (g_net_protocol != null && g_net_protocol.active()) {
             g_net_protocol.setWMIcons(window, icons);
             return getWMID() != ICE_WM;
--- a/jdk/src/solaris/classes/sun/awt/X11/XWarningWindow.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XWarningWindow.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,11 +25,10 @@
 package sun.awt.X11;
 
 import java.awt.*;
-import java.awt.event.*;
 import java.awt.geom.Point2D;
 import java.lang.ref.WeakReference;
-import sun.java2d.SunGraphics2D;
-import sun.java2d.pipe.Region;
+
+import sun.awt.IconInfo;
 import sun.awt.AWTAccessor;
 import sun.awt.SunToolkit;
 
@@ -56,37 +55,37 @@
      * 3 - 48x48
      */
     private int currentSize = -1;
-    private static XIconInfo[][] icons;
-    private static XIconInfo getSecurityIconInfo(int size, int num) {
+    private static IconInfo[][] icons;
+    private static IconInfo getSecurityIconInfo(int size, int num) {
         synchronized (XWarningWindow.class) {
             if (icons == null) {
-                icons = new XIconInfo[4][3];
+                icons = new IconInfo[4][3];
                 if (XlibWrapper.dataModel == 32) {
-                    icons[0][0] = new XIconInfo(XAWTIcon32_security_icon_bw16_png.security_icon_bw16_png);
-                    icons[0][1] = new XIconInfo(XAWTIcon32_security_icon_interim16_png.security_icon_interim16_png);
-                    icons[0][2] = new XIconInfo(XAWTIcon32_security_icon_yellow16_png.security_icon_yellow16_png);
-                    icons[1][0] = new XIconInfo(XAWTIcon32_security_icon_bw24_png.security_icon_bw24_png);
-                    icons[1][1] = new XIconInfo(XAWTIcon32_security_icon_interim24_png.security_icon_interim24_png);
-                    icons[1][2] = new XIconInfo(XAWTIcon32_security_icon_yellow24_png.security_icon_yellow24_png);
-                    icons[2][0] = new XIconInfo(XAWTIcon32_security_icon_bw32_png.security_icon_bw32_png);
-                    icons[2][1] = new XIconInfo(XAWTIcon32_security_icon_interim32_png.security_icon_interim32_png);
-                    icons[2][2] = new XIconInfo(XAWTIcon32_security_icon_yellow32_png.security_icon_yellow32_png);
-                    icons[3][0] = new XIconInfo(XAWTIcon32_security_icon_bw48_png.security_icon_bw48_png);
-                    icons[3][1] = new XIconInfo(XAWTIcon32_security_icon_interim48_png.security_icon_interim48_png);
-                    icons[3][2] = new XIconInfo(XAWTIcon32_security_icon_yellow48_png.security_icon_yellow48_png);
+                    icons[0][0] = new IconInfo(sun.awt.AWTIcon32_security_icon_bw16_png.security_icon_bw16_png);
+                    icons[0][1] = new IconInfo(sun.awt.AWTIcon32_security_icon_interim16_png.security_icon_interim16_png);
+                    icons[0][2] = new IconInfo(sun.awt.AWTIcon32_security_icon_yellow16_png.security_icon_yellow16_png);
+                    icons[1][0] = new IconInfo(sun.awt.AWTIcon32_security_icon_bw24_png.security_icon_bw24_png);
+                    icons[1][1] = new IconInfo(sun.awt.AWTIcon32_security_icon_interim24_png.security_icon_interim24_png);
+                    icons[1][2] = new IconInfo(sun.awt.AWTIcon32_security_icon_yellow24_png.security_icon_yellow24_png);
+                    icons[2][0] = new IconInfo(sun.awt.AWTIcon32_security_icon_bw32_png.security_icon_bw32_png);
+                    icons[2][1] = new IconInfo(sun.awt.AWTIcon32_security_icon_interim32_png.security_icon_interim32_png);
+                    icons[2][2] = new IconInfo(sun.awt.AWTIcon32_security_icon_yellow32_png.security_icon_yellow32_png);
+                    icons[3][0] = new IconInfo(sun.awt.AWTIcon32_security_icon_bw48_png.security_icon_bw48_png);
+                    icons[3][1] = new IconInfo(sun.awt.AWTIcon32_security_icon_interim48_png.security_icon_interim48_png);
+                    icons[3][2] = new IconInfo(sun.awt.AWTIcon32_security_icon_yellow48_png.security_icon_yellow48_png);
                 } else {
-                    icons[0][0] = new XIconInfo(XAWTIcon64_security_icon_bw16_png.security_icon_bw16_png);
-                    icons[0][1] = new XIconInfo(XAWTIcon64_security_icon_interim16_png.security_icon_interim16_png);
-                    icons[0][2] = new XIconInfo(XAWTIcon64_security_icon_yellow16_png.security_icon_yellow16_png);
-                    icons[1][0] = new XIconInfo(XAWTIcon64_security_icon_bw24_png.security_icon_bw24_png);
-                    icons[1][1] = new XIconInfo(XAWTIcon64_security_icon_interim24_png.security_icon_interim24_png);
-                    icons[1][2] = new XIconInfo(XAWTIcon64_security_icon_yellow24_png.security_icon_yellow24_png);
-                    icons[2][0] = new XIconInfo(XAWTIcon64_security_icon_bw32_png.security_icon_bw32_png);
-                    icons[2][1] = new XIconInfo(XAWTIcon64_security_icon_interim32_png.security_icon_interim32_png);
-                    icons[2][2] = new XIconInfo(XAWTIcon64_security_icon_yellow32_png.security_icon_yellow32_png);
-                    icons[3][0] = new XIconInfo(XAWTIcon64_security_icon_bw48_png.security_icon_bw48_png);
-                    icons[3][1] = new XIconInfo(XAWTIcon64_security_icon_interim48_png.security_icon_interim48_png);
-                    icons[3][2] = new XIconInfo(XAWTIcon64_security_icon_yellow48_png.security_icon_yellow48_png);
+                    icons[0][0] = new IconInfo(sun.awt.AWTIcon64_security_icon_bw16_png.security_icon_bw16_png);
+                    icons[0][1] = new IconInfo(sun.awt.AWTIcon64_security_icon_interim16_png.security_icon_interim16_png);
+                    icons[0][2] = new IconInfo(sun.awt.AWTIcon64_security_icon_yellow16_png.security_icon_yellow16_png);
+                    icons[1][0] = new IconInfo(sun.awt.AWTIcon64_security_icon_bw24_png.security_icon_bw24_png);
+                    icons[1][1] = new IconInfo(sun.awt.AWTIcon64_security_icon_interim24_png.security_icon_interim24_png);
+                    icons[1][2] = new IconInfo(sun.awt.AWTIcon64_security_icon_yellow24_png.security_icon_yellow24_png);
+                    icons[2][0] = new IconInfo(sun.awt.AWTIcon64_security_icon_bw32_png.security_icon_bw32_png);
+                    icons[2][1] = new IconInfo(sun.awt.AWTIcon64_security_icon_interim32_png.security_icon_interim32_png);
+                    icons[2][2] = new IconInfo(sun.awt.AWTIcon64_security_icon_yellow32_png.security_icon_yellow32_png);
+                    icons[3][0] = new IconInfo(sun.awt.AWTIcon64_security_icon_bw48_png.security_icon_bw48_png);
+                    icons[3][1] = new IconInfo(sun.awt.AWTIcon64_security_icon_interim48_png.security_icon_interim48_png);
+                    icons[3][2] = new IconInfo(sun.awt.AWTIcon64_security_icon_yellow48_png.security_icon_yellow48_png);
                 }
             }
         }
@@ -125,7 +124,7 @@
         try {
             if (newSize != currentSize) {
                 currentSize = newSize;
-                XIconInfo ico = getSecurityIconInfo(currentSize, 0);
+                IconInfo ico = getSecurityIconInfo(currentSize, 0);
                 XlibWrapper.SetBitmapShape(XToolkit.getDisplay(), getWindow(),
                         ico.getWidth(), ico.getHeight(), ico.getIntData());
                 AWTAccessor.getWindowAccessor().setSecurityWarningSize(
@@ -136,7 +135,7 @@
         }
     }
 
-    private XIconInfo getSecurityIconInfo() {
+    private IconInfo getSecurityIconInfo() {
         updateIconSize();
         return getSecurityIconInfo(currentSize, currentIcon);
     }
--- a/jdk/src/solaris/classes/sun/awt/X11/XWindow.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XWindow.java	Wed Jul 05 19:00:49 2017 +0200
@@ -402,7 +402,7 @@
                     ((Component)e.getSource()).dispatchEvent(e);
                 }
             }, PeerEvent.ULTIMATE_PRIORITY_EVENT);
-        if (focusLog.isLoggable(PlatformLogger.FINER) && (e instanceof FocusEvent)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER) && (e instanceof FocusEvent)) {
             focusLog.finer("Sending " + e);
         }
         XToolkit.postEvent(XToolkit.targetToAppContext(e.getSource()), pe);
@@ -662,7 +662,7 @@
         if (isEventDisabled(xev)) {
             return;
         }
-        if (eventLog.isLoggable(PlatformLogger.FINE)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
             eventLog.fine(xbe.toString());
         }
         long when;
@@ -698,7 +698,7 @@
             /*
                multiclick checking
             */
-            if (eventLog.isLoggable(PlatformLogger.FINEST)) {
+            if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
                 eventLog.finest("lastWindow = " + lastWindow + ", lastButton "
                 + lastButton + ", lastTime " + lastTime + ", multiClickTime "
                 + XToolkit.getMultiClickTime());
@@ -891,7 +891,7 @@
         super.handleXCrossingEvent(xev);
         XCrossingEvent xce = xev.get_xcrossing();
 
-        if (eventLog.isLoggable(PlatformLogger.FINEST)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
             eventLog.finest(xce.toString());
         }
 
@@ -995,7 +995,7 @@
         Rectangle oldBounds = getBounds();
 
         super.handleConfigureNotifyEvent(xev);
-        if (insLog.isLoggable(PlatformLogger.FINER)) {
+        if (insLog.isLoggable(PlatformLogger.Level.FINER)) {
             insLog.finer("Configure, {0}, event disabled: {1}",
                      xev.get_xconfigure(), isEventDisabled(xev));
         }
@@ -1017,7 +1017,7 @@
 
     public void handleMapNotifyEvent(XEvent xev) {
         super.handleMapNotifyEvent(xev);
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Mapped {0}", this);
         }
         if (isEventDisabled(xev)) {
@@ -1041,7 +1041,7 @@
     }
 
     private void dumpKeysymArray(XKeyEvent ev) {
-        if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
+        if (keyEventLog.isLoggable(PlatformLogger.Level.FINE)) {
             keyEventLog.fine("  "+Long.toHexString(XlibWrapper.XKeycodeToKeysym(XToolkit.getDisplay(), ev.get_keycode(), 0))+
                              "\n        "+Long.toHexString(XlibWrapper.XKeycodeToKeysym(XToolkit.getDisplay(), ev.get_keycode(), 1))+
                              "\n        "+Long.toHexString(XlibWrapper.XKeycodeToKeysym(XToolkit.getDisplay(), ev.get_keycode(), 2))+
@@ -1071,18 +1071,18 @@
         //return (uni > 0? uni + 0x01000000 : 0);
     }
     void logIncomingKeyEvent(XKeyEvent ev) {
-        if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
+        if (keyEventLog.isLoggable(PlatformLogger.Level.FINE)) {
             keyEventLog.fine("--XWindow.java:handleKeyEvent:"+ev);
         }
         dumpKeysymArray(ev);
-        if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
+        if (keyEventLog.isLoggable(PlatformLogger.Level.FINE)) {
             keyEventLog.fine("XXXXXXXXXXXXXX javakeycode will be most probably:0x"+ Integer.toHexString(XKeysym.getJavaKeycodeOnly(ev)));
         }
     }
     public void handleKeyPress(XEvent xev) {
         super.handleKeyPress(xev);
         XKeyEvent ev = xev.get_xkey();
-        if (eventLog.isLoggable(PlatformLogger.FINE)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
             eventLog.fine(ev.toString());
         }
         if (isEventDisabled(xev)) {
@@ -1097,14 +1097,14 @@
         int unicodeKey = 0;
         keysym[0] = XConstants.NoSymbol;
 
-        if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
+        if (keyEventLog.isLoggable(PlatformLogger.Level.FINE)) {
             logIncomingKeyEvent( ev );
         }
         if ( //TODO check if there's an active input method instance
              // without calling a native method. Is it necessary though?
             haveCurrentX11InputMethodInstance()) {
             if (x11inputMethodLookupString(ev.pData, keysym)) {
-                if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
+                if (keyEventLog.isLoggable(PlatformLogger.Level.FINE)) {
                     keyEventLog.fine("--XWindow.java XIM did process event; return; dec keysym processed:"+(keysym[0])+
                                    "; hex keysym processed:"+Long.toHexString(keysym[0])
                                    );
@@ -1112,7 +1112,7 @@
                 return;
             }else {
                 unicodeKey = keysymToUnicode( keysym[0], ev.get_state() );
-                if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
+                if (keyEventLog.isLoggable(PlatformLogger.Level.FINE)) {
                     keyEventLog.fine("--XWindow.java XIM did NOT process event, hex keysym:"+Long.toHexString(keysym[0])+"\n"+
                                      "                                         unicode key:"+Integer.toHexString((int)unicodeKey));
                 }
@@ -1122,7 +1122,7 @@
             // Produce do-it-yourself keysym and perhaps unicode character.
             keysym[0] = xkeycodeToKeysym(ev);
             unicodeKey = keysymToUnicode( keysym[0], ev.get_state() );
-            if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
+            if (keyEventLog.isLoggable(PlatformLogger.Level.FINE)) {
                 keyEventLog.fine("--XWindow.java XIM is absent;             hex keysym:"+Long.toHexString(keysym[0])+"\n"+
                                  "                                         unicode key:"+Integer.toHexString((int)unicodeKey));
             }
@@ -1148,7 +1148,7 @@
         // is undefined, we still have a guess of what has been engraved on a keytop.
         int unicodeFromPrimaryKeysym = keysymToUnicode( xkeycodeToPrimaryKeysym(ev) ,0);
 
-        if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
+        if (keyEventLog.isLoggable(PlatformLogger.Level.FINE)) {
             keyEventLog.fine(">>>Fire Event:"+
                (ev.get_type() == XConstants.KeyPress ? "KEY_PRESSED; " : "KEY_RELEASED; ")+
                "jkeycode:decimal="+jkc.getJavaKeycode()+
@@ -1173,7 +1173,7 @@
 
 
         if (unicodeKey > 0 && !isDeadKey) {
-                if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
+                if (keyEventLog.isLoggable(PlatformLogger.Level.FINE)) {
                     keyEventLog.fine("fire _TYPED on "+unicodeKey);
                 }
                 postKeyEvent( java.awt.event.KeyEvent.KEY_TYPED,
@@ -1193,7 +1193,7 @@
     public void handleKeyRelease(XEvent xev) {
         super.handleKeyRelease(xev);
         XKeyEvent ev = xev.get_xkey();
-        if (eventLog.isLoggable(PlatformLogger.FINE)) {
+        if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
             eventLog.fine(ev.toString());
         }
         if (isEventDisabled(xev)) {
@@ -1205,7 +1205,7 @@
     private void handleKeyRelease(XKeyEvent ev) {
         int unicodeKey = 0;
 
-        if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
+        if (keyEventLog.isLoggable(PlatformLogger.Level.FINE)) {
             logIncomingKeyEvent( ev );
         }
         // Keysym should be converted to Unicode, if possible and necessary,
@@ -1220,7 +1220,7 @@
         if( jkc == null ) {
             jkc = new XKeysym.Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_UNDEFINED, java.awt.event.KeyEvent.KEY_LOCATION_UNKNOWN);
         }
-        if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
+        if (keyEventLog.isLoggable(PlatformLogger.Level.FINE)) {
             keyEventLog.fine(">>>Fire Event:"+
                (ev.get_type() == XConstants.KeyPress ? "KEY_PRESSED; " : "KEY_RELEASED; ")+
                "jkeycode:decimal="+jkc.getJavaKeycode()+
@@ -1357,12 +1357,12 @@
     void updateSizeHints(int x, int y, int width, int height) {
         long flags = XUtilConstants.PSize | (isLocationByPlatform() ? 0 : (XUtilConstants.PPosition | XUtilConstants.USPosition));
         if (!isResizable()) {
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("Window {0} is not resizable", this);
             }
             flags |= XUtilConstants.PMinSize | XUtilConstants.PMaxSize;
         } else {
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("Window {0} is resizable", this);
             }
         }
@@ -1372,12 +1372,12 @@
     void updateSizeHints(int x, int y) {
         long flags = isLocationByPlatform() ? 0 : (XUtilConstants.PPosition | XUtilConstants.USPosition);
         if (!isResizable()) {
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("Window {0} is not resizable", this);
             }
             flags |= XUtilConstants.PMinSize | XUtilConstants.PMaxSize | XUtilConstants.PSize;
         } else {
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("Window {0} is resizable", this);
             }
         }
--- a/jdk/src/solaris/classes/sun/awt/X11/XWindowAttributesData.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XWindowAttributesData.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,8 +23,7 @@
  * questions.
  */
 package sun.awt.X11;
-import java.awt.Image;
-import java.util.ArrayList;
+import sun.awt.IconInfo;
 
 class XWindowAttributesData {
     static int NORMAL           = 0;
@@ -51,7 +50,7 @@
     boolean initialResizability;
     int visibilityState; // updated by native X11 event handling code.
     String title;
-    java.util.List<XIconInfo> icons;
+    java.util.List<IconInfo> icons;
     boolean iconsInherited;
     int decorations;            // for future expansion to be able to
                                 // specify native decorations
--- a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -30,8 +30,6 @@
 import java.awt.event.FocusEvent;
 import java.awt.event.WindowEvent;
 
-import java.awt.image.BufferedImage;
-
 import java.awt.peer.ComponentPeer;
 import java.awt.peer.WindowPeer;
 
@@ -55,6 +53,7 @@
 import sun.awt.SunToolkit;
 import sun.awt.X11GraphicsDevice;
 import sun.awt.X11GraphicsEnvironment;
+import sun.awt.IconInfo;
 
 import sun.java2d.pipe.Region;
 
@@ -226,7 +225,7 @@
         Window owner = t_window.getOwner();
         if (owner != null) {
             ownerPeer = (XWindowPeer)owner.getPeer();
-            if (focusLog.isLoggable(PlatformLogger.FINER)) {
+            if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                 focusLog.finer("Owner is " + owner);
                 focusLog.finer("Owner peer is " + ownerPeer);
                 focusLog.finer("Owner X window " + Long.toHexString(ownerPeer.getWindow()));
@@ -239,7 +238,7 @@
                 XToolkit.awtLock();
                 try {
                     // Set WM_TRANSIENT_FOR
-                    if (focusLog.isLoggable(PlatformLogger.FINE)) {
+                    if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
                         focusLog.fine("Setting transient on " + Long.toHexString(getWindow())
                                       + " for " + Long.toHexString(ownerWindow));
                     }
@@ -294,23 +293,23 @@
         Window target = (Window)this.target;
         java.util.List<Image> iconImages = ((Window)target).getIconImages();
         XWindowPeer ownerPeer = getOwnerPeer();
-        winAttr.icons = new ArrayList<XIconInfo>();
+        winAttr.icons = new ArrayList<IconInfo>();
         if (iconImages.size() != 0) {
             //read icon images from target
             winAttr.iconsInherited = false;
             for (Iterator<Image> i = iconImages.iterator(); i.hasNext(); ) {
                 Image image = i.next();
                 if (image == null) {
-                    if (log.isLoggable(PlatformLogger.FINEST)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                         log.finest("XWindowPeer.updateIconImages: Skipping the image passed into Java because it's null.");
                     }
                     continue;
                 }
-                XIconInfo iconInfo;
+                IconInfo iconInfo;
                 try {
-                    iconInfo = new XIconInfo(image);
+                    iconInfo = new IconInfo(image);
                 } catch (Exception e){
-                    if (log.isLoggable(PlatformLogger.FINEST)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                         log.finest("XWindowPeer.updateIconImages: Perhaps the image passed into Java is broken. Skipping this icon.");
                     }
                     continue;
@@ -346,12 +345,12 @@
      * It does scale some of these icons to appropriate size
      * if it's necessary.
      */
-    static java.util.List<XIconInfo> normalizeIconImages(java.util.List<XIconInfo> icons) {
-        java.util.List<XIconInfo> result = new ArrayList<XIconInfo>();
+    static java.util.List<IconInfo> normalizeIconImages(java.util.List<IconInfo> icons) {
+        java.util.List<IconInfo> result = new ArrayList<IconInfo>();
         int totalLength = 0;
         boolean haveLargeIcon = false;
 
-        for (XIconInfo icon : icons) {
+        for (IconInfo icon : icons) {
             int width = icon.getWidth();
             int height = icon.getHeight();
             int length = icon.getRawLength();
@@ -381,7 +380,7 @@
             }
         }
 
-        if (iconLog.isLoggable(PlatformLogger.FINEST)) {
+        if (iconLog.isLoggable(PlatformLogger.Level.FINEST)) {
             iconLog.finest(">>> Length_ of buffer of icons data: " + totalLength +
                            ", maximum length: " + MAXIMUM_BUFFER_LENGTH_NET_WM_ICON);
         }
@@ -392,16 +391,16 @@
     /*
      * Dumps each icon from the list
      */
-    static void dumpIcons(java.util.List<XIconInfo> icons) {
-        if (iconLog.isLoggable(PlatformLogger.FINEST)) {
+    static void dumpIcons(java.util.List<IconInfo> icons) {
+        if (iconLog.isLoggable(PlatformLogger.Level.FINEST)) {
             iconLog.finest(">>> Sizes of icon images:");
-            for (Iterator<XIconInfo> i = icons.iterator(); i.hasNext(); ) {
+            for (Iterator<IconInfo> i = icons.iterator(); i.hasNext(); ) {
                 iconLog.finest("    {0}", i.next());
             }
         }
     }
 
-    public void recursivelySetIcon(java.util.List<XIconInfo> icons) {
+    public void recursivelySetIcon(java.util.List<IconInfo> icons) {
         dumpIcons(winAttr.icons);
         setIconHints(icons);
         Window target = (Window)this.target;
@@ -418,28 +417,28 @@
         }
     }
 
-    java.util.List<XIconInfo> getIconInfo() {
+    java.util.List<IconInfo> getIconInfo() {
         return winAttr.icons;
     }
-    void setIconHints(java.util.List<XIconInfo> icons) {
+    void setIconHints(java.util.List<IconInfo> icons) {
         //This does nothing for XWindowPeer,
         //It's overriden in XDecoratedPeer
     }
 
-    private static ArrayList<XIconInfo> defaultIconInfo;
-    protected synchronized static java.util.List<XIconInfo> getDefaultIconInfo() {
+    private static ArrayList<IconInfo> defaultIconInfo;
+    protected synchronized static java.util.List<IconInfo> getDefaultIconInfo() {
         if (defaultIconInfo == null) {
-            defaultIconInfo = new ArrayList<XIconInfo>();
+            defaultIconInfo = new ArrayList<IconInfo>();
             if (XlibWrapper.dataModel == 32) {
-                defaultIconInfo.add(new XIconInfo(XAWTIcon32_java_icon16_png.java_icon16_png));
-                defaultIconInfo.add(new XIconInfo(XAWTIcon32_java_icon24_png.java_icon24_png));
-                defaultIconInfo.add(new XIconInfo(XAWTIcon32_java_icon32_png.java_icon32_png));
-                defaultIconInfo.add(new XIconInfo(XAWTIcon32_java_icon48_png.java_icon48_png));
+                defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon32_java_icon16_png.java_icon16_png));
+                defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon32_java_icon24_png.java_icon24_png));
+                defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon32_java_icon32_png.java_icon32_png));
+                defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon32_java_icon48_png.java_icon48_png));
             } else {
-                defaultIconInfo.add(new XIconInfo(XAWTIcon64_java_icon16_png.java_icon16_png));
-                defaultIconInfo.add(new XIconInfo(XAWTIcon64_java_icon24_png.java_icon24_png));
-                defaultIconInfo.add(new XIconInfo(XAWTIcon64_java_icon32_png.java_icon32_png));
-                defaultIconInfo.add(new XIconInfo(XAWTIcon64_java_icon48_png.java_icon48_png));
+                defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon64_java_icon16_png.java_icon16_png));
+                defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon64_java_icon24_png.java_icon24_png));
+                defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon64_java_icon32_png.java_icon32_png));
+                defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon64_java_icon48_png.java_icon48_png));
             }
         }
         return defaultIconInfo;
@@ -667,7 +666,7 @@
             return;
         }
 
-        if (log.isLoggable(PlatformLogger.FINEST)) {
+        if (log.isLoggable(PlatformLogger.Level.FINEST)) {
             log.finest("XWindowPeer: Check if we've been moved to a new screen since we're running in Xinerama mode");
         }
 
@@ -704,7 +703,7 @@
             }
         }
         if (newScreenNum != curScreenNum) {
-            if (log.isLoggable(PlatformLogger.FINEST)) {
+            if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                 log.finest("XWindowPeer: Moved to a new screen");
             }
             executeDisplayChangedOnEDT(newGC);
@@ -779,7 +778,7 @@
         // override_redirect all we can do is check whether our parent
         // is active. If it is - we can freely synthesize focus transfer.
         // Luckily, this logic is already implemented in requestWindowFocus.
-        if (focusLog.isLoggable(PlatformLogger.FINE)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
             focusLog.fine("Requesting window focus");
         }
         requestWindowFocus(time, timeProvided);
@@ -807,7 +806,7 @@
     public void handleFocusEvent(XEvent xev) {
         XFocusChangeEvent xfe = xev.get_xfocus();
         FocusEvent fe;
-        if (focusLog.isLoggable(PlatformLogger.FINE)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
             focusLog.fine("{0}", xfe);
         }
         if (isEventDisabled(xev)) {
@@ -992,7 +991,7 @@
     }
 
     private void updateAlwaysOnTop() {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Promoting always-on-top state {0}", Boolean.valueOf(alwaysOnTop));
         }
         XWM.getWM().setLayer(this,
@@ -1174,7 +1173,7 @@
 
     public void dispose() {
         if (isGrabbed()) {
-            if (grabLog.isLoggable(PlatformLogger.FINE)) {
+            if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
                 grabLog.fine("Generating UngrabEvent on {0} because of the window disposal", this);
             }
             postEventToEventQueue(new sun.awt.UngrabEvent(getEventSource()));
@@ -1519,7 +1518,7 @@
             synchronized(getStateLock()) {
                 XDialogPeer blockerPeer = (XDialogPeer) AWTAccessor.getComponentAccessor().getPeer(d);
                 if (blocked) {
-                    if (log.isLoggable(PlatformLogger.FINE)) {
+                    if (log.isLoggable(PlatformLogger.Level.FINE)) {
                         log.fine("{0} is blocked by {1}", this, blockerPeer);
                     }
                     modalBlocker = d;
@@ -1912,7 +1911,7 @@
 
     @Override
     public void xSetVisible(boolean visible) {
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Setting visible on " + this + " to " + visible);
         }
         XToolkit.awtLock();
@@ -2054,7 +2053,7 @@
 
     public void handleXCrossingEvent(XEvent xev) {
         XCrossingEvent xce = xev.get_xcrossing();
-        if (grabLog.isLoggable(PlatformLogger.FINE)) {
+        if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
             grabLog.fine("{0}, when grabbed {1}, contains {2}",
                          xce, isGrabbed(), containsGlobal(xce.get_x_root(), xce.get_y_root()));
         }
@@ -2067,7 +2066,7 @@
             // since it generates MOUSE_ENTERED/MOUSE_EXITED for frame and dialog.
             // (fix for 6390326)
             XBaseWindow target = XToolkit.windowToXWindow(xce.get_window());
-            if (grabLog.isLoggable(PlatformLogger.FINER)) {
+            if (grabLog.isLoggable(PlatformLogger.Level.FINER)) {
                 grabLog.finer("  -  Grab event target {0}", target);
             }
             if (target != null && target != this) {
@@ -2080,7 +2079,7 @@
 
     public void handleMotionNotify(XEvent xev) {
         XMotionEvent xme = xev.get_xmotion();
-        if (grabLog.isLoggable(PlatformLogger.FINER)) {
+        if (grabLog.isLoggable(PlatformLogger.Level.FINER)) {
             grabLog.finer("{0}, when grabbed {1}, contains {2}",
                           xme, isGrabbed(), containsGlobal(xme.get_x_root(), xme.get_y_root()));
         }
@@ -2111,7 +2110,7 @@
                 xme.set_x(localCoord.x);
                 xme.set_y(localCoord.y);
             }
-            if (grabLog.isLoggable(PlatformLogger.FINER)) {
+            if (grabLog.isLoggable(PlatformLogger.Level.FINER)) {
                 grabLog.finer("  -  Grab event target {0}", target);
             }
             if (target != null) {
@@ -2145,7 +2144,7 @@
         if (xbe.get_button() > SunToolkit.MAX_BUTTONS_SUPPORTED) {
             return;
         }
-        if (grabLog.isLoggable(PlatformLogger.FINE)) {
+        if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
             grabLog.fine("{0}, when grabbed {1}, contains {2} ({3}, {4}, {5}x{6})",
                          xbe, isGrabbed(), containsGlobal(xbe.get_x_root(), xbe.get_y_root()), getAbsoluteX(), getAbsoluteY(), getWidth(), getHeight());
         }
@@ -2156,7 +2155,7 @@
             // translation)
             XBaseWindow target = XToolkit.windowToXWindow(xbe.get_window());
             try {
-                if (grabLog.isLoggable(PlatformLogger.FINER)) {
+                if (grabLog.isLoggable(PlatformLogger.Level.FINER)) {
                     grabLog.finer("  -  Grab event target {0} (press target {1})", target, pressTarget);
                 }
                 if (xbe.get_type() == XConstants.ButtonPress
@@ -2192,7 +2191,7 @@
                         // According to the specification of UngrabEvent, post it
                         // when press occurs outside of the window and not on its owned windows
                         if (xbe.get_type() == XConstants.ButtonPress) {
-                            if (grabLog.isLoggable(PlatformLogger.FINE)) {
+                            if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
                                 grabLog.fine("Generating UngrabEvent on {0} because not inside of shell", this);
                             }
                             postEventToEventQueue(new sun.awt.UngrabEvent(getEventSource()));
@@ -2213,14 +2212,14 @@
                             // toplevel == null - outside of
                             // hierarchy, toplevel is Dialog - should
                             // send ungrab (but shouldn't for Window)
-                            if (grabLog.isLoggable(PlatformLogger.FINE)) {
+                            if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
                                 grabLog.fine("Generating UngrabEvent on {0} because hierarchy ended", this);
                             }
                             postEventToEventQueue(new sun.awt.UngrabEvent(getEventSource()));
                         }
                     } else {
                         // toplevel is null - outside of hierarchy
-                        if (grabLog.isLoggable(PlatformLogger.FINE)) {
+                        if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
                             grabLog.fine("Generating UngrabEvent on {0} because toplevel is null", this);
                         }
                         postEventToEventQueue(new sun.awt.UngrabEvent(getEventSource()));
@@ -2228,7 +2227,7 @@
                     }
                 } else {
                     // target doesn't map to XAWT window - outside of hierarchy
-                    if (grabLog.isLoggable(PlatformLogger.FINE)) {
+                    if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
                         grabLog.fine("Generating UngrabEvent on because target is null {0}", this);
                     }
                     postEventToEventQueue(new sun.awt.UngrabEvent(getEventSource()));
Binary file jdk/src/solaris/classes/sun/awt/X11/security-icon-bw16.png has changed
Binary file jdk/src/solaris/classes/sun/awt/X11/security-icon-bw24.png has changed
Binary file jdk/src/solaris/classes/sun/awt/X11/security-icon-bw32.png has changed
Binary file jdk/src/solaris/classes/sun/awt/X11/security-icon-bw48.png has changed
Binary file jdk/src/solaris/classes/sun/awt/X11/security-icon-interim16.png has changed
Binary file jdk/src/solaris/classes/sun/awt/X11/security-icon-interim24.png has changed
Binary file jdk/src/solaris/classes/sun/awt/X11/security-icon-interim32.png has changed
Binary file jdk/src/solaris/classes/sun/awt/X11/security-icon-interim48.png has changed
Binary file jdk/src/solaris/classes/sun/awt/X11/security-icon-yellow16.png has changed
Binary file jdk/src/solaris/classes/sun/awt/X11/security-icon-yellow24.png has changed
Binary file jdk/src/solaris/classes/sun/awt/X11/security-icon-yellow32.png has changed
Binary file jdk/src/solaris/classes/sun/awt/X11/security-icon-yellow48.png has changed
--- a/jdk/src/solaris/classes/sun/awt/X11GraphicsEnvironment.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11GraphicsEnvironment.java	Wed Jul 05 19:00:49 2017 +0200
@@ -324,7 +324,7 @@
             // pRunningXinerama() simply returns a global boolean variable,
             // so there is no need to synchronize here
             xinerState = Boolean.valueOf(pRunningXinerama());
-            if (screenLog.isLoggable(PlatformLogger.FINER)) {
+            if (screenLog.isLoggable(PlatformLogger.Level.FINER)) {
                 screenLog.finer("Running Xinerama: " + xinerState);
             }
         }
@@ -408,7 +408,7 @@
             (unionRect.width / 2) + unionRect.x < center.x + 1 &&
             (unionRect.height / 2) + unionRect.y < center.y + 1) {
 
-            if (screenLog.isLoggable(PlatformLogger.FINER)) {
+            if (screenLog.isLoggable(PlatformLogger.Level.FINER)) {
                 screenLog.finer("Video Wall: center point is at center of all displays.");
             }
             return unionRect;
@@ -416,7 +416,7 @@
 
         // next, check if at center of one monitor
         if (centerMonitorRect != null) {
-            if (screenLog.isLoggable(PlatformLogger.FINER)) {
+            if (screenLog.isLoggable(PlatformLogger.Level.FINER)) {
                 screenLog.finer("Center point at center of a particular " +
                                 "monitor, but not of the entire virtual display.");
             }
@@ -424,7 +424,7 @@
         }
 
         // otherwise, the center is at some weird spot: return unionRect
-        if (screenLog.isLoggable(PlatformLogger.FINER)) {
+        if (screenLog.isLoggable(PlatformLogger.Level.FINER)) {
             screenLog.finer("Center point is somewhere strange - return union of all bounds.");
         }
         return unionRect;
--- a/jdk/src/solaris/classes/sun/awt/X11InputMethod.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/awt/X11InputMethod.java	Wed Jul 05 19:00:49 2017 +0200
@@ -326,7 +326,7 @@
             return;
 
         if (lastXICFocussedComponent != null){
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 log.fine("XICFocused {0}, AWTFocused {1}",
                          lastXICFocussedComponent, awtFocussedComponent);
             }
--- a/jdk/src/solaris/classes/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/nio/ch/UnixAsynchronousSocketChannelImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -241,7 +241,7 @@
         synchronized (stateLock) {
             state = ST_CONNECTED;
             localAddress = Net.localAddress(fd);
-            remoteAddress = pendingRemote;
+            remoteAddress = (InetSocketAddress)pendingRemote;
         }
     }
 
--- a/jdk/src/solaris/classes/sun/nio/ch/sctp/SctpNet.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/nio/ch/sctp/SctpNet.java	Wed Jul 05 19:00:49 2017 +0200
@@ -94,18 +94,44 @@
 
     static Set<SocketAddress> getLocalAddresses(int fd)
             throws IOException {
-        HashSet<SocketAddress> set = null;
+        Set<SocketAddress> set = null;
         SocketAddress[] saa = getLocalAddresses0(fd);
 
         if (saa != null) {
-            set = new HashSet<SocketAddress>(saa.length);
-            for (SocketAddress sa : saa)
-                set.add(sa);
+            set = getRevealedLocalAddressSet(saa);
         }
 
         return set;
     }
 
+    private static Set<SocketAddress> getRevealedLocalAddressSet(
+            SocketAddress[] saa)
+    {
+         SecurityManager sm = System.getSecurityManager();
+         Set<SocketAddress> set = new HashSet<>(saa.length);
+         for (SocketAddress sa : saa) {
+             set.add(getRevealedLocalAddress(sa, sm));
+         }
+         return set;
+    }
+
+    private static SocketAddress getRevealedLocalAddress(SocketAddress sa,
+                                                         SecurityManager sm)
+    {
+        if (sm == null || sa == null)
+            return sa;
+        InetSocketAddress ia = (InetSocketAddress)sa;
+        try{
+            sm.checkConnect(ia.getAddress().getHostAddress(), -1);
+            // Security check passed
+        } catch (SecurityException e) {
+            // Return loopback address
+            return new InetSocketAddress(InetAddress.getLoopbackAddress(),
+                                         ia.getPort());
+        }
+        return sa;
+    }
+
     static Set<SocketAddress> getRemoteAddresses(int fd, int assocId)
             throws IOException {
         HashSet<SocketAddress> set = null;
--- a/jdk/src/solaris/classes/sun/nio/fs/GnomeFileTypeDetector.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/nio/fs/GnomeFileTypeDetector.java	Wed Jul 05 19:00:49 2017 +0200
@@ -67,6 +67,8 @@
         NativeBuffer buffer = NativeBuffers.asNativeBuffer(path.getByteArrayForSysCalls());
         try {
             if (gioAvailable) {
+                // GIO may access file so need permission check
+                path.checkRead();
                 byte[] type = probeUsingGio(buffer.address());
                 return (type == null) ? null : new String(type);
             } else {
@@ -76,7 +78,6 @@
                 String s = new String(type);
                 return s.equals(GNOME_VFS_MIME_TYPE_UNKNOWN) ? null : s;
             }
-
         } finally {
             buffer.release();
         }
--- a/jdk/src/solaris/classes/sun/print/UnixPrintServiceLookup.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/classes/sun/print/UnixPrintServiceLookup.java	Wed Jul 05 19:00:49 2017 +0200
@@ -362,10 +362,33 @@
      */
     private PrintService getServiceByName(PrinterName nameAttr) {
         String name = nameAttr.getValue();
-        PrintService printer = null;
         if (name == null || name.equals("") || !checkPrinterName(name)) {
             return null;
         }
+        /* check is all printers are already available */
+        if (printServices != null) {
+            for (PrintService printService : printServices) {
+                if (printService.getName().equals(name)) {
+                    return printService;
+                }
+            }
+        }
+        /* take CUPS into account first */
+        if (CUPSPrinter.isCupsRunning()) {
+            try {
+                return new IPPPrintService(name,
+                                           new URL("http://"+
+                                                   CUPSPrinter.getServer()+":"+
+                                                   CUPSPrinter.getPort()+"/"+
+                                                   name));
+            } catch (Exception e) {
+                IPPPrintService.debug_println(debugPrefix+
+                                              " getServiceByName Exception "+
+                                              e);
+            }
+        }
+        /* fallback if nothing not having a printer at this point */
+        PrintService printer = null;
         if (isMac() || isSysV()) {
             printer = getNamedPrinterNameSysV(name);
         } else {
--- a/jdk/src/solaris/native/sun/awt/awt_GraphicsEnv.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/native/sun/awt/awt_GraphicsEnv.c	Wed Jul 05 19:00:49 2017 +0200
@@ -907,6 +907,8 @@
 static jint canUseShmExt = UNSET_MITSHM;
 static jint canUseShmExtPixmaps = UNSET_MITSHM;
 
+extern int mitShmPermissionMask;
+
 void TryInitMITShm(JNIEnv *env, jint *shmExt, jint *shmPixmaps) {
     XShmSegmentInfo shminfo;
     int XShmMajor, XShmMinor;
@@ -930,7 +932,8 @@
      * we need to test that we can actually do XShmAttach.
      */
     if (XShmQueryExtension(awt_display)) {
-        shminfo.shmid = shmget(IPC_PRIVATE, 0x10000, IPC_CREAT|0777);
+        shminfo.shmid = shmget(IPC_PRIVATE, 0x10000,
+                               IPC_CREAT|mitShmPermissionMask);
         if (shminfo.shmid < 0) {
             AWT_UNLOCK();
             J2dRlsTraceLn1(J2D_TRACE_ERROR,
@@ -1366,12 +1369,18 @@
     mid = (*env)->GetMethodID(env, clazz, "<init>", "(IIII)V");
     if (mid != NULL) {
         if (usingXinerama) {
-            bounds = (*env)->NewObject(env, clazz, mid, fbrects[screen].x,
-                                                        fbrects[screen].y,
-                                                        fbrects[screen].width,
-                                                        fbrects[screen].height);
-        }
-        else {
+            if (0 <= screen && screen < awt_numScreens) {
+                bounds = (*env)->NewObject(env, clazz, mid, fbrects[screen].x,
+                                                            fbrects[screen].y,
+                                                            fbrects[screen].width,
+                                                            fbrects[screen].height);
+            } else {
+                jclass exceptionClass = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+                if (exceptionClass != NULL) {
+                    (*env)->ThrowNew(env, exceptionClass, "Illegal screen index");
+                }
+            }
+        } else {
             XWindowAttributes xwa;
             memset(&xwa, 0, sizeof(xwa));
 
--- a/jdk/src/solaris/native/sun/awt/awt_GraphicsEnv.h	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/native/sun/awt/awt_GraphicsEnv.h	Wed Jul 05 19:00:49 2017 +0200
@@ -47,6 +47,9 @@
 #include <X11/extensions/shmproto.h>
 #endif
 
+#define MITSHM_PERM_COMMON (0666)
+#define MITSHM_PERM_OWNER  (0600)
+
 extern int XShmQueryExtension();
 
 void TryInitMITShm(JNIEnv *env, jint *shmExt, jint *shmPixmaps);
--- a/jdk/src/solaris/native/sun/awt/awt_InputMethod.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/native/sun/awt/awt_InputMethod.c	Wed Jul 05 19:00:49 2017 +0200
@@ -447,7 +447,7 @@
  */
 #define INITIAL_LOOKUP_BUF_SIZE 512
 
-Bool
+Boolean
 awt_x11inputmethod_lookupString(XKeyPressedEvent *event, KeySym *keysymp)
 {
     JNIEnv *env = GetJNIEnv();
@@ -457,8 +457,8 @@
     int mblen;
     jstring javastr;
     XIC ic;
-    Bool result = True;
-    static Bool composing = False;
+    Boolean result = True;
+    static Boolean composing = False;
 
     /*
       printf("lookupString: entering...\n");
--- a/jdk/src/solaris/native/sun/awt/awt_Robot.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/native/sun/awt/awt_Robot.c	Wed Jul 05 19:00:49 2017 +0200
@@ -39,6 +39,7 @@
 #include <X11/extensions/XInput.h>
 #include <X11/extensions/XI.h>
 #include <jni.h>
+#include <sizecalc.h>
 #include "robot_common.h"
 #include "canvas.h"
 #include "wsutils.h"
@@ -174,7 +175,7 @@
 
     num_buttons = numberOfButtons;
     tmp = (*env)->GetIntArrayElements(env, buttonDownMasks, JNI_FALSE);
-    masks = (jint *)malloc(sizeof(jint) * num_buttons);
+    masks = (jint *)SAFE_SIZE_ARRAY_ALLOC(malloc, sizeof(jint), num_buttons);
     if (masks == (jint *) NULL) {
         JNU_ThrowOutOfMemoryError((JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2), NULL);
         (*env)->ReleaseIntArrayElements(env, buttonDownMasks, tmp, 0);
@@ -231,8 +232,9 @@
     image = getWindowImage(awt_display, rootWindow, x, y, width, height);
 
     /* Array to use to crunch around the pixel values */
-    ary = (jint *) malloc(width * height * sizeof (jint));
-    if (ary == NULL) {
+    if (!IS_SAFE_SIZE_MUL(width, height) ||
+        !(ary = (jint *) SAFE_SIZE_ARRAY_ALLOC(malloc, width * height, sizeof (jint))))
+    {
         JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError");
         XDestroyImage(image);
         AWT_UNLOCK();
--- a/jdk/src/solaris/native/sun/awt/awt_UNIXToolkit.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/native/sun/awt/awt_UNIXToolkit.c	Wed Jul 05 19:00:49 2017 +0200
@@ -29,6 +29,7 @@
 #include <dlfcn.h>
 
 #include <jni.h>
+#include <sizecalc.h>
 #include "sun_awt_UNIXToolkit.h"
 
 #ifndef HEADLESS
@@ -148,7 +149,8 @@
     }
 
     len = (*env)->GetStringUTFLength(env, filename);
-    filename_str = (char *)malloc(sizeof(char) * (len + 1));
+    filename_str = (char *)SAFE_SIZE_ARRAY_ALLOC(malloc,
+            sizeof(char), len + 1);
     if (filename_str == NULL) {
         JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError");
         return JNI_FALSE;
@@ -189,7 +191,8 @@
     }
 
     len = (*env)->GetStringUTFLength(env, stock_id);
-    stock_id_str = (char *)malloc(sizeof(char) * (len + 1));
+    stock_id_str = (char *)SAFE_SIZE_ARRAY_ALLOC(malloc,
+            sizeof(char), len + 1);
     if (stock_id_str == NULL) {
         JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError");
         return JNI_FALSE;
@@ -200,7 +203,8 @@
     if (detail != NULL)
     {
         len = (*env)->GetStringUTFLength(env, detail);
-        detail_str = (char *)malloc(sizeof(char) * (len + 1));
+        detail_str = (char *)SAFE_SIZE_ARRAY_ALLOC(malloc,
+                sizeof(char), len + 1);
         if (detail_str == NULL) {
             JNU_ThrowOutOfMemoryError(env, "OutOfMemoryError");
             return JNI_FALSE;
--- a/jdk/src/solaris/native/sun/awt/fontpath.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/native/sun/awt/fontpath.c	Wed Jul 05 19:00:49 2017 +0200
@@ -41,6 +41,7 @@
 #include <jni.h>
 #include <jni_util.h>
 #include <jvm_md.h>
+#include <sizecalc.h>
 #ifndef HEADLESS
 #include <X11/Xlib.h>
 #include <awt.h>
@@ -225,7 +226,7 @@
 
     if ( fDirP->num == 0 ) return;
 
-    appendDirList = malloc ( fDirP->num * sizeof ( int ));
+    appendDirList = SAFE_SIZE_ARRAY_ALLOC(malloc, fDirP->num, sizeof ( int ));
     if ( appendDirList == NULL ) {
       return;  /* if it fails we cannot do much */
     }
@@ -282,7 +283,7 @@
     }
 
 
-    newFontPath = malloc ( totalDirCount * sizeof ( char **) );
+    newFontPath = SAFE_SIZE_ARRAY_ALLOC(malloc, totalDirCount, sizeof ( char **) );
     /* if it fails free things and get out */
     if ( newFontPath == NULL ) {
       free ( ( void *) appendDirList );
@@ -303,7 +304,12 @@
 
         /* printf ( "Appending %s\n", fDirP->name[index] ); */
 
-        onePath = malloc ( ( strlen (fDirP->name[index]) + 2 )* sizeof( char ) );
+        onePath = SAFE_SIZE_ARRAY_ALLOC(malloc, strlen (fDirP->name[index]) + 2, sizeof( char ) );
+        if (onePath == NULL) {
+            free ( ( void *) appendDirList );
+            XFreeFontPath ( origFontPath );
+            return;
+        }
         strcpy ( onePath, fDirP->name[index] );
         strcat ( onePath, "/" );
         newFontPath[nPaths++] = onePath;
--- a/jdk/src/solaris/native/sun/awt/gtk2_interface.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/native/sun/awt/gtk2_interface.c	Wed Jul 05 19:00:49 2017 +0200
@@ -31,6 +31,7 @@
 #include "gtk2_interface.h"
 #include "java_awt_Transparency.h"
 #include "jvm_md.h"
+#include "sizecalc.h"
 
 #define GTK2_LIB_VERSIONED VERSIONED_JNI_LIB_NAME("gtk-x11-2.0", "0")
 #define GTK2_LIB JNI_LIB_NAME("gtk-x11-2.0")
@@ -765,7 +766,8 @@
         gtk_modules_env && strstr (gtk_modules_env, "gail"))
     {
         /* the new env will be smaller than the old one */
-        gchar *s, *new_env = malloc (sizeof(ENV_PREFIX)+strlen (gtk_modules_env));
+        gchar *s, *new_env = SAFE_SIZE_STRUCT_ALLOC(malloc,
+                sizeof(ENV_PREFIX), 1, strlen (gtk_modules_env));
 
         if (new_env != NULL )
         {
--- a/jdk/src/solaris/native/sun/awt/splashscreen/splashscreen_sys.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/native/sun/awt/splashscreen/splashscreen_sys.c	Wed Jul 05 19:00:49 2017 +0200
@@ -41,6 +41,7 @@
 #include <locale.h>
 #include <fcntl.h>
 #include <poll.h>
+#include <sizecalc.h>
 
 static Bool shapeSupported;
 static int shapeEventBase, shapeErrorBase;
@@ -76,9 +77,12 @@
         goto done;
     }
     inSize = strlen(in);
+    buf = SAFE_SIZE_ARRAY_ALLOC(malloc, inSize, 2);
+    if (!buf) {
+        return NULL;
+    }
     bufSize = inSize*2; // need 2 bytes per char for UCS-2, this is
                         // 2 bytes per source byte max
-    buf = malloc(bufSize);
     out = buf; outSize = bufSize;
     /* linux iconv wants char** source and solaris wants const char**...
        cast to void* */
@@ -114,12 +118,20 @@
     initRect(&maskRect, 0, 0, splash->width, splash->height, 1,
             splash->width * splash->imageFormat.depthBytes,
             splash->frames[imageIndex].bitmapBits, &splash->imageFormat);
-    rects =
-        malloc(sizeof(XRectangle) * (splash->width / 2 + 1) * splash->height);
+    if (!IS_SAFE_SIZE_MUL(splash->width / 2 + 1, splash->height)) {
+        return;
+    }
+    rects = SAFE_SIZE_ARRAY_ALLOC(malloc,
+            sizeof(XRectangle), (splash->width / 2 + 1) * splash->height);
+    if (!rects) {
+        return;
+    }
 
     frame->numRects = BitmapToYXBandedRectangles(&maskRect, rects);
-    frame->rects = malloc(frame->numRects * sizeof(XRectangle));
-    memcpy(frame->rects, rects, frame->numRects * sizeof(XRectangle));
+    frame->rects = SAFE_SIZE_ARRAY_ALLOC(malloc, frame->numRects, sizeof(XRectangle));
+    if (frame->rects) { // handle the error after the if(){}
+        memcpy(frame->rects, rects, frame->numRects * sizeof(XRectangle));
+    }
     free(rects);
 }
 
--- a/jdk/src/solaris/native/sun/java2d/x11/X11SurfaceData.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/native/sun/java2d/x11/X11SurfaceData.c	Wed Jul 05 19:00:49 2017 +0200
@@ -88,6 +88,7 @@
 jint useMitShmExt = CANT_USE_MITSHM;
 jint useMitShmPixmaps = CANT_USE_MITSHM;
 jint forceSharedPixmaps = JNI_FALSE;
+int mitShmPermissionMask = MITSHM_PERM_OWNER;
 
 /* Cached shared image, one for all surface datas. */
 static XImage * cachedXImage;
@@ -118,6 +119,13 @@
     if (getenv("NO_AWT_MITSHM") == NULL &&
         getenv("NO_J2D_MITSHM") == NULL) {
         char * force;
+        char * permission = getenv("J2D_MITSHM_PERMISSION");
+        if (permission != NULL) {
+            if (strcmp(permission, "common") == 0) {
+                mitShmPermissionMask = MITSHM_PERM_COMMON;
+            }
+        }
+
         TryInitMITShm(env, &useMitShmExt, &useMitShmPixmaps);
 
         if(allowShmPixmaps) {
@@ -537,7 +545,8 @@
         return NULL;
     }
     shminfo->shmid =
-        shmget(IPC_PRIVATE, height * img->bytes_per_line, IPC_CREAT|0777);
+        shmget(IPC_PRIVATE, height * img->bytes_per_line,
+               IPC_CREAT|mitShmPermissionMask);
     if (shminfo->shmid < 0) {
         J2dRlsTraceLn1(J2D_TRACE_ERROR,
                        "X11SD_SetupSharedSegment shmget has failed: %s",
--- a/jdk/src/solaris/native/sun/nio/ch/Net.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/native/sun/nio/ch/Net.c	Wed Jul 05 19:00:49 2017 +0200
@@ -124,6 +124,11 @@
     return (ipv6_available()) ? JNI_TRUE : JNI_FALSE;
 }
 
+JNIEXPORT jint JNICALL
+Java_sun_nio_ch_Net_isExclusiveBindAvailable(JNIEnv *env, jclass clazz) {
+    return -1;
+}
+
 JNIEXPORT jboolean JNICALL
 Java_sun_nio_ch_Net_canIPv6SocketJoinIPv4Group0(JNIEnv* env, jclass cl)
 {
@@ -206,8 +211,8 @@
 }
 
 JNIEXPORT void JNICALL
-Java_sun_nio_ch_Net_bind0(JNIEnv *env, jclass clazz, jboolean preferIPv6,
-                          jobject fdo, jobject iao, int port)
+Java_sun_nio_ch_Net_bind0(JNIEnv *env, jclass clazz, jobject fdo, jboolean preferIPv6,
+                          jboolean useExclBind, jobject iao, int port)
 {
     SOCKADDR sa;
     int sa_len = SOCKADDR_LEN;
--- a/jdk/src/solaris/native/sun/xawt/XToolkit.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/native/sun/xawt/XToolkit.c	Wed Jul 05 19:00:49 2017 +0200
@@ -685,8 +685,7 @@
     if (result == 0) {
         /* poll() timed out -- update timeout value */
         update_poll_timeout(TIMEOUT_TIMEDOUT);
-        PRINT2("%s(): TIMEOUT_TIMEDOUT curPollTimeout = %d \n",
-              performPoll, curPollTimeout);
+        PRINT2("performPoll(): TIMEOUT_TIMEDOUT curPollTimeout = %d \n", curPollTimeout);
     }
     if (pollFds[1].revents) {
         int count;
@@ -695,14 +694,12 @@
         do {
             count = read(AWT_READPIPE, read_buf, AWT_POLL_BUFSIZE );
         } while (count == AWT_POLL_BUFSIZE );
-        PRINT2("%s():  data on the AWT pipe: curPollTimeout = %d \n",
-               performPoll, curPollTimeout);
+        PRINT2("performPoll():  data on the AWT pipe: curPollTimeout = %d \n", curPollTimeout);
     }
     if (pollFds[0].revents) {
         // Events in X pipe
         update_poll_timeout(TIMEOUT_EVENTS);
-        PRINT2("%s(): TIMEOUT_EVENTS curPollTimeout = %ld \n",
-               performPoll, curPollTimeout);
+        PRINT2("performPoll(): TIMEOUT_EVENTS curPollTimeout = %ld \n", curPollTimeout);
     }
     return;
 
--- a/jdk/src/solaris/native/sun/xawt/XlibWrapper.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/solaris/native/sun/xawt/XlibWrapper.c	Wed Jul 05 19:00:49 2017 +0200
@@ -38,6 +38,7 @@
 #include <jni.h>
 #include <jni_util.h>
 #include <jlong.h>
+#include <sizecalc.h>
 
 #include <awt.h>
 #include <jvm.h>
@@ -2228,6 +2229,10 @@
     RECT_T * pRect;
     int numrects;
 
+    if (!IS_SAFE_SIZE_MUL(width / 2 + 1, height)) {
+        return;
+    }
+
     AWT_CHECK_HAVE_LOCK();
 
     len = (*env)->GetArrayLength(env, bitmap);
@@ -2240,7 +2245,10 @@
         return;
     }
 
-    pRect = (RECT_T *)malloc(worstBufferSize * sizeof(RECT_T));
+    pRect = (RECT_T *)SAFE_SIZE_ARRAY_ALLOC(malloc, worstBufferSize, sizeof(RECT_T));
+    if (!pRect) {
+        return;
+    }
 
     /* Note: the values[0] and values[1] are supposed to contain the width
      * and height (see XIconInfo.getIntData() for details). So, we do +2.
--- a/jdk/src/windows/classes/java/lang/ProcessImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/java/lang/ProcessImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -170,7 +170,19 @@
         return matchList.toArray(new String[matchList.size()]);
     }
 
-    private static String createCommandLine(boolean isCmdFile,
+    private static final int VERIFICATION_CMD_BAT = 0;
+    private static final int VERIFICATION_WIN32 = 1;
+    private static final int VERIFICATION_LEGACY = 2;
+    private static final char ESCAPE_VERIFICATION[][] = {
+        // We guarantee the only command file execution for implicit [cmd.exe] run.
+        //    http://technet.microsoft.com/en-us/library/bb490954.aspx
+        {' ', '\t', '<', '>', '&', '|', '^'},
+
+        {' ', '\t', '<', '>'},
+        {' ', '\t'}
+    };
+
+    private static String createCommandLine(int verificationType,
                                      final String executablePath,
                                      final String cmd[])
     {
@@ -181,9 +193,8 @@
         for (int i = 1; i < cmd.length; ++i) {
             cmdbuf.append(' ');
             String s = cmd[i];
-            if (needsEscaping(isCmdFile, s)) {
-                cmdbuf.append('"');
-                cmdbuf.append(s);
+            if (needsEscaping(verificationType, s)) {
+                cmdbuf.append('"').append(s);
 
                 // The code protects the [java.exe] and console command line
                 // parser, that interprets the [\"] combination as an escape
@@ -197,7 +208,7 @@
                 // command line parser. The case of the [""] tail escape
                 // sequence could not be realized due to the argument validation
                 // procedure.
-                if (!isCmdFile && s.endsWith("\\")) {
+                if ((verificationType != VERIFICATION_CMD_BAT) && s.endsWith("\\")) {
                     cmdbuf.append('\\');
                 }
                 cmdbuf.append('"');
@@ -208,11 +219,6 @@
         return cmdbuf.toString();
     }
 
-    // We guarantee the only command file execution for implicit [cmd.exe] run.
-    //    http://technet.microsoft.com/en-us/library/bb490954.aspx
-    private static final char CMD_BAT_ESCAPE[] = {' ', '\t', '<', '>', '&', '|', '^'};
-    private static final char WIN32_EXECUTABLE_ESCAPE[] = {' ', '\t', '<', '>'};
-
     private static boolean isQuoted(boolean noQuotesInside, String arg,
             String errorMessage) {
         int lastPos = arg.length() - 1;
@@ -235,7 +241,7 @@
         return false;
     }
 
-    private static boolean needsEscaping(boolean isCmdFile, String arg) {
+    private static boolean needsEscaping(int verificationType, String arg) {
         // Switch off MS heuristic for internal ["].
         // Please, use the explicit [cmd.exe] call
         // if you need the internal ["].
@@ -243,13 +249,12 @@
 
         // For [.exe] or [.com] file the unpaired/internal ["]
         // in the argument is not a problem.
-        boolean argIsQuoted = isQuoted(isCmdFile, arg,
-            "Argument has embedded quote, use the explicit CMD.EXE call.");
+        boolean argIsQuoted = isQuoted(
+            (verificationType == VERIFICATION_CMD_BAT),
+            arg, "Argument has embedded quote, use the explicit CMD.EXE call.");
 
         if (!argIsQuoted) {
-            char testEscape[] = isCmdFile
-                    ? CMD_BAT_ESCAPE
-                    : WIN32_EXECUTABLE_ESCAPE;
+            char testEscape[] = ESCAPE_VERIFICATION[verificationType];
             for (int i = 0; i < testEscape.length; ++i) {
                 if (arg.indexOf(testEscape[i]) >= 0) {
                     return true;
@@ -315,24 +320,26 @@
     {
         String cmdstr;
         SecurityManager security = System.getSecurityManager();
-        boolean allowAmbigousCommands = false;
+        boolean allowAmbiguousCommands = false;
         if (security == null) {
-            String value = System.getProperty("jdk.lang.Process.allowAmbigousCommands");
+            allowAmbiguousCommands = true;
+            String value = System.getProperty("jdk.lang.Process.allowAmbiguousCommands");
             if (value != null)
-                allowAmbigousCommands = !"false".equalsIgnoreCase(value);
+                allowAmbiguousCommands = !"false".equalsIgnoreCase(value);
         }
-        if (allowAmbigousCommands) {
+        if (allowAmbiguousCommands) {
             // Legacy mode.
 
             // Normalize path if possible.
             String executablePath = new File(cmd[0]).getPath();
 
-            // No worry about internal and unpaired ["] .
-            if (needsEscaping(false, executablePath) )
+            // No worry about internal, unpaired ["], and redirection/piping.
+            if (needsEscaping(VERIFICATION_LEGACY, executablePath) )
                 executablePath = quoteString(executablePath);
 
             cmdstr = createCommandLine(
-                false, //legacy mode doesn't worry about extended verification
+                //legacy mode doesn't worry about extended verification
+                VERIFICATION_LEGACY,
                 executablePath,
                 cmd);
         } else {
@@ -369,7 +376,9 @@
             // [.exe] extension heuristic.
             cmdstr = createCommandLine(
                     // We need the extended verification procedure for CMD files.
-                    isShellFile(executablePath),
+                    isShellFile(executablePath)
+                        ? VERIFICATION_CMD_BAT
+                        : VERIFICATION_WIN32,
                     quoteString(executablePath),
                     cmd);
         }
--- a/jdk/src/windows/classes/java/net/DefaultDatagramSocketImplFactory.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/java/net/DefaultDatagramSocketImplFactory.java	Wed Jul 05 19:00:49 2017 +0200
@@ -56,24 +56,45 @@
     /* If the version supports a dual stack TCP implementation */
     private static boolean useDualStackImpl = false;
 
+    /* sun.net.useExclusiveBind */
+    private static String exclBindProp;
+
+    /* True if exclusive binding is on for Windows */
+    private static boolean exclusiveBind = true;
+
+
     static {
         // Determine Windows Version.
-        java.security.AccessController.doPrivileged( new PrivilegedAction<Object>() {
-                public Object run() {
-                    version = 0;
-                    try {
-                        version = Float.parseFloat(System.getProperties().getProperty("os.version"));
-                        preferIPv4Stack = Boolean.parseBoolean(
-                                          System.getProperties().getProperty("java.net.preferIPv4Stack"));
-                    } catch (NumberFormatException e ) {
-                        assert false : e;
+        java.security.AccessController.doPrivileged(
+                new PrivilegedAction<Object>() {
+                    public Object run() {
+                        version = 0;
+                        try {
+                            version = Float.parseFloat(System.getProperties()
+                                    .getProperty("os.version"));
+                            preferIPv4Stack = Boolean.parseBoolean(
+                                              System.getProperties()
+                                              .getProperty(
+                                                   "java.net.preferIPv4Stack"));
+                            exclBindProp = System.getProperty(
+                                    "sun.net.useExclusiveBind");
+                        } catch (NumberFormatException e ) {
+                            assert false : e;
+                        }
+                        return null; // nothing to return
                     }
-                    return null; // nothing to return
-                } });
+                });
 
         // (version >= 6.0) implies Vista or greater.
         if (version >= 6.0 && !preferIPv4Stack) {
-            useDualStackImpl = true;
+                useDualStackImpl = true;
+        }
+        if (exclBindProp != null) {
+            // sun.net.useExclusiveBind is true
+            exclusiveBind = exclBindProp.length() == 0 ? true
+                    : Boolean.parseBoolean(exclBindProp);
+        } else if (version < 6.0) {
+            exclusiveBind = false;
         }
 
         // impl.prefix
@@ -105,10 +126,12 @@
                 throw new SocketException("can't instantiate DatagramSocketImpl");
             }
         } else {
+            if (isMulticast)
+                exclusiveBind = false;
             if (useDualStackImpl && !isMulticast)
-                return new DualStackPlainDatagramSocketImpl();
+                return new DualStackPlainDatagramSocketImpl(exclusiveBind);
             else
-                return new TwoStacksPlainDatagramSocketImpl();
+                return new TwoStacksPlainDatagramSocketImpl(exclusiveBind);
         }
     }
 }
--- a/jdk/src/windows/classes/java/net/DualStackPlainDatagramSocketImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/java/net/DualStackPlainDatagramSocketImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -45,6 +45,22 @@
 {
     static JavaIOFileDescriptorAccess fdAccess = SharedSecrets.getJavaIOFileDescriptorAccess();
 
+    // true if this socket is exclusively bound
+    private final boolean exclusiveBind;
+
+    /*
+     * Set to true if SO_REUSEADDR is set after the socket is bound to
+     * indicate SO_REUSEADDR is being emulated
+     */
+    private boolean reuseAddressEmulated;
+
+    // emulates SO_REUSEADDR when exclusiveBind is true and socket is bound
+    private boolean isReuseAddress;
+
+    DualStackPlainDatagramSocketImpl(boolean exclBind) {
+        exclusiveBind = exclBind;
+    }
+
     protected void datagramSocketCreate() throws SocketException {
         if (fd == null)
             throw new SocketException("Socket closed");
@@ -61,7 +77,7 @@
         if (laddr == null)
             throw new NullPointerException("argument address");
 
-        socketBind(nativefd, laddr, lport);
+        socketBind(nativefd, laddr, lport, exclusiveBind);
         if (lport == 0) {
             localPort = socketLocalPort(nativefd);
         } else {
@@ -141,6 +157,7 @@
         fdAccess.set(fd, -1);
     }
 
+    @SuppressWarnings("fallthrough")
     protected void socketSetOption(int opt, Object val) throws SocketException {
         int nativefd = checkAndReturnNativeFD();
 
@@ -153,6 +170,13 @@
                 optionValue = ((Integer)val).intValue();
                 break;
             case SO_REUSEADDR :
+                if (exclusiveBind && localPort != 0)  {
+                    // socket already bound, emulate SO_REUSEADDR
+                    reuseAddressEmulated = true;
+                    isReuseAddress = (Boolean)val;
+                    return;
+                }
+                //Intentional fallthrough
             case SO_BROADCAST :
                 optionValue = ((Boolean)val).booleanValue() ? 1 : 0;
                 break;
@@ -170,6 +194,8 @@
         if (opt == SO_BINDADDR) {
             return socketLocalAddress(nativefd);
         }
+        if (opt == SO_REUSEADDR && reuseAddressEmulated)
+            return isReuseAddress;
 
         int value = socketGetIntOption(nativefd, opt);
         Object returnValue = null;
@@ -238,8 +264,8 @@
 
     private static native int socketCreate(boolean v6Only);
 
-    private static native void socketBind(int fd, InetAddress localAddress, int localport)
-        throws SocketException;
+    private static native void socketBind(int fd, InetAddress localAddress,
+            int localport, boolean exclBind) throws SocketException;
 
     private static native void socketConnect(int fd, InetAddress address, int port)
         throws SocketException;
--- a/jdk/src/windows/classes/java/net/DualStackPlainSocketImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/java/net/DualStackPlainSocketImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -42,10 +42,20 @@
 {
     static JavaIOFileDescriptorAccess fdAccess = SharedSecrets.getJavaIOFileDescriptorAccess();
 
-    public DualStackPlainSocketImpl() {}
+
+    // true if this socket is exclusively bound
+    private final boolean exclusiveBind;
+
+    // emulates SO_REUSEADDR when exclusiveBind is true
+    private boolean isReuseAddress;
 
-    public DualStackPlainSocketImpl(FileDescriptor fd) {
+    public DualStackPlainSocketImpl(boolean exclBind) {
+        exclusiveBind = exclBind;
+    }
+
+    public DualStackPlainSocketImpl(FileDescriptor fd, boolean exclBind) {
         this.fd = fd;
+        exclusiveBind = exclBind;
     }
 
     void socketCreate(boolean stream) throws IOException {
@@ -93,7 +103,7 @@
         if (address == null)
             throw new NullPointerException("inet address argument is null.");
 
-        bind0(nativefd, address, port);
+        bind0(nativefd, address, port, exclusiveBind);
         if (port == 0) {
             localport = localPort0(nativefd);
         } else {
@@ -162,6 +172,8 @@
         shutdown0(nativefd, howto);
     }
 
+    // Intentional fallthrough after SO_REUSEADDR
+    @SuppressWarnings("fallthrough")
     void socketSetOption(int opt, boolean on, Object value)
         throws SocketException {
         int nativefd = checkAndReturnNativeFD();
@@ -173,10 +185,16 @@
         int optionValue = 0;
 
         switch(opt) {
+            case SO_REUSEADDR :
+                if (exclusiveBind) {
+                    // SO_REUSEADDR emulated when using exclusive bind
+                    isReuseAddress = on;
+                    return;
+                }
+                // intentional fallthrough
             case TCP_NODELAY :
             case SO_OOBINLINE :
             case SO_KEEPALIVE :
-            case SO_REUSEADDR :
                 optionValue = on ? 1 : 0;
                 break;
             case SO_SNDBUF :
@@ -207,6 +225,10 @@
             return 0;  // return value doesn't matter.
         }
 
+        // SO_REUSEADDR emulated when using exclusive bind
+        if (opt == SO_REUSEADDR && exclusiveBind)
+            return isReuseAddress? 1 : -1;
+
         int value = getIntOption(nativefd, opt);
 
         switch (opt) {
@@ -243,7 +265,8 @@
 
     static native int socket0(boolean stream, boolean v6Only) throws IOException;
 
-    static native void bind0(int fd, InetAddress localAddress, int localport)
+    static native void bind0(int fd, InetAddress localAddress, int localport,
+                             boolean exclBind)
         throws IOException;
 
     static native int connect0(int fd, InetAddress remote, int remotePort)
--- a/jdk/src/windows/classes/java/net/PlainSocketImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/java/net/PlainSocketImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -54,6 +54,12 @@
     /* If the version supports a dual stack TCP implementation */
     private static boolean useDualStackImpl = false;
 
+    /* sun.net.useExclusiveBind */
+    private static String exclBindProp;
+
+    /* True if exclusive binding is on for Windows */
+    private static boolean exclusiveBind = true;
+
     static {
         java.security.AccessController.doPrivileged( new PrivilegedAction<Object>() {
                 public Object run() {
@@ -62,6 +68,7 @@
                         version = Float.parseFloat(System.getProperties().getProperty("os.version"));
                         preferIPv4Stack = Boolean.parseBoolean(
                                           System.getProperties().getProperty("java.net.preferIPv4Stack"));
+                        exclBindProp = System.getProperty("sun.net.useExclusiveBind");
                     } catch (NumberFormatException e ) {
                         assert false : e;
                     }
@@ -70,7 +77,15 @@
 
         // (version >= 6.0) implies Vista or greater.
         if (version >= 6.0 && !preferIPv4Stack) {
-            useDualStackImpl = true;
+                useDualStackImpl = true;
+        }
+
+        if (exclBindProp != null) {
+            // sun.net.useExclusiveBind is true
+            exclusiveBind = exclBindProp.length() == 0 ? true
+                    : Boolean.parseBoolean(exclBindProp);
+        } else if (version < 6.0) {
+            exclusiveBind = false;
         }
     }
 
@@ -79,9 +94,9 @@
      */
     PlainSocketImpl() {
         if (useDualStackImpl) {
-            impl = new DualStackPlainSocketImpl();
+            impl = new DualStackPlainSocketImpl(exclusiveBind);
         } else {
-            impl = new TwoStacksPlainSocketImpl();
+            impl = new TwoStacksPlainSocketImpl(exclusiveBind);
         }
     }
 
@@ -90,9 +105,9 @@
      */
     PlainSocketImpl(FileDescriptor fd) {
         if (useDualStackImpl) {
-            impl = new DualStackPlainSocketImpl(fd);
+            impl = new DualStackPlainSocketImpl(fd, exclusiveBind);
         } else {
-            impl = new TwoStacksPlainSocketImpl(fd);
+            impl = new TwoStacksPlainSocketImpl(fd, exclusiveBind);
         }
     }
 
--- a/jdk/src/windows/classes/java/net/TwoStacksPlainDatagramSocketImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/java/net/TwoStacksPlainDatagramSocketImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -66,6 +66,22 @@
         init();
     }
 
+    // true if this socket is exclusively bound
+    private final boolean exclusiveBind;
+
+    /*
+     * Set to true if SO_REUSEADDR is set after the socket is bound to
+     * indicate SO_REUSEADDR is being emulated
+     */
+    private boolean reuseAddressEmulated;
+
+    // emulates SO_REUSEADDR when exclusiveBind is true and socket is bound
+    private boolean isReuseAddress;
+
+    TwoStacksPlainDatagramSocketImpl(boolean exclBind) {
+        exclusiveBind = exclBind;
+    }
+
     protected synchronized void create() throws SocketException {
         fd1 = new FileDescriptor();
         try {
@@ -84,6 +100,14 @@
         }
     }
 
+    @Override
+    protected synchronized void bind0(int lport, InetAddress laddr)
+        throws SocketException
+    {
+        bind0(lport, laddr, exclusiveBind);
+
+    }
+
     protected synchronized void receive(DatagramPacket p)
         throws IOException {
         try {
@@ -104,8 +128,24 @@
             }
             int family = connectedAddress == null ? -1 : connectedAddress.holder().getFamily();
             return socketLocalAddress(family);
-        } else
+        } else if (optID == SO_REUSEADDR && reuseAddressEmulated) {
+            return isReuseAddress;
+        } else {
             return super.getOption(optID);
+        }
+    }
+
+    protected void socketSetOption(int opt, Object val)
+        throws SocketException
+    {
+        if (opt == SO_REUSEADDR && exclusiveBind && localPort != 0)  {
+            // socket already bound, emulate
+            reuseAddressEmulated = true;
+            isReuseAddress = (Boolean)val;
+        } else {
+            socketNativeSetOption(opt, val);
+        }
+
     }
 
     protected boolean isClosed() {
@@ -123,7 +163,8 @@
 
     /* Native methods */
 
-    protected synchronized native void bind0(int lport, InetAddress laddr)
+    protected synchronized native void bind0(int lport, InetAddress laddr,
+                                             boolean exclBind)
         throws SocketException;
 
     protected native void send(DatagramPacket p) throws IOException;
@@ -155,7 +196,7 @@
 
     protected native void datagramSocketClose();
 
-    protected native void socketSetOption(int opt, Object val)
+    protected native void socketNativeSetOption(int opt, Object val)
         throws SocketException;
 
     protected native Object socketGetOption(int opt) throws SocketException;
--- a/jdk/src/windows/classes/java/net/TwoStacksPlainSocketImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/java/net/TwoStacksPlainSocketImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -66,14 +66,23 @@
      */
     private int lastfd = -1;
 
+    // true if this socket is exclusively bound
+    private final boolean exclusiveBind;
+
+    // emulates SO_REUSEADDR when exclusiveBind is true
+    private boolean isReuseAddress;
+
     static {
         initProto();
     }
 
-    public TwoStacksPlainSocketImpl() {}
+    public TwoStacksPlainSocketImpl(boolean exclBind) {
+        exclusiveBind = exclBind;
+    }
 
-    public TwoStacksPlainSocketImpl(FileDescriptor fd) {
+    public TwoStacksPlainSocketImpl(FileDescriptor fd, boolean exclBind) {
         this.fd = fd;
+        exclusiveBind = exclBind;
     }
 
     /**
@@ -116,13 +125,33 @@
             InetAddressContainer in = new InetAddressContainer();
             socketGetOption(opt, in);
             return in.addr;
+        } else if (opt == SO_REUSEADDR && exclusiveBind) {
+            // SO_REUSEADDR emulated when using exclusive bind
+            return isReuseAddress;
         } else
             return super.getOption(opt);
     }
 
+    @Override
+    void socketBind(InetAddress address, int port) throws IOException {
+        socketBind(address, port, exclusiveBind);
+    }
+
+    @Override
+    void socketSetOption(int opt, boolean on, Object value)
+        throws SocketException
+    {
+        // SO_REUSEADDR emulated when using exclusive bind
+        if (opt == SO_REUSEADDR && exclusiveBind)
+            isReuseAddress = on;
+        else
+            socketNativeSetOption(opt, on, value);
+    }
+
     /**
      * Closes the socket.
      */
+    @Override
     protected void close() throws IOException {
         synchronized(fdLock) {
             if (fd != null || fd1 != null) {
@@ -155,6 +184,7 @@
         }
     }
 
+    @Override
     void reset() throws IOException {
         if (fd != null || fd1 != null) {
             socketClose();
@@ -167,6 +197,7 @@
     /*
      * Return true if already closed or close is pending
      */
+    @Override
     public boolean isClosedOrPending() {
         /*
          * Lock on fdLock to ensure that we wait if a
@@ -190,7 +221,7 @@
     native void socketConnect(InetAddress address, int port, int timeout)
         throws IOException;
 
-    native void socketBind(InetAddress address, int port)
+    native void socketBind(InetAddress address, int port, boolean exclBind)
         throws IOException;
 
     native void socketListen(int count) throws IOException;
@@ -203,7 +234,7 @@
 
     native void socketShutdown(int howto) throws IOException;
 
-    native void socketSetOption(int cmd, boolean on, Object value)
+    native void socketNativeSetOption(int cmd, boolean on, Object value)
         throws SocketException;
 
     native int socketGetOption(int opt, Object iaContainerObj) throws SocketException;
--- a/jdk/src/windows/classes/sun/awt/windows/WComponentPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WComponentPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -177,7 +177,7 @@
     void dynamicallyLayoutContainer() {
         // If we got the WM_SIZING, this must be a Container, right?
         // In fact, it must be the top-level Container.
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             Container parent = WToolkit.getNativeContainer((Component)target);
             if (parent != null) {
                 log.fine("Assertion (parent == null) failed");
@@ -282,7 +282,7 @@
             paintArea.add(r, e.getID());
         }
 
-        if (log.isLoggable(PlatformLogger.FINEST)) {
+        if (log.isLoggable(PlatformLogger.Level.FINEST)) {
             switch(e.getID()) {
             case PaintEvent.UPDATE:
                 log.finest("coalescePaintEvent: UPDATE: add: x = " +
@@ -360,7 +360,7 @@
     }
 
     void handleJavaFocusEvent(FocusEvent fe) {
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer(fe.toString());
         }
         setFocus(fe.getID() == FocusEvent.FOCUS_GAINED);
@@ -682,7 +682,7 @@
           case WKeyboardFocusManagerPeer.SNFH_FAILURE:
               return false;
           case WKeyboardFocusManagerPeer.SNFH_SUCCESS_PROCEED:
-              if (focusLog.isLoggable(PlatformLogger.FINER)) {
+              if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                   focusLog.finer("Proceeding with request to " + lightweightChild + " in " + target);
               }
               Window parentWindow = SunToolkit.getContainingWindow((Component)target);
@@ -695,7 +695,7 @@
               }
               boolean res = wpeer.requestWindowFocus(cause);
 
-              if (focusLog.isLoggable(PlatformLogger.FINER)) {
+              if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
                   focusLog.finer("Requested window focus: " + res);
               }
               // If parent window can be made focused and has been made focused(synchronously)
@@ -717,7 +717,7 @@
     }
 
     private boolean rejectFocusRequestHelper(String logMsg) {
-        if (focusLog.isLoggable(PlatformLogger.FINER)) {
+        if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
             focusLog.finer(logMsg);
         }
         WKeyboardFocusManagerPeer.removeLastFocusRequest((Component)target);
@@ -1094,7 +1094,7 @@
      */
     @SuppressWarnings("deprecation")
     public void applyShape(Region shape) {
-        if (shapeLog.isLoggable(PlatformLogger.FINER)) {
+        if (shapeLog.isLoggable(PlatformLogger.Level.FINER)) {
             shapeLog.finer("*** INFO: Setting shape: PEER: " + this
                             + "; TARGET: " + target
                             + "; SHAPE: " + shape);
--- a/jdk/src/windows/classes/sun/awt/windows/WDesktopProperties.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WDesktopProperties.java	Wed Jul 05 19:00:49 2017 +0200
@@ -110,7 +110,7 @@
      */
     private synchronized void setBooleanProperty(String key, boolean value) {
         assert( key != null );
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine(key + "=" + String.valueOf(value));
         }
         map.put(key, Boolean.valueOf(value));
@@ -121,7 +121,7 @@
      */
     private synchronized void setIntegerProperty(String key, int value) {
         assert( key != null );
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine(key + "=" + String.valueOf(value));
         }
         map.put(key, Integer.valueOf(value));
@@ -132,7 +132,7 @@
      */
     private synchronized void setStringProperty(String key, String value) {
         assert( key != null );
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine(key + "=" + value);
         }
         map.put(key, value);
@@ -144,7 +144,7 @@
     private synchronized void setColorProperty(String key, int r, int g, int b) {
         assert( key != null && r <= 255 && g <=255 && b <= 255 );
         Color color = new Color(r, g, b);
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine(key + "=" + color);
         }
         map.put(key, color);
@@ -172,14 +172,14 @@
             name = mappedName;
         }
         Font    font = new Font(name, style, size);
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine(key + "=" + font);
         }
         map.put(key, font);
 
         String sizeKey = key + ".height";
         Integer iSize = Integer.valueOf(size);
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine(sizeKey + "=" + iSize);
         }
         map.put(sizeKey, iSize);
@@ -192,7 +192,7 @@
         assert( key != null && winEventName != null );
 
         Runnable soundRunnable = new WinPlaySound(winEventName);
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine(key + "=" + soundRunnable);
         }
         map.put(key, soundRunnable);
--- a/jdk/src/windows/classes/sun/awt/windows/WMenuItemPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WMenuItemPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -165,7 +165,7 @@
                         ResourceBundle rb = ResourceBundle.getBundle("sun.awt.windows.awtLocalization");
                         return Font.decode(rb.getString("menuFont"));
                     } catch (MissingResourceException e) {
-                        if (log.isLoggable(PlatformLogger.FINE)) {
+                        if (log.isLoggable(PlatformLogger.Level.FINE)) {
                             log.fine("WMenuItemPeer: " + e.getMessage()+". Using default MenuItem font.", e);
                         }
                         return new Font("SanSerif", Font.PLAIN, 11);
--- a/jdk/src/windows/classes/sun/awt/windows/WPrinterJob.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WPrinterJob.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1269,11 +1269,13 @@
         mLastFontFamily = null;
     }
 
+    private boolean defaultCopies = true;
     /**
      * Set the number of copies to be printed.
      */
     public void setCopies(int copies) {
         super.setCopies(copies);
+        defaultCopies = false;
         mAttCopies = copies;
         setNativeCopies(copies);
     }
@@ -1529,8 +1531,9 @@
     }
 
     /* SheetCollate */
-    private final boolean getCollateAttrib() {
-        return (mAttCollate == 1);
+    private final int getCollateAttrib() {
+        // -1 means unset, 0 uncollated, 1 collated.
+        return mAttCollate;
     }
 
     private void setCollateAttrib(Attribute attr) {
@@ -1553,6 +1556,10 @@
         int orient = PageFormat.PORTRAIT;
         OrientationRequested orientReq = (attributes == null) ? null :
             (OrientationRequested)attributes.get(OrientationRequested.class);
+        if (orientReq == null) {
+            orientReq = (OrientationRequested)
+               myService.getDefaultAttributeValue(OrientationRequested.class);
+        }
         if (orientReq != null) {
             if (orientReq == OrientationRequested.REVERSE_LANDSCAPE) {
                 orient = PageFormat.REVERSE_LANDSCAPE;
@@ -1573,7 +1580,11 @@
 
     /* Copies and Page Range. */
     private final int getCopiesAttrib() {
-        return getCopiesInt();
+        if (defaultCopies) {
+            return 0;
+        } else {
+            return getCopiesInt();
+        }
      }
 
     private final void setRangeCopiesAttribute(int from, int to,
@@ -1584,6 +1595,7 @@
                 attributes.add(new PageRanges(from, to));
                 setPageRange(from, to);
             }
+            defaultCopies = false;
             attributes.add(new Copies(copies));
             /* Since this is called from native to tell Java to sync
              * up with native, we don't call this class's own setCopies()
--- a/jdk/src/windows/classes/sun/awt/windows/WScrollPanePeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WScrollPanePeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -161,7 +161,7 @@
         }
 
         public PeerEvent coalesceEvents(PeerEvent newEvent) {
-            if (log.isLoggable(PlatformLogger.FINEST)) {
+            if (log.isLoggable(PlatformLogger.Level.FINEST)) {
                 log.finest("ScrollEvent coalesced: " + newEvent);
             }
             if (newEvent instanceof ScrollEvent) {
@@ -204,7 +204,7 @@
             } else if (orient == Adjustable.HORIZONTAL) {
                 adj = (ScrollPaneAdjustable)sp.getHAdjustable();
             } else {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine("Assertion failed: unknown orient");
                 }
             }
@@ -231,7 +231,7 @@
                   newpos = this.pos;
                   break;
               default:
-                  if (log.isLoggable(PlatformLogger.FINE)) {
+                  if (log.isLoggable(PlatformLogger.Level.FINE)) {
                       log.fine("Assertion failed: unknown type");
                   }
                   return;
@@ -259,7 +259,7 @@
             {
                 hwAncestor = hwAncestor.getParent();
             }
-            if (log.isLoggable(PlatformLogger.FINE)) {
+            if (log.isLoggable(PlatformLogger.Level.FINE)) {
                 if (hwAncestor == null) {
                     log.fine("Assertion (hwAncestor != null) failed, " +
                              "couldn't find heavyweight ancestor of scroll pane child");
--- a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java	Wed Jul 05 19:00:49 2017 +0200
@@ -112,7 +112,7 @@
         initIDs();
 
         // Print out which version of Windows is running
-        if (log.isLoggable(PlatformLogger.FINE)) {
+        if (log.isLoggable(PlatformLogger.Level.FINE)) {
             log.fine("Win version: " + getWindowsVersion());
         }
 
@@ -848,7 +848,7 @@
         lazilyInitWProps();
         Boolean prop = (Boolean) desktopProperties.get("awt.dynamicLayoutSupported");
 
-        if (log.isLoggable(PlatformLogger.FINER)) {
+        if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("In WTK.isDynamicLayoutSupported()" +
                       "   nativeDynamic == " + nativeDynamic +
                       "   wprops.dynamic == " + prop);
@@ -886,7 +886,7 @@
         Map<String, Object> props = wprops.getProperties();
         for (String propName : props.keySet()) {
             Object val = props.get(propName);
-            if (log.isLoggable(PlatformLogger.FINER)) {
+            if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("changed " + propName + " to " + val);
             }
             setDesktopProperty(propName, val);
--- a/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java	Wed Jul 05 19:00:49 2017 +0200
@@ -460,7 +460,7 @@
 
     public void updateGC() {
         int scrn = getScreenImOn();
-        if (screenLog.isLoggable(PlatformLogger.FINER)) {
+        if (screenLog.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer("Screen number: " + scrn);
         }
 
@@ -485,7 +485,7 @@
         // is now mostly on.
         winGraphicsConfig = (Win32GraphicsConfig)newDev
                             .getDefaultConfiguration();
-        if (screenLog.isLoggable(PlatformLogger.FINE)) {
+        if (screenLog.isLoggable(PlatformLogger.Level.FINE)) {
             if (winGraphicsConfig == null) {
                 screenLog.fine("Assertion (winGraphicsConfig != null) failed");
             }
@@ -730,7 +730,7 @@
             TranslucentWindowPainter currentPainter = painter;
             if (currentPainter != null) {
                 currentPainter.updateWindow(repaint);
-            } else if (log.isLoggable(PlatformLogger.FINER)) {
+            } else if (log.isLoggable(PlatformLogger.Level.FINER)) {
                 log.finer("Translucent window painter is null in updateWindow");
             }
         }
@@ -766,7 +766,7 @@
         public void propertyChange(PropertyChangeEvent e) {
             boolean isDisposed = (Boolean)e.getNewValue();
             if (isDisposed != true) {
-                if (log.isLoggable(PlatformLogger.FINE)) {
+                if (log.isLoggable(PlatformLogger.Level.FINE)) {
                     log.fine(" Assertion (newValue != true) failed for AppContext.GUI_DISPOSED ");
                 }
             }
--- a/jdk/src/windows/classes/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/sun/nio/ch/WindowsAsynchronousSocketChannelImpl.java	Wed Jul 05 19:00:49 2017 +0200
@@ -137,7 +137,9 @@
 
     // invoked by WindowsAsynchronousServerSocketChannelImpl when new connection
     // accept
-    void setConnected(SocketAddress localAddress, SocketAddress remoteAddress) {
+    void setConnected(InetSocketAddress localAddress,
+                      InetSocketAddress remoteAddress)
+    {
         synchronized (stateLock) {
             state = ST_CONNECTED;
             this.localAddress = localAddress;
--- a/jdk/src/windows/classes/sun/print/Win32PrintService.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/classes/sun/print/Win32PrintService.java	Wed Jul 05 19:00:49 2017 +0200
@@ -180,6 +180,9 @@
     private static final int DMDUP_VERTICAL = 2;
     private static final int DMDUP_HORIZONTAL = 3;
     private static final int DMCOLLATE_TRUE = 1;
+    private static final int DMCOLOR_MONOCHROME = 1;
+    private static final int DMCOLOR_COLOR = 2;
+
 
     // media sizes with indices above dmPaperToPrintService' length
     private static final int DMPAPER_A2 = 66;
@@ -1041,6 +1044,7 @@
         int defOrient = defaults[5];
         int defSides = defaults[6];
         int defCollate = defaults[7];
+        int defColor = defaults[8];
 
         if (category == Copies.class) {
             if (defCopies > 0) {
@@ -1049,11 +1053,10 @@
                 return new Copies(1);
             }
         } else if (category == Chromaticity.class) {
-            int caps = getPrinterCapabilities();
-            if ((caps & DEVCAP_COLOR) == 0) {
+            if (defColor == DMCOLOR_COLOR) {
+                return Chromaticity.COLOR;
+            } else {
                 return Chromaticity.MONOCHROME;
-            } else {
-                return Chromaticity.COLOR;
             }
         } else if (category == JobName.class) {
             return new JobName("Java Printing", null);
--- a/jdk/src/windows/native/java/io/WinNTFileSystem_md.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/java/io/WinNTFileSystem_md.c	Wed Jul 05 19:00:49 2017 +0200
@@ -230,7 +230,7 @@
     } else if (GetLastError() == ERROR_SHARING_VIOLATION &&
                (h = FindFirstFileW(path, &wfd)) != INVALID_HANDLE_VALUE) {
         attr = getFinalAttributesIfReparsePoint(path, wfd.dwFileAttributes);
-        CloseHandle(h);
+        FindClose(h);
     }
     return attr;
 }
@@ -541,6 +541,10 @@
     WCHAR *pathbuf = pathToNTPath(env, path, JNI_FALSE);
     if (pathbuf == NULL)
         return JNI_FALSE;
+    if (isReservedDeviceNameW(pathbuf)) {
+        free(pathbuf);
+        return JNI_FALSE;
+    }
     h = CreateFileW(
         pathbuf,                              /* Wide char path name */
         GENERIC_READ | GENERIC_WRITE,         /* Read and write permission */
--- a/jdk/src/windows/native/java/net/DualStackPlainDatagramSocketImpl.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/java/net/DualStackPlainDatagramSocketImpl.c	Wed Jul 05 19:00:49 2017 +0200
@@ -113,7 +113,7 @@
  * Signature: (ILjava/net/InetAddress;I)V
  */
 JNIEXPORT void JNICALL Java_java_net_DualStackPlainDatagramSocketImpl_socketBind
-  (JNIEnv *env, jclass clazz, jint fd, jobject iaObj, jint port) {
+  (JNIEnv *env, jclass clazz, jint fd, jobject iaObj, jint port, jboolean exclBind) {
     SOCKETADDRESS sa;
     int rv;
     int sa_len = sizeof(sa);
@@ -122,8 +122,7 @@
                                  &sa_len, JNI_TRUE) != 0) {
         return;
     }
-
-    rv = bind(fd, (struct sockaddr *)&sa, sa_len);
+    rv = NET_WinBind(fd, (struct sockaddr *)&sa, sa_len, exclBind);
 
     if (rv == SOCKET_ERROR) {
         if (WSAGetLastError() == WSAEACCES) {
--- a/jdk/src/windows/native/java/net/DualStackPlainSocketImpl.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/java/net/DualStackPlainSocketImpl.c	Wed Jul 05 19:00:49 2017 +0200
@@ -82,7 +82,9 @@
  * Signature: (ILjava/net/InetAddress;I)V
  */
 JNIEXPORT void JNICALL Java_java_net_DualStackPlainSocketImpl_bind0
-  (JNIEnv *env, jclass clazz, jint fd, jobject iaObj, jint port) {
+  (JNIEnv *env, jclass clazz, jint fd, jobject iaObj, jint port,
+   jboolean exclBind)
+{
     SOCKETADDRESS sa;
     int rv;
     int sa_len = sizeof(sa);
@@ -92,7 +94,7 @@
       return;
     }
 
-    rv = NET_Bind(fd, (struct sockaddr *)&sa, sa_len);
+    rv = NET_WinBind(fd, (struct sockaddr *)&sa, sa_len, exclBind);
 
     if (rv == SOCKET_ERROR)
         NET_ThrowNew(env, WSAGetLastError(), "JVM_Bind");
--- a/jdk/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c	Wed Jul 05 19:00:49 2017 +0200
@@ -421,7 +421,8 @@
 
 JNIEXPORT void JNICALL
 Java_java_net_TwoStacksPlainDatagramSocketImpl_bind0(JNIEnv *env, jobject this,
-                                           jint port, jobject addressObj) {
+                                           jint port, jobject addressObj,
+                                           jboolean exclBind) {
     jobject fdObj = (*env)->GetObjectField(env, this, pdsi_fdID);
     jobject fd1Obj = (*env)->GetObjectField(env, this, pdsi_fd1ID);
 
@@ -464,7 +465,7 @@
         v6bind.addr = &lcladdr;
         v6bind.ipv4_fd = fd;
         v6bind.ipv6_fd = fd1;
-        if (NET_BindV6(&v6bind) != -1) {
+        if (NET_BindV6(&v6bind, exclBind) != -1) {
             /* check if the fds have changed */
             if (v6bind.ipv4_fd != fd) {
                 fd = v6bind.ipv4_fd;
@@ -491,7 +492,7 @@
             return;
         }
     } else {
-        if (bind(fd, (struct sockaddr *)&lcladdr, lcladdrlen) == -1) {
+        if (NET_WinBind(fd, (struct sockaddr *)&lcladdr, lcladdrlen, exclBind) == -1) {
             if (WSAGetLastError() == WSAEACCES) {
                 WSASetLastError(WSAEADDRINUSE);
             }
@@ -1782,11 +1783,11 @@
 
 /*
  * Class:     java_net_TwoStacksPlainDatagramSocketImpl
- * Method:    socketSetOption
+ * Method:    socketNativeSetOption
  * Signature: (ILjava/lang/Object;)V
  */
 JNIEXPORT void JNICALL
-Java_java_net_TwoStacksPlainDatagramSocketImpl_socketSetOption(JNIEnv *env,jobject this,
+Java_java_net_TwoStacksPlainDatagramSocketImpl_socketNativeSetOption(JNIEnv *env,jobject this,
                                                       jint opt,jobject value) {
 
     int fd=-1, fd1=-1;
--- a/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c	Wed Jul 05 19:00:49 2017 +0200
@@ -394,7 +394,8 @@
  */
 JNIEXPORT void JNICALL
 Java_java_net_TwoStacksPlainSocketImpl_socketBind(JNIEnv *env, jobject this,
-                                         jobject iaObj, jint localport) {
+                                         jobject iaObj, jint localport,
+                                         jboolean exclBind) {
 
     /* fdObj is the FileDescriptor field on this */
     jobject fdObj, fd1Obj;
@@ -438,13 +439,12 @@
                           (struct sockaddr *)&him, &len, JNI_FALSE) != 0) {
       return;
     }
-
     if (ipv6_supported) {
         struct ipv6bind v6bind;
         v6bind.addr = &him;
         v6bind.ipv4_fd = fd;
         v6bind.ipv6_fd = fd1;
-        rv = NET_BindV6(&v6bind);
+        rv = NET_BindV6(&v6bind, exclBind);
         if (rv != -1) {
             /* check if the fds have changed */
             if (v6bind.ipv4_fd != fd) {
@@ -469,7 +469,7 @@
             }
         }
     } else {
-        rv = NET_Bind(fd, (struct sockaddr *)&him, len);
+        rv = NET_WinBind(fd, (struct sockaddr *)&him, len, exclBind);
     }
 
     if (rv == -1) {
@@ -835,11 +835,12 @@
  *
  *
  * Class:     java_net_TwoStacksPlainSocketImpl
- * Method:    socketSetOption
+ * Method:    socketNativeSetOption
  * Signature: (IZLjava/lang/Object;)V
  */
 JNIEXPORT void JNICALL
-Java_java_net_TwoStacksPlainSocketImpl_socketSetOption(JNIEnv *env, jobject this,
+Java_java_net_TwoStacksPlainSocketImpl_socketNativeSetOption(JNIEnv *env,
+                                              jobject this,
                                               jint cmd, jboolean on,
                                               jobject value) {
     int fd, fd1;
--- a/jdk/src/windows/native/java/net/net_util_md.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/java/net/net_util_md.c	Wed Jul 05 19:00:49 2017 +0200
@@ -387,12 +387,24 @@
                int optlen)
 {
     int rv;
+    int parg;
+    int plen = sizeof(parg);
 
     if (level == IPPROTO_IP && optname == IP_TOS) {
         int *tos = (int *)optval;
         *tos &= (IPTOS_TOS_MASK | IPTOS_PREC_MASK);
     }
 
+    if (optname == SO_REUSEADDR) {
+        /*
+         * Do not set SO_REUSEADDE if SO_EXCLUSIVEADDUSE is already set
+         */
+        rv = NET_GetSockOpt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *)&parg, &plen);
+        if (rv == 0 && parg == 1) {
+            return rv;
+        }
+    }
+
     rv = setsockopt(s, level, optname, optval, optlen);
 
     if (rv == SOCKET_ERROR) {
@@ -456,15 +468,32 @@
 }
 
 /*
+ * Sets SO_ECLUSIVEADDRUSE if SO_REUSEADDR is not already set.
+ */
+void setExclusiveBind(int fd) {
+    int parg;
+    int plen = sizeof(parg);
+    int rv = 0;
+    rv = NET_GetSockOpt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&parg, &plen);
+    if (rv == 0 && parg == 0) {
+        parg = 1;
+        rv = NET_SetSockOpt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*)&parg, plen);
+    }
+}
+
+/*
  * Wrapper for bind winsock call - transparent converts an
  * error related to binding to a port that has exclusive access
  * into an error indicating the port is in use (facilitates
  * better error reporting).
+ *
+ * Should be only called by the wrapper method NET_WinBind
  */
 JNIEXPORT int JNICALL
 NET_Bind(int s, struct sockaddr *him, int len)
 {
-    int rv = bind(s, him, len);
+    int rv;
+    rv = bind(s, him, len);
 
     if (rv == SOCKET_ERROR) {
         /*
@@ -479,6 +508,18 @@
     return rv;
 }
 
+/*
+ * Wrapper for NET_Bind call. Sets SO_EXCLUSIVEADDRUSE
+ * if required, and then calls NET_BIND
+ */
+JNIEXPORT int JNICALL
+NET_WinBind(int s, struct sockaddr *him, int len, jboolean exclBind)
+{
+    if (exclBind == JNI_TRUE)
+        setExclusiveBind(s);
+    return NET_Bind(s, him, len);
+}
+
 JNIEXPORT int JNICALL
 NET_SocketClose(int fd) {
     struct linger l;
@@ -625,7 +666,7 @@
  */
 
 JNIEXPORT int JNICALL
-NET_BindV6(struct ipv6bind* b) {
+NET_BindV6(struct ipv6bind* b, jboolean exclBind) {
     int fd=-1, ofd=-1, rv, len;
     /* need to defer close until new sockets created */
     int close_fd=-1, close_ofd=-1;
@@ -638,8 +679,8 @@
     if (family == AF_INET && (b->addr->him4.sin_addr.s_addr != INADDR_ANY)) {
         /* bind to v4 only */
         int ret;
-        ret = NET_Bind ((int)b->ipv4_fd, (struct sockaddr *)b->addr,
-                                sizeof (struct sockaddr_in));
+        ret = NET_WinBind ((int)b->ipv4_fd, (struct sockaddr *)b->addr,
+                                sizeof (struct sockaddr_in), exclBind);
         if (ret == SOCKET_ERROR) {
             CLOSE_SOCKETS_AND_RETURN;
         }
@@ -650,8 +691,8 @@
     if (family == AF_INET6 && (!IN6_IS_ADDR_ANY(&b->addr->him6.sin6_addr))) {
         /* bind to v6 only */
         int ret;
-        ret = NET_Bind ((int)b->ipv6_fd, (struct sockaddr *)b->addr,
-                                sizeof (struct SOCKADDR_IN6));
+        ret = NET_WinBind ((int)b->ipv6_fd, (struct sockaddr *)b->addr,
+                                sizeof (struct SOCKADDR_IN6), exclBind);
         if (ret == SOCKET_ERROR) {
             CLOSE_SOCKETS_AND_RETURN;
         }
@@ -680,7 +721,7 @@
         oaddr.him4.sin_addr.s_addr = INADDR_ANY;
     }
 
-    rv = NET_Bind (fd, (struct sockaddr *)b->addr, SOCKETADDRESS_LEN(b->addr));
+    rv = NET_WinBind(fd, (struct sockaddr *)b->addr, SOCKETADDRESS_LEN(b->addr), exclBind);
     if (rv == SOCKET_ERROR) {
         CLOSE_SOCKETS_AND_RETURN;
     }
@@ -692,8 +733,8 @@
     }
     bound_port = GET_PORT (b->addr);
     SET_PORT (&oaddr, bound_port);
-    if ((rv=NET_Bind (ofd, (struct sockaddr *) &oaddr,
-                                SOCKETADDRESS_LEN (&oaddr))) == SOCKET_ERROR) {
+    if ((rv=NET_WinBind (ofd, (struct sockaddr *) &oaddr,
+                         SOCKETADDRESS_LEN (&oaddr), exclBind)) == SOCKET_ERROR) {
         int retries;
         int sotype, arglen=sizeof(sotype);
 
@@ -729,7 +770,8 @@
 
             /* bind random port on first socket */
             SET_PORT (&oaddr, 0);
-            rv = NET_Bind (ofd, (struct sockaddr *)&oaddr, SOCKETADDRESS_LEN(&oaddr));
+            rv = NET_WinBind (ofd, (struct sockaddr *)&oaddr, SOCKETADDRESS_LEN(&oaddr),
+                              exclBind);
             if (rv == SOCKET_ERROR) {
                 CLOSE_SOCKETS_AND_RETURN;
             }
@@ -745,7 +787,8 @@
             }
             bound_port = GET_PORT (&oaddr);
             SET_PORT (b->addr, bound_port);
-            rv = NET_Bind (fd, (struct sockaddr *)b->addr, SOCKETADDRESS_LEN(b->addr));
+            rv = NET_WinBind (fd, (struct sockaddr *)b->addr, SOCKETADDRESS_LEN(b->addr),
+                              exclBind);
 
             if (rv != SOCKET_ERROR) {
                 if (family == AF_INET) {
--- a/jdk/src/windows/native/java/net/net_util_md.h	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/java/net/net_util_md.h	Wed Jul 05 19:00:49 2017 +0200
@@ -311,7 +311,7 @@
  */
 JNIEXPORT int JNICALL NET_Timeout2(int fd, int fd1, long timeout, int *fdret);
 
-JNIEXPORT int JNICALL NET_BindV6(struct ipv6bind* b);
+JNIEXPORT int JNICALL NET_BindV6(struct ipv6bind* b, jboolean exclBind);
 
 #define NET_WAIT_READ   0x01
 #define NET_WAIT_WRITE  0x02
@@ -319,6 +319,9 @@
 
 extern jint NET_Wait(JNIEnv *env, jint fd, jint flags, jint timeout);
 
+JNIEXPORT int JNICALL NET_WinBind(int s, struct sockaddr *him, int len,
+                                   jboolean exclBind);
+
 /* XP versions of the native routines */
 
 JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByName0_XP
--- a/jdk/src/windows/native/sun/awt/splashscreen/splashscreen_sys.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/awt/splashscreen/splashscreen_sys.c	Wed Jul 05 19:00:49 2017 +0200
@@ -37,6 +37,7 @@
 #include <windowsx.h>
 #include <windows.h>
 #include <winuser.h>
+#include "sizecalc.h"
 
 #ifndef WS_EX_LAYERED
 #define WS_EX_LAYERED 0x80000
@@ -67,7 +68,10 @@
     len = strlen(in);
     outChars = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, in, len,
                                        NULL, 0);
-    buf = malloc(outChars*sizeof(WCHAR));
+    buf = (WCHAR*) SAFE_SIZE_ARRAY_ALLOC(malloc, outChars, sizeof(WCHAR));
+    if (!buf) {
+        return NULL;
+    }
     rc = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, in, len,
                                  buf, outChars);
     if (rc==0) {
@@ -98,8 +102,14 @@
         return;
 
     /* reserving memory for the worst case */
-    pRgnData = (RGNDATA *) malloc(sizeof(RGNDATAHEADER) +
-            sizeof(RECT) * (splash->width / 2 + 1) * splash->height);
+    if (!IS_SAFE_SIZE_MUL(splash->width / 2 + 1, splash->height)) {
+        return;
+    }
+    pRgnData = (RGNDATA *) SAFE_SIZE_STRUCT_ALLOC(malloc, sizeof(RGNDATAHEADER),
+            sizeof(RECT), (splash->width / 2 + 1) * splash->height);
+    if (!pRgnData) {
+        return;
+    }
     pRgnHdr = (RGNDATAHEADER *) pRgnData;
     initRect(&maskRect, 0, 0, splash->width, splash->height, 1,
             splash->width * splash->imageFormat.depthBytes,
@@ -130,7 +140,6 @@
 {
     unsigned numColors = splash->screenFormat.colorMap ?
         splash->screenFormat.numColors : 0;
-    unsigned bmiSize;
     BITMAPV4HEADER *pBmi;
     HPALETTE hOldPal = NULL;
 
@@ -138,8 +147,11 @@
         return;
     if (splash->currentFrame < 0 || splash->currentFrame >= splash->frameCount)
         return;
-    bmiSize = sizeof(BITMAPV4HEADER) + sizeof(RGBQUAD) * numColors;
-    pBmi = (BITMAPV4HEADER *) alloca(bmiSize);
+    pBmi = (BITMAPV4HEADER *) SAFE_SIZE_STRUCT_ALLOC(alloca, sizeof(BITMAPV4HEADER),
+            sizeof(RGBQUAD), numColors);
+    if (!pBmi) {
+        return;
+    }
     memset(pBmi, 0, sizeof(BITMAPV4HEADER));
     if (splash->screenFormat.colorMap)
         memcpy(((BYTE *) pBmi) + sizeof(BITMAPV4HEADER),
@@ -163,8 +175,11 @@
        here on demand */
     if (!splash->hPalette) {
         unsigned i;
-        LOGPALETTE *pLogPal =
-            malloc(sizeof(LOGPALETTE) + sizeof(PALETTEENTRY) * numColors);
+        LOGPALETTE *pLogPal = (LOGPALETTE *) SAFE_SIZE_STRUCT_ALLOC(malloc,
+                sizeof(LOGPALETTE), sizeof(PALETTEENTRY), numColors);
+        if (!pLogPal) {
+            return;
+        }
 
         pLogPal->palVersion = 0x300;
         pLogPal->palNumEntries = (WORD) numColors;
--- a/jdk/src/windows/native/sun/font/lcdglyph.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/font/lcdglyph.c	Wed Jul 05 19:00:49 2017 +0200
@@ -54,6 +54,7 @@
 #include <jni.h>
 #include <jni_util.h>
 #include <jlong_md.h>
+#include <sizecalc.h>
 #include <sun_font_FileFontStrike.h>
 
 #include "fontscalerdefs.h"
@@ -374,11 +375,11 @@
     bmi.bmiHeader.biBitCount = 24;
     bmi.bmiHeader.biCompression = BI_RGB;
 
-    dibImageSize = dibBytesWidth*height;
-    dibImage = malloc(dibImageSize);
+    dibImage = SAFE_SIZE_ARRAY_ALLOC(malloc, dibBytesWidth, height);
     if (dibImage == NULL) {
         FREE_AND_RETURN;
     }
+    dibImageSize = dibBytesWidth*height;
     memset(dibImage, 0, dibImageSize);
 
     err = GetDIBits(hMemoryDC, hBitmap, 0, height, dibImage,
@@ -407,11 +408,12 @@
      * that extra "1" was added as padding, so the sub-pixel positioning of
      * fractional metrics could index into it.
      */
-    imageSize = bytesWidth*height;
-    glyphInfo = (GlyphInfo*)malloc(sizeof(GlyphInfo)+imageSize);
+    glyphInfo = (GlyphInfo*)SAFE_SIZE_STRUCT_ALLOC(malloc, sizeof(GlyphInfo),
+            bytesWidth, height);
     if (glyphInfo == NULL) {
         FREE_AND_RETURN;
     }
+    imageSize = bytesWidth*height;
     glyphInfo->cellInfo = NULL;
     glyphInfo->rowBytes = bytesWidth;
     glyphInfo->width = width;
--- a/jdk/src/windows/native/sun/java2d/opengl/WGLSurfaceData.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/java2d/opengl/WGLSurfaceData.c	Wed Jul 05 19:00:49 2017 +0200
@@ -30,6 +30,7 @@
 #include "jni.h"
 #include "jlong.h"
 #include "jni_util.h"
+#include "sizecalc.h"
 #include "OGLRenderQueue.h"
 #include "WGLGraphicsConfig.h"
 #include "WGLSurfaceData.h"
@@ -603,7 +604,7 @@
     height = h;
     srcx = srcy = dstx = dsty = 0;
 
-    pDst = malloc(height * scanStride);
+    pDst = SAFE_SIZE_ARRAY_ALLOC(malloc, height, scanStride);
     if (pDst == NULL) {
         return JNI_FALSE;
     }
--- a/jdk/src/windows/native/sun/java2d/windows/GDIBlitLoops.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/java2d/windows/GDIBlitLoops.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -166,6 +166,7 @@
                 // when using ByteGray surfaces.  Eventually, we should use
                 // the new Disposer mechanism to delete this native memory.
                 if (byteGrayPalette == NULL) {
+                    // assert (256 * sizeof(RGBQUAD)) <= SIZE_MAX
                     byteGrayPalette = (RGBQUAD *)safe_Malloc(256 * sizeof(RGBQUAD));
                     for (int i = 0; i < 256; ++i) {
                         byteGrayPalette[i].rgbRed = i;
--- a/jdk/src/windows/native/sun/java2d/windows/GDIRenderer.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/java2d/windows/GDIRenderer.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -84,7 +84,7 @@
         *pNpoints = outpoints;
     }
     if (outpoints > POLYTEMPSIZE) {
-        pPoints = (POINT *) safe_Malloc(sizeof(POINT) * outpoints);
+        pPoints = (POINT *) SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(POINT), outpoints);
     }
     BOOL isempty = fixend;
     for (int i = 0; i < npoints; i++) {
--- a/jdk/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1056,8 +1056,9 @@
             int topInset = wsdo->insets.top;
             Region_StartIteration(env, &clipInfo);
             jint numrects = Region_CountIterationRects(&clipInfo);
-            DWORD nCount = sizeof(RGNDATAHEADER) + numrects * sizeof(RECT);
-            RGNDATA *lpRgnData = (RGNDATA *) safe_Malloc(nCount);
+            RGNDATA *lpRgnData = (RGNDATA *) SAFE_SIZE_STRUCT_ALLOC(safe_Malloc,
+                    sizeof(RGNDATAHEADER), numrects, sizeof(RECT));
+            const DWORD nCount = sizeof(RGNDATAHEADER) + numrects * sizeof(RECT);
             lpRgnData->rdh.dwSize = sizeof(RGNDATAHEADER);
             lpRgnData->rdh.iType = RDH_RECTANGLES;
             lpRgnData->rdh.nCount = numrects;
--- a/jdk/src/windows/native/sun/nio/ch/Net.c	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/nio/ch/Net.c	Wed Jul 05 19:00:49 2017 +0200
@@ -101,6 +101,18 @@
     return JNI_FALSE;
 }
 
+JNIEXPORT jint JNICALL
+Java_sun_nio_ch_Net_isExclusiveBindAvailable(JNIEnv *env, jclass clazz) {
+    OSVERSIONINFO ver;
+    int version;
+    ver.dwOSVersionInfoSize = sizeof(ver);
+    GetVersionEx(&ver);
+    version = ver.dwMajorVersion * 10 + ver.dwMinorVersion;
+    //if os <= xp exclusive binding is off by default
+    return version >= 60 ? 1 : 0;
+}
+
+
 JNIEXPORT jboolean JNICALL
 Java_sun_nio_ch_Net_canIPv6SocketJoinIPv4Group0(JNIEnv* env, jclass cl)
 {
@@ -144,8 +156,8 @@
 }
 
 JNIEXPORT void JNICALL
-Java_sun_nio_ch_Net_bind0(JNIEnv *env, jclass clazz, jboolean preferIPv6,
-                          jobject fdo, jobject iao, jint port)
+Java_sun_nio_ch_Net_bind0(JNIEnv *env, jclass clazz, jobject fdo, jboolean preferIPv6,
+                          jboolean isExclBind, jobject iao, jint port)
 {
     SOCKETADDRESS sa;
     int rv;
@@ -155,7 +167,7 @@
       return;
     }
 
-    rv = NET_Bind(fdval(env, fdo), (struct sockaddr *)&sa, sa_len);
+    rv = NET_WinBind(fdval(env, fdo), (struct sockaddr *)&sa, sa_len, isExclBind);
     if (rv == SOCKET_ERROR)
         NET_ThrowNew(env, WSAGetLastError(), "bind");
 }
--- a/jdk/src/windows/native/sun/windows/CmdIDList.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/CmdIDList.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -39,7 +39,7 @@
 {
     m_capacity = ARRAY_INITIAL_SIZE;
     m_first_free = -1;
-    m_array = (CmdIDEntry *)safe_Malloc(m_capacity * sizeof(AwtObject*));
+    m_array = (CmdIDEntry *)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, m_capacity, sizeof(AwtObject*));
     BuildFreeList(0);
 }
 
@@ -80,8 +80,8 @@
             m_capacity += ARRAY_SIZE_INCREMENT;
             if (m_capacity > ARRAY_MAXIMUM_SIZE)
                 m_capacity = ARRAY_MAXIMUM_SIZE;
-            m_array = (CmdIDEntry *)safe_Realloc(m_array,
-                                        m_capacity * sizeof(CmdIDEntry*));
+            m_array = (CmdIDEntry *)SAFE_SIZE_ARRAY_REALLOC(safe_Realloc, m_array,
+                                        m_capacity, sizeof(CmdIDEntry*));
             BuildFreeList(old_capacity);
         }
     }
--- a/jdk/src/windows/native/sun/windows/Devices.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/Devices.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -171,8 +171,8 @@
     J2dTraceLn1(J2D_TRACE_INFO, "Devices::Devices numDevices=%d", numDevices);
     this->numDevices = numDevices;
     this->refCount = 0;
-    devices = (AwtWin32GraphicsDevice**)safe_Malloc
-        (numDevices * sizeof(AwtWin32GraphicsDevice *));
+    devices = (AwtWin32GraphicsDevice**)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc,
+        numDevices, sizeof(AwtWin32GraphicsDevice *));
 }
 
 /**
@@ -188,7 +188,8 @@
     J2dTraceLn(J2D_TRACE_INFO, "Devices::UpdateInstance");
 
     int numScreens = CountMonitors();
-    HMONITOR *monHds = (HMONITOR *)safe_Malloc(numScreens * sizeof(HMONITOR));
+    HMONITOR *monHds = (HMONITOR *)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc,
+            numScreens, sizeof(HMONITOR));
     if (numScreens != CollectMonitors(monHds, numScreens)) {
         J2dRlsTraceLn(J2D_TRACE_ERROR,
                       "Devices::UpdateInstance: Failed to get all "\
--- a/jdk/src/windows/native/sun/windows/ShellFolder2.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/ShellFolder2.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -393,6 +393,9 @@
     if (cb == 0)
         return 0;
 
+    if (!IS_SAFE_SIZE_ADD(cb, sizeof(SHITEMID))) {
+        return 0;
+    }
     // Allocate space for this as well as null-terminating entry.
     LPITEMIDLIST newPIDL = (LPITEMIDLIST)pMalloc->Alloc(cb + sizeof(SHITEMID));
 
@@ -433,6 +436,9 @@
     int len1 = pidlLength(parentPIDL);
     int len2 = pidlLength(relativePIDL);
 
+    if (!IS_SAFE_SIZE_ADD(len1, len2) || !IS_SAFE_SIZE_ADD(len1 + len2, sizeof(SHITEMID))) {
+        return 0;
+    }
     LPITEMIDLIST newPIDL = (LPITEMIDLIST)pMalloc->Alloc(len1 + len2 + sizeof(SHITEMID));
     memcpy(newPIDL, parentPIDL, len1);
     memcpy(((LPBYTE) newPIDL) + len1, relativePIDL, len2);
--- a/jdk/src/windows/native/sun/windows/WPrinterJob.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/WPrinterJob.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -750,7 +750,7 @@
 
 
 #define GETDEFAULT_ERROR        -50
-#define NDEFAULT 8
+#define NDEFAULT 9
 
 JNIEXPORT jintArray JNICALL
 Java_sun_print_Win32PrintService_getDefaultSettings(JNIEnv *env,
@@ -810,7 +810,7 @@
       int numSizes = ::DeviceCapabilities(printerName, printerPort,
                                           DC_PAPERS, NULL, NULL);
       if (numSizes > 0) {
-          LPTSTR papers = (LPTSTR)safe_Malloc(numSizes * sizeof(WORD));
+          LPTSTR papers = (LPTSTR)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, numSizes, sizeof(WORD));
           if (papers != NULL &&
               ::DeviceCapabilities(printerName, printerPort,
                                    DC_PAPERS, papers, NULL) != -1) {
@@ -859,6 +859,11 @@
       defIndices[7] = pDevMode->dmCollate;
   }
 
+  if (pDevMode->dmFields & DM_COLOR) {
+      defIndices[8] = pDevMode->dmColor;
+  }
+
+
   GlobalFree(pDevMode);
   ::ClosePrinter(hPrinter);
 
--- a/jdk/src/windows/native/sun/windows/alloc.h	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/alloc.h	Wed Jul 05 19:00:49 2017 +0200
@@ -40,6 +40,9 @@
     class bad_alloc {};
 }
 
+#define SIZECALC_ALLOC_THROWING_BAD_ALLOC
+#include "sizecalc.h"
+
 class awt_toolkit_shutdown {};
 
 // Disable "C++ Exception Specification ignored" warnings.
--- a/jdk/src/windows/native/sun/windows/awt.h	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/awt.h	Wed Jul 05 19:00:49 2017 +0200
@@ -326,7 +326,7 @@
         m_dwSize = cbTCharCount;
         m_pStr = (0 == m_dwSize)
             ? NULL
-            : (LPWSTR)safe_Malloc( (m_dwSize+1)*sizeof(WCHAR) );
+            : (LPWSTR)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, (m_dwSize+1), sizeof(WCHAR) );
     }
 
     JavaStringBuffer(JNIEnv *env, jstring text) {
@@ -336,7 +336,7 @@
         if (0 == m_dwSize) {
             m_pStr = NULL;
         } else {
-            m_pStr = (LPWSTR)safe_Malloc( (m_dwSize+1)*sizeof(WCHAR) );
+            m_pStr = (LPWSTR)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, (m_dwSize+1), sizeof(WCHAR) );
             env->GetStringRegion(text, 0, m_dwSize, reinterpret_cast<jchar *>(m_pStr));
             m_pStr[m_dwSize] = 0;
         }
@@ -353,7 +353,7 @@
         //The function is used only for space reservation in staff buffer for
         //followed data copying process. And that is the reason why we ignore
         //the special case m_dwSize==0 here.
-        m_pStr = (LPWSTR)safe_Realloc(m_pStr, (m_dwSize+1)*sizeof(WCHAR) );
+        m_pStr = (LPWSTR)SAFE_SIZE_ARRAY_REALLOC(safe_Realloc, m_pStr, m_dwSize+1, sizeof(WCHAR) );
     }
     //we are in UNICODE now, so LPWSTR:=:LPTSTR
     operator LPWSTR() { return getNonEmptyString(); }
--- a/jdk/src/windows/native/sun/windows/awt_BitmapUtil.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_BitmapUtil.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -39,13 +39,13 @@
 HBITMAP BitmapUtil::CreateTransparencyMaskFromARGB(int width, int height, int* imageData)
 {
     //Scan lines should be aligned to word boundary
-    int bufLength = ((width + 15) / 16 * 2) * height;//buf length (bytes)
+    if (!IS_SAFE_SIZE_ADD(width, 15)) return NULL;
+    char* buf = SAFE_SIZE_NEW_ARRAY2(char, (width + 15) / 16 * 2, height);
+    if (buf == NULL) return NULL;
     int* srcPos = imageData;
-    char* buf = new char[bufLength];
     char* bufPos = buf;
     int tmp = 0;
     int cbit = 0x80;
-    if (buf == NULL) return NULL;
     for (int i = 0; i < height; i++) {
         for (int j = 0; j < width; j++) {
             //cbit is shifted right for every pixel
@@ -251,8 +251,12 @@
             reinterpret_cast<BITMAPINFO*>(&bi), DIB_RGB_COLORS);
 
     /* reserving memory for the worst case */
-    RGNDATA * pRgnData = (RGNDATA *) safe_Malloc(sizeof(RGNDATAHEADER) +
-            sizeof(RECT) * (width / 2 + 1) * height);
+    if (!IS_SAFE_SIZE_MUL(width / 2 + 1, height)) {
+        throw std::bad_alloc();
+    }
+    RGNDATA * pRgnData = (RGNDATA *) SAFE_SIZE_STRUCT_ALLOC(safe_Malloc,
+            sizeof(RGNDATAHEADER),
+            sizeof(RECT), (width / 2 + 1) * height);
     RGNDATAHEADER * pRgnHdr = (RGNDATAHEADER *) pRgnData;
     pRgnHdr->dwSize = sizeof(RGNDATAHEADER);
     pRgnHdr->iType = RDH_RECTANGLES;
--- a/jdk/src/windows/native/sun/windows/awt_Component.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_Component.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -2186,12 +2186,12 @@
         if (insets != NULL) {
             ::OffsetRgn(rgn, insets->left, insets->top);
         }
-        int size = ::GetRegionData(rgn, 0, NULL);
+        DWORD size = ::GetRegionData(rgn, 0, NULL);
         if (size == 0) {
             ::DeleteObject((HGDIOBJ)rgn);
             return;
         }
-        char* buffer = new char[size];
+        char* buffer = new char[size]; // safe because sizeof(char)==1
         memset(buffer, 0, size);
         LPRGNDATA rgndata = (LPRGNDATA)buffer;
         rgndata->rdh.dwSize = sizeof(RGNDATAHEADER);
@@ -6134,18 +6134,30 @@
         c = (AwtComponent *)pData;
         if (::IsWindow(c->GetHWnd())) {
             HRGN hRgn = NULL;
+
+            // If all the params are zeros, the shape must be simply reset.
+            // Otherwise, convert it into a region.
             if (region || x1 || x2 || y1 || y2) {
-                // If all the params are zeros, the shape must be simply reset.
-                // Otherwise, convert it into a region.
-                RGNDATA *pRgnData = NULL;
-                RGNDATAHEADER *pRgnHdr;
-
-                /* reserving memory for the worst case */
-                size_t worstBufferSize = size_t(((x2 - x1) / 2 + 1) * (y2 - y1));
-                pRgnData = (RGNDATA *) safe_Malloc(sizeof(RGNDATAHEADER) +
-                        sizeof(RECT_T) * worstBufferSize);
-                pRgnHdr = (RGNDATAHEADER *) pRgnData;
-
+                RECT_T rects[256];
+                RECT_T *pRect = rects;
+
+                const int numrects = RegionToYXBandedRectangles(env, x1, y1, x2, y2,
+                        region, &pRect, sizeof(rects)/sizeof(rects[0]));
+                if (!pRect) {
+                    // RegionToYXBandedRectangles doesn't use safe_Malloc(),
+                    // so throw the exception explicitly
+                    throw std::bad_alloc();
+                }
+
+                RGNDATA *pRgnData = (RGNDATA *) SAFE_SIZE_STRUCT_ALLOC(safe_Malloc,
+                        sizeof(RGNDATAHEADER), sizeof(RECT_T), numrects);
+                memcpy((BYTE*)pRgnData + sizeof(RGNDATAHEADER), pRect, sizeof(RECT_T) * numrects);
+                if (pRect != rects) {
+                    free(pRect);
+                }
+                pRect = NULL;
+
+                RGNDATAHEADER *pRgnHdr = (RGNDATAHEADER *) pRgnData;
                 pRgnHdr->dwSize = sizeof(RGNDATAHEADER);
                 pRgnHdr->iType = RDH_RECTANGLES;
                 pRgnHdr->nRgnSize = 0;
@@ -6153,9 +6165,7 @@
                 pRgnHdr->rcBound.left = 0;
                 pRgnHdr->rcBound.bottom = LONG(y2 - y1);
                 pRgnHdr->rcBound.right = LONG(x2 - x1);
-
-                RECT_T * pRect = (RECT_T *) (((BYTE *) pRgnData) + sizeof(RGNDATAHEADER));
-                pRgnHdr->nCount = RegionToYXBandedRectangles(env, x1, y1, x2, y2, region, &pRect, worstBufferSize);
+                pRgnHdr->nCount = numrects;
 
                 hRgn = ::ExtCreateRegion(NULL,
                         sizeof(RGNDATAHEADER) + sizeof(RECT_T) * pRgnHdr->nCount, pRgnData);
@@ -6297,7 +6307,7 @@
     jint * tmp = env->GetIntArrayElements(obj, JNI_FALSE);
 
     jsize len = env->GetArrayLength(obj);
-    AwtComponent::masks = new jint[len];
+    AwtComponent::masks = SAFE_SIZE_NEW_ARRAY(jint, len);
     for (int i = 0; i < len; i++) {
         AwtComponent::masks[i] = tmp[i];
     }
@@ -7184,4 +7194,5 @@
         removedDCs = removedDCs->next;
         delete tmpDCList;
     }
-}
\ No newline at end of file
+}
+
--- a/jdk/src/windows/native/sun/windows/awt_Cursor.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_Cursor.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -345,14 +345,14 @@
         return;
     }
 
-    int length = env->GetArrayLength(andMask);
-    jbyte *andMaskPtr = new jbyte[length];
+    jsize length = env->GetArrayLength(andMask);
+    jbyte *andMaskPtr = new jbyte[length]; // safe because sizeof(jbyte)==1
     env->GetByteArrayRegion(andMask, 0, length, andMaskPtr);
 
     HBITMAP hMask = ::CreateBitmap(nW, nH, 1, 1, (BYTE *)andMaskPtr);
     ::GdiFlush();
 
-    int *cols = new int[nW*nH];
+    int *cols = SAFE_SIZE_NEW_ARRAY2(int, nW, nH);
 
     jint *intRasterDataPtr = NULL;
     HBITMAP hColor = NULL;
--- a/jdk/src/windows/native/sun/windows/awt_DataTransferer.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_DataTransferer.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -281,13 +281,13 @@
         }
 
         UINT bufsize = 512; // in characters, not in bytes
-        buffer = (LPTSTR)safe_Malloc(bufsize*sizeof(TCHAR));
+        buffer = (LPTSTR)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, bufsize, sizeof(TCHAR));
 
         for (UINT i = 0; i < nFilenames; i++) {
             UINT size = ::DragQueryFile(hdrop, i, NULL, 0);
             if (size > bufsize) {
                 bufsize = size;
-                buffer = (LPTSTR)safe_Realloc(buffer, bufsize*sizeof(TCHAR));
+                buffer = (LPTSTR)SAFE_SIZE_ARRAY_REALLOC(safe_Realloc, buffer, bufsize, sizeof(TCHAR));
             }
             ::DragQueryFile(hdrop, i, buffer, bufsize);
 
@@ -359,7 +359,7 @@
         return NULL;
     }
 
-    jbyte* bBytes = (jbyte*)safe_Malloc(size * sizeof(jbyte));
+    jbyte* bBytes = (jbyte*)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, size, sizeof(jbyte));
 
     try {
 
@@ -771,9 +771,9 @@
                         } else {
                             LPBYTE lpbMfBuffer = NULL;
                             try {
-                                UINT uMfSizeWithHead = uMfSize + sizeof(METAFILEPICT);
-
-                                lpbMfBuffer = (LPBYTE)safe_Malloc(uMfSizeWithHead);
+                                lpbMfBuffer = (LPBYTE)SAFE_SIZE_STRUCT_ALLOC(safe_Malloc,
+                                        sizeof(METAFILEPICT), uMfSize, 1);
+                                const UINT uMfSizeWithHead = uMfSize + sizeof(METAFILEPICT);
                                 VERIFY(::GetMetaFileBitsEx(hmf, uMfSize,
                                                             lpbMfBuffer + sizeof(METAFILEPICT)) == uMfSize);
                                 bytes = env->NewByteArray(uMfSizeWithHead);
--- a/jdk/src/windows/native/sun/windows/awt_DesktopProperties.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_DesktopProperties.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -171,7 +171,7 @@
     if (*valueType == REG_EXPAND_SZ) {
         // Pending: buffer must be null-terminated at this point
         valueChar = ExpandEnvironmentStrings(buffer, NULL, 0);
-        LPTSTR buffer2 = (LPTSTR)safe_Malloc(valueChar*sizeof(TCHAR));
+        LPTSTR buffer2 = (LPTSTR)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, valueChar, sizeof(TCHAR));
         ExpandEnvironmentStrings(buffer, buffer2, valueChar);
         free(buffer);
         return buffer2;
@@ -588,11 +588,11 @@
     }
 
     LPTSTR valueName = TEXT("PlaceN");
-    LPTSTR valueNameBuf = (LPTSTR)safe_Malloc((lstrlen(valueName) + 1) * sizeof(TCHAR));
+    LPTSTR valueNameBuf = (LPTSTR)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, (lstrlen(valueName) + 1), sizeof(TCHAR));
     lstrcpy(valueNameBuf, valueName);
 
     LPTSTR propKey = TEXT("win.comdlg.placesBarPlaceN");
-    LPTSTR propKeyBuf = (LPTSTR)safe_Malloc((lstrlen(propKey) + 1) * sizeof(TCHAR));
+    LPTSTR propKeyBuf = (LPTSTR)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, (lstrlen(propKey) + 1), sizeof(TCHAR));
     lstrcpy(propKeyBuf, propKey);
 
     int i = 0;
--- a/jdk/src/windows/native/sun/windows/awt_DnDDT.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_DnDDT.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -1037,8 +1037,8 @@
         if (m_dataObject->QueryGetData(&tmp) != S_OK) continue;
 
         if (m_nformats % CACHE_INCR == 0) {
-            m_formats = (FORMATETC *)safe_Realloc(m_formats,
-                                                  (CACHE_INCR + m_nformats) *
+            m_formats = (FORMATETC *)SAFE_SIZE_ARRAY_REALLOC(safe_Realloc, m_formats,
+                                                  CACHE_INCR + m_nformats,
                                                   sizeof(FORMATETC));
         }
 
--- a/jdk/src/windows/native/sun/windows/awt_Frame.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_Frame.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -380,9 +380,11 @@
 
             if (!sm_suppressFocusAndActivation) {
                 if (IsLightweightFrame() || IsEmbeddedFrame()) {
-                    AwtWindow::SynthesizeWmActivate(FALSE, GetHWnd(), NULL);
+                    HWND oppositeToplevelHWnd = AwtComponent::GetTopLevelParentForWindow((HWND)wParam);
+                    if (oppositeToplevelHWnd != AwtComponent::GetFocusedWindow()) {
+                        AwtWindow::SynthesizeWmActivate(FALSE, GetHWnd(), NULL);
+                    }
                 }
-
             } else if (sm_restoreFocusAndActivation) {
                 if (AwtComponent::GetFocusedWindow() != NULL) {
                     AwtWindow *focusedWindow = (AwtWindow*)GetComponent(AwtComponent::GetFocusedWindow());
--- a/jdk/src/windows/native/sun/windows/awt_InputMethod.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_InputMethod.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -333,7 +333,7 @@
     // list which is returned by GetKeyboardLayoutList ensures to match first when
     // looking up suitable layout.
     int layoutCount = ::GetKeyboardLayoutList(0, NULL) + 1;  // +1 for user's preferred HKL
-    HKL FAR * hKLList = (HKL FAR *)safe_Malloc(sizeof(HKL)*layoutCount);
+    HKL FAR * hKLList = (HKL FAR *)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(HKL), layoutCount);
     DASSERT(!safe_ExceptionOccurred(env));
     ::GetKeyboardLayoutList(layoutCount - 1, &(hKLList[1]));
     hKLList[0] = getDefaultKeyboardLayout(); // put user's preferred layout on top of the list
@@ -444,7 +444,7 @@
 
     // get list of available HKLs
     int layoutCount = ::GetKeyboardLayoutList(0, NULL);
-    HKL FAR * hKLList = (HKL FAR *)safe_Malloc(sizeof(HKL)*layoutCount);
+    HKL FAR * hKLList = (HKL FAR *)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(HKL), layoutCount);
     DASSERT(!safe_ExceptionOccurred(env));
     ::GetKeyboardLayoutList(layoutCount, hKLList);
 
@@ -453,7 +453,7 @@
     int destIndex = 0;
     int javaLocaleNameCount = 0;
     int current = 0;
-    const char ** javaLocaleNames = (const char **)safe_Malloc(sizeof(char *)*layoutCount);
+    const char ** javaLocaleNames = (const char **)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(char *), layoutCount);
     DASSERT(!safe_ExceptionOccurred(env));
     for (; srcIndex < layoutCount; srcIndex++) {
         const char * srcLocaleName = getJavaIDFromLangID(LOWORD(hKLList[srcIndex]));
@@ -517,7 +517,7 @@
     jstring infojStr = NULL;
 
     if ((buffSize = ::ImmGetDescription(hkl, szImmDescription, 0)) > 0) {
-        szImmDescription = (LPTSTR) safe_Malloc((buffSize+1) * sizeof(TCHAR));
+        szImmDescription = (LPTSTR) SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, (buffSize+1), sizeof(TCHAR));
 
         if (szImmDescription != NULL) {
             ImmGetDescription(hkl, szImmDescription, (buffSize+1));
--- a/jdk/src/windows/native/sun/windows/awt_PrintControl.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_PrintControl.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -252,7 +252,7 @@
     AwtPrintControl::getCopiesID =
       env->GetMethodID(cls, "getCopiesAttrib", "()I");
     AwtPrintControl::getCollateID =
-      env->GetMethodID(cls, "getCollateAttrib","()Z");
+      env->GetMethodID(cls, "getCollateAttrib","()I");
     AwtPrintControl::getOrientID =
       env->GetMethodID(cls, "getOrientAttrib", "()I");
     AwtPrintControl::getFromPageID =
@@ -484,8 +484,8 @@
                                               NULL, NULL);
 
     if (numPaperSizes > 0) {
-        papers = (WORD*)safe_Malloc(sizeof(WORD) * numPaperSizes);
-        paperSizes = (POINT *)safe_Malloc(sizeof(*paperSizes) *
+        papers = (WORD*)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(WORD), numPaperSizes);
+        paperSizes = (POINT *)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(*paperSizes),
                                           numPaperSizes);
 
         DWORD result1 = DeviceCapabilities(printer, port,
@@ -690,12 +690,6 @@
     pd.Flags = PD_ENABLEPRINTHOOK | PD_RETURNDC | PD_USEDEVMODECOPIESANDCOLLATE;
     pd.lpfnPrintHook = (LPPRINTHOOKPROC)PrintDlgHook;
 
-    if (env->CallBooleanMethod(printCtrl, AwtPrintControl::getCollateID)) {
-        pd.Flags |= PD_COLLATE;
-    }
-
-    pd.nCopies = (WORD)env->CallIntMethod(printCtrl,
-                                          AwtPrintControl::getCopiesID);
     pd.nFromPage = (WORD)env->CallIntMethod(printCtrl,
                                             AwtPrintControl::getFromPageID);
     pd.nToPage = (WORD)env->CallIntMethod(printCtrl,
@@ -729,37 +723,52 @@
       DEVMODE *devmode = (DEVMODE *)::GlobalLock(pd.hDevMode);
       DASSERT(!IsBadWritePtr(devmode, sizeof(DEVMODE)));
 
-      devmode->dmFields |= DM_COPIES | DM_COLLATE | DM_ORIENTATION |
-          DM_PAPERSIZE | DM_PRINTQUALITY | DM_COLOR | DM_DUPLEX;
-
-      devmode->dmCopies = pd.nCopies;
+      WORD copies = (WORD)env->CallIntMethod(printCtrl,
+                                             AwtPrintControl::getCopiesID);
+      if (copies > 0) {
+          devmode->dmFields |= DM_COPIES;
+          devmode->dmCopies = copies;
+      }
 
       jint orient = env->CallIntMethod(printCtrl,
                                        AwtPrintControl::getOrientID);
-      if (orient == 0) {
+      if (orient == 0) {  // PageFormat.LANDSCAPE == 0
+        devmode->dmFields |= DM_ORIENTATION;
         devmode->dmOrientation = DMORIENT_LANDSCAPE;
-      } else if (orient == 1) {
+      } else if (orient == 1) { // PageFormat.PORTRAIT == 1
+        devmode->dmFields |= DM_ORIENTATION;
         devmode->dmOrientation = DMORIENT_PORTRAIT;
       }
 
-      devmode->dmCollate = (pd.Flags & PD_COLLATE) ? DMCOLLATE_TRUE
-        : DMCOLLATE_FALSE;
+      // -1 means unset, so we'll accept the printer default.
+      int collate = env->CallIntMethod(printCtrl,
+                                       AwtPrintControl::getCollateID);
+      if (collate == 1) {
+        devmode->dmFields |= DM_COLLATE;
+        devmode->dmCollate = DMCOLLATE_TRUE;
+      } else if (collate == 0) {
+        devmode->dmFields |= DM_COLLATE;
+        devmode->dmCollate = DMCOLLATE_FALSE;
+      }
 
       int quality = env->CallIntMethod(printCtrl,
                                        AwtPrintControl::getQualityID);
       if (quality) {
+        devmode->dmFields |= DM_PRINTQUALITY;
         devmode->dmPrintQuality = quality;
       }
 
       int color = env->CallIntMethod(printCtrl,
                                      AwtPrintControl::getColorID);
       if (color) {
+        devmode->dmFields |= DM_COLOR;
         devmode->dmColor = color;
       }
 
       int sides = env->CallIntMethod(printCtrl,
                                      AwtPrintControl::getSidesID);
       if (sides) {
+        devmode->dmFields |= DM_DUPLEX;
         devmode->dmDuplex = (int)sides;
       }
 
@@ -771,6 +780,7 @@
 
       double newWid = 0.0, newHt = 0.0;
       if (wid_ht != NULL && wid_ht[0] != 0 && wid_ht[1] != 0) {
+        devmode->dmFields |= DM_PAPERSIZE;
         devmode->dmPaperSize = AwtPrintControl::getNearestMatchingPaper(
                                              printName,
                                              portName,
--- a/jdk/src/windows/native/sun/windows/awt_PrintJob.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_PrintJob.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -433,7 +433,7 @@
         int measure = PSD_INTHOUSANDTHSOFINCHES;
         int sz = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IMEASURE, NULL, 0);
         if (sz > 0) {
-          LPTSTR str = (LPTSTR)safe_Malloc(sizeof(TCHAR) * sz);
+          LPTSTR str = (LPTSTR)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(TCHAR), sz);
           if (str != NULL) {
             sz = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IMEASURE, str, sz);
             if (sz > 0) {
@@ -645,7 +645,7 @@
           int sz = GetLocaleInfo(LOCALE_USER_DEFAULT,
                                  LOCALE_IMEASURE, NULL, 0);
           if (sz > 0) {
-            LPTSTR str = (LPTSTR)safe_Malloc(sizeof(TCHAR) * sz);
+            LPTSTR str = (LPTSTR)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(TCHAR), sz);
             if (str != NULL) {
               sz = GetLocaleInfo(LOCALE_USER_DEFAULT,
                                  LOCALE_IMEASURE, str, sz);
@@ -2302,8 +2302,8 @@
      * rounded advances will drift away from the true advance.
      */
     if (glyphPos != NULL && strLen > 0) {
-         xadvances = (int*)safe_Malloc(strLen * sizeof(int));
-         xyadvances = (int*)safe_Malloc(strLen * sizeof(int) * 2);
+         xadvances = (int*)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, strLen, sizeof(int));
+         xyadvances = (int*)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, strLen, sizeof(int) * 2);
     }
     if (xadvances != NULL && xyadvances != NULL) {
         int *inxAdvances = xadvances;
@@ -2513,8 +2513,9 @@
     if ((imgWidthByteSz % sizeof(DWORD)) != 0)
         padBytes = sizeof(DWORD) - (imgWidthByteSz % sizeof(DWORD));
 
+    jbyte* alignedImage = (jbyte*) SAFE_SIZE_ARRAY_ALLOC(safe_Malloc,
+            imgWidthByteSz+padBytes, ROUND_TO_LONG(srcHeight));
     long newImgSize = (imgWidthByteSz+padBytes) * ROUND_TO_LONG(srcHeight);
-    jbyte* alignedImage = (jbyte*) safe_Malloc(newImgSize);
 
     if (alignedImage != NULL) {
         memset(alignedImage, 0xff, newImgSize);
@@ -3116,7 +3117,7 @@
                                        DC_PAPERSIZE, NULL, NULL);
 
     if (numPaperSizes > 0) {
-        paperSizes = (POINT *)safe_Malloc(sizeof(*paperSizes) * numPaperSizes);
+        paperSizes = (POINT *)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(*paperSizes), numPaperSizes);
 
         DWORD result = DeviceCapabilities(deviceName, portName,
                                           DC_PAPERSIZE, (LPTSTR) paperSizes,
@@ -3766,8 +3767,8 @@
     numPaperSizes = (int)DeviceCapabilities(printer, port, DC_PAPERSIZE,
                                             NULL, NULL);
     if (numPaperSizes > 0) {
-        papers = (WORD*)safe_Malloc(sizeof(WORD) * numPaperSizes);
-        paperSizes = (POINT *)safe_Malloc(sizeof(*paperSizes) * numPaperSizes);
+        papers = (WORD*)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(WORD), numPaperSizes);
+        paperSizes = (POINT *)SAFE_SIZE_ARRAY_ALLOC(safe_Malloc, sizeof(*paperSizes), numPaperSizes);
 
         DWORD result1 = DeviceCapabilities(printer, port,
                                            DC_PAPERS, (LPTSTR) papers, NULL);
--- a/jdk/src/windows/native/sun/windows/awt_Robot.cpp	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/src/windows/native/sun/windows/awt_Robot.cpp	Wed Jul 05 19:00:49 2017 +0200
@@ -234,7 +234,9 @@
     static const int BITS_PER_PIXEL = 32;
     static const int BYTES_PER_PIXEL = BITS_PER_PIXEL/8;
 
+    if (!IS_SAFE_SIZE_MUL(width, height)) throw std::bad_alloc();
     int numPixels = width*height;
+    if (!IS_SAFE_SIZE_MUL(BYTES_PER_PIXEL, numPixels)) throw std::bad_alloc();
     int pixelDataSize = BYTES_PER_PIXEL*numPixels;
     DASSERT(pixelDataSize > 0 && pixelDataSize % 4 == 0);
     // allocate memory for BITMAPINFO + pixel data
@@ -244,6 +246,9 @@
     // end of our block of memory.  Now we allocate sufficient memory.
     // See MSDN docs for BITMAPINFOHEADER -bchristi
 
+    if (!IS_SAFE_SIZE_ADD(sizeof(BITMAPINFOHEADER) + 3 * sizeof(RGBQUAD), pixelDataSize)) {
+        throw std::bad_alloc();
+    }
     BITMAPINFO * pinfo = (BITMAPINFO *)(new BYTE[sizeof(BITMAPINFOHEADER) + 3 * sizeof(RGBQUAD) + pixelDataSize]);
 
     // pixel data starts after 3 RGBQUADS for color masks
--- a/jdk/test/ProblemList.txt	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/ProblemList.txt	Wed Jul 05 19:00:49 2017 +0200
@@ -314,6 +314,13 @@
 
 ############################################################################
 
+# jdk_time
+
+# 8016623
+java/time/test/java/time/format/TestDateTimeTextProvider.java   generic-all
+
+############################################################################
+
 # jdk_tools
 
 # 6461635
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/java/swing/plaf/gtk/4928019/bug4928019.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,244 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 4928019
+ * @summary Makes sure all the basic classes can be created with GTK.
+ * @author Scott Violet
+ */
+
+import javax.swing.*;
+import javax.swing.plaf.basic.*;
+
+public class bug4928019 {
+    public static void main(String[] args) throws Throwable {
+        try {
+            UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
+        } catch (UnsupportedLookAndFeelException ex) {
+            System.err.println("GTKLookAndFeel is not supported on this platform." +
+                    " Test is considered passed.");
+            return;
+        } catch (ClassNotFoundException ex) {
+            System.err.println("GTKLookAndFeel class is not found." +
+                    " Test is considered passed.");
+            return;
+        }
+        new JButton() {
+            public void updateUI() {
+                setUI(new BasicButtonUI());
+            }
+        };
+        new JCheckBox() {
+            public void updateUI() {
+                setUI(new BasicCheckBoxUI());
+            }
+        };
+        new JCheckBoxMenuItem() {
+            public void updateUI() {
+                setUI(new BasicCheckBoxMenuItemUI());
+            }
+        };
+        new JColorChooser() {
+            public void updateUI() {
+                setUI(new BasicColorChooserUI());
+            }
+        };
+        new JComboBox() {
+            public void updateUI() {
+                setUI(new BasicComboBoxUI());
+            }
+        };
+        new JDesktopPane() {
+            public void updateUI() {
+                setUI(new BasicDesktopPaneUI());
+            }
+        };
+        new JEditorPane() {
+            public void updateUI() {
+                setUI(new BasicEditorPaneUI());
+            }
+        };
+        new JFileChooser() {
+            public void updateUI() {
+                setUI(new BasicFileChooserUI(null));
+            }
+        };
+        new JFormattedTextField() {
+            public void updateUI() {
+                setUI(new BasicFormattedTextFieldUI());
+            }
+        };
+        new JInternalFrame() {
+            public void updateUI() {
+                setUI(new BasicInternalFrameUI(null));
+            }
+        };
+        new JLabel() {
+            public void updateUI() {
+                setUI(new BasicLabelUI());
+            }
+        };
+        new JList() {
+            public void updateUI() {
+                setUI(new BasicListUI());
+            }
+        };
+        new JMenuBar() {
+            public void updateUI() {
+                setUI(new BasicMenuBarUI());
+            }
+        };
+        new JMenuItem() {
+            public void updateUI() {
+                setUI(new BasicMenuItemUI());
+            }
+        };
+        new JMenu() {
+            public void updateUI() {
+                setUI(new BasicMenuUI());
+            }
+        };
+        new JOptionPane() {
+            public void updateUI() {
+                setUI(new BasicOptionPaneUI());
+            }
+        };
+        new JPanel() {
+            public void updateUI() {
+                setUI(new BasicPanelUI());
+            }
+        };
+        new JPasswordField() {
+            public void updateUI() {
+                setUI(new BasicPasswordFieldUI());
+            }
+        };
+        new JPopupMenu() {
+            public void updateUI() {
+                setUI(new BasicPopupMenuUI());
+            }
+        };
+        new JProgressBar() {
+            public void updateUI() {
+                setUI(new BasicProgressBarUI());
+            }
+        };
+        new JRadioButton() {
+            public void updateUI() {
+                setUI(new BasicRadioButtonUI());
+            }
+        };
+        new JRadioButtonMenuItem() {
+            public void updateUI() {
+                setUI(new BasicRadioButtonMenuItemUI());
+            }
+        };
+        new JRootPane() {
+            public void updateUI() {
+                setUI(new BasicRootPaneUI());
+            }
+        };
+        new JScrollBar() {
+            public void updateUI() {
+                setUI(new BasicScrollBarUI());
+            }
+        };
+        new JScrollPane() {
+            public void updateUI() {
+                setUI(new BasicScrollPaneUI());
+            }
+        };
+        new JSeparator() {
+            public void updateUI() {
+                setUI(new BasicSeparatorUI());
+            }
+        };
+        new JSlider() {
+            public void updateUI() {
+                setUI(new BasicSliderUI(null));
+            }
+        };
+        new JSpinner() {
+            public void updateUI() {
+                setUI(new BasicSpinnerUI());
+            }
+        };
+        new JSplitPane() {
+            public void updateUI() {
+                setUI(new BasicSplitPaneUI());
+            }
+        };
+        new JTabbedPane() {
+            public void updateUI() {
+                setUI(new BasicTabbedPaneUI());
+            }
+        };
+        new JTable() {
+            public void updateUI() {
+                setUI(new BasicTableUI());
+            }
+        };
+        new JTextArea() {
+            public void updateUI() {
+                setUI(new BasicTextAreaUI());
+            }
+        };
+        new JTextField() {
+            public void updateUI() {
+                setUI(new BasicTextFieldUI());
+            }
+        };
+        new JTextPane() {
+            public void updateUI() {
+                setUI(new BasicTextPaneUI());
+            }
+        };
+        new JToggleButton() {
+            public void updateUI() {
+                setUI(new BasicToggleButtonUI());
+            }
+        };
+        new JToolBar() {
+            public void updateUI() {
+                setUI(new BasicToolBarUI());
+            }
+        };
+        new JToolTip() {
+            public void updateUI() {
+                setUI(new BasicToolTipUI());
+            }
+        };
+        new JTree() {
+            public void updateUI() {
+                setUI(new BasicTreeUI());
+            }
+        };
+        new JViewport() {
+            public void updateUI() {
+                setUI(new BasicViewportUI());
+            }
+        };
+        System.out.println("DONE");
+    }
+}
--- a/jdk/test/com/sun/org/apache/xml/internal/security/TruncateHMAC.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/com/sun/org/apache/xml/internal/security/TruncateHMAC.java	Wed Jul 05 19:00:49 2017 +0200
@@ -97,6 +97,7 @@
                 System.out.println("PASSED");
             } else {
                 System.out.println("FAILED");
+                atLeastOneFailed = true;
             }
         }
     }
--- a/jdk/test/com/sun/org/apache/xml/internal/security/transforms/ClassLoaderTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/com/sun/org/apache/xml/internal/security/transforms/ClassLoaderTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,7 @@
 /**
  * @test
  * @author Sean Mullan
- * @bug 6461674
+ * @bug 6461674 8009217
  * @compile -XDignore.symbol.file ClassLoaderTest.java MyTransform.java
  * @run main ClassLoaderTest
  * @summary Ensure Transform.register works with transform implementations
@@ -43,13 +43,12 @@
 
     public static void main(String[] args) throws Exception {
 
-        Transform.init();
         File file = new File(BASE);
         URL[] urls = new URL[1];
         urls[0] = file.toURI().toURL();
         URLClassLoader ucl = new URLClassLoader(urls);
-        Class c = ucl.loadClass("MyTransform");
-        Constructor cons = c.getConstructor();
+        Class<?> c = ucl.loadClass("MyTransform");
+        Constructor<?> cons = c.getConstructor(new Class[] {});
         Object o = cons.newInstance();
         // Apache code swallows the ClassNotFoundExc, so we need to
         // check if the Transform has already been registered by registering
--- a/jdk/test/com/sun/org/apache/xml/internal/security/transforms/MyTransform.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/com/sun/org/apache/xml/internal/security/transforms/MyTransform.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -21,13 +21,8 @@
  * questions.
  */
 
-import java.io.IOException;
-import javax.xml.parsers.ParserConfigurationException;
-import org.xml.sax.SAXException;
-import com.sun.org.apache.xml.internal.security.c14n.*;
-import com.sun.org.apache.xml.internal.security.exceptions.*;
-import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
-import com.sun.org.apache.xml.internal.security.transforms.*;
+import com.sun.org.apache.xml.internal.security.transforms.Transform;
+import com.sun.org.apache.xml.internal.security.transforms.TransformSpi;
 
 public class MyTransform extends TransformSpi {
 
@@ -37,21 +32,13 @@
     public MyTransform() {
         try {
             System.out.println("Registering Transform");
-            Transform.init();
             Transform.register(URI, "MyTransform");
-        } catch (AlgorithmAlreadyRegisteredException e) {
-            // should not occur, so ignore
+        } catch (Exception e) {
+            e.printStackTrace();
         }
     }
 
     protected String engineGetURI() {
         return URI;
     }
-
-    protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input)
-        throws IOException, CanonicalizationException,
-               InvalidCanonicalizerException, TransformationException,
-               ParserConfigurationException, SAXException {
-        throw new TransformationException("Unsupported Operation");
-    }
 }
--- a/jdk/test/demo/zipfs/ZipFSTester.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/demo/zipfs/ZipFSTester.java	Wed Jul 05 19:00:49 2017 +0200
@@ -341,6 +341,9 @@
 
     // test file stamp
     static void testTime(Path src) throws Exception {
+        BasicFileAttributes attrs = Files
+                        .getFileAttributeView(src, BasicFileAttributeView.class)
+                        .readAttributes();
         // create a new filesystem, copy this file into it
         Map<String, Object> env = new HashMap<String, Object>();
         env.put("create", "true");
@@ -352,10 +355,6 @@
         Path dst = getPathWithParents(fs, "me");
         Files.copy(src, dst, COPY_ATTRIBUTES);
         checkEqual(src, dst);
-
-        BasicFileAttributes attrs = Files
-                        .getFileAttributeView(src, BasicFileAttributeView.class)
-                        .readAttributes();
         System.out.println("mtime: " + attrs.lastModifiedTime());
         System.out.println("ctime: " + attrs.creationTime());
         System.out.println("atime: " + attrs.lastAccessTime());
--- a/jdk/test/demo/zipfs/basic.sh	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/demo/zipfs/basic.sh	Wed Jul 05 19:00:49 2017 +0200
@@ -22,7 +22,7 @@
 #
 # @test
 # @bug 6990846 7009092 7009085 7015391 7014948 7005986 7017840 7007596
-# 7157656 8002390 7012868 7012856
+# 7157656 8002390 7012868 7012856 8015728
 # @summary Test ZipFileSystem demo
 # @build Basic PathOps ZipFSTester
 # @run shell basic.sh
--- a/jdk/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.html	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.html	Wed Jul 05 19:00:49 2017 +0200
@@ -1,6 +1,5 @@
 <html>
 <!--  
-
   @test
   @bug 8005932
   @summary Java 7 on mac os x only provides text clipboard formats
@@ -9,10 +8,9 @@
   @library ../../regtesthelpers/process
   @build Util
   @build ProcessResults ProcessCommunicator
-
+  @run applet/othervm MissedHtmlAndRtfBug.html
+-->
 
-  @run applet/othervm MissedHtmlAndRtfBug.html
-*/>
 <head>
     <title>Java 7 on mac os x only provides text clipboard formats</title>
 </head>
--- a/jdk/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/awt/DataFlavor/MissedHtmlAndRtfBug/MissedHtmlAndRtfBug.java	Wed Jul 05 19:00:49 2017 +0200
@@ -22,7 +22,6 @@
  */
 
 /*
-  @test
   @bug 8005932
   @summary Java 7 on mac os x only provides text clipboard formats
   @author mikhail.cherkasov@oracle.com
@@ -30,10 +29,9 @@
   @library ../../regtesthelpers/process
   @build Util
   @build ProcessResults ProcessCommunicator
-
-
   @run applet/othervm MissedHtmlAndRtfBug.html
 */
+
 import java.awt.*;
 import java.awt.datatransfer.DataFlavor;
 import java.awt.event.*;
--- a/jdk/test/java/awt/Focus/TypeAhead/TestFocusFreeze.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/awt/Focus/TypeAhead/TestFocusFreeze.java	Wed Jul 05 19:00:49 2017 +0200
@@ -132,6 +132,7 @@
     }
     protected synchronized void enqueueKeyEvents(long after, Component untilFocused) {
         super.enqueueKeyEvents(after, untilFocused);
+        robot.delay(1);
         robot.keyPress(KeyEvent.VK_SPACE);
         robot.delay(50);
         robot.keyRelease(KeyEvent.VK_SPACE);
--- a/jdk/test/java/awt/GraphicsDevice/CheckDisplayModes.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/awt/GraphicsDevice/CheckDisplayModes.java	Wed Jul 05 19:00:49 2017 +0200
@@ -37,6 +37,10 @@
     public static void main(String[] args) {
         GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
         GraphicsDevice graphicDevice = ge.getDefaultScreenDevice();
+        if (!graphicDevice.isDisplayChangeSupported()) {
+            System.err.println("Display mode change is not supported on this host. Test is considered passed.");
+            return;
+        }
         DisplayMode defaultDisplayMode = graphicDevice.getDisplayMode();
         checkDisplayMode(defaultDisplayMode);
         graphicDevice.setDisplayMode(defaultDisplayMode);
--- a/jdk/test/java/awt/Mixing/MixingInHwPanel.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/awt/Mixing/MixingInHwPanel.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,7 +22,7 @@
  */
 
 /*
-  @test %W% %E%
+  @test
   @bug 6829858
   @summary Mixing should work inside heavyweight containers
   @author anthony.petrov@sun.com: area=awt.mixing
@@ -104,7 +104,7 @@
 
         // And click the part of the button that has been previously hidden
         Point bLoc = button.getLocationOnScreen();
-        robot.mouseMove(bLoc.x + button.getWidth() - 6, bLoc.y + button.getHeight() / 2);
+        robot.mouseMove(bLoc.x + button.getWidth() - 15, bLoc.y + button.getHeight() / 2);
 
         Util.waitForIdle(robot);
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Mouse/EnterExitEvents/FullscreenEnterEventTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,166 @@
+/*
+* Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+*
+* This code is free software; you can redistribute it and/or modify it
+* under the terms of the GNU General Public License version 2 only, as
+* published by the Free Software Foundation.
+*
+* This code is distributed in the hope that it will be useful, but WITHOUT
+* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+* version 2 for more details (a copy is included in the LICENSE file that
+* accompanied this code).
+*
+* You should have received a copy of the GNU General Public License version
+* 2 along with this work; if not, write to the Free Software Foundation,
+* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+*
+* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+* or visit www.oracle.com if you need additional information or have any
+* questions.
+*/
+
+import sun.misc.OSEnvironment;
+import test.java.awt.regtesthelpers.Util;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.InputEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+
+/*
+ * @test
+ * @bug 8013468
+ * @summary Cursor does not update properly when in fullscreen mode on Mac
+ *    The core reason of the issue was the lack of a mouse entered event in fullscreen
+ * @library ../../regtesthelpers
+ * @build Util
+ * @author Petr Pchelko area=awt.event
+ * @run main FullscreenEnterEventTest
+ */
+public class FullscreenEnterEventTest {
+
+    private static String OS = System.getProperty("os.name").toLowerCase();
+
+    private static JFrame frame;
+
+    private static volatile int mouseEnterCount = 0;
+
+    private static volatile boolean windowEnteringFullScreen = false;
+    private static volatile boolean windowEnteredFullScreen = false;
+
+    public static void main(String[] args) throws Exception {
+
+        if (!OS.contains("mac")) {
+            System.out.println("The test is applicable only to Mac OS X. Passed");
+            return;
+        }
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                createAndShowGUI();
+            }
+        });
+
+        //Move the mouse away from the frame and check the View-base full screen mode
+        Robot r = Util.createRobot();
+        Util.waitForIdle(r);
+        r.mouseMove(500, 500);
+        Util.waitForIdle(r);
+        mouseEnterCount = 0;
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(frame);
+            }
+        });
+        Util.waitForIdle(r);
+        if (mouseEnterCount != 1) {
+            throw new RuntimeException("No MouseEntered event for view-base full screen. Failed.");
+        }
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(null);
+            }
+        });
+
+        //Test native full screen support
+        Point fullScreenButtonPos = frame.getLocation();
+        fullScreenButtonPos.translate(frame.getWidth() - 10, 10);
+        r.mouseMove(fullScreenButtonPos.x, fullScreenButtonPos.y);
+        mouseEnterCount = 0;
+
+        //Cant use waitForIdle for full screen transition.
+        int waitCount = 0;
+        while (!windowEnteringFullScreen) {
+            r.mousePress(InputEvent.BUTTON1_MASK);
+            r.mouseRelease(InputEvent.BUTTON1_MASK);
+            Thread.sleep(100);
+            if (waitCount++ > 10) throw new RuntimeException("Can't enter full screen mode. Failed");
+        }
+
+        waitCount = 0;
+        while (!windowEnteredFullScreen) {
+            Thread.sleep(200);
+            if (waitCount++ > 10) throw new RuntimeException("Can't enter full screen mode. Failed");
+        }
+
+        if (mouseEnterCount != 1) {
+            throw new RuntimeException("No MouseEntered event for native full screen. Failed.");
+        }
+    }
+
+    private static void createAndShowGUI() {
+        frame = new JFrame(" Fullscreen OSX Bug ");
+        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+        enableFullScreen(frame);
+        frame.addMouseListener(new MouseAdapter() {
+            @Override
+            public void mouseEntered(MouseEvent e) {
+                mouseEnterCount++;
+            }
+        });
+        frame.setBounds(100, 100, 100, 100);
+        frame.pack();
+        frame.setVisible(true);
+
+    }
+
+    /*
+     *  Use reflection to make a test compilable on not Mac OS X
+     */
+    private static void enableFullScreen(Window window) {
+        try {
+            Class fullScreenUtilities = Class.forName("com.apple.eawt.FullScreenUtilities");
+            Method setWindowCanFullScreen = fullScreenUtilities.getMethod("setWindowCanFullScreen", Window.class, boolean.class);
+            setWindowCanFullScreen.invoke(fullScreenUtilities, window, true);
+            Class fullScreenListener = Class.forName("com.apple.eawt.FullScreenListener");
+            Object listenerObject = Proxy.newProxyInstance(fullScreenListener.getClassLoader(), new Class[]{fullScreenListener}, new InvocationHandler() {
+                @Override
+                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+                    switch (method.getName()) {
+                        case "windowEnteringFullScreen":
+                            windowEnteringFullScreen = true;
+                            break;
+                        case "windowEnteredFullScreen":
+                            windowEnteredFullScreen = true;
+                            break;
+                    }
+                    return null;
+                }
+            });
+            Method addFullScreenListener = fullScreenUtilities.getMethod("addFullScreenListenerTo", Window.class, fullScreenListener);
+            addFullScreenListener.invoke(fullScreenUtilities, window, listenerObject);
+        } catch (Exception e) {
+            throw new RuntimeException("FullScreen utilities not available", e);
+        }
+    }
+
+}
--- a/jdk/test/java/awt/event/KeyEvent/KeyReleasedInAppletTest/KeyReleasedInAppletTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/awt/event/KeyEvent/KeyReleasedInAppletTest/KeyReleasedInAppletTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -39,7 +39,6 @@
 import java.util.Hashtable;
 
 /*
-@test
 @bug 8010009
 @summary [macosx] Unable type into online word games on MacOSX
 @author petr.pchelko : area=awt.keyboard
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/font/LineBreakMeasurer/AllFontsLBM.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 8012617
+ * @summary ArrayIndexOutOfBoundsException in LineBreakMeasurer
+ */
+
+import java.awt.*;
+import java.awt.image.*;
+import java.awt.font.*;
+import java.awt.geom.*;
+import java.text.*;
+import java.util.Hashtable;
+
+public class AllFontsLBM {
+
+    public static void main(String[] args) {
+        Font[] allFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
+        for (int i=0;i<allFonts.length; i++) {
+           try {
+           Font f = allFonts[i].deriveFont(Font.PLAIN, 20);
+
+           if ( f.getFontName().startsWith("HiraKaku") ) {
+               continue;
+           }
+
+           System.out.println("Try : " + f.getFontName());
+           System.out.flush();
+           breakLines(f);
+           } catch (Exception e) {
+              System.out.println(allFonts[i]);
+           }
+        }
+    }
+
+     static void breakLines(Font font) {
+        AttributedString vanGogh = new AttributedString(
+        "Many people believe that Vincent van Gogh painted his best works " +
+        "during the two-year period he spent in Provence. Here is where he " +
+        "painted The Starry Night--which some consider to be his greatest " +
+        "work of all. However, as his artistic brilliance reached new " +
+        "heights in Provence, his physical and mental health plummeted. ",
+        new Hashtable());
+        vanGogh.addAttribute(TextAttribute.FONT, font);
+        BufferedImage bi = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
+        Graphics2D g2d = bi.createGraphics();
+        AttributedCharacterIterator aci = vanGogh.getIterator();
+        FontRenderContext frc = new FontRenderContext(null, false, false);
+        LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
+        lbm.setPosition(aci.getBeginIndex());
+        while (lbm.getPosition() < aci.getEndIndex()) {
+             lbm.nextLayout(100f);
+        }
+
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/font/TextLayout/KerningLeak.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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.
+ */
+
+/**
+ * @bug 8015334
+ * @summary Memory leak with kerning.
+ */
+
+import java.awt.EventQueue;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.font.TextAttribute;
+import java.util.HashMap;
+import java.util.Map;
+import javax.swing.JLabel;
+import javax.swing.SwingUtilities;
+
+public class KerningLeak {
+
+    public static void main(String[] args) {
+        EventQueue.invokeLater(new Runnable() {
+            @Override
+            public void run() {
+                leak();
+            }
+        });
+    }
+
+    private static void leak() {
+        Map<TextAttribute, Object> textAttributes = new HashMap<>();
+        textAttributes.put(TextAttribute.FAMILY, "Sans Serif");
+        textAttributes.put(TextAttribute.SIZE, 12);
+        textAttributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
+        Font font = Font.getFont(textAttributes);
+        JLabel label = new JLabel();
+        int dummy = 0;
+        for (int i = 0; i < 500; i++) {
+            if (i % 10 == 0) System.out.println("Starting iter " + (i+1));
+            for (int j = 0; j <1000; j++) {
+                FontMetrics fm = label.getFontMetrics(font);
+                dummy += SwingUtilities.computeStringWidth(fm, Integer.toString(j));
+            }
+        }
+        System.out.println("done " + dummy);
+    }
+}
--- a/jdk/test/java/awt/image/mlib/MlibOpsTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/awt/image/mlib/MlibOpsTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug     6556332
+ * @bug     6556332 8011992 8012112
  * @summary Test verifies that on-demnad loading of medialib library does
  *          not break imageing ops based on this library.
  * @run     main MlibOpsTest
--- a/jdk/test/java/io/File/CreateNewFile.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/io/File/CreateNewFile.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,7 +22,7 @@
  */
 
 /* @test
-   @bug 4130498 4391178
+   @bug 4130498 4391178 6198547
    @summary Basic test for createNewFile method
  */
 
@@ -51,5 +51,20 @@
         } catch (IOException e) {
             // Exception expected
         }
+
+        testCreateExistingDir();
+    }
+
+    // Test JDK-6198547
+    private static void testCreateExistingDir() throws IOException {
+        File tmpFile = new File("hugo");
+        if (tmpFile.exists() && !tmpFile.delete())
+            throw new RuntimeException("Cannot delete " + tmpFile);
+        if (!tmpFile.mkdir())
+            throw new RuntimeException("Cannot create dir " + tmpFile);
+        if (!tmpFile.exists())
+            throw new RuntimeException("Cannot see created dir " + tmpFile);
+        if (tmpFile.createNewFile())
+            throw new RuntimeException("Should fail to create file " + tmpFile);
     }
 }
--- a/jdk/test/java/io/File/NulFile.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/io/File/NulFile.java	Wed Jul 05 19:00:49 2017 +0200
@@ -612,7 +612,7 @@
             try {
                 File.createTempFile(prefix, suffix, directory);
             } catch (IOException ex) {
-                if ("Unable to create temporary file".equals(ex.getMessage()))
+                if (ExceptionMsg.equals(ex.getMessage()))
                     exceptionThrown = true;
             }
         }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/io/File/createTempFile/SpecialTempFile.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 8013827 8011950
+ * @summary Check whether File.createTempFile can handle special parameters
+ *          on Windows platforms
+ * @author Dan Xu
+ */
+
+import java.io.File;
+import java.io.IOException;
+
+public class SpecialTempFile {
+
+    private static void test(String name, String[] prefix, String[] suffix) {
+        if (prefix == null || suffix == null
+            || prefix.length != suffix.length)
+        {
+            return;
+        }
+
+        final String exceptionMsg = "Unable to create temporary file";
+        final String errMsg = "IOException is expected";
+
+        for (int i = 0; i < prefix.length; i++) {
+            boolean exceptionThrown = false;
+            File f = null;
+            System.out.println("In test " + name
+                               + ", creating temp file with prefix, "
+                               + prefix[i] + ", suffix, " + suffix[i]);
+            try {
+                f = File.createTempFile(prefix[i], suffix[i]);
+            } catch (IOException e) {
+                if (exceptionMsg.equals(e.getMessage()))
+                    exceptionThrown = true;
+                else
+                    System.out.println("Wrong error message:" + e.getMessage());
+            }
+            if (!exceptionThrown || f != null)
+                throw new RuntimeException(errMsg);
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        if (!System.getProperty("os.name").startsWith("Windows"))
+            return;
+
+        // Test JDK-8013827
+        String[] resvPre = { "LPT1.package.zip", "com7.4.package.zip" };
+        String[] resvSuf = { ".temp", ".temp" };
+        test("ReservedName", resvPre, resvSuf);
+
+        // Test JDK-8011950
+        String[] slashPre = { "///..///", "temp", "///..///" };
+        String[] slashSuf = { ".temp", "///..///..", "///..///.." };
+        test("SlashedName", slashPre, slashSuf);
+    }
+}
--- a/jdk/test/java/lang/Runtime/exec/ExecCommand.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/lang/Runtime/exec/ExecCommand.java	Wed Jul 05 19:00:49 2017 +0200
@@ -24,15 +24,18 @@
 
 /**
  * @test
- * @bug 8012453
+ * @bug 8012453 8016046
  * @run main/othervm ExecCommand
  * @summary workaround for legacy applications with Runtime.getRuntime().exec(String command)
  */
 
 import java.io.BufferedWriter;
 import java.io.File;
+import java.io.FileNotFoundException;
 import java.io.FileWriter;
 import java.io.IOException;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
 import java.security.AccessControlException;
 
 public class ExecCommand {
@@ -57,16 +60,22 @@
             if ( ncmd.equals(".\\Program")
               || ncmd.equals("\".\\Program")
               || ncmd.equals(".\\Program Files\\do.cmd")
-              || ncmd.equals(".\\Program.cmd"))
+              || ncmd.equals(".\\Program.cmd")
+              || ncmd.equals("cmd"))
             {
                 return;
             }
             super.checkExec(cmd);
         }
+
+        @Override public void checkDelete(String file) {}
+        @Override public void checkRead(String file) {}
     }
 
     // Parameters for the Runtime.exec calls
     private static final String TEST_RTE_ARG[] = {
+        "cmd /C dir > dirOut.txt",
+        "cmd /C dir > \".\\Program Files\\dirOut.txt\"",
         ".\\Program Files\\do.cmd",
         "\".\\Program Files\\doNot.cmd\" arg",
         "\".\\Program Files\\do.cmd\" arg",
@@ -83,15 +92,29 @@
 
     // Golden image for results
     private static final String TEST_RTE_GI[][] = {
-                    //Pure system | Legacy mode | Legacy mode & SM
+                    //Def Legacy mode, Enforced mode, Set Legacy mode, Set Legacy mode & SM
+        // [cmd /C dir > dirOut.txt]
+        new String[]{"Success",
+                     "IOException",  // [cmd /C dir ">" dirOut.txt] no redirection
+                     "Success",
+                     "IOException"}, //SM - no legacy mode, bad command
+
+        // [cmd /C dir > ".\Program Files\dirOut.txt"]
+        new String[]{"Success",
+                     "IOException",  // [cmd /C dir ">" ".\Program Files\dirOut.txt"] no redirection
+                     "Success",
+                     "IOException"}, //SM - no legacy mode, bad command
+
         // [.\Program File\do.cmd]
-        new String[]{"IOException",  // [.\Program] not found
+        new String[]{"Success",
+                     "IOException",  // [.\Program] not found
                      "Success",
                      "IOException"}, //SM - no legacy mode [.\Program] - OK
 
         // [".\Program File\doNot.cmd" arg]
         new String[]{"Success",
                      "Success",
+                     "Success",
                      "AccessControlException"}, //SM   - [".\Program] - OK,
                                  //     [.\\Program Files\\doNot.cmd] - Fail
 
@@ -99,14 +122,27 @@
         // AccessControlException
         new String[]{"Success",
                      "Success",
+                     "Success",
                      "Success"}, //SM - [".\Program] - OK,
                                  //     [.\\Program Files\\do.cmd] - OK
 
         // compatibility
-        new String[]{"Success", "Success", "Success"}, //[".\Program.cmd"]
-        new String[]{"Success", "Success", "Success"}  //[.\Program.cmd]
+        new String[]{"Success", "Success", "Success", "Success"}, //[".\Program.cmd"]
+        new String[]{"Success", "Success", "Success", "Success"}  //[.\Program.cmd]
     };
 
+    private static void deleteOut(String path) {
+        try {
+            Files.delete(FileSystems.getDefault().getPath(path));
+        } catch (IOException ex) {
+            //that is OK
+        }
+    }
+    private static void checkOut(String path) throws FileNotFoundException {
+        if (Files.notExists(FileSystems.getDefault().getPath(path)))
+            throw new FileNotFoundException(path);
+    }
+
     public static void main(String[] _args) throws Exception {
         if (!System.getProperty("os.name").startsWith("Windows")) {
             return;
@@ -126,20 +162,51 @@
         }
 
         // action
-        for (int k = 0; k < 3; ++k) {
+        for (int k = 0; k < 4; ++k) {
             switch (k) {
+            case 0:
+                // the "jdk.lang.Process.allowAmbiguousCommands" is undefined
+                // "true" by default with the legacy verification procedure
+                break;
             case 1:
-                System.setProperty("jdk.lang.Process.allowAmbigousCommands", "");
+                System.setProperty("jdk.lang.Process.allowAmbiguousCommands", "false");
                 break;
             case 2:
+                System.setProperty("jdk.lang.Process.allowAmbiguousCommands", "");
+                break;
+            case 3:
                 System.setSecurityManager( new SecurityMan() );
                 break;
             }
             for (int i = 0; i < TEST_RTE_ARG.length; ++i) {
                 String outRes;
                 try {
+                    // tear up
+                    switch (i) {
+                    case 0:
+                        // [cmd /C dir > dirOut.txt]
+                        deleteOut(".\\dirOut.txt");
+                        break;
+                    case 1:
+                        // [cmd /C dir > ".\Program Files\dirOut.txt"]
+                        deleteOut(".\\Program Files\\dirOut.txt");
+                        break;
+                    }
+
                     Process exec = Runtime.getRuntime().exec(TEST_RTE_ARG[i]);
                     exec.waitFor();
+
+                    //exteded check
+                    switch (i) {
+                    case 0:
+                        // [cmd /C dir > dirOut.txt]
+                        checkOut(".\\dirOut.txt");
+                        break;
+                    case 1:
+                        // [cmd /C dir > ".\Program Files\dirOut.txt"]
+                        checkOut(".\\Program Files\\dirOut.txt");
+                        break;
+                    }
                     outRes = "Success";
                 } catch (IOException ioe) {
                     outRes = "IOException: " + ioe.getMessage();
@@ -150,8 +217,8 @@
                 }
 
                 if (!outRes.startsWith(TEST_RTE_GI[i][k])) {
-                    throw new Error("Unexpected output! Step" + k + "" + i
-                                + " \nArgument: " + TEST_RTE_ARG[i]
+                    throw new Error("Unexpected output! Step" + k + ":" + i
+                                + "\nArgument: " + TEST_RTE_ARG[i]
                                 + "\nExpected: " + TEST_RTE_GI[i][k]
                                 + "\n  Output: " + outRes);
                 } else {
--- a/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,8 +23,8 @@
 
 /*
  * @test
- * @bug 7146431
- * @summary Test that internal JAXP packages cannot be accessed
+ * @bug 7146431 8000450
+ * @summary Test that internal packages cannot be accessed
  */
 
 public class CheckPackageAccess {
@@ -32,6 +32,7 @@
     public static void main(String[] args) throws Exception {
 
         String[] pkgs = new String[] {
+            "com.sun.corba.se.impl.",
             "com.sun.org.apache.xerces.internal.utils.",
             "com.sun.org.apache.xalan.internal.utils." };
         SecurityManager sm = new SecurityManager();
@@ -40,7 +41,11 @@
             System.out.println("Checking package access for " + pkg);
             try {
                 sm.checkPackageAccess(pkg);
-                throw new Exception("Expected SecurityException not thrown");
+                throw new Exception("Expected PackageAccess SecurityException not thrown");
+            } catch (SecurityException se) { }
+            try {
+                sm.checkPackageDefinition(pkg);
+                throw new Exception("Expected PackageDefinition SecurityException not thrown");
             } catch (SecurityException se) { }
         }
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/Thread/StopThrowable.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 7059085
+ * @summary Check that Thread.stop(Throwable) throws UOE
+ * @run testng StopThrowable
+ */
+
+import org.testng.annotations.Test;
+
+import java.util.concurrent.CountDownLatch;
+
+public class StopThrowable {
+
+    @Test(expectedExceptions=UnsupportedOperationException.class)
+    public void testStopSelf() {
+        Thread.currentThread().stop(new ThreadDeath());
+    }
+
+    private static void awaitUnchecked(CountDownLatch latch) {
+        try {
+            latch.await();
+        } catch (InterruptedException e) {
+            // should not happen
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Test(expectedExceptions=UnsupportedOperationException.class)
+    public void testStopOther() throws Throwable {
+        CountDownLatch ready = new CountDownLatch(1);
+        CountDownLatch done = new CountDownLatch(1);
+        Thread t = new Thread( () ->  { ready.countDown(); awaitUnchecked(done); } );
+        t.start();
+        try {
+            ready.await();
+            t.stop(new ThreadDeath());
+        } finally {
+            done.countDown();
+        }
+    }
+
+    @Test(expectedExceptions=UnsupportedOperationException.class)
+    public void testNull() {
+        Thread.currentThread().stop(null);
+    }
+}
--- a/jdk/test/java/lang/ThreadGroup/Suspend.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/lang/ThreadGroup/Suspend.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013 Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,47 +23,55 @@
 
 /**
  * @test
- * @bug 4176355
+ * @bug 4176355 7181748
  * @summary Suspending a ThreadGroup that contains the current thread has
  *          unpredictable results.
  */
 
 public class Suspend implements Runnable {
-    private static Thread first=null;
-    private static Thread second=null;
-    private static ThreadGroup group = new ThreadGroup("");
-    private static int count = 0;
 
-    Suspend() {
-        Thread thread = new Thread(group, this);
-        if (first == null)
-            first = thread;
-        else
-            second = thread;
-
-        thread.start();
-    }
+    private static volatile int count = 0;
+    private static final ThreadGroup group = new ThreadGroup("");
+    private static final Thread first = new Thread(group, new Suspend());
+    private static final Thread second = new Thread(group, new Suspend());
 
     public void run() {
         while (true) {
             try {
-                Thread.sleep(1000); // Give other thread a chance to start
-                if (Thread.currentThread() == first)
-                    group.suspend();
-                else
+                Thread.sleep(100);
+                if (Thread.currentThread() == first) {
+                    if (second.isAlive()) {
+                        group.suspend();
+                    }
+                } else {
                     count++;
-            } catch(InterruptedException e){
+                }
+            } catch (InterruptedException e) {
             }
         }
     }
 
     public static void main(String[] args) throws Exception {
-        for (int i=0; i<2; i++)
-            new Suspend();
-        Thread.sleep(3000);
+        // Launch two threads as part of the same thread group
+        first.start();
+        second.start();
+
+        // Wait for the thread group suspend to be issued
+        while (!first.isAlive() || !second.isAlive()) {
+            Thread.sleep(100);
+        }
+        Thread.sleep(1000);
+        // Suppose, the thread group is now suspended
+
+        count = 0;
+        Thread.sleep(1000);
+
+        // Increment of the count indicates that the second thread is still running
         boolean failed = (count > 1);
-        first.stop(); second.stop();
-        if (failed)
+        first.stop();
+        second.stop();
+        if (failed) {
             throw new RuntimeException("Failure.");
+        }
     }
 }
--- a/jdk/test/java/lang/instrument/MakeJAR4.sh	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/lang/instrument/MakeJAR4.sh	Wed Jul 05 19:00:49 2017 +0200
@@ -43,4 +43,4 @@
 done
 
 
-${JAR} "{TESTTOOLVMOPTS}" cvfm ${AGENT}.jar ${AGENT}.mf ${AGENT}*.class ${OTHER}*.java
+${JAR} ${TESTTOOLVMOPTS} cvfm ${AGENT}.jar ${AGENT}.mf ${AGENT}*.class ${OTHER}*.java
--- a/jdk/test/java/lang/instrument/RetransformBigClass.sh	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/lang/instrument/RetransformBigClass.sh	Wed Jul 05 19:00:49 2017 +0200
@@ -23,7 +23,6 @@
 
 # @test
 # @bug 7122253
-# @ignore until the fix for 7122253 (from HotSpot) is in a promoted build
 # @summary Retransform a big class.
 # @author Daniel D. Daugherty
 #
--- a/jdk/test/java/lang/invoke/7196190/MHProxyTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,181 +0,0 @@
-/*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
- * 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 7196190
- * @summary Improve method of handling MethodHandles
- *
- * @run main/othervm MHProxyTest
- */
-
-import java.lang.invoke.*;
-import java.security.*;
-import static java.lang.invoke.MethodHandles.*;
-import static java.lang.invoke.MethodType.*;
-
-public class MHProxyTest {
-    private static final Class<?> C_Unsafe;
-    private static final MethodHandle MH_getUnsafe;
-    static {
-        // Do these before there is a SM installed.
-        C_Unsafe = sun.misc.Unsafe.class;  // EXPECT A WARNING ON THIS LINE
-        Lookup lookup = lookup();
-        MethodHandle gumh = null;
-        try {
-            gumh = lookup.findStatic(C_Unsafe, "getUnsafe", methodType(C_Unsafe));
-        } catch (ReflectiveOperationException ex) {
-            throw new InternalError(ex.toString());
-        }
-        MH_getUnsafe = gumh;
-        // Try some different lookups:
-        try {
-            lookup.in(Object.class).findStatic(C_Unsafe, "getUnsafe", methodType(C_Unsafe));
-        } catch (ReflectiveOperationException ex) {
-            throw new InternalError(ex.toString());
-        }
-        lookup = lookup().in(C_Unsafe);
-        try {
-            lookup.in(C_Unsafe).findStatic(C_Unsafe, "getUnsafe", methodType(C_Unsafe));
-        } catch (ReflectiveOperationException ex) {
-            throw new InternalError(ex.toString());
-        }
-    }
-
-    public static void main(String[] args) throws Throwable {
-        System.setSecurityManager(new SecurityManager());
-        Lookup lookup = lookup();
-        testBasic(lookup);
-        testDoPriv(lookup);
-        testSetVar();
-        Lookup l2 = lookup.in(Object.class);
-        System.out.println("=== "+l2);
-        testBasic(l2);
-        testDoPriv(l2);
-        Lookup l3 = lookup.in(C_Unsafe);
-        System.out.println("=== "+l3);
-        testBasic(l3);
-        testDoPriv(l3);
-        if (failure != null)
-            throw failure;
-    }
-
-    private static Throwable failure;
-    private static void fail(Throwable ex) {
-        if (failure == null)
-            failure = ex;
-        StackTraceElement frame = new Exception().getStackTrace()[1];
-        System.out.printf("Failed at %s:%d: %s\n", frame.getFileName(), frame.getLineNumber(), ex);
-    }
-    private static void ok(Throwable ex) {
-        StackTraceElement frame = new Exception().getStackTrace()[1];
-        System.out.printf("OK at %s:%d: %s\n", frame.getFileName(), frame.getLineNumber(), ex);
-    }
-
-    private static void testBasic(Lookup lookup) throws Throwable {
-        // Verify that we can't get to this guy under the SM:
-        try {
-            MethodHandle badmh = lookup.findStatic(C_Unsafe, "getUnsafe", methodType(C_Unsafe));
-            assert(badmh.type() == methodType(C_Unsafe));
-            badmh = badmh.asType(badmh.type().generic());
-            Object u = C_Unsafe.cast(badmh.invokeExact());
-            assert(C_Unsafe.isInstance(u));
-            fail(new AssertionError("got mh to getUnsafe!"));
-        } catch (SecurityException ex) {
-            ok(ex);
-        }
-        try {
-            Object u = MH_getUnsafe.invokeWithArguments();
-            assert(C_Unsafe.isInstance(u));
-            fail(new AssertionError("got the Unsafe object! (MH invoke)"));
-        } catch (SecurityException ex) {
-            ok(ex);
-        }
-        try {
-            MethodHandle mh = MH_getUnsafe;
-            mh = mh.asType(mh.type().generic());
-            mh = foldArguments(identity(Object.class), mh);
-            mh = filterReturnValue(mh, identity(Object.class));
-            Object u = mh.invokeExact();
-            assert(C_Unsafe.isInstance(u));
-            fail(new AssertionError("got the Unsafe object! (MH invokeWithArguments)"));
-        } catch (SecurityException ex) {
-            ok(ex);
-        }
-    }
-
-    private static void testDoPriv(Lookup lookup) throws Throwable {
-        PrivilegedAction privAct = MethodHandleProxies.asInterfaceInstance(PrivilegedAction.class, MH_getUnsafe);
-        try {
-            Object u = AccessController.doPrivileged(privAct);
-            assert(C_Unsafe.isInstance(u));
-            fail(new AssertionError("got the Unsafe object! (static doPriv)"));
-        } catch (SecurityException ex) {
-            ok(ex);
-        }
-        MethodHandle MH_doPriv = lookup.findStatic(AccessController.class, "doPrivileged",
-                                                   methodType(Object.class, PrivilegedAction.class));
-        MH_doPriv = MH_doPriv.bindTo(privAct);
-        try {
-            Object u = MH_doPriv.invoke();
-            assert(C_Unsafe.isInstance(u));
-            fail(new AssertionError("got the Unsafe object! (MH + doPriv)"));
-        } catch (SecurityException ex) {
-            ok(ex);
-        }
-        // try one more layer of indirection:
-        Runnable rbl = MethodHandleProxies.asInterfaceInstance(Runnable.class, MH_doPriv);
-        try {
-            rbl.run();
-            fail(new AssertionError("got the Unsafe object! (Runnable + MH + doPriv)"));
-        } catch (SecurityException ex) {
-            ok(ex);
-        }
-    }
-
-    private static void testSetVar() throws Throwable {
-        {
-            // Test the box pattern:
-            Object[] box = new Object[1];
-            MethodHandle MH_getFoo = identity(Object.class).bindTo("foo");
-            MethodHandle MH_storeToBox = insertArguments(arrayElementSetter(Object[].class), 0, box, 0);
-            MethodHandle mh = filterReturnValue(MH_getFoo, MH_storeToBox);
-            mh.invokeExact();
-            assert(box[0] == "foo");
-        }
-        {
-            Object[] box = new Object[1];
-            MethodHandle MH_storeToBox = insertArguments(arrayElementSetter(Object[].class), 0, box, 0);
-            MethodHandle mh = filterReturnValue(MH_getUnsafe.asType(MH_getUnsafe.type().generic()), MH_storeToBox);
-            try {
-                mh.invokeExact();
-                Object u = box[0];
-                assert(C_Unsafe.isInstance(u));
-                fail(new AssertionError("got the Unsafe object! (MH + setElement)"));
-            } catch (SecurityException ex) {
-                ok(ex);
-            }
-        }
-    }
-}
--- a/jdk/test/java/lang/management/MXBean/MXBeanBehavior.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/lang/management/MXBean/MXBeanBehavior.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/lang/management/ManagementFactory/MBeanServerMXBeanUnsupportedTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/lang/management/ManagementFactory/MBeanServerMXBeanUnsupportedTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/math/BigInteger/BigIntegerTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/math/BigInteger/BigIntegerTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,15 +23,19 @@
 
 /*
  * @test
- * @bug 4181191 4161971 4227146 4194389 4823171 4624738 4812225
+ * @bug 4181191 4161971 4227146 4194389 4823171 4624738 4812225 4837946
  * @summary tests methods in BigInteger
  * @run main/timeout=400 BigIntegerTest
  * @author madbot
  */
 
-import java.util.Random;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
 import java.math.BigInteger;
-import java.io.*;
+import java.util.Random;
 
 /**
  * This is a simple test class created to ensure that the results
@@ -48,21 +52,42 @@
  *
  */
 public class BigIntegerTest {
+    //
+    // Bit large number thresholds based on the int thresholds
+    // defined in BigInteger itself:
+    //
+    // KARATSUBA_THRESHOLD        = 50  ints = 1600 bits
+    // TOOM_COOK_THRESHOLD        = 75  ints = 2400 bits
+    // KARATSUBA_SQUARE_THRESHOLD = 90  ints = 2880 bits
+    // TOOM_COOK_SQUARE_THRESHOLD = 140 ints = 4480 bits
+    //
+    static final int BITS_KARATSUBA = 1600;
+    static final int BITS_TOOM_COOK = 2400;
+    static final int BITS_KARATSUBA_SQUARE = 2880;
+    static final int BITS_TOOM_COOK_SQUARE = 4480;
+
+    static final int ORDER_SMALL = 60;
+    static final int ORDER_MEDIUM = 100;
+    // #bits for testing Karatsuba and Burnikel-Ziegler
+    static final int ORDER_KARATSUBA = 1800;
+    // #bits for testing Toom-Cook
+    static final int ORDER_TOOM_COOK = 3000;
+    // #bits for testing Karatsuba squaring
+    static final int ORDER_KARATSUBA_SQUARE = 3200;
+    // #bits for testing Toom-Cook squaring
+    static final int ORDER_TOOM_COOK_SQUARE = 4600;
+
     static Random rnd = new Random();
     static int size = 1000; // numbers per batch
     static boolean failure = false;
 
-    // Some variables for sizing test numbers in bits
-    private static int order1 = 100;
-    private static int order2 = 60;
-    private static int order3 = 30;
-
-    public static void pow() {
+    public static void pow(int order) {
         int failCount1 = 0;
 
         for (int i=0; i<size; i++) {
-            int power = rnd.nextInt(6) +2;
-            BigInteger x = fetchNumber(order1);
+            // Test identity x^power == x*x*x ... *x
+            int power = rnd.nextInt(6) + 2;
+            BigInteger x = fetchNumber(order);
             BigInteger y = x.pow(power);
             BigInteger z = x;
 
@@ -72,22 +97,39 @@
             if (!y.equals(z))
                 failCount1++;
         }
-        report("pow", failCount1);
+        report("pow for " + order + " bits", failCount1);
     }
 
-    public static void arithmetic() {
+    public static void square(int order) {
+        int failCount1 = 0;
+
+        for (int i=0; i<size; i++) {
+            // Test identity x^2 == x*x
+            BigInteger x  = fetchNumber(order);
+            BigInteger xx = x.multiply(x);
+            BigInteger x2 = x.pow(2);
+
+            if (!x2.equals(xx))
+                failCount1++;
+        }
+        report("square for " + order + " bits", failCount1);
+    }
+
+    public static void arithmetic(int order) {
         int failCount = 0;
 
         for (int i=0; i<size; i++) {
-            BigInteger x = fetchNumber(order1);
+            BigInteger x = fetchNumber(order);
             while(x.compareTo(BigInteger.ZERO) != 1)
-                x = fetchNumber(order1);
-            BigInteger y = fetchNumber(order1/2);
+                x = fetchNumber(order);
+            BigInteger y = fetchNumber(order/2);
             while(x.compareTo(y) == -1)
-                y = fetchNumber(order1/2);
+                y = fetchNumber(order/2);
             if (y.equals(BigInteger.ZERO))
                 y = y.add(BigInteger.ONE);
 
+            // Test identity ((x/y))*y + x%y - x == 0
+            // using separate divide() and remainder()
             BigInteger baz = x.divide(y);
             baz = baz.multiply(y);
             baz = baz.add(x.remainder(y));
@@ -95,19 +137,21 @@
             if (!baz.equals(BigInteger.ZERO))
                 failCount++;
         }
-        report("Arithmetic I", failCount);
+        report("Arithmetic I for " + order + " bits", failCount);
 
         failCount = 0;
         for (int i=0; i<100; i++) {
-            BigInteger x = fetchNumber(order1);
+            BigInteger x = fetchNumber(order);
             while(x.compareTo(BigInteger.ZERO) != 1)
-                x = fetchNumber(order1);
-            BigInteger y = fetchNumber(order1/2);
+                x = fetchNumber(order);
+            BigInteger y = fetchNumber(order/2);
             while(x.compareTo(y) == -1)
-                y = fetchNumber(order1/2);
+                y = fetchNumber(order/2);
             if (y.equals(BigInteger.ZERO))
                 y = y.add(BigInteger.ONE);
 
+            // Test identity ((x/y))*y + x%y - x == 0
+            // using divideAndRemainder()
             BigInteger baz[] = x.divideAndRemainder(y);
             baz[0] = baz[0].multiply(y);
             baz[0] = baz[0].add(baz[1]);
@@ -115,7 +159,118 @@
             if (!baz[0].equals(BigInteger.ZERO))
                 failCount++;
         }
-        report("Arithmetic II", failCount);
+        report("Arithmetic II for " + order + " bits", failCount);
+    }
+
+    /**
+     * Sanity test for Karatsuba and 3-way Toom-Cook multiplication.
+     * For each of the Karatsuba and 3-way Toom-Cook multiplication thresholds,
+     * construct two factors each with a mag array one element shorter than the
+     * threshold, and with the most significant bit set and the rest of the bits
+     * random. Each of these numbers will therefore be below the threshold but
+     * if shifted left be above the threshold. Call the numbers 'u' and 'v' and
+     * define random shifts 'a' and 'b' in the range [1,32]. Then we have the
+     * identity
+     * <pre>
+     * (u << a)*(v << b) = (u*v) << (a + b)
+     * </pre>
+     * For Karatsuba multiplication, the right hand expression will be evaluated
+     * using the standard naive algorithm, and the left hand expression using
+     * the Karatsuba algorithm. For 3-way Toom-Cook multiplication, the right
+     * hand expression will be evaluated using Karatsuba multiplication, and the
+     * left hand expression using 3-way Toom-Cook multiplication.
+     */
+    public static void multiplyLarge() {
+        int failCount = 0;
+
+        BigInteger base = BigInteger.ONE.shiftLeft(BITS_KARATSUBA - 32 - 1);
+        for (int i=0; i<size; i++) {
+            BigInteger x = fetchNumber(BITS_KARATSUBA - 32 - 1);
+            BigInteger u = base.add(x);
+            int a = 1 + rnd.nextInt(31);
+            BigInteger w = u.shiftLeft(a);
+
+            BigInteger y = fetchNumber(BITS_KARATSUBA - 32 - 1);
+            BigInteger v = base.add(y);
+            int b = 1 + rnd.nextInt(32);
+            BigInteger z = v.shiftLeft(b);
+
+            BigInteger multiplyResult = u.multiply(v).shiftLeft(a + b);
+            BigInteger karatsubaMultiplyResult = w.multiply(z);
+
+            if (!multiplyResult.equals(karatsubaMultiplyResult)) {
+                failCount++;
+            }
+        }
+
+        report("multiplyLarge Karatsuba", failCount);
+
+        failCount = 0;
+        base = base.shiftLeft(BITS_TOOM_COOK - BITS_KARATSUBA);
+        for (int i=0; i<size; i++) {
+            BigInteger x = fetchNumber(BITS_TOOM_COOK - 32 - 1);
+            BigInteger u = base.add(x);
+            BigInteger u2 = u.shiftLeft(1);
+            BigInteger y = fetchNumber(BITS_TOOM_COOK - 32 - 1);
+            BigInteger v = base.add(y);
+            BigInteger v2 = v.shiftLeft(1);
+
+            BigInteger multiplyResult = u.multiply(v).shiftLeft(2);
+            BigInteger toomCookMultiplyResult = u2.multiply(v2);
+
+            if (!multiplyResult.equals(toomCookMultiplyResult)) {
+                failCount++;
+            }
+        }
+
+        report("multiplyLarge Toom-Cook", failCount);
+    }
+
+    /**
+     * Sanity test for Karatsuba and 3-way Toom-Cook squaring.
+     * This test is analogous to {@link AbstractMethodError#multiplyLarge}
+     * with both factors being equal. The squaring methods will not be tested
+     * unless the <code>bigInteger.multiply(bigInteger)</code> tests whether
+     * the parameter is the same instance on which the method is being invoked
+     * and calls <code>square()</code> accordingly.
+     */
+    public static void squareLarge() {
+        int failCount = 0;
+
+        BigInteger base = BigInteger.ONE.shiftLeft(BITS_KARATSUBA_SQUARE - 32 - 1);
+        for (int i=0; i<size; i++) {
+            BigInteger x = fetchNumber(BITS_KARATSUBA_SQUARE - 32 - 1);
+            BigInteger u = base.add(x);
+            int a = 1 + rnd.nextInt(31);
+            BigInteger w = u.shiftLeft(a);
+
+            BigInteger squareResult = u.multiply(u).shiftLeft(2*a);
+            BigInteger karatsubaSquareResult = w.multiply(w);
+
+            if (!squareResult.equals(karatsubaSquareResult)) {
+                failCount++;
+            }
+        }
+
+        report("squareLarge Karatsuba", failCount);
+
+        failCount = 0;
+        base = base.shiftLeft(BITS_TOOM_COOK_SQUARE - BITS_KARATSUBA_SQUARE);
+        for (int i=0; i<size; i++) {
+            BigInteger x = fetchNumber(BITS_TOOM_COOK_SQUARE - 32 - 1);
+            BigInteger u = base.add(x);
+            int a = 1 + rnd.nextInt(31);
+            BigInteger w = u.shiftLeft(a);
+
+            BigInteger squareResult = u.multiply(u).shiftLeft(2*a);
+            BigInteger toomCookSquareResult = w.multiply(w);
+
+            if (!squareResult.equals(toomCookSquareResult)) {
+                failCount++;
+            }
+        }
+
+        report("squareLarge Toom-Cook", failCount);
     }
 
     public static void bitCount() {
@@ -160,14 +315,14 @@
         report("BitLength", failCount);
     }
 
-    public static void bitOps() {
+    public static void bitOps(int order) {
         int failCount1 = 0, failCount2 = 0, failCount3 = 0;
 
         for (int i=0; i<size*5; i++) {
-            BigInteger x = fetchNumber(order1);
+            BigInteger x = fetchNumber(order);
             BigInteger y;
 
-            /* Test setBit and clearBit (and testBit) */
+            // Test setBit and clearBit (and testBit)
             if (x.signum() < 0) {
                 y = BigInteger.valueOf(-1);
                 for (int j=0; j<x.bitLength(); j++)
@@ -182,7 +337,7 @@
             if (!x.equals(y))
                 failCount1++;
 
-            /* Test flipBit (and testBit) */
+            // Test flipBit (and testBit)
             y = BigInteger.valueOf(x.signum()<0 ? -1 : 0);
             for (int j=0; j<x.bitLength(); j++)
                 if (x.signum()<0  ^  x.testBit(j))
@@ -190,13 +345,13 @@
             if (!x.equals(y))
                 failCount2++;
         }
-        report("clearBit/testBit", failCount1);
-        report("flipBit/testBit", failCount2);
+        report("clearBit/testBit for " + order + " bits", failCount1);
+        report("flipBit/testBit for " + order + " bits", failCount2);
 
         for (int i=0; i<size*5; i++) {
-            BigInteger x = fetchNumber(order1);
+            BigInteger x = fetchNumber(order);
 
-            /* Test getLowestSetBit() */
+            // Test getLowestSetBit()
             int k = x.getLowestSetBit();
             if (x.signum() == 0) {
                 if (k != -1)
@@ -210,43 +365,43 @@
                     failCount3++;
             }
         }
-        report("getLowestSetBit", failCount3);
+        report("getLowestSetBit for " + order + " bits", failCount3);
     }
 
-    public static void bitwise() {
+    public static void bitwise(int order) {
 
-        /* Test identity x^y == x|y &~ x&y */
+        // Test identity x^y == x|y &~ x&y
         int failCount = 0;
         for (int i=0; i<size; i++) {
-            BigInteger x = fetchNumber(order1);
-            BigInteger y = fetchNumber(order1);
+            BigInteger x = fetchNumber(order);
+            BigInteger y = fetchNumber(order);
             BigInteger z = x.xor(y);
             BigInteger w = x.or(y).andNot(x.and(y));
             if (!z.equals(w))
                 failCount++;
         }
-        report("Logic (^ | & ~)", failCount);
+        report("Logic (^ | & ~) for " + order + " bits", failCount);
 
-        /* Test identity x &~ y == ~(~x | y) */
+        // Test identity x &~ y == ~(~x | y)
         failCount = 0;
         for (int i=0; i<size; i++) {
-            BigInteger x = fetchNumber(order1);
-            BigInteger y = fetchNumber(order1);
+            BigInteger x = fetchNumber(order);
+            BigInteger y = fetchNumber(order);
             BigInteger z = x.andNot(y);
             BigInteger w = x.not().or(y).not();
             if (!z.equals(w))
                 failCount++;
         }
-        report("Logic (&~ | ~)", failCount);
+        report("Logic (&~ | ~) for " + order + " bits", failCount);
     }
 
-    public static void shift() {
+    public static void shift(int order) {
         int failCount1 = 0;
         int failCount2 = 0;
         int failCount3 = 0;
 
         for (int i=0; i<100; i++) {
-            BigInteger x = fetchNumber(order1);
+            BigInteger x = fetchNumber(order);
             int n = Math.abs(rnd.nextInt()%200);
 
             if (!x.shiftLeft(n).equals
@@ -274,18 +429,18 @@
             if (!x.shiftLeft(n).shiftRight(n).equals(x))
                 failCount3++;
         }
-        report("baz shiftLeft", failCount1);
-        report("baz shiftRight", failCount2);
-        report("baz shiftLeft/Right", failCount3);
+        report("baz shiftLeft for " + order + " bits", failCount1);
+        report("baz shiftRight for " + order + " bits", failCount2);
+        report("baz shiftLeft/Right for " + order + " bits", failCount3);
     }
 
-    public static void divideAndRemainder() {
+    public static void divideAndRemainder(int order) {
         int failCount1 = 0;
 
         for (int i=0; i<size; i++) {
-            BigInteger x = fetchNumber(order1).abs();
+            BigInteger x = fetchNumber(order).abs();
             while(x.compareTo(BigInteger.valueOf(3L)) != 1)
-                x = fetchNumber(order1).abs();
+                x = fetchNumber(order).abs();
             BigInteger z = x.divide(BigInteger.valueOf(2L));
             BigInteger y[] = x.divideAndRemainder(x);
             if (!y[0].equals(BigInteger.ONE)) {
@@ -306,7 +461,7 @@
                 System.err.println("      y :"+y);
             }
         }
-        report("divideAndRemainder I", failCount1);
+        report("divideAndRemainder for " + order + " bits", failCount1);
     }
 
     public static void stringConv() {
@@ -331,13 +486,13 @@
         report("String Conversion", failCount);
     }
 
-    public static void byteArrayConv() {
+    public static void byteArrayConv(int order) {
         int failCount = 0;
 
         for (int i=0; i<size; i++) {
-            BigInteger x = fetchNumber(order1);
+            BigInteger x = fetchNumber(order);
             while (x.equals(BigInteger.ZERO))
-                x = fetchNumber(order1);
+                x = fetchNumber(order);
             BigInteger y = new BigInteger(x.toByteArray());
             if (!x.equals(y)) {
                 failCount++;
@@ -345,19 +500,19 @@
                 System.err.println("new is "+y);
             }
         }
-        report("Array Conversion", failCount);
+        report("Array Conversion for " + order + " bits", failCount);
     }
 
-    public static void modInv() {
+    public static void modInv(int order) {
         int failCount = 0, successCount = 0, nonInvCount = 0;
 
         for (int i=0; i<size; i++) {
-            BigInteger x = fetchNumber(order1);
+            BigInteger x = fetchNumber(order);
             while(x.equals(BigInteger.ZERO))
-                x = fetchNumber(order1);
-            BigInteger m = fetchNumber(order1).abs();
+                x = fetchNumber(order);
+            BigInteger m = fetchNumber(order).abs();
             while(m.compareTo(BigInteger.ONE) != 1)
-                m = fetchNumber(order1).abs();
+                m = fetchNumber(order).abs();
 
             try {
                 BigInteger inv = x.modInverse(m);
@@ -374,10 +529,10 @@
                 nonInvCount++;
             }
         }
-        report("Modular Inverse", failCount);
+        report("Modular Inverse for " + order + " bits", failCount);
     }
 
-    public static void modExp() {
+    public static void modExp(int order1, int order2) {
         int failCount = 0;
 
         for (int i=0; i<size/10; i++) {
@@ -398,13 +553,14 @@
                 failCount++;
             }
         }
-        report("Exponentiation I", failCount);
+        report("Exponentiation I for " + order1 + " and " +
+               order2 + " bits", failCount);
     }
 
     // This test is based on Fermat's theorem
     // which is not ideal because base must not be multiple of modulus
     // and modulus must be a prime or pseudoprime (Carmichael number)
-    public static void modExp2() {
+    public static void modExp2(int order) {
         int failCount = 0;
 
         for (int i=0; i<10; i++) {
@@ -412,11 +568,11 @@
             while(m.compareTo(BigInteger.ONE) != 1)
                 m = new BigInteger(100, 5, rnd);
             BigInteger exp = m.subtract(BigInteger.ONE);
-            BigInteger base = fetchNumber(order1).abs();
+            BigInteger base = fetchNumber(order).abs();
             while(base.compareTo(m) != -1)
-                base = fetchNumber(order1).abs();
+                base = fetchNumber(order).abs();
             while(base.equals(BigInteger.ZERO))
-                base = fetchNumber(order1).abs();
+                base = fetchNumber(order).abs();
 
             BigInteger one = base.modPow(exp, m);
             if (!one.equals(BigInteger.ONE)) {
@@ -426,7 +582,7 @@
                 failCount++;
             }
         }
-        report("Exponentiation II", failCount);
+        report("Exponentiation II for " + order + " bits", failCount);
     }
 
     private static final int[] mersenne_powers = {
@@ -704,36 +860,62 @@
      */
     public static void main(String[] args) throws Exception {
 
+        // Some variables for sizing test numbers in bits
+        int order1 = ORDER_MEDIUM;
+        int order2 = ORDER_SMALL;
+        int order3 = ORDER_KARATSUBA;
+        int order4 = ORDER_TOOM_COOK;
+
         if (args.length >0)
             order1 = (int)((Integer.parseInt(args[0]))* 3.333);
         if (args.length >1)
             order2 = (int)((Integer.parseInt(args[1]))* 3.333);
         if (args.length >2)
             order3 = (int)((Integer.parseInt(args[2]))* 3.333);
+        if (args.length >3)
+            order4 = (int)((Integer.parseInt(args[3]))* 3.333);
 
         prime();
         nextProbablePrime();
 
-        arithmetic();
-        divideAndRemainder();
-        pow();
+        arithmetic(order1);   // small numbers
+        arithmetic(order3);   // Karatsuba / Burnikel-Ziegler range
+        arithmetic(order4);   // Toom-Cook range
+
+        divideAndRemainder(order1);   // small numbers
+        divideAndRemainder(order3);   // Karatsuba / Burnikel-Ziegler range
+        divideAndRemainder(order4);   // Toom-Cook range
+
+        pow(order1);
+        pow(order3);
+        pow(order4);
+
+        square(ORDER_MEDIUM);
+        square(ORDER_KARATSUBA_SQUARE);
+        square(ORDER_TOOM_COOK_SQUARE);
 
         bitCount();
         bitLength();
-        bitOps();
-        bitwise();
+        bitOps(order1);
+        bitwise(order1);
 
-        shift();
+        shift(order1);
+
+        byteArrayConv(order1);
 
-        byteArrayConv();
+        modInv(order1);   // small numbers
+        modInv(order3);   // Karatsuba / Burnikel-Ziegler range
+        modInv(order4);   // Toom-Cook range
 
-        modInv();
-        modExp();
-        modExp2();
+        modExp(order1, order2);
+        modExp2(order1);
 
         stringConv();
         serialize();
 
+        multiplyLarge();
+        squareLarge();
+
         if (failure)
             throw new RuntimeException("Failure in BigIntegerTest.");
     }
@@ -747,7 +929,7 @@
      */
     private static BigInteger fetchNumber(int order) {
         boolean negative = rnd.nextBoolean();
-        int numType = rnd.nextInt(6);
+        int numType = rnd.nextInt(7);
         BigInteger result = null;
         if (order < 2) order = 2;
 
@@ -783,6 +965,19 @@
                     result = result.or(temp);
                 }
                 break;
+            case 5: // Runs of consecutive ones and zeros
+                result = ZERO;
+                int remaining = order;
+                int bit = rnd.nextInt(2);
+                while (remaining > 0) {
+                    int runLength = Math.min(remaining, rnd.nextInt(order));
+                    result = result.shiftLeft(runLength);
+                    if (bit > 0)
+                        result = result.add(ONE.shiftLeft(runLength).subtract(ONE));
+                    remaining -= runLength;
+                    bit = 1 - bit;
+                }
+                break;
 
             default: // random bits
                 result = new BigInteger(order, rnd);
--- a/jdk/test/java/net/CookieHandler/CookieManagerTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/net/CookieHandler/CookieManagerTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -24,20 +24,14 @@
 /*
  * @test
  * @summary Unit test for java.net.CookieManager
- * @bug 6244040 7150552
+ * @bug 6244040 7150552 7051862
  * @run main/othervm -ea CookieManagerTest
  * @author Edward Wang
  */
 
 import com.sun.net.httpserver.*;
 import java.io.IOException;
-import java.net.CookieHandler;
-import java.net.CookieManager;
-import java.net.CookiePolicy;
-import java.net.HttpURLConnection;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.URL;
+import java.net.*;
 
 public class CookieManagerTest {
 
@@ -51,15 +45,37 @@
         if (httpTrans.badRequest) {
             throw new RuntimeException("Test failed : bad cookie header");
         }
+        checkCookiePolicy();
     }
 
-    public static void startHttpServer() throws IOException {
+   public static void startHttpServer() throws IOException {
         httpTrans = new CookieTransactionHandler();
         server = HttpServer.create(new InetSocketAddress(0), 0);
         server.createContext("/", httpTrans);
         server.start();
     }
 
+    /*
+     * Checks if CookiePolicy.ACCEPT_ORIGINAL_SERVER#shouldAccept()
+     * returns false for null arguments
+     */
+    private static void checkCookiePolicy() throws Exception {
+        CookiePolicy cp = CookiePolicy.ACCEPT_ORIGINAL_SERVER;
+        boolean retVal;
+        retVal = cp.shouldAccept(null, null);
+        checkValue(retVal);
+        retVal = cp.shouldAccept(null, new HttpCookie("CookieName", "CookieVal"));
+        checkValue(retVal);
+        retVal = cp.shouldAccept((new URL("http", "localhost", 2345, "/")).toURI(),
+                                  null);
+        checkValue(retVal);
+    }
+
+    private static void checkValue(boolean val) {
+        if (val)
+            throw new RuntimeException("Return value is not false!");
+    }
+
     public static void makeHttpCall() throws IOException {
         try {
             System.out.println("http server listenining on: "
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/net/CookieHandler/LocalHostCookie.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+import com.sun.net.httpserver.*;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.*;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Executors;
+
+/*
+ * @test
+ * @bug 7169142
+ * @summary CookieHandler does not work with localhost
+ * @run main/othervm LocalHostCookie
+ */
+public class LocalHostCookie {
+
+    public static void main(String[] args) throws Exception {
+        new LocalHostCookie().runTest();
+    }
+
+    public void runTest() throws Exception {
+        Server s = null;
+        try {
+            s = new Server();
+            s.startServer();
+            URL url = new URL("http","localhost", s.getPort(), "/");
+            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
+            urlConnection.setRequestMethod("GET");
+            urlConnection.setDoOutput(true);
+            urlConnection.connect();
+            urlConnection.getInputStream();
+
+            CookieHandler cookieHandler = CookieHandler.getDefault();
+            if (cookieHandler == null) {
+                cookieHandler = new java.net.CookieManager();
+                CookieHandler.setDefault(cookieHandler);
+            }
+            cookieHandler.put(urlConnection.getURL().toURI(),
+                    urlConnection.getHeaderFields());
+            Map<String, List<String>> map =
+                    cookieHandler.get(urlConnection.getURL().toURI(),
+                    urlConnection.getHeaderFields());
+            if (map.containsKey("Cookie")) {
+                List<String> list = map.get("Cookie");
+                // name-value list will be empty if ".local" is not appended
+                if (list == null || list.size() ==  0) {
+                    throw new RuntimeException("Test failed!");
+                }
+            }
+        } finally {
+            s.stopServer();
+        }
+    }
+
+    class Server {
+        HttpServer server;
+
+        public void startServer() {
+            InetSocketAddress addr = new InetSocketAddress(0);
+            try {
+                server = HttpServer.create(addr, 0);
+            } catch (IOException ioe) {
+                throw new RuntimeException("Server could not be created");
+            }
+
+            server.createContext("/", new MyCookieHandler());
+            server.start();
+        }
+
+        public int getPort() {
+            return server.getAddress().getPort();
+        }
+
+        public void stopServer() {
+            server.stop(0);
+        }
+    }
+
+    class MyCookieHandler implements HttpHandler {
+
+        @Override
+        public void handle(HttpExchange exchange) throws IOException {
+            String requestMethod = exchange.getRequestMethod();
+            if (requestMethod.equalsIgnoreCase("GET")){
+                Headers responseHeaders = exchange.getResponseHeaders();
+                responseHeaders.set("Content-Type", "text/plain");
+                responseHeaders.set("Date", "June 13th 2012");
+                // No domain value set
+                responseHeaders.set("Set-Cookie2", "name=value");
+                exchange.sendResponseHeaders(200, 0);
+                OutputStream os = exchange.getResponseBody();
+                String str = "This is what the server sent!";
+                os.write(str.getBytes());
+                os.flush();
+                os.close();
+            }
+        }
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/security/Signature/SignatureGetAlgorithm.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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.
+ */
+
+/*
+ * Portions Copyright (c) 2013 IBM Corporation
+ */
+
+/*
+ * @test
+ * @bug 8014620
+ * @summary Signature.getAlgorithm return null in special case
+ * @run main/othervm SignatureGetAlgorithm
+ * @author youdwei
+ */
+import java.security.*;
+
+public class SignatureGetAlgorithm {
+
+    public static void main(String[] args) throws Exception {
+        Provider testProvider = new TestProvider();
+        Security.addProvider(testProvider);
+        Signature sig = Signature.getInstance("MySignatureAlg");
+        String algorithm = sig.getAlgorithm();
+        System.out.println("Algorithm Name: " + algorithm);
+        if (algorithm == null) {
+            throw new Exception("algorithm name should be 'MySignatureAlg'");
+        }
+    }
+
+    public static class TestProvider extends Provider {
+        TestProvider() {
+            super("test", 1.0, "test");
+            put("Signature.MySignatureAlg",
+                "SignatureGetAlgorithm$MySignatureAlg");
+        }
+    }
+
+    public static class MySignatureAlg extends Signature {
+
+        public MySignatureAlg() {
+            super(null);
+        }
+
+        MySignatureAlg(String s) {
+            super(s);
+        }
+
+        @Override
+        protected void engineInitVerify(PublicKey publicKey)
+                throws InvalidKeyException {
+        }
+
+        @Override
+        protected void engineInitSign(PrivateKey privateKey)
+                throws InvalidKeyException {
+        }
+
+        @Override
+        protected void engineUpdate(byte b) throws SignatureException {
+        }
+
+        @Override
+        protected void engineUpdate(byte[] b, int off, int len)
+                throws SignatureException {
+        }
+
+        @Override
+        protected byte[] engineSign()
+                throws SignatureException {
+            return new byte[0];
+        }
+
+        @Override
+        protected boolean engineVerify(byte[] sigBytes)
+                throws SignatureException {
+            return false;
+        }
+
+        @Override
+        @Deprecated
+        protected void engineSetParameter(String param, Object value)
+                throws InvalidParameterException {
+        }
+
+        @Override
+        @Deprecated
+        protected Object engineGetParameter(String param)
+                throws InvalidParameterException {
+            return null;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/text/Format/DateFormat/Bug7177315.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 7177315
+ * @summary Make sure that space characters are properly skipped when
+ *          parsing 2-digit year values.
+ */
+
+import java.text.*;
+import java.util.*;
+
+public class Bug7177315 {
+    private static final String EXPECTED = "01/01/2012";
+    private static final String[] DATA = {
+        "01/01/12",
+        "01/01/ 12",
+        "01/01/       12",
+        "1/1/12",
+        "1/1/  12"
+    };
+
+    public static void main (String[] args) throws ParseException {
+        SimpleDateFormat parseFormat = new SimpleDateFormat("MM/dd/yy", Locale.US);
+        Calendar cal = new GregorianCalendar(2012-80, Calendar.JANUARY, 1);
+        parseFormat.set2DigitYearStart(cal.getTime());
+        SimpleDateFormat fmtFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
+
+        for (String text : DATA) {
+            Date date = parseFormat.parse(text);
+            String got = fmtFormat.format(date);
+            if (!EXPECTED.equals(got)) {
+                throw new RuntimeException("got: " + got + ", expected: " + EXPECTED);
+            }
+        }
+    }
+}
--- a/jdk/test/java/text/Format/DateFormat/WeekDateTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/text/Format/DateFormat/WeekDateTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,8 +32,8 @@
 import static java.util.GregorianCalendar.*;
 
 public class WeekDateTest {
-    static SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyy-MM-dd");
-    static SimpleDateFormat ywdFormat = new SimpleDateFormat("YYYY-'W'ww-u");
+    static SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
+    static SimpleDateFormat ywdFormat = new SimpleDateFormat("YYYY-'W'ww-u", Locale.US);
     static {
         ymdFormat.setCalendar(newCalendar());
         ywdFormat.setCalendar(newCalendar());
--- a/jdk/test/java/util/BitSet/BitSetStreamTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/BitSet/BitSetStreamTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -65,10 +65,10 @@
         { "index 0", IntStream.of(0) },
         { "index 255", IntStream.of(255) },
         { "every bit", IntStream.range(0, 255) },
-        { "step 2", IntStream.range(0, 255, 2) },
-        { "step 3", IntStream.range(0, 255, 3) },
-        { "step 5", IntStream.range(0, 255, 5) },
-        { "step 7", IntStream.range(0, 255, 7) },
+        { "step 2", IntStream.range(0, 255).map(f -> f * 2) },
+        { "step 3", IntStream.range(0, 255).map(f -> f * 3) },
+        { "step 5", IntStream.range(0, 255).map(f -> f * 5) },
+        { "step 7", IntStream.range(0, 255).map(f -> f * 7) },
         { "1, 10, 100, 1000", IntStream.of(1, 10, 100, 1000) },
         { "25 fibs", IntStream.generate(new Fibs()).limit(25) }
     };
--- a/jdk/test/java/util/Locale/LocaleProviders.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/Locale/LocaleProviders.java	Wed Jul 05 19:00:49 2017 +0200
@@ -207,6 +207,7 @@
             String jreResult = "\u5e73\u6210 16.11.03 (\u6c34) \u5348\u524d 11:53:47";
             Locale l = new Locale("ja", "JP", "JP");
             SimpleDateFormat sdf = new SimpleDateFormat("GGGG yyyy.MMM.dd '('E')' a hh:mm:ss", l);
+            sdf.setTimeZone(TimeZone.getTimeZone("PST"));
             String result = sdf.format(sampleDate);
             System.out.println(result);
             if (LocaleProviderAdapter.getAdapterPreference()
--- a/jdk/test/java/util/Map/Defaults.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/Map/Defaults.java	Wed Jul 05 19:00:49 2017 +0200
@@ -36,6 +36,7 @@
 import java.util.Collections;
 import java.util.EnumMap;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Hashtable;
 import java.util.IdentityHashMap;
 import java.util.Iterator;
@@ -47,6 +48,7 @@
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentSkipListMap;
+import java.util.function.BiFunction;
 import java.util.function.Supplier;
 
 import org.testng.annotations.Test;
@@ -60,14 +62,14 @@
 
 public class Defaults {
 
-    @Test(dataProvider = "Nulls Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=all keys=withNull values=withNull")
     public void testGetOrDefaultNulls(String description, Map<IntegerEnum, String> map) {
-        assertTrue(map.containsKey(null), "null key absent");
-        assertNull(map.get(null), "value not null");
-        assertSame(map.get(null), map.getOrDefault(null, EXTRA_VALUE), "values should match");
+        assertTrue(map.containsKey(null), description + ": null key absent");
+        assertNull(map.get(null), description + ": value not null");
+        assertSame(map.get(null), map.getOrDefault(null, EXTRA_VALUE), description + ": values should match");
     }
 
-    @Test(dataProvider = "Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=all keys=all values=all")
     public void testGetOrDefault(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(KEYS[1]), "expected key missing");
         assertSame(map.get(KEYS[1]), map.getOrDefault(KEYS[1], EXTRA_VALUE), "values should match");
@@ -76,7 +78,7 @@
         assertNull(map.getOrDefault(EXTRA_KEY, null), "null not returned as default");
     }
 
-    @Test(dataProvider = "R/W Nulls Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
     public void testPutIfAbsentNulls(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(null), "null key absent");
         assertNull(map.get(null), "value not null");
@@ -96,7 +98,7 @@
         assertSame(map.get(null), EXTRA_VALUE, "value not expected");
     }
 
-    @Test(dataProvider = "R/W Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
     public void testPutIfAbsent(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(KEYS[1]));
         Object expected = map.get(KEYS[1]);
@@ -109,7 +111,7 @@
         assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);
     }
 
-    @Test(dataProvider = "Nulls Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=all keys=all values=all")
     public void testForEach(String description, Map<IntegerEnum, String> map) {
         IntegerEnum[] EACH_KEY = new IntegerEnum[map.size()];
 
@@ -120,10 +122,43 @@
             assertSame(v, map.get(k));
         });
 
-        assertEquals(KEYS, EACH_KEY);
+        assertEquals(KEYS, EACH_KEY, description);
     }
 
-    @Test(dataProvider = "R/W Nulls Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
+    public static void testReplaceAll(String description, Map<IntegerEnum, String> map) {
+        IntegerEnum[] EACH_KEY = new IntegerEnum[map.size()];
+        Set<String> EACH_REPLACE = new HashSet<>(map.size());
+
+        map.replaceAll((k,v) -> {
+            int idx = (null == k) ? 0 : k.ordinal(); // substitute for index.
+            assertNull(EACH_KEY[idx]);
+            EACH_KEY[idx] = (idx == 0) ? KEYS[0] : k; // substitute for comparison.
+            assertSame(v, map.get(k));
+            String replacement = v + " replaced";
+            EACH_REPLACE.add(replacement);
+            return replacement;
+        });
+
+        assertEquals(KEYS, EACH_KEY, description);
+        assertEquals(map.values().size(), EACH_REPLACE.size(), description + EACH_REPLACE);
+        assertTrue(EACH_REPLACE.containsAll(map.values()), description + " : " + EACH_REPLACE + " != " + map.values());
+        assertTrue(map.values().containsAll(EACH_REPLACE), description + " : " + EACH_REPLACE + " != " + map.values());
+    }
+
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=nonNull values=nonNull")
+    public static void testReplaceAllNoNullReplacement(String description, Map<IntegerEnum, String> map) {
+        assertThrows(
+            () -> { map.replaceAll(null); },
+            NullPointerException.class,
+            description);
+        assertThrows(
+            () -> { map.replaceAll((k,v) -> null); },
+            NullPointerException.class,
+            description);
+    }
+
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
     public static void testRemoveNulls(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(null), "null key absent");
         assertNull(map.get(null), "value not null");
@@ -136,7 +171,7 @@
         assertFalse(map.remove(null, null));
     }
 
-    @Test(dataProvider = "R/W Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
     public static void testRemove(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(KEYS[1]));
         Object expected = map.get(KEYS[1]);
@@ -151,7 +186,7 @@
         assertFalse(map.remove(EXTRA_KEY, EXTRA_VALUE));
     }
 
-    @Test(dataProvider = "R/W Nulls Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
     public void testReplaceKVNulls(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(null), "null key absent");
         assertNull(map.get(null), "value not null");
@@ -159,7 +194,7 @@
         assertSame(map.get(null), EXTRA_VALUE);
     }
 
-    @Test(dataProvider = "R/W Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
     public void testReplaceKV(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(KEYS[1]));
         Object expected = map.get(KEYS[1]);
@@ -177,7 +212,7 @@
         assertSame(map.get(EXTRA_KEY), expected);
     }
 
-    @Test(dataProvider = "R/W Nulls Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
     public void testReplaceKVVNulls(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(null), "null key absent");
         assertNull(map.get(null), "value not null");
@@ -189,7 +224,7 @@
         assertSame(map.get(null), EXTRA_VALUE);
     }
 
-    @Test(dataProvider = "R/W Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
     public void testReplaceKVV(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(KEYS[1]));
         Object expected = map.get(KEYS[1]);
@@ -212,7 +247,7 @@
         assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);
     }
 
-    @Test(dataProvider = "R/W Nulls Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
     public void testComputeIfAbsentNulls(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(null), "null key absent");
         assertNull(map.get(null), "value not null");
@@ -220,7 +255,7 @@
         assertSame(map.get(null), EXTRA_VALUE, description);
     }
 
-    @Test(dataProvider = "R/W Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
     public void testComputeIfAbsent(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(KEYS[1]));
         Object expected = map.get(KEYS[1]);
@@ -234,7 +269,7 @@
         assertSame(map.get(EXTRA_KEY), EXTRA_VALUE);
     }
 
-    @Test(dataProvider = "R/W Nulls Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
     public void testComputeIfPresentNulls(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(null));
         assertNull(map.get(null));
@@ -246,7 +281,7 @@
         assertSame(map.get(null), null, description);
     }
 
-    @Test(dataProvider = "R/W Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
     public void testComputeIfPresent(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(KEYS[1]));
         Object value = map.get(KEYS[1]);
@@ -267,7 +302,7 @@
         assertSame(map.get(EXTRA_KEY), null);
     }
 
-    @Test(dataProvider = "R/W Nulls Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
     public void testComputeNulls(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(null), "null key absent");
         assertNull(map.get(null), "value not null");
@@ -287,7 +322,7 @@
         }), null, description);
     }
 
-    @Test(dataProvider = "R/W Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
     public void testCompute(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(KEYS[1]));
         Object value = map.get(KEYS[1]);
@@ -314,7 +349,7 @@
     }
 
 
-    @Test(dataProvider = "R/W Nulls Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull")
     public void testMergeNulls(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(null), "null key absent");
         assertNull(map.get(null), "value not null");
@@ -327,7 +362,7 @@
         assertSame(map.get(null), EXTRA_VALUE, description);
     }
 
-    @Test(dataProvider = "R/W Map<IntegerEnum,String>")
+    @Test(dataProvider = "Map<IntegerEnum,String> rw=true keys=all values=all")
     public void testMerge(String description, Map<IntegerEnum, String> map) {
         assertTrue(map.containsKey(KEYS[1]));
         Object value = map.get(KEYS[1]);
@@ -391,52 +426,58 @@
     private static final IntegerEnum EXTRA_KEY = IntegerEnum.EXTRA_KEY;
     private static final String EXTRA_VALUE = String.valueOf(TEST_SIZE);
 
-    @DataProvider(name = "Map<IntegerEnum,String>", parallel = true)
-    public static Iterator<Object[]> allNullsMapProvider() {
+    @DataProvider(name = "Map<IntegerEnum,String> rw=all keys=all values=all", parallel = true)
+    public static Iterator<Object[]> allMapProvider() {
         return makeAllMaps().iterator();
     }
 
-    @DataProvider(name = "Nulls Map<IntegerEnum,String>", parallel = true)
-    public static Iterator<Object[]> allMapProvider() {
-        return makeRWMaps(true).iterator();
+    @DataProvider(name = "Map<IntegerEnum,String> rw=all keys=withNull values=withNull", parallel = true)
+    public static Iterator<Object[]> allMapWithNullsProvider() {
+        return makeAllMapsWithNulls().iterator();
     }
 
-    @DataProvider(name = "R/W Map<IntegerEnum,String>", parallel = true)
-    public static Iterator<Object[]> rwMapProvider() {
+    @DataProvider(name = "Map<IntegerEnum,String> rw=true keys=nonNull values=nonNull", parallel = true)
+    public static Iterator<Object[]> rwNonNullMapProvider() {
+        return makeRWNoNullsMaps().iterator();
+    }
+
+    @DataProvider(name = "Map<IntegerEnum,String> rw=true keys=nonNull values=all", parallel = true)
+    public static Iterator<Object[]> rwNonNullKeysMapProvider() {
         return makeRWMapsNoNulls().iterator();
     }
 
-    @DataProvider(name = "R/W Nulls Map<IntegerEnum,String>", parallel = true)
-    public static Iterator<Object[]> rwNullsMapProvider() {
-        return makeRWMaps(true).iterator();
+    @DataProvider(name = "Map<IntegerEnum,String> rw=true keys=all values=all", parallel = true)
+    public static Iterator<Object[]> rwMapProvider() {
+        return makeAllRWMaps().iterator();
     }
 
-    private static Collection<Object[]> makeAllMapsNoNulls() {
+    @DataProvider(name = "Map<IntegerEnum,String> rw=true keys=withNull values=withNull", parallel = true)
+    public static Iterator<Object[]> rwNullsMapProvider() {
+        return makeAllRWMapsWithNulls().iterator();
+    }
+
+    private static Collection<Object[]> makeAllRWMapsWithNulls() {
         Collection<Object[]> all = new ArrayList<>();
 
-        all.addAll(makeRWMaps(false));
-        all.addAll(makeRWNoNullsMaps());
-        all.addAll(makeROMaps(false));
+        all.addAll(makeRWMaps(true, true));
 
         return all;
     }
 
+
     private static Collection<Object[]> makeRWMapsNoNulls() {
         Collection<Object[]> all = new ArrayList<>();
 
-        all.addAll(makeRWMaps(false));
+        all.addAll(makeRWNoNullKeysMaps(false));
         all.addAll(makeRWNoNullsMaps());
 
         return all;
     }
 
-    private static Collection<Object[]> makeAllMaps() {
+    private static Collection<Object[]> makeAllROMaps() {
         Collection<Object[]> all = new ArrayList<>();
 
         all.addAll(makeROMaps(false));
-        all.addAll(makeRWMaps(false));
-        all.addAll(makeRWNoNullsMaps());
-        all.addAll(makeRWMaps(true));
         all.addAll(makeROMaps(true));
 
         return all;
@@ -445,52 +486,99 @@
     private static Collection<Object[]> makeAllRWMaps() {
         Collection<Object[]> all = new ArrayList<>();
 
-        all.addAll(makeRWMaps(false));
         all.addAll(makeRWNoNullsMaps());
-        all.addAll(makeRWMaps(true));
+        all.addAll(makeRWMaps(false,true));
+        all.addAll(makeRWMaps(true,true));
+        all.addAll(makeRWNoNullKeysMaps(true));
+        return all;
+    }
+
+    private static Collection<Object[]> makeAllMaps() {
+        Collection<Object[]> all = new ArrayList<>();
+
+        all.addAll(makeAllROMaps());
+        all.addAll(makeAllRWMaps());
 
         return all;
     }
 
-    private static Collection<Object[]> makeRWMaps(boolean nulls) {
+    private static Collection<Object[]> makeAllMapsWithNulls() {
+        Collection<Object[]> all = new ArrayList<>();
+
+        all.addAll(makeROMaps(true));
+        all.addAll(makeRWMaps(true,true));
+
+        return all;
+    }
+    /**
+     *
+     * @param nullKeys include null keys
+     * @param nullValues include null values
+     * @return
+     */
+    private static Collection<Object[]> makeRWMaps(boolean nullKeys, boolean nullValues) {
         return Arrays.asList(
-            new Object[]{"HashMap", makeMap(HashMap::new, nulls)},
-            new Object[]{"IdentityHashMap", makeMap(IdentityHashMap::new, nulls)},
-            new Object[]{"LinkedHashMap", makeMap(LinkedHashMap::new, nulls)},
-            new Object[]{"WeakHashMap", makeMap(WeakHashMap::new, nulls)},
-            new Object[]{"Collections.checkedMap(HashMap)", Collections.checkedMap(makeMap(HashMap::new, nulls), IntegerEnum.class, String.class)},
-            new Object[]{"Collections.synchronizedMap(HashMap)", Collections.synchronizedMap(makeMap(HashMap::new, nulls))},
-            new Object[]{"ExtendsAbstractMap", makeMap(ExtendsAbstractMap::new, nulls)});
+            new Object[]{"HashMap", makeMap(HashMap::new, nullKeys, nullValues)},
+            new Object[]{"IdentityHashMap", makeMap(IdentityHashMap::new, nullKeys, nullValues)},
+            new Object[]{"LinkedHashMap", makeMap(LinkedHashMap::new, nullKeys, nullValues)},
+            new Object[]{"WeakHashMap", makeMap(WeakHashMap::new, nullKeys, nullValues)},
+            new Object[]{"Collections.checkedMap(HashMap)", Collections.checkedMap(makeMap(HashMap::new, nullKeys, nullValues), IntegerEnum.class, String.class)},
+            new Object[]{"Collections.synchronizedMap(HashMap)", Collections.synchronizedMap(makeMap(HashMap::new, nullKeys, nullValues))},
+            new Object[]{"ExtendsAbstractMap", makeMap(ExtendsAbstractMap::new, nullKeys, nullValues)});
+    }
+
+    /**
+     *
+     * @param nulls include null values
+     * @return
+     */
+    private static Collection<Object[]> makeRWNoNullKeysMaps(boolean nulls) {
+        return Arrays.asList(
+                // null key hostile
+                new Object[]{"EnumMap", makeMap(() -> new EnumMap(IntegerEnum.class), false, nulls)},
+                new Object[]{"Collections.synchronizedMap(EnumMap)", Collections.synchronizedMap(makeMap(() -> new EnumMap(IntegerEnum.class), false, nulls))}
+                );
     }
 
     private static Collection<Object[]> makeRWNoNullsMaps() {
         return Arrays.asList(
-            // null hostile
-            new Object[]{"EnumMap", makeMap(() -> new EnumMap(IntegerEnum.class), false)},
-            new Object[]{"Hashtable", makeMap(Hashtable::new, false)},
-            new Object[]{"TreeMap", makeMap(TreeMap::new, false)},
-            new Object[]{"ConcurrentHashMap", makeMap(ConcurrentHashMap::new, false)},
-            new Object[]{"ConcurrentSkipListMap", makeMap(ConcurrentSkipListMap::new, false)},
-            new Object[]{"Collections.checkedMap(ConcurrentHashMap)", Collections.checkedMap(makeMap(ConcurrentHashMap::new, false), IntegerEnum.class, String.class)},
-            new Object[]{"Collections.synchronizedMap(EnumMap)", Collections.synchronizedMap(makeMap(() -> new EnumMap(IntegerEnum.class), false))},
-            new Object[]{"ImplementsConcurrentMap", makeMap(ImplementsConcurrentMap::new, false)});
+            // null key and value hostile
+            new Object[]{"Hashtable", makeMap(Hashtable::new, false, false)},
+            new Object[]{"TreeMap", makeMap(TreeMap::new, false, false)},
+            new Object[]{"ConcurrentHashMap", makeMap(ConcurrentHashMap::new, false, false)},
+            new Object[]{"ConcurrentSkipListMap", makeMap(ConcurrentSkipListMap::new, false, false)},
+            new Object[]{"Collections.checkedMap(ConcurrentHashMap)", Collections.checkedMap(makeMap(ConcurrentHashMap::new, false, false), IntegerEnum.class, String.class)},
+            new Object[]{"ImplementsConcurrentMap", makeMap(ImplementsConcurrentMap::new, false, false)}
+            );
     }
 
+    /**
+     *
+     * @param nulls include nulls
+     * @return
+     */
     private static Collection<Object[]> makeROMaps(boolean nulls) {
         return Arrays.asList(new Object[][]{
-            new Object[]{"Collections.unmodifiableMap(HashMap)", Collections.unmodifiableMap(makeMap(HashMap::new, nulls))}
+            new Object[]{"Collections.unmodifiableMap(HashMap)", Collections.unmodifiableMap(makeMap(HashMap::new, nulls, nulls))}
         });
     }
 
-    private static Map<IntegerEnum, String> makeMap(Supplier<Map<IntegerEnum, String>> supplier, boolean nulls) {
+     /**
+     *
+     * @param supplier a supplier of mutable map instances.
+     *
+     * @param nullKeys   include null keys
+     * @param nullValues include null values
+     * @return
+     */
+    private static Map<IntegerEnum, String> makeMap(Supplier<Map<IntegerEnum, String>> supplier, boolean nullKeys, boolean nullValues) {
         Map<IntegerEnum, String> result = supplier.get();
 
         for (int each = 0; each < TEST_SIZE; each++) {
-            if (nulls) {
-                result.put((each == 0) ? null : KEYS[each], null);
-            } else {
-                result.put(KEYS[each], VALUES[each]);
-            }
+            IntegerEnum key = nullKeys ? (each == 0) ? null : KEYS[each] : KEYS[each];
+            String value = nullValues ? (each == 0) ? null : VALUES[each] : VALUES[each];
+
+            result.put(key, value);
         }
 
         return result;
@@ -520,6 +608,12 @@
             : "Failed to throw " + throwable.getCanonicalName());
     }
 
+    public static <T extends Throwable> void assertThrows(Class<T> throwable, String message, Thrower<T>... throwers) {
+        for(Thrower<T> thrower : throwers) {
+            assertThrows(thrower, throwable, message);
+        }
+    }
+
     public static <T> void assertInstance(T actual, Class<? extends T> expected) {
         assertInstance(expected.isInstance(actual), null);
     }
--- a/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -170,7 +170,7 @@
                    () -> Spliterators.spliteratorUnknownSize(exp.iterator(), 0));
 
             db.add("Spliterators.spliterator(Spliterators.iteratorFromSpliterator(Spliterator ), ...)",
-                   () -> Spliterators.spliterator(Spliterators.iteratorFromSpliterator(exp.spliterator()), exp.size(), 0));
+                   () -> Spliterators.spliterator(Spliterators.iterator(exp.spliterator()), exp.size(), 0));
 
             db.add("Spliterators.spliterator(T[], ...)",
                    () -> Spliterators.spliterator(exp.toArray(new Integer[0]), 0));
@@ -549,10 +549,10 @@
                    () -> Arrays.spliterator(exp));
 
             db.add("Spliterators.spliterator(PrimitiveIterator.OfInt, ...)",
-                   () -> Spliterators.spliterator(Spliterators.iteratorFromSpliterator(Arrays.spliterator(exp)), exp.length, 0));
+                   () -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0));
 
             db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfInt, ...)",
-                   () -> Spliterators.spliteratorUnknownSize(Spliterators.iteratorFromSpliterator(Arrays.spliterator(exp)), 0));
+                   () -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0));
 
             class IntSpliteratorFromArray extends Spliterators.AbstractIntSpliterator {
                 int[] a;
@@ -702,10 +702,10 @@
                    () -> Arrays.spliterator(exp));
 
             db.add("Spliterators.spliterator(PrimitiveIterator.OfLong, ...)",
-                   () -> Spliterators.spliterator(Spliterators.iteratorFromSpliterator(Arrays.spliterator(exp)), exp.length, 0));
+                   () -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0));
 
             db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfLong, ...)",
-                   () -> Spliterators.spliteratorUnknownSize(Spliterators.iteratorFromSpliterator(Arrays.spliterator(exp)), 0));
+                   () -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0));
 
             class LongSpliteratorFromArray extends Spliterators.AbstractLongSpliterator {
                 long[] a;
@@ -862,10 +862,10 @@
                    () -> Arrays.spliterator(exp));
 
             db.add("Spliterators.spliterator(PrimitiveIterator.OfDouble, ...)",
-                   () -> Spliterators.spliterator(Spliterators.iteratorFromSpliterator(Arrays.spliterator(exp)), exp.length, 0));
+                   () -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0));
 
             db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfDouble, ...)",
-                   () -> Spliterators.spliteratorUnknownSize(Spliterators.iteratorFromSpliterator(Arrays.spliterator(exp)), 0));
+                   () -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0));
 
             class DoubleSpliteratorFromArray extends Spliterators.AbstractDoubleSpliterator {
                 double[] a;
--- a/jdk/test/java/util/concurrent/Executors/PrivilegedCallables.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/concurrent/Executors/PrivilegedCallables.java	Wed Jul 05 19:00:49 2017 +0200
@@ -43,7 +43,8 @@
 
     final Random rnd = new Random();
 
-    @SuppressWarnings("serial") Throwable[] throwables = {
+    @SuppressWarnings("serial")
+    Throwable[] throwables = {
         new Exception() {},
         new RuntimeException() {},
         new Error() {}
@@ -51,6 +52,11 @@
     Throwable randomThrowable() {
         return throwables[rnd.nextInt(throwables.length)];
     }
+    void throwThrowable(Throwable t) throws Exception {
+        if (t instanceof Error) throw (Error) t;
+        if (t instanceof RuntimeException) throw (RuntimeException) t;
+        throw (Exception) t;
+    }
 
     //----------------------------------------------------------------
     // A Policy class designed to make permissions fiddling very easy.
@@ -119,9 +125,8 @@
             if (rnd.nextBoolean()) {
                 final Throwable t = randomThrowable();
                 real = new Callable<Integer>() {
-                    @SuppressWarnings("deprecation")
                     public Integer call() throws Exception {
-                        Thread.currentThread().stop(t);
+                        throwThrowable(t);
                         return null; }};
                 try {
                     c.call();
--- a/jdk/test/java/util/concurrent/FutureTask/Throw.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/concurrent/FutureTask/Throw.java	Wed Jul 05 19:00:49 2017 +0200
@@ -31,10 +31,9 @@
 
 public class Throw {
 
-    @SuppressWarnings("deprecation")
     static void THROW(final Throwable t) {
         if (t != null)
-            Thread.currentThread().stop(t);
+            Throw.<RuntimeException>uncheckedThrow(t);
     }
 
     Callable<Void> thrower(final Throwable t) {
@@ -138,4 +137,8 @@
             catch (Throwable t) {
                 if (k.isAssignableFrom(t.getClass())) pass();
                 else unexpected(t);}}
+    @SuppressWarnings("unchecked") static <T extends Throwable>
+        void uncheckedThrow(Throwable t) throws T {
+        throw (T)t; // rely on vacuous cast
+    }
 }
--- a/jdk/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/concurrent/ThreadPoolExecutor/ThrowingTasks.java	Wed Jul 05 19:00:49 2017 +0200
@@ -101,8 +101,10 @@
     static class Thrower implements Runnable {
         Throwable t;
         Thrower(Throwable t) { this.t = t; }
-        @SuppressWarnings("deprecation")
-        public void run() { if (t != null) Thread.currentThread().stop(t); }
+        public void run() {
+            if (t != null)
+                ThrowingTasks.<RuntimeException>uncheckedThrow(t);
+        }
     }
 
     static final Thrower noThrower      = new Thrower(null);
@@ -265,4 +267,8 @@
         try {realMain(args);} catch (Throwable t) {unexpected(t);}
         System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
         if (failed > 0) throw new AssertionError("Some tests failed");}
+    @SuppressWarnings("unchecked") static <T extends Throwable>
+        void uncheckedThrow(Throwable t) throws T {
+        throw (T)t; // rely on vacuous cast
+    }
 }
--- a/jdk/test/java/util/concurrent/locks/Lock/FlakyMutex.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/concurrent/locks/Lock/FlakyMutex.java	Wed Jul 05 19:00:49 2017 +0200
@@ -37,7 +37,7 @@
  * tryAcquire method that randomly throws various Throwable
  * subclasses.
  */
-@SuppressWarnings({"deprecation", "serial"})
+@SuppressWarnings("serial")
 public class FlakyMutex implements Lock {
     static class MyError extends Error {}
     static class MyException extends Exception {}
@@ -49,7 +49,7 @@
         switch (rnd.nextInt(10)) {
         case 0: throw new MyError();
         case 1: throw new MyRuntimeException();
-        case 2: Thread.currentThread().stop(new MyException()); break;
+        case 2: FlakyMutex.<RuntimeException>uncheckedThrow(new MyException());
         default: /* Do nothing */ break;
         }
     }
@@ -146,4 +146,8 @@
         try {realMain(args);} catch (Throwable t) {unexpected(t);}
         System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
         if (failed > 0) throw new AssertionError("Some tests failed");}
+    @SuppressWarnings("unchecked") static <T extends Throwable>
+        void uncheckedThrow(Throwable t) throws T {
+        throw (T)t; // rely on vacuous cast
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/logging/LogManagerInstanceTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.util.logging.*;
+
+/*
+ * @test
+ * @bug 8010727
+ * @summary  LogManager.addLogger should succeed to add a logger named ""
+ *           if LogManager.getLogger("") returns null.
+ *
+ * @run main LogManagerInstanceTest
+ */
+
+public class LogManagerInstanceTest {
+    public static void main(String[] argv) {
+        LogManager mgr = LogManager.getLogManager();
+        if (getRootLogger(mgr) == null) {
+            throw new RuntimeException("Root logger not exist");
+        }
+
+        SecondLogManager mgr2 = new SecondLogManager();
+        Logger root = getRootLogger(mgr2);
+        if (mgr2.base != root) {
+            throw new RuntimeException(mgr2.base + " is not the root logger");
+        }
+    }
+
+    private static Logger getRootLogger(LogManager mgr) {
+        Logger l = mgr.getLogger("");
+        if (l != null && !l.getName().isEmpty()) {
+            throw new RuntimeException(l.getName() + " is not an invalid root logger");
+        }
+        return l;
+    }
+
+    static class SecondLogManager extends LogManager {
+        final Logger base;
+        private SecondLogManager() {
+            Logger root = getLogger("");
+            if (root == null) {
+                root = new BaseLogger("", null);
+                if (!super.addLogger(root))
+                    throw new RuntimeException("Fail to addLogger " + root);
+            } else {
+                System.out.println("Root logger already exists");
+            }
+            this.base = root;
+        }
+    }
+    static class BaseLogger extends Logger {
+        BaseLogger(String name, String rbname) {
+            super(name, rbname);
+        }
+    }
+}
--- a/jdk/test/java/util/stream/bootlib/java/util/stream/DoubleStreamTestDataProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/bootlib/java/util/stream/DoubleStreamTestDataProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -92,15 +92,6 @@
                 }
                 list.add(new Object[]{"SpinedList:" + name,
                         TestData.Factory.ofSpinedBuffer("SpinedList:" + name, isl)});
-
-                list.add(streamDataDescr("Primitives.range(0,l): " + doubles.length,
-                                         () -> DoubleStream.range(0, doubles.length)));
-                list.add(streamDataDescr("Primitives.range(0,l,2): " + doubles.length,
-                                         () -> DoubleStream.range(0, doubles.length, 2)));
-                list.add(streamDataDescr("Primitives.range(0,l,3): " + doubles.length,
-                                         () -> DoubleStream.range(0, doubles.length, 3)));
-                list.add(streamDataDescr("Primitives.range(0,l,7): " + doubles.length,
-                                         () -> DoubleStream.range(0, doubles.length, 7)));
             }
             testData = list.toArray(new Object[0][]);
         }
@@ -128,15 +119,6 @@
                                             () -> Spliterators.spliterator(isl.iterator(), doubles.length, 0)));
                 spliterators.add(splitDescr("Primitives.s(SpinedBuffer.iterator()):" + name,
                                             () -> Spliterators.spliteratorUnknownSize(isl.iterator(), 0)));
-
-                spliterators.add(splitDescr("Primitives.range(0,l):" + name,
-                                            () -> DoubleStream.range(0, doubles.length).spliterator()));
-                spliterators.add(splitDescr("Primitives.range(0,l,2):" + name,
-                                            () -> DoubleStream.range(0, doubles.length, 2).spliterator()));
-                spliterators.add(splitDescr("Primitives.range(0,l,3):" + name,
-                                            () -> DoubleStream.range(0, doubles.length, 3).spliterator()));
-                spliterators.add(splitDescr("Primitives.range(0,l,7):" + name,
-                                            () -> DoubleStream.range(0, doubles.length, 7).spliterator()));
                 // Need more!
             }
             spliteratorTestData = spliterators.toArray(new Object[0][]);
@@ -144,10 +126,6 @@
 
     }
 
-    static <T> Object[] streamDataDescr(String description, Supplier<DoubleStream> s) {
-        return new Object[] { description, TestData.Factory.ofDoubleSupplier(description, s) };
-    }
-
     static <T> Object[] splitDescr(String description, Supplier<Spliterator.OfDouble> s) {
         return new Object[] { description, s };
     }
--- a/jdk/test/java/util/stream/bootlib/java/util/stream/IntStreamTestDataProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/bootlib/java/util/stream/IntStreamTestDataProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -95,12 +95,8 @@
 
                 list.add(streamDataDescr("IntStream.intRange(0,l): " + ints.length,
                                          () -> IntStream.range(0, ints.length)));
-                list.add(streamDataDescr("IntStream.intRange(0,l,2): " + ints.length,
-                                         () -> IntStream.range(0, ints.length, 2)));
-                list.add(streamDataDescr("IntStream.intRange(0,l,3): " + ints.length,
-                                         () -> IntStream.range(0, ints.length, 3)));
-                list.add(streamDataDescr("IntStream.intRange(0,l,7): " + ints.length,
-                                         () -> IntStream.range(0, ints.length, 7)));
+                list.add(streamDataDescr("IntStream.rangeClosed(0,l): " + ints.length,
+                                         () -> IntStream.rangeClosed(0, ints.length)));
             }
             testData = list.toArray(new Object[0][]);
         }
@@ -131,12 +127,8 @@
 
                 spliterators.add(splitDescr("IntStream.intRange(0,l):" + name,
                                             () -> IntStream.range(0, ints.length).spliterator()));
-                spliterators.add(splitDescr("IntStream.intRange(0,l,2):" + name,
-                                            () -> IntStream.range(0, ints.length, 2).spliterator()));
-                spliterators.add(splitDescr("IntStream.intRange(0,l,3):" + name,
-                                            () -> IntStream.range(0, ints.length, 3).spliterator()));
-                spliterators.add(splitDescr("IntStream.intRange(0,l,7):" + name,
-                                            () -> IntStream.range(0, ints.length, 7).spliterator()));
+                spliterators.add(splitDescr("IntStream.intRangeClosed(0,l):" + name,
+                                            () -> IntStream.rangeClosed(0, ints.length).spliterator()));
 
                 // Need more!
             }
--- a/jdk/test/java/util/stream/bootlib/java/util/stream/LongStreamTestDataProvider.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/bootlib/java/util/stream/LongStreamTestDataProvider.java	Wed Jul 05 19:00:49 2017 +0200
@@ -95,12 +95,8 @@
 
                 list.add(streamDataDescr("LongStream.longRange(0,l): " + longs.length,
                                          () -> LongStream.range(0, longs.length)));
-                list.add(streamDataDescr("LongStream.longRange(0,l,2): " + longs.length,
-                                         () -> LongStream.range(0, longs.length, 2)));
-                list.add(streamDataDescr("LongStream.longRange(0,l,3): " + longs.length,
-                                         () -> LongStream.range(0, longs.length, 3)));
-                list.add(streamDataDescr("LongStream.longRange(0,l,7): " + longs.length,
-                                         () -> LongStream.range(0, longs.length, 7)));
+                list.add(streamDataDescr("LongStream.longRangeClosed(0,l): " + longs.length,
+                                         () -> LongStream.rangeClosed(0, longs.length)));
             }
             testData = list.toArray(new Object[0][]);
         }
@@ -131,12 +127,8 @@
 
                 spliterators.add(splitDescr("LongStream.longRange(0,l):" + name,
                                             () -> LongStream.range(0, longs.length).spliterator()));
-                spliterators.add(splitDescr("LongStream.longRange(0,l,2):" + name,
-                                            () -> LongStream.range(0, longs.length, 2).spliterator()));
-                spliterators.add(splitDescr("LongStream.longRange(0,l,3):" + name,
-                                            () -> LongStream.range(0, longs.length, 3).spliterator()));
-                spliterators.add(splitDescr("LongStream.longRange(0,l,7):" + name,
-                                            () -> LongStream.range(0, longs.length, 7).spliterator()));
+                spliterators.add(splitDescr("LongStream.longRangeClosed(0,l):" + name,
+                                            () -> LongStream.rangeClosed(0, longs.length).spliterator()));
                 // Need more!
             }
             spliteratorTestData = spliterators.toArray(new Object[0][]);
--- a/jdk/test/java/util/stream/bootlib/java/util/stream/TestData.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/bootlib/java/util/stream/TestData.java	Wed Jul 05 19:00:49 2017 +0200
@@ -45,7 +45,7 @@
 
     @Override
     default Iterator<T> iterator() {
-        return Spliterators.iteratorFromSpliterator(spliterator());
+        return Spliterators.iterator(spliterator());
     }
 
     Spliterator<T> spliterator();
@@ -292,7 +292,7 @@
 
             @Override
             public PrimitiveIterator.OfInt iterator() {
-                return Spliterators.iteratorFromSpliterator(spliterator());
+                return Spliterators.iterator(spliterator());
             }
 
             @Override
@@ -317,7 +317,7 @@
 
             @Override
             public PrimitiveIterator.OfLong iterator() {
-                return Spliterators.iteratorFromSpliterator(spliterator());
+                return Spliterators.iterator(spliterator());
             }
 
             @Override
@@ -342,7 +342,7 @@
 
             @Override
             public PrimitiveIterator.OfDouble iterator() {
-                return Spliterators.iteratorFromSpliterator(spliterator());
+                return Spliterators.iterator(spliterator());
             }
 
             @Override
--- a/jdk/test/java/util/stream/boottest/java/util/stream/DoubleNodeTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/boottest/java/util/stream/DoubleNodeTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -48,7 +48,7 @@
             List<Node<Double>> nodes = new ArrayList<>();
 
             nodes.add(Nodes.node(array));
-            nodes.add(degenerateTree(Spliterators.iteratorFromSpliterator(Arrays.spliterator(array))));
+            nodes.add(degenerateTree(Spliterators.iterator(Arrays.spliterator(array))));
             nodes.add(tree(toList(array), l -> Nodes.node(toDoubleArray(l))));
             nodes.add(fill(array, Nodes.doubleBuilder(array.length)));
             nodes.add(fill(array, Nodes.doubleBuilder()));
@@ -122,12 +122,12 @@
 
     @Test(dataProvider = "nodes")
     public void testAsArray(double[] array, Node.OfDouble n) {
-        assertEquals(n.asDoubleArray(), array);
+        assertEquals(n.asPrimitiveArray(), array);
     }
 
     @Test(dataProvider = "nodes")
     public void testFlattenAsArray(double[] array, Node.OfDouble n) {
-        assertEquals(Nodes.flattenDouble(n).asDoubleArray(), array);
+        assertEquals(Nodes.flattenDouble(n).asPrimitiveArray(), array);
     }
 
     @Test(dataProvider = "nodes")
--- a/jdk/test/java/util/stream/boottest/java/util/stream/IntNodeTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/boottest/java/util/stream/IntNodeTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -48,7 +48,7 @@
             List<Node<Integer>> nodes = new ArrayList<>();
 
             nodes.add(Nodes.node(array));
-            nodes.add(degenerateTree(Spliterators.iteratorFromSpliterator(Arrays.spliterator(array))));
+            nodes.add(degenerateTree(Spliterators.iterator(Arrays.spliterator(array))));
             nodes.add(tree(toList(array), l -> Nodes.node(toIntArray(l))));
             nodes.add(fill(array, Nodes.intBuilder(array.length)));
             nodes.add(fill(array, Nodes.intBuilder()));
@@ -122,12 +122,12 @@
 
     @Test(dataProvider = "nodes")
     public void testAsArray(int[] array, Node.OfInt n) {
-        assertEquals(n.asIntArray(), array);
+        assertEquals(n.asPrimitiveArray(), array);
     }
 
     @Test(dataProvider = "nodes")
     public void testFlattenAsArray(int[] array, Node.OfInt n) {
-        assertEquals(Nodes.flattenInt(n).asIntArray(), array);
+        assertEquals(Nodes.flattenInt(n).asPrimitiveArray(), array);
     }
 
     @Test(dataProvider = "nodes")
--- a/jdk/test/java/util/stream/boottest/java/util/stream/LongNodeTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/boottest/java/util/stream/LongNodeTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -48,7 +48,7 @@
             List<Node<Long>> nodes = new ArrayList<>();
 
             nodes.add(Nodes.node(array));
-            nodes.add(degenerateTree(Spliterators.iteratorFromSpliterator(Arrays.spliterator(array))));
+            nodes.add(degenerateTree(Spliterators.iterator(Arrays.spliterator(array))));
             nodes.add(tree(toList(array), l -> Nodes.node(toLongArray(l))));
             nodes.add(fill(array, Nodes.longBuilder(array.length)));
             nodes.add(fill(array, Nodes.longBuilder()));
@@ -122,12 +122,12 @@
 
     @Test(dataProvider = "nodes")
     public void testAsArray(long[] array, Node.OfLong n) {
-        assertEquals(n.asLongArray(), array);
+        assertEquals(n.asPrimitiveArray(), array);
     }
 
     @Test(dataProvider = "nodes")
     public void testFlattenAsArray(long[] array, Node.OfLong n) {
-        assertEquals(Nodes.flattenLong(n).asLongArray(), array);
+        assertEquals(Nodes.flattenLong(n).asPrimitiveArray(), array);
     }
 
     @Test(dataProvider = "nodes")
--- a/jdk/test/java/util/stream/boottest/java/util/stream/SpinedBufferTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/boottest/java/util/stream/SpinedBufferTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -210,7 +210,7 @@
         list2.clear();
         sb.forEach((int i) -> list2.add(i));
         assertEquals(list1, list2);
-        int[] array = sb.asIntArray();
+        int[] array = sb.asPrimitiveArray();
         list2.clear();
         for (int i : array)
             list2.add(i);
@@ -285,7 +285,7 @@
         list2.clear();
         sb.forEach((long i) -> list2.add(i));
         assertEquals(list1, list2);
-        long[] array = sb.asLongArray();
+        long[] array = sb.asPrimitiveArray();
         list2.clear();
         for (long i : array)
             list2.add(i);
@@ -300,7 +300,7 @@
 
         for (int size : sizes) {
             // @@@ replace with double range when implemented
-            double[] array = LongStream.range(0, size).doubles().toArray();
+            double[] array = LongStream.range(0, size).asDoubleStream().toArray();
             SpinedBuffer.OfDouble sb = new SpinedBuffer.OfDouble();
             Arrays.stream(array).forEach(sb);
 
@@ -361,7 +361,7 @@
         list2.clear();
         sb.forEach((double i) -> list2.add(i));
         assertEquals(list1, list2);
-        double[] array = sb.asDoubleArray();
+        double[] array = sb.asPrimitiveArray();
         list2.clear();
         for (double i : array)
             list2.add(i);
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/DoublePrimitiveOpsTests.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/DoublePrimitiveOpsTests.java	Wed Jul 05 19:00:49 2017 +0200
@@ -44,12 +44,12 @@
 
     public void testToArray() {
         {
-            double[] array =  LongStream.range(1, 10).doubles().map(i -> i * 2).toArray();
+            double[] array =  LongStream.range(1, 10).asDoubleStream().map(i -> i * 2).toArray();
             assertEquals(array, new double[]{2, 4, 6, 8, 10, 12, 14, 16, 18});
         }
 
         {
-            double[] array =  LongStream.range(1, 10).parallel().doubles().map(i -> i * 2).toArray();
+            double[] array =  LongStream.range(1, 10).parallel().asDoubleStream().map(i -> i * 2).toArray();
             assertEquals(array, new double[]{2, 4, 6, 8, 10, 12, 14, 16, 18});
         }
     }
@@ -99,7 +99,7 @@
         }
 
         {
-            double[] actual = LongStream.range(1, 100).parallel().doubles().limit(9).toArray();
+            double[] actual = LongStream.range(1, 100).parallel().asDoubleStream().limit(9).toArray();
             Assert.assertTrue(Arrays.equals(expected, actual));
         }
     }
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ExplodeOpTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ExplodeOpTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -110,7 +110,7 @@
         result = exerciseOps(data, s -> DoubleStream.empty());
         assertEquals(0, result.size());
 
-        exerciseOps(data, s -> s.flatMap(e -> DoubleStream.range(0, e)));
-        exerciseOps(data, s -> s.flatMap(e -> DoubleStream.range(0, e).limit(10)));
+        exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, (int) e).asDoubleStream()));
+        exerciseOps(data, s -> s.flatMap(e -> IntStream.range(0, (int) e).limit(10).asDoubleStream()));
     }
 }
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ForEachOpTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/ForEachOpTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -205,7 +205,7 @@
     public void testDoubleForEachOrdered() {
         List<Integer> input = countTo(10000);
         TestData.OfDouble data = TestData.Factory.ofDoubleSupplier("[1, 10000]",
-                                                                   () -> DoubleStream.range(1, 10001));
+                                                                   () -> IntStream.range(1, 10001).asDoubleStream());
 
         Function<DoubleStream, List<Integer>> terminalFunc = s -> {
             List<Integer> l = new ArrayList<>();
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/MapOpTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/MapOpTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -24,16 +24,6 @@
 
 import org.testng.annotations.Test;
 
-import java.util.function.DoubleToIntFunction;
-import java.util.function.DoubleToLongFunction;
-import java.util.function.Function;
-import java.util.function.IntToDoubleFunction;
-import java.util.function.IntToLongFunction;
-import java.util.function.LongToDoubleFunction;
-import java.util.function.LongToIntFunction;
-import java.util.function.ToDoubleFunction;
-import java.util.function.ToIntFunction;
-import java.util.function.ToLongFunction;
 import java.util.stream.*;
 
 import static java.util.stream.LambdaTestHelpers.*;
@@ -98,8 +88,8 @@
         exerciseOps(data, s -> s.mapToObj(i -> i));
         exerciseOps(data, s -> s.map(i -> 0));
         exerciseOps(data, s -> s.map(i -> i * 2));
-        exerciseOps(data, s -> s.longs());
-        exerciseOps(data, s -> s.doubles());
+        exerciseOps(data, s -> s.asLongStream());
+        exerciseOps(data, s -> s.asDoubleStream());
         exerciseOps(data, s -> s.boxed());
         exerciseOps(data, s -> s.mapToObj(Integer::toString));
         exerciseOps(data, s -> s.mapToLong(i -> i));
@@ -113,7 +103,7 @@
         exerciseOps(data, s -> s.mapToObj(i -> i));
         exerciseOps(data, s -> s.map(i -> 0L));
         exerciseOps(data, s -> s.map(i -> i * 2L));
-        exerciseOps(data, s -> s.doubles());
+        exerciseOps(data, s -> s.asDoubleStream());
         exerciseOps(data, s -> s.boxed());
         exerciseOps(data, s -> s.mapToObj(e -> Long.toString(e)));
         exerciseOps(data, s -> s.mapToInt(i -> (int) i));
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/MatchOpTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/MatchOpTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -318,17 +318,17 @@
     }
 
     public void testDoubleStreamMatches() {
-        assertDoublePredicates(() -> LongStream.range(0, 0).doubles(), Kind.ANY, DOUBLE_PREDICATES, false, false, false, false);
-        assertDoublePredicates(() -> LongStream.range(0, 0).doubles(), Kind.ALL, DOUBLE_PREDICATES, true, true, true, true);
-        assertDoublePredicates(() -> LongStream.range(0, 0).doubles(), Kind.NONE, DOUBLE_PREDICATES, true, true, true, true);
+        assertDoublePredicates(() -> LongStream.range(0, 0).asDoubleStream(), Kind.ANY, DOUBLE_PREDICATES, false, false, false, false);
+        assertDoublePredicates(() -> LongStream.range(0, 0).asDoubleStream(), Kind.ALL, DOUBLE_PREDICATES, true, true, true, true);
+        assertDoublePredicates(() -> LongStream.range(0, 0).asDoubleStream(), Kind.NONE, DOUBLE_PREDICATES, true, true, true, true);
 
-        assertDoublePredicates(() -> LongStream.range(1, 2).doubles(), Kind.ANY, DOUBLE_PREDICATES, true, false, false, true);
-        assertDoublePredicates(() -> LongStream.range(1, 2).doubles(), Kind.ALL, DOUBLE_PREDICATES, true, false, false, true);
-        assertDoublePredicates(() -> LongStream.range(1, 2).doubles(), Kind.NONE, DOUBLE_PREDICATES, false, true, true, false);
+        assertDoublePredicates(() -> LongStream.range(1, 2).asDoubleStream(), Kind.ANY, DOUBLE_PREDICATES, true, false, false, true);
+        assertDoublePredicates(() -> LongStream.range(1, 2).asDoubleStream(), Kind.ALL, DOUBLE_PREDICATES, true, false, false, true);
+        assertDoublePredicates(() -> LongStream.range(1, 2).asDoubleStream(), Kind.NONE, DOUBLE_PREDICATES, false, true, true, false);
 
-        assertDoublePredicates(() -> LongStream.range(1, 6).doubles(), Kind.ANY, DOUBLE_PREDICATES, true, false, true, true);
-        assertDoublePredicates(() -> LongStream.range(1, 6).doubles(), Kind.ALL, DOUBLE_PREDICATES, true, false, false, false);
-        assertDoublePredicates(() -> LongStream.range(1, 6).doubles(), Kind.NONE, DOUBLE_PREDICATES, false, true, false, false);
+        assertDoublePredicates(() -> LongStream.range(1, 6).asDoubleStream(), Kind.ANY, DOUBLE_PREDICATES, true, false, true, true);
+        assertDoublePredicates(() -> LongStream.range(1, 6).asDoubleStream(), Kind.ALL, DOUBLE_PREDICATES, true, false, false, false);
+        assertDoublePredicates(() -> LongStream.range(1, 6).asDoubleStream(), Kind.NONE, DOUBLE_PREDICATES, false, true, false, false);
     }
 
     @Test(dataProvider = "DoubleStreamTestData", dataProviderClass = DoubleStreamTestDataProvider.class)
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/MinMaxTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/MinMaxTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -80,8 +80,8 @@
     public void testDoubleMinMax() {
         assertEquals(DoubleStream.empty().min(), OptionalDouble.empty());
         assertEquals(DoubleStream.empty().max(), OptionalDouble.empty());
-        assertEquals(1.0, LongStream.range(1, 1001).doubles().min().getAsDouble());
-        assertEquals(1000.0, LongStream.range(1, 1001).doubles().max().getAsDouble());
+        assertEquals(1.0, LongStream.range(1, 1001).asDoubleStream().min().getAsDouble());
+        assertEquals(1000.0, LongStream.range(1, 1001).asDoubleStream().max().getAsDouble());
     }
 
     @Test(dataProvider = "DoubleStreamTestData", dataProviderClass = DoubleStreamTestDataProvider.class)
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/PrimitiveSumTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/PrimitiveSumTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -34,7 +34,7 @@
 
         withData(data).
                 terminal(s -> (long) s.sum()).
-                expectedResult(data.stream().longs().reduce(0, LambdaTestHelpers.lrPlus)).
+                expectedResult(data.stream().asLongStream().reduce(0, LambdaTestHelpers.lrPlus)).
                 exercise();
     }
 
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/RangeTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/RangeTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -24,10 +24,11 @@
 
 import java.util.Arrays;
 import java.util.Optional;
-import java.util.stream.DoubleStream;
+import java.util.Spliterator;
 import java.util.stream.IntStream;
 import java.util.stream.LongStream;
 import java.util.stream.OpTestCase;
+import java.util.stream.SpliteratorTestHelper;
 import java.util.stream.Stream;
 import java.util.stream.TestData;
 
@@ -54,73 +55,76 @@
 
     //
 
-    public void testIntRangeErrors() {
+    public void testIntRange() {
+        // Half-open
         for (int start : Arrays.asList(1, 10, -1, -10)) {
             for (int end : Arrays.asList(1, 10, -1, -10)) {
-                for (int step : Arrays.asList(0, 1, -1, Integer.MAX_VALUE, Integer.MIN_VALUE)) {
-                    if (step > 0)
-                        executeAndNoCatch(() -> IntStream.range(start, end, step));
-                    else
-                        executeAndCatch(() -> IntStream.range(start, end, step));
-                }
-            }
-        }
-    }
-
-    public void testIntRange() {
-        // Without step
-        for (int start : Arrays.asList(1, 10, -1, -10)) {
-            for (int end : Arrays.asList(1, 10, -1, -10)) {
-                int step = 1;
                 int size = (start < end) ? end - start : 0;
                 int[] exp = new int[size];
-                if (start < end) {
-                    for (int i = start, p = 0; i < end; i++, p++) {
-                        exp[p] = i;
-                    }
+                for (int i = start, p = 0; i < end; i++, p++) {
+                    exp[p] = i;
                 }
 
                 int[] inc = IntStream.range(start, end).toArray();
                 assertEquals(inc.length, size);
                 assertTrue(Arrays.equals(exp, inc));
 
-                withData(intRangeData(start, end, step)).stream(s -> s).
+                withData(intRangeData(start, end)).stream(s -> s).
+                        expectedResult(exp).exercise();
+            }
+        }
+
+        // Closed
+        for (int start : Arrays.asList(1, 10, -1, -10)) {
+            for (int end : Arrays.asList(1, 10, -1, -10)) {
+                int size = (start <= end) ? end - start + 1 : 0;
+                int[] exp = new int[size];
+                for (int i = start, p = 0; i <= end; i++, p++) {
+                    exp[p] = i;
+                }
+
+                int[] inc = IntStream.rangeClosed(start, end).toArray();
+                assertEquals(inc.length, size);
+                assertTrue(Arrays.equals(exp, inc));
+
+                withData(intRangeClosedData(start, end)).stream(s -> s).
                         expectedResult(exp).exercise();
             }
         }
 
-        // With step
-        for (int start : Arrays.asList(1, 10, -1, -10)) {
-            for (int end : Arrays.asList(1, 10, -1, -10)) {
-                for (int step : Arrays.asList(1, -1, -2, 2)) {
-                    if (step > 0) {
-                        int d = end - start;
-                        int size = (start < end) ? (d / step) + ((d % step == 0) ? 0 : 1) : 0;
-                        int[] exp = new int[size];
-                        if (start < end) {
-                            for (int i = start, p = 0; i < end; i += step, p++) {
-                                exp[p] = i;
-                            }
-                        }
+        // Closed, maximum upper bound of Integer.MAX_VALUE
+        {
+            int[] inc = IntStream.rangeClosed(Integer.MAX_VALUE - 1, Integer.MAX_VALUE).toArray();
+            assertEquals(2, inc.length);
+            assertEquals(Integer.MAX_VALUE - 1, inc[0]);
+            assertEquals(Integer.MAX_VALUE, inc[1]);
 
-                        int[] inc = IntStream.range(start, end, step).toArray();
-                        assertEquals(inc.length, size);
-                        assertTrue(Arrays.equals(exp, inc));
+            inc = IntStream.rangeClosed(Integer.MAX_VALUE, Integer.MAX_VALUE).toArray();
+            assertEquals(1, inc.length);
+            assertEquals(Integer.MAX_VALUE, inc[0]);
 
-                        withData(intRangeData(start, end, step)).stream(s -> s).
-                                expectedResult(exp).exercise();
-                    }
-                }
-            }
+            SpliteratorTestHelper.testIntSpliterator(
+                    () -> IntStream.rangeClosed(Integer.MAX_VALUE - 8, Integer.MAX_VALUE).spliterator());
+        }
+
+        // Range wider than Integer.MAX_VALUE
+        {
+            Spliterator.OfInt s = IntStream.rangeClosed(Integer.MIN_VALUE, Integer.MAX_VALUE).
+                    spliterator();
+            assertEquals(s.estimateSize(), 1L << 32);
         }
     }
 
-    TestData.OfInt intRangeData(int start, int end, int step) {
-        return TestData.Factory.ofIntSupplier("int range", () -> IntStream.range(start, end, step));
+    TestData.OfInt intRangeData(int start, int end) {
+        return TestData.Factory.ofIntSupplier("int range", () -> IntStream.range(start, end));
+    }
+
+    TestData.OfInt intRangeClosedData(int start, int end) {
+        return TestData.Factory.ofIntSupplier("int rangeClosed", () -> IntStream.rangeClosed(start, end));
     }
 
     public void tesIntRangeReduce() {
-        withData(intRangeData(0, 10000, 1)).
+        withData(intRangeData(0, 10000)).
                 terminal(s -> s.reduce(0, Integer::sum)).exercise();
     }
 
@@ -137,74 +141,69 @@
 
     //
 
-    public void testLongRangeErrors() {
-        for (long start : Arrays.asList(1, 10, -1, -10)) {
-            for (long end : Arrays.asList(1, 10, -1, -10)) {
-                for (long step : Arrays.asList(0L, 1L, -1L, Long.MAX_VALUE, Long.MIN_VALUE)) {
-                    if (step > 0)
-                        executeAndNoCatch(() -> LongStream.range(start, end, step));
-                    else
-                        executeAndCatch(() -> LongStream.range(start, end, step));
-                }
-            }
-        }
-    }
-
     public void testLongRange() {
-        // Without step
+        // Half-open
         for (long start : Arrays.asList(1, 1000, -1, -1000)) {
             for (long end : Arrays.asList(1, 1000, -1, -1000)) {
-                long step = 1;
                 long size = start < end ? end - start : 0;
                 long[] exp = new long[(int) size];
-                if (start < end) {
-                    for (long i = start, p = 0; i < end; i++, p++) {
-                        exp[(int) p] = i;
-                    }
+                for (long i = start, p = 0; i < end; i++, p++) {
+                    exp[(int) p] = i;
                 }
 
                 long[] inc = LongStream.range(start, end).toArray();
                 assertEquals(inc.length, size);
                 assertTrue(Arrays.equals(exp, inc));
 
-                withData(longRangeData(start, end, step)).stream(s -> s).
+                withData(longRangeData(start, end)).stream(s -> s).
+                        expectedResult(exp).exercise();
+            }
+        }
+
+        // Closed
+        for (long start : Arrays.asList(1, 1000, -1, -1000)) {
+            for (long end : Arrays.asList(1, 1000, -1, -1000)) {
+                long size = start <= end ? end - start + 1: 0;
+                long[] exp = new long[(int) size];
+                for (long i = start, p = 0; i <= end; i++, p++) {
+                    exp[(int) p] = i;
+                }
+
+                long[] inc = LongStream.rangeClosed(start, end).toArray();
+                assertEquals(inc.length, size);
+                assertTrue(Arrays.equals(exp, inc));
+
+                withData(longRangeClosedData(start, end)).stream(s -> s).
                         expectedResult(exp).exercise();
             }
         }
 
-        // With step
-        for (long start : Arrays.asList(1, 1000, -1, -1000)) {
-            for (long end : Arrays.asList(1, 1000, -1, -1000)) {
-                for (long step : Arrays.asList(1, -1, -2, 2)) {
-                    if (step > 0) {
+        // Closed, maximum upper bound of Long.MAX_VALUE
+        {
+            long[] inc = LongStream.rangeClosed(Long.MAX_VALUE - 1, Long.MAX_VALUE).toArray();
+            assertEquals(2, inc.length);
+            assertEquals(Long.MAX_VALUE - 1, inc[0]);
+            assertEquals(Long.MAX_VALUE, inc[1]);
 
-                        long d = end - start;
-                        long size = start < end ? (d / step) + ((d % step == 0) ? 0 : 1) : 0;
-                        long[] exp = new long[(int) size];
-                        if (start < end) {
-                            for (long i = start, p = 0; i < end; i += step, p++) {
-                                exp[(int) p] = i;
-                            }
-                        }
+            inc = LongStream.rangeClosed(Long.MAX_VALUE, Long.MAX_VALUE).toArray();
+            assertEquals(1, inc.length);
+            assertEquals(Long.MAX_VALUE, inc[0]);
 
-                        long[] inc = LongStream.range(start, end, step).toArray();
-                        assertEquals(inc.length, size);
-                        assertTrue(Arrays.equals(exp, inc));
-
-                        withData(longRangeData(start, end, step)).stream(s -> s).
-                                expectedResult(exp).exercise();
-                    }
-                }
-            }
+            SpliteratorTestHelper.testLongSpliterator(
+                    () -> LongStream.rangeClosed(Long.MAX_VALUE - 8, Long.MAX_VALUE).spliterator());
         }
     }
 
-    TestData.OfLong longRangeData(long start, long end, long step) {
-        return TestData.Factory.ofLongSupplier("long range", () -> LongStream.range(start, end, step));
+    TestData.OfLong longRangeData(long start, long end) {
+        return TestData.Factory.ofLongSupplier("long range", () -> LongStream.range(start, end));
+    }
+
+    TestData.OfLong longRangeClosedData(long start, long end) {
+        return TestData.Factory.ofLongSupplier("long rangeClosed", () -> LongStream.rangeClosed(start, end));
     }
 
     public void testLongRangeReduce() {
-        withData(longRangeData(0, 10000, 1)).
+        withData(longRangeData(0, 10000)).
                 terminal(s -> s.reduce(0, Long::sum)).exercise();
     }
 
@@ -219,182 +218,116 @@
         assertEquals(first, LongStream.iterate(0, i -> i + 1).parallel().filter(i -> i > 10000).findFirst().getAsLong());
     }
 
-    //
-
-    public void testDoubleRangeErrors() {
-        for (double start : Arrays.asList(1, 10, -1, -10)) {
-            for (double end : Arrays.asList(1, 10, -1, -10)) {
-                for (double step : Arrays.asList(0.0, +0.0, -0.0, 1.0, -1.0, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY)) {
-                    try {
-                        if (step > 0)
-                            executeAndNoCatch(() -> DoubleStream.range(start, end, step));
-                        else
-                            executeAndCatch(() -> DoubleStream.range(start, end, step));
-                    }
-                    catch (AssertionError e) {
-                        System.out.printf("start=%f, end=%f, step=%f%n", start, end, step);
-                        throw e;
-                    }
-                }
-            }
-        }
-
-        for (double start : Arrays.asList(0.0, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN)) {
-            for (double end : Arrays.asList(0.0, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN)) {
-                for (double step : Arrays.asList(1.0, -1.0, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN)) {
-                    try {
-                        if ((start == 0.0 && end == 0.0 && step > 0)
-                            || (start > end && step > 0)) {
-                            executeAndNoCatch(() -> DoubleStream.range(start, end, step));
-                        }
-                        else {
-                            executeAndCatch(() -> DoubleStream.range(start, end, step));
-                        }
-                    }
-                    catch (AssertionError e) {
-                        System.out.printf("start=%f, end=%f, step=%f%n", start, end, step);
-                        throw e;
-                    }
-                }
-            }
-        }
-    }
-
-    public void testDoubleRange() {
-        // Without step
-        for (double start : Arrays.asList(1, 1000, -1, -1000)) {
-            for (double end : Arrays.asList(1, 1000, -1, -1000)) {
-                double step = 1;
-                double size = start < end ? Math.ceil((end - start) / step) : 0;
-                double[] exp = new double[(int) size];
-                for (long i = 0; i < size; i++) {
-                    exp[(int) i] = start + i * step;
-                }
-
-                double[] inc = DoubleStream.range(start, end).toArray();
-                assertEquals(inc.length, (int) size);
-                assertTrue(Arrays.equals(exp, inc));
-
-                withData(doubleRangeData(start, end, step)).stream(s -> s).
-                        expectedResult(exp).exercise();
-            }
-        }
-
-        // With step
-        for (double start : Arrays.asList(1, 1000, -1, -1000)) {
-            for (double end : Arrays.asList(1, 1000, -1, -1000)) {
-                for (double step : Arrays.asList(1, -1, -2, 2)) {
-                    if (step <= 0)
-                        continue;
-                    double size = start < end ? Math.ceil((end - start) / step) : 0;
-                    double[] exp = new double[(int) size];
-                    for (long i = 0; i < size; i++) {
-                        exp[(int) i] = start + i * step;
-                    }
-
-                    double[] inc = DoubleStream.range(start, end, step).toArray();
-                    assertEquals(inc.length, (int) size);
-                    assertTrue(Arrays.equals(exp, inc));
-
-                    withData(doubleRangeData(start, end, step)).stream(s -> s).
-                            expectedResult(exp).exercise();
-                }
-            }
-        }
-
-        // With non-integer values
-        for (double step : Arrays.asList(Math.PI / 1000.0, Math.PI / 1000.0, Math.PI / 10000.0)) {
-            double start = -Math.PI;
-            double end = Math.PI;
-            double size = start < end ? Math.ceil((end - start) / step) : 0;
-            double[] exp = new double[(int) size];
-            for (long i = 0; i < size; i++) {
-                exp[(int) i] = start + i * step;
-            }
-
-            withData(doubleRangeData(start, end, step)).stream(s -> s).
-                    expectedResult(exp).exercise();
-        }
-    }
-
-    TestData.OfDouble doubleRangeData(double start, double end, double step) {
-        return TestData.Factory.ofDoubleSupplier("double range", () -> DoubleStream.range(start, end, step));
-    }
-
-    public void tesDoubleRangeReduce() {
-        withData(doubleRangeData(0, 10000, 1)).
-                terminal(s -> s.reduce(0, Double::sum)).exercise();
-    }
-
-    public void testDoubleInfiniteRangeLimit() {
-        withData(TestData.Factory.ofDoubleSupplier(
-                "double range", () -> DoubleStream.iterate(0, i -> i + 1).limit(10000))).
-                terminal(s -> s.reduce(0, Double::sum)).exercise();
-    }
-
-    public void testDoubleInfiniteRangeFindFirst() {
-        double first = DoubleStream.iterate(0, i -> i + 1).filter(i -> i > 10000).findFirst().getAsDouble();
-        assertEquals(first, DoubleStream.iterate(0, i -> i + 1).parallel().filter(i -> i > 10000).findFirst().getAsDouble());
-    }
-
-    //
-
-    private static int[] reverse(int[] a) {
-        int[] b = new int[a.length];
-        for (int i = 0; i < a.length; i++) {
-            b[b.length - i - 1] = a[i];
-        }
-        return b;
-    }
-
-    private static long[] reverse(long[] a) {
-        long[] b = new long[a.length];
-        for (int i = 0; i < a.length; i++) {
-            b[b.length - i - 1] = a[i];
-        }
-        return b;
-    }
-
-    private static double[] reverse(double[] a) {
-        double[] b = new double[a.length];
-        for (int i = 0; i < a.length; i++) {
-            b[b.length - i - 1] = a[i];
-        }
-        return b;
-    }
-
-    private void executeAndCatch(Runnable r) {
-        executeAndCatch(IllegalArgumentException.class, r);
-    }
-
-    private void executeAndNoCatch(Runnable r) {
-        executeAndCatch(null, r);
-    }
-
-    private void executeAndCatch(Class<? extends Exception> expected, Runnable r) {
-        Exception caught = null;
-        try {
-            r.run();
-        }
-        catch (Exception e) {
-            caught = e;
-        }
-
-        if (expected != null) {
-            assertNotNull(caught,
-                          String.format("No Exception was thrown, expected an Exception of %s to be thrown",
-                                        expected.getName()));
-            assertTrue(expected.isInstance(caught),
-                       String.format("Exception thrown %s not an instance of %s",
-                                     caught.getClass().getName(), expected.getName()));
-        }
-        else {
-            if (caught != null) {
-                assertNull(caught,
-                           String.format("Unexpected exception of %s was thrown",
-                                         caught.getClass().getName()));
-            }
-        }
-    }
-
+    // Enable when Stream.concat is present and range implementations are
+    // updated to use that
+//    private static void assertSizedAndSubSized(Spliterator<?> s) {
+//        assertTrue(s.hasCharacteristics(Spliterator.SIZED | Spliterator.SUBSIZED));
+//    }
+//
+//    private static void assertNotSizedAndSubSized(Spliterator<?> s) {
+//        assertFalse(s.hasCharacteristics(Spliterator.SIZED | Spliterator.SUBSIZED));
+//    }
+//
+//    public void testLongLongRange() {
+//        // Test [Long.MIN_VALUE, Long.MAX_VALUE)
+//        // This will concatenate streams of three ranges
+//        //   [Long.MIN_VALUE, x) [x, 0) [0, Long.MAX_VALUE)
+//        // where x = Long.divideUnsigned(0 - Long.MIN_VALUE, 2) + 1
+//        {
+//            Spliterator.OfLong s = LongStream.range(Long.MIN_VALUE, Long.MAX_VALUE).spliterator();
+//
+//            assertEquals(s.estimateSize(), Long.MAX_VALUE);
+//            assertNotSizedAndSubSized(s);
+//
+//            Spliterator.OfLong s1 = s.trySplit();
+//            assertNotSizedAndSubSized(s1);
+//            assertSizedAndSubSized(s);
+//
+//            Spliterator.OfLong s2 = s1.trySplit();
+//            assertSizedAndSubSized(s1);
+//            assertSizedAndSubSized(s2);
+//
+//            assertTrue(s.estimateSize() == Long.MAX_VALUE);
+//            assertTrue(s1.estimateSize() < Long.MAX_VALUE);
+//            assertTrue(s2.estimateSize() < Long.MAX_VALUE);
+//
+//            assertEquals(s.estimateSize() + s1.estimateSize() + s2.estimateSize(),
+//                         Long.MAX_VALUE - Long.MIN_VALUE);
+//        }
+//
+//        long[][] ranges = { {Long.MIN_VALUE, 0}, {-1, Long.MAX_VALUE} };
+//        for (int i = 0; i < ranges.length; i++) {
+//            long start = ranges[i][0];
+//            long end = ranges[i][1];
+//
+//            Spliterator.OfLong s = LongStream.range(start, end).spliterator();
+//
+//            assertEquals(s.estimateSize(), Long.MAX_VALUE);
+//            assertNotSizedAndSubSized(s);
+//
+//            Spliterator.OfLong s1 = s.trySplit();
+//            assertSizedAndSubSized(s1);
+//            assertSizedAndSubSized(s);
+//
+//            assertTrue(s.estimateSize() < Long.MAX_VALUE);
+//            assertTrue(s1.estimateSize() < Long.MAX_VALUE);
+//
+//            assertEquals(s.estimateSize() + s1.estimateSize(), end - start);
+//        }
+//    }
+//
+//    public void testLongLongRangeClosed() {
+//        // Test [Long.MIN_VALUE, Long.MAX_VALUE]
+//        // This will concatenate streams of four ranges
+//        //   [Long.MIN_VALUE, x) [x, 0) [0, y) [y, Long.MAX_VALUE]
+//        // where x = Long.divideUnsigned(0 - Long.MIN_VALUE, 2) + 1
+//        //       y = Long.divideUnsigned(Long.MAX_VALUE, 2) + 1
+//
+//        {
+//            Spliterator.OfLong s = LongStream.rangeClosed(Long.MIN_VALUE, Long.MAX_VALUE).spliterator();
+//
+//            assertEquals(s.estimateSize(), Long.MAX_VALUE);
+//            assertNotSizedAndSubSized(s);
+//
+//            Spliterator.OfLong s1 = s.trySplit();
+//            assertNotSizedAndSubSized(s1);
+//            assertNotSizedAndSubSized(s);
+//
+//            Spliterator.OfLong s2 = s1.trySplit();
+//            assertSizedAndSubSized(s1);
+//            assertSizedAndSubSized(s2);
+//
+//            Spliterator.OfLong s3 = s.trySplit();
+//            assertSizedAndSubSized(s3);
+//            assertSizedAndSubSized(s);
+//
+//            assertTrue(s.estimateSize() < Long.MAX_VALUE);
+//            assertTrue(s3.estimateSize() < Long.MAX_VALUE);
+//            assertTrue(s1.estimateSize() < Long.MAX_VALUE);
+//            assertTrue(s2.estimateSize() < Long.MAX_VALUE);
+//
+//            assertEquals(s.estimateSize() + s3.estimateSize() + s1.estimateSize() + s2.estimateSize(),
+//                         Long.MAX_VALUE - Long.MIN_VALUE + 1);
+//        }
+//
+//        long[][] ranges = { {Long.MIN_VALUE, 0}, {-1, Long.MAX_VALUE} };
+//        for (int i = 0; i < ranges.length; i++) {
+//            long start = ranges[i][0];
+//            long end = ranges[i][1];
+//
+//            Spliterator.OfLong s = LongStream.rangeClosed(start, end).spliterator();
+//
+//            assertEquals(s.estimateSize(), Long.MAX_VALUE);
+//            assertNotSizedAndSubSized(s);
+//
+//            Spliterator.OfLong s1 = s.trySplit();
+//            assertSizedAndSubSized(s1);
+//            assertSizedAndSubSized(s);
+//
+//            assertTrue(s.estimateSize() < Long.MAX_VALUE);
+//            assertTrue(s1.estimateSize() < Long.MAX_VALUE);
+//
+//            assertEquals(s.estimateSize() + s1.estimateSize(), end - start + 1);
+//        }
+//    }
 }
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SortedOpTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -150,7 +150,7 @@
     }
 
     private IntStream unknownSizeIntStream(int[] a) {
-        return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(Spliterators.iteratorFromSpliterator(Arrays.spliterator(a)), 0));
+        return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0));
     }
 
     @Test(dataProvider = "IntStreamTestData", dataProviderClass = IntStreamTestDataProvider.class)
@@ -193,7 +193,7 @@
     }
 
     private LongStream unknownSizeLongStream(long[] a) {
-        return StreamSupport.longStream(Spliterators.spliteratorUnknownSize(Spliterators.iteratorFromSpliterator(Arrays.spliterator(a)), 0));
+        return StreamSupport.longStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0));
     }
 
     @Test(dataProvider = "LongStreamTestData", dataProviderClass = LongStreamTestDataProvider.class)
@@ -236,7 +236,7 @@
     }
 
     private DoubleStream unknownSizeDoubleStream(double[] a) {
-        return StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(Spliterators.iteratorFromSpliterator(Arrays.spliterator(a)), 0));
+        return StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(a)), 0));
     }
 
     @Test(dataProvider = "DoubleStreamTestData", dataProviderClass = DoubleStreamTestDataProvider.class)
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamBuilderTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamBuilderTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -275,7 +275,7 @@
     @Test(dataProvider = "sizes")
     public void testDoubleAfterBuilding(int size) {
         StreamBuilder.OfDouble sb = DoubleStream.builder();
-        DoubleStream.range(0, size).forEach(sb);
+        IntStream.range(0, size).asDoubleStream().forEach(sb);
         sb.build();
 
         checkISE(() -> sb.accept(1));
@@ -287,13 +287,13 @@
     public void testDoubleStreamBuilder(int size) {
         testDoubleStreamBuilder(size, (s) -> {
             StreamBuilder.OfDouble sb = DoubleStream.builder();
-            DoubleStream.range(0, s).forEach(sb);
+            IntStream.range(0, s).asDoubleStream().forEach(sb);
             return sb.build();
         });
 
         testDoubleStreamBuilder(size, (s) -> {
             StreamBuilder.OfDouble sb = DoubleStream.builder();
-            DoubleStream.range(0, s).forEach(i -> {
+            IntStream.range(0, s).asDoubleStream().forEach(i -> {
                 StreamBuilder.OfDouble _sb = sb.add(i);
                 assertTrue(sb == _sb);
             });
@@ -307,12 +307,12 @@
 
         withData(data).
                 stream(s -> s).
-                expectedResult(DoubleStream.range(0, size).toArray()).
+                expectedResult(IntStream.range(0, size).asDoubleStream().toArray()).
                 exercise();
 
         withData(data).
                 stream(s -> s.map(i -> i)).
-                expectedResult(DoubleStream.range(0, size).toArray()).
+                expectedResult(IntStream.range(0, size).asDoubleStream().toArray()).
                 exercise();
     }
 
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamSpliteratorTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamSpliteratorTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -526,7 +526,7 @@
                 for (boolean proxyEstimateSize : new boolean[]{false, true}) {
                     // Size is assumed to be larger than the target size for no splitting
                     // @@@ Need way to obtain the target size
-                    Spliterator.OfDouble sp = intermediateOp.apply(DoubleStream.range(0, 1000)).spliterator();
+                    Spliterator.OfDouble sp = intermediateOp.apply(IntStream.range(0, 1000).asDoubleStream()).spliterator();
                     ProxyNoExactSizeSpliterator.OfDouble psp = new ProxyNoExactSizeSpliterator.OfDouble(sp, proxyEstimateSize);
                     DoubleStream s = StreamSupport.doubleParallelStream(psp);
                     terminalOp.accept(s);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/print/PrintServiceLookup/GetPrintServices.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import javax.print.PrintService;
+import javax.print.PrintServiceLookup;
+import javax.print.attribute.AttributeSet;
+import javax.print.attribute.HashAttributeSet;
+import javax.print.attribute.standard.PrinterName;
+
+/*
+ * @test
+ * @bug 8013810
+ * @summary Test that print service returned without filter are of the same class as with name filter
+ */
+public class GetPrintServices {
+
+  public static void main(String[] args) throws Exception {
+    for (PrintService service : PrintServiceLookup.lookupPrintServices(null, null)) {
+      String serviceName = service.getName();
+      PrintService serviceByName = lookupByName(serviceName);
+      if (!service.equals(serviceByName)) {
+        throw new RuntimeException("NOK " + serviceName
+                                   + " expected: " + service.getClass().getName()
+                                   + " got: " + serviceByName.getClass().getName());
+      }
+    }
+    System.out.println("Test PASSED");
+  }
+
+  private static PrintService lookupByName(String name) {
+    AttributeSet attributes = new HashAttributeSet();
+    attributes.add(new PrinterName(name, null));
+    for (PrintService service : PrintServiceLookup.lookupPrintServices(null, attributes)) {
+      return service;
+    }
+    return null;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JFileChooser/8013442/Test8013442.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 8013442
+ * @summary Tests that at least one file filter is selected
+ * @author Sergey Malenkov
+ */
+
+import java.io.File;
+import java.util.concurrent.CountDownLatch;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.SwingUtilities;
+import javax.swing.UIManager;
+import javax.swing.UIManager.LookAndFeelInfo;
+import javax.swing.filechooser.FileFilter;
+
+public class Test8013442 extends FileFilter implements Runnable, Thread.UncaughtExceptionHandler {
+    private static final CountDownLatch LATCH = new CountDownLatch(1);
+
+    public static void main(String[] args) throws InterruptedException {
+        SwingUtilities.invokeLater(new Test8013442());
+        LATCH.await(); // workaround for jtreg
+    }
+
+    private int index;
+    private LookAndFeelInfo[] infos;
+    private JFileChooser chooser;
+
+    @Override
+    public boolean accept(File file) {
+        return !file.isFile() || file.getName().toLowerCase().endsWith(".txt");
+    }
+
+    @Override
+    public String getDescription() {
+        return "Text files";
+    }
+
+    @Override
+    public void run() {
+        if (this.infos == null) {
+            this.infos = UIManager.getInstalledLookAndFeels();
+            Thread.currentThread().setUncaughtExceptionHandler(this);
+        }
+        if (this.infos.length == this.index) {
+            LATCH.countDown(); // release main thread
+        } else if (this.chooser == null) {
+            // change LaF before creation of Swing components
+            LookAndFeelInfo info = this.infos[this.index];
+            System.out.println(info.getName());
+            try {
+                UIManager.setLookAndFeel(info.getClassName());
+            }
+            catch (Exception exception) {
+                throw new Error("could not change look and feel", exception);
+            }
+            // create and show new file chooser
+            JFrame frame = new JFrame(getClass().getSimpleName());
+            frame.add(this.chooser = new JFileChooser());
+            frame.setSize(800, 600);
+            frame.setLocationRelativeTo(null);
+            frame.setVisible(true);
+            SwingUtilities.invokeLater(this);
+        }
+        else {
+            int count = this.chooser.getChoosableFileFilters().length;
+            System.out.println("count = " + count + "; " + this.chooser.isAcceptAllFileFilterUsed());
+            if (count == 0) {
+                if (null != this.chooser.getFileFilter()) {
+                    throw new Error("file filter is selected");
+                }
+                // close window and stop testing file chooser for current LaF
+                SwingUtilities.getWindowAncestor(this.chooser).dispose();
+                this.chooser = null;
+                this.index++;
+            } else {
+                if (null == this.chooser.getFileFilter()) {
+                    throw new Error("file filter is not selected");
+                }
+                if (count == 2) {
+                    // remove default file filter
+                    this.chooser.setAcceptAllFileFilterUsed(false);
+                } else if (this.chooser.isAcceptAllFileFilterUsed()) {
+                    // remove add file filter
+                    this.chooser.addChoosableFileFilter(this);
+                } else {
+                    // remove custom file filter
+                    this.chooser.removeChoosableFileFilter(this);
+                }
+            }
+            SwingUtilities.invokeLater(this);
+        }
+    }
+
+    public void uncaughtException(Thread thread, Throwable throwable) {
+        throwable.printStackTrace();
+        System.exit(1);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JMenu/4692443/bug4692443.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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
+ * @library ../../regtesthelpers
+ * @build Util
+ * @bug 4692443 7105030
+ * @summary JMenu: MenuListener.menuSelected() event fired too late when using mnemonics
+ * @author Alexander Zuev
+ * @run main bug4692443
+ */
+
+import javax.swing.*;
+import javax.swing.event.*;
+import java.awt.event.*;
+import java.awt.*;
+import sun.awt.SunToolkit;
+
+public class bug4692443 {
+
+    public static PassedListener pass;
+    public static FailedListener fail;
+    public static volatile Boolean passed;
+
+    public static void main(String args[]) throws Throwable {
+
+        fail = new FailedListener();
+        pass = new PassedListener();
+        passed = false;
+        Robot robo = new Robot();
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                createAndShowGUI();
+            }
+        });
+
+        SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
+        toolkit.realSync();
+
+        try {
+                robo = new Robot();
+            } catch (AWTException e) {
+                throw new RuntimeException("Robot could not be created");
+            }
+            int altKey = java.awt.event.KeyEvent.VK_ALT;
+            robo.setAutoDelay(100);
+            Util.hitMnemonics(robo, KeyEvent.VK_F); // Enter File menu
+            robo.keyPress(KeyEvent.VK_S);  // Enter submenu
+            robo.keyRelease(KeyEvent.VK_S);
+            robo.keyPress(KeyEvent.VK_O); // Launch "One" action
+            robo.keyRelease(KeyEvent.VK_O);
+            robo.keyPress(KeyEvent.VK_M); // Launch "One" action
+            robo.keyRelease(KeyEvent.VK_M);
+
+            toolkit.realSync();
+
+            if (!passed) {
+                throw new RuntimeException("Test failed.");
+            }
+
+    }
+
+    private static void createAndShowGUI() {
+        JFrame mainFrame = new JFrame("Bug 4692443");
+        JMenuBar mbar = new JMenuBar();
+        JMenu menu = new JMenu("File");
+        menu.setMnemonic('F');
+        menu.add(new JMenuItem("Menu Item 1")).setMnemonic('I');
+        final JMenu submenu = new JMenu("Submenu");
+        submenu.setMnemonic('S');
+        submenu.addMenuListener(new MenuListener() {
+            public void menuSelected(MenuEvent e) {
+                JMenuItem item = submenu.add(new JMenuItem("One", 'O'));
+                item.addActionListener(pass);
+                submenu.add(new JMenuItem("Two", 'w'));
+                submenu.add(new JMenuItem("Three", 'r'));
+            }
+            public void menuDeselected(MenuEvent e) {
+                submenu.removeAll();
+            }
+            public void menuCanceled(MenuEvent e) {
+                submenu.removeAll();
+            }
+        });
+        menu.add(submenu);
+        JMenuItem menuItem = menu.add(new JMenuItem("Menu Item 2"));
+        menuItem.setMnemonic('M');
+        menuItem.addActionListener(fail);
+        mbar.add(menu);
+        mainFrame.setJMenuBar(mbar);
+
+        mainFrame.setSize(200, 200);
+        mainFrame.setLocation(200, 200);
+        mainFrame.setVisible(true);
+        mainFrame.toFront();
+    }
+
+    public static class FailedListener implements ActionListener {
+        public void actionPerformed(ActionEvent ev) {
+            throw new RuntimeException("Test failed.");
+        }
+    }
+
+    public static class PassedListener implements ActionListener {
+        public void actionPerformed(ActionEvent ev) {
+            passed = true;
+        }
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JTree/8013571/Test8013571.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import javax.swing.JTree;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.DefaultTreeModel;
+
+/*
+ * @test
+ * @bug 8016545
+ * @summary Tests beans with public fields
+ * @author Sergey Malenkov
+ */
+
+public class Test8013571 extends DefaultTreeModel {
+    public static void main(String[] args) {
+        DefaultMutableTreeNode root = create("root");
+        root.add(create("colors", "blue", "violet", "red", "yellow"));
+        root.add(create("sports", "basketball", "soccer", "football", "hockey"));
+        root.add(create("food", "hot dogs", "pizza", "ravioli", "bananas"));
+        Test8013571 model = new Test8013571(root);
+        JTree tree = new JTree(model);
+        model.fireTreeChanged(tree);
+    }
+
+    private static DefaultMutableTreeNode create(String name, String... values) {
+        DefaultMutableTreeNode node = new DefaultMutableTreeNode(name);
+        for (String value : values) {
+            node.add(create(value));
+        }
+        return node;
+    }
+
+    private Test8013571(DefaultMutableTreeNode root) {
+        super(root);
+    }
+
+    private void fireTreeChanged(Object source) {
+        fireTreeNodesInserted(source, null, null, null);
+        fireTreeNodesChanged(source, null, null, null);
+        fireTreeNodesRemoved(source, null, null, null);
+        fireTreeStructureChanged(source, null, null, null);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/plaf/basic/BasicComboBoxEditor/Test8015336.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import javax.swing.JComboBox;
+
+/*
+ * @test
+ * @bug 8015336
+ * @summary No NPE for BasicComboBoxEditor.setItem(null)
+ * @author Sergey Malenkov
+ */
+public class Test8015336 {
+    public static void main(String[] args) throws Exception {
+        new JComboBox().getEditor().setItem(new Test8015336());
+    }
+
+    @Override
+    public String toString() {
+        return null;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/text/View/8015853/bug8015853.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 8015853
+ * @summary  Tests the rendering of a large HTML document
+ * @author Dmitry Markov
+ * @run main bug8015853
+ */
+
+import java.io.*;
+import java.net.URL;
+import java.util.Scanner;
+import javax.swing.*;
+import javax.swing.text.html.HTMLEditorKit;
+
+public class bug8015853 {
+
+    private static String text = "";
+
+    public static void main(String[] args) throws Exception {
+
+        try {
+            URL path = ClassLoader.getSystemResource("bug8015853.txt");
+            File file = new File(path.toURI());
+            Scanner scanner = new Scanner(file);
+            while (scanner.hasNextLine()) {
+                text += scanner.nextLine() + "\n";
+            }
+            scanner.close();
+        } catch (Exception ex) {
+            throw new RuntimeException(ex);
+        }
+
+        text += text;
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            public void run() {
+                createAndShowGUI();
+            }
+        });
+    }
+
+    private static void createAndShowGUI() {
+        try {
+            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
+        } catch (Exception ex) {
+            throw new RuntimeException(ex);
+        }
+        JFrame frame = new JFrame();
+        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+
+        JEditorPane editorPane = new JEditorPane();
+        HTMLEditorKit editorKit = new HTMLEditorKit();
+        editorPane.setEditorKit(editorKit);
+        editorPane.setText(text);
+
+        frame.add(editorPane);
+        frame.setVisible(true);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/text/View/8015853/bug8015853.txt	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,67 @@
+</font><font size=2 color="#0000aa"><i>/*
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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.
+ */</font></i><font size=2 color=black>
+<b>import</b> java.io.*;
+<b>import</b> java.net.URL;
+<b>import</b> java.util.Scanner;
+<b>import</b> javax.swing.*;
+<b>import</b> javax.swing.text.html.HTMLEditorKit;
+<b>public</b> <b>class</b> bug8015853 {
+    <b>private</b> <b>static</b> String text = </font><font size=2 color="#00bb00">""</font><font size=2 color=black>;
+    <b>public</b> <b>static</b> <b>void</b> main(String[] args) throws Exception {
+    
+        <b>try</b> {
+            URL path = ClassLoader.getSystemResource(</font><font size=2 color="#00bb00">"bug8015853.txt"</font><font size=2 color=black>);
+            File file = <b>new</b> File(path.toURI());
+            Scanner scanner = <b>new</b> Scanner(file);
+            <b>while</b> (scanner.hasNextLine()) {
+                text += scanner.nextLine() + </font><font size=2 color="#00bb00">"\n"</font><font size=2 color=black>;
+            }
+            scanner.close();
+        } <b>catch</b> (Exception ex) {
+            <b>throw</b> <b>new</b> RuntimeException(ex);
+        }
+        
+        System.out.println(text);
+        
+        SwingUtilities.invokeAndWait(<b>new</b> Runnable() {
+            <b>public</b> <b>void</b> run() {
+                createAndShowGUI();
+            }
+        });
+    }
+    <b>private</b> <b>static</b> <b>void</b> createAndShowGUI() {
+        <b>try</b> {
+            UIManager.setLookAndFeel(</font><font size=2 color="#00bb00">"javax.swing.plaf.metal.MetalLookAndFeel"</font><font size=2 color=black>);
+        } <b>catch</b> (Exception ex) {
+            <b>throw</b> <b>new</b> RuntimeException(ex);
+        }
+        JFrame frame = <b>new</b> JFrame();
+        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+        JEditorPane editorPane = <b>new</b> JEditorPane();
+        HTMLEditorKit editorKit = <b>new</b> HTMLEditorKit();
+        editorPane.setEditorKit(editorKit);
+        editorPane.setText(text);
+        frame.add(editorPane);
+        frame.setVisible(<b>true</b>);
+    }
+}
\ No newline at end of file
--- a/jdk/test/javax/xml/crypto/dsig/GenerationTests.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/javax/xml/crypto/dsig/GenerationTests.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,7 +27,7 @@
  * @summary Basic unit tests for generating XML Signatures with JSR 105
  * @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java
  *     X509KeySelector.java GenerationTests.java
- * @run main GenerationTests
+ * @run main/othervm GenerationTests
  * @author Sean Mullan
  */
 
@@ -487,6 +487,7 @@
                                                Collections.singletonList(obj),
                                                "signature", null);
         DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA"), doc);
+        dsc.setIdAttributeNS(nc, null, "Id");
 
         sig.sign(dsc);
 
@@ -494,6 +495,7 @@
 
         DOMValidateContext dvc = new DOMValidateContext
             (kvks, doc.getDocumentElement());
+        dvc.setIdAttributeNS(nc, null, "Id");
         XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
 
         if (sig.equals(sig2) == false) {
--- a/jdk/test/javax/xml/crypto/dsig/SecurityManager/XMLDSigWithSecMgr.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/javax/xml/crypto/dsig/SecurityManager/XMLDSigWithSecMgr.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -140,6 +140,10 @@
             // validate a signature with SecurityManager enabled
             DOMValidateContext dvc = new DOMValidateContext
                 (kp.getPublic(), envelope.getFirstChild());
+
+            // disable secure validation mode so that http reference will work
+            dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
+
             sig = fac.unmarshalXMLSignature(dvc);
             if (!sig.validate(dvc)) {
                 throw new Exception
--- a/jdk/test/javax/xml/crypto/dsig/ValidationTests.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/javax/xml/crypto/dsig/ValidationTests.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,7 +27,7 @@
  * @summary Basic unit tests for validating XML Signatures with JSR 105
  * @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java
  *     X509KeySelector.java ValidationTests.java
- * @run main ValidationTests
+ * @run main/othervm ValidationTests
  * @author Sean Mullan
  */
 import java.io.File;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/xml/jaxp/XPath/8009579/XPathExceptionInitCause.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 8009579
+ * @summary The initCause() incorrectly initialise the cause in
+ * XPathException class when used with XPathException(String)
+ * constructor.
+ * @run main XPathExceptionInitCause
+ * @author aleksej.efimov@oracle.com
+ */
+
+import javax.xml.xpath.XPathException;
+import java.io.ByteArrayOutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectInputStream;
+import java.io.IOException;
+import java.io.InvalidClassException;
+
+
+public class XPathExceptionInitCause {
+
+    /* This is a serial form of XPathException with two causes serialized
+     * by JDK7 code:
+     *
+     *  ByteArrayOutputStream fser = new ByteArrayOutputStream();
+     *  ObjectOutputStream oos = new ObjectOutputStream(fser);
+     *  oos.writeObject(new XPathException(new Exception()).initCause(null));
+     *  oos.close();
+     */
+    static final byte [] TWOCAUSES = {-84,-19,0,5,115,114,0,30,106,97,118,97,120,46,120,
+        109,108,46,120,112,97,116,104,46,88,80,97,116,104,69,120,99,101,112,116,
+        105,111,110,-26,-127,97,60,-120,119,127,28,2,0,1,76,0,5,99,97,117,115,101,
+        116,0,21,76,106,97,118,97,47,108,97,110,103,47,84,104,114,111,119,97,98,
+        108,101,59,120,114,0,19,106,97,118,97,46,108,97,110,103,46,69,120,99,101,
+        112,116,105,111,110,-48,-3,31,62,26,59,28,-60,2,0,0,120,114,0,19,106,97,
+        118,97,46,108,97,110,103,46,84,104,114,111,119,97,98,108,101,-43,-58,53,
+        39,57,119,-72,-53,3,0,4,76,0,5,99,97,117,115,101,113,0,126,0,1,76,0,13,
+        100,101,116,97,105,108,77,101,115,115,97,103,101,116,0,18,76,106,97,118,
+        97,47,108,97,110,103,47,83,116,114,105,110,103,59,91,0,10,115,116,97,99,
+        107,84,114,97,99,101,116,0,30,91,76,106,97,118,97,47,108,97,110,103,47,83,
+        116,97,99,107,84,114,97,99,101,69,108,101,109,101,110,116,59,76,0,20,115,
+        117,112,112,114,101,115,115,101,100,69,120,99,101,112,116,105,111,110,115,
+        116,0,16,76,106,97,118,97,47,117,116,105,108,47,76,105,115,116,59,120,112,
+        112,112,117,114,0,30,91,76,106,97,118,97,46,108,97,110,103,46,83,116,97,99,
+        107,84,114,97,99,101,69,108,101,109,101,110,116,59,2,70,42,60,60,-3,34,57,
+        2,0,0,120,112,0,0,0,1,115,114,0,27,106,97,118,97,46,108,97,110,103,46,83,
+        116,97,99,107,84,114,97,99,101,69,108,101,109,101,110,116,97,9,-59,-102,
+        38,54,-35,-123,2,0,4,73,0,10,108,105,110,101,78,117,109,98,101,114,76,0,
+        14,100,101,99,108,97,114,105,110,103,67,108,97,115,115,113,0,126,0,4,76,
+        0,8,102,105,108,101,78,97,109,101,113,0,126,0,4,76,0,10,109,101,116,104,
+        111,100,78,97,109,101,113,0,126,0,4,120,112,0,0,0,31,116,0,23,88,80,97,116,
+        104,69,120,99,101,112,116,105,111,110,83,101,114,105,97,108,105,122,101,
+        116,0,28,88,80,97,116,104,69,120,99,101,112,116,105,111,110,83,101,114,105,
+        97,108,105,122,101,46,106,97,118,97,116,0,4,109,97,105,110,115,114,0,38,
+        106,97,118,97,46,117,116,105,108,46,67,111,108,108,101,99,116,105,111,110,
+        115,36,85,110,109,111,100,105,102,105,97,98,108,101,76,105,115,116,-4,15,
+        37,49,-75,-20,-114,16,2,0,1,76,0,4,108,105,115,116,113,0,126,0,6,120,114,
+        0,44,106,97,118,97,46,117,116,105,108,46,67,111,108,108,101,99,116,105,111,
+        110,115,36,85,110,109,111,100,105,102,105,97,98,108,101,67,111,108,108,101,
+        99,116,105,111,110,25,66,0,-128,-53,94,-9,30,2,0,1,76,0,1,99,116,0,22,76,
+        106,97,118,97,47,117,116,105,108,47,67,111,108,108,101,99,116,105,111,110,
+        59,120,112,115,114,0,19,106,97,118,97,46,117,116,105,108,46,65,114,114,97,
+        121,76,105,115,116,120,-127,-46,29,-103,-57,97,-99,3,0,1,73,0,4,115,105,
+        122,101,120,112,0,0,0,0,119,4,0,0,0,0,120,113,0,126,0,20,120,115,113,0,126,
+        0,2,113,0,126,0,21,112,117,113,0,126,0,8,0,0,0,1,115,113,0,126,0,10,0,0,0,
+        31,113,0,126,0,12,113,0,126,0,13,113,0,126,0,14,113,0,126,0,18,120
+    };
+
+    /* This is a serial form of ordinary XPathException serialized by JDK7 code:
+     *
+     *  Throwable cause = new Throwable( "message 1" );
+     *  XPathException xpathexcep = new XPathException( "message 2" );
+     *  xpathexcep.initCause( cause );
+     *  ByteArrayOutputStream fser = new ByteArrayOutputStream();
+     *  ObjectOutputStream oos = new ObjectOutputStream(fser);
+     *  oos.writeObject(xpathexcep);
+     *  oos.close();
+     */
+    static final byte [] NORMALJDK7SER = {-84,-19,0,5,115,114,0,30,106,97,118,97,120,
+        46,120,109,108,46,120,112,97,116,104,46,88,80,97,116,104,69,120,99,101,112,
+        116,105,111,110,-26,-127,97,60,-120,119,127,28,2,0,1,76,0,5,99,97,117,115,
+        101,116,0,21,76,106,97,118,97,47,108,97,110,103,47,84,104,114,111,119,97,
+        98,108,101,59,120,114,0,19,106,97,118,97,46,108,97,110,103,46,69,120,99,
+        101,112,116,105,111,110,-48,-3,31,62,26,59,28,-60,2,0,0,120,114,0,19,106,
+        97,118,97,46,108,97,110,103,46,84,104,114,111,119,97,98,108,101,-43,-58,
+        53,39,57,119,-72,-53,3,0,4,76,0,5,99,97,117,115,101,113,0,126,0,1,76,0,13,
+        100,101,116,97,105,108,77,101,115,115,97,103,101,116,0,18,76,106,97,118,
+        97,47,108,97,110,103,47,83,116,114,105,110,103,59,91,0,10,115,116,97,99,
+        107,84,114,97,99,101,116,0,30,91,76,106,97,118,97,47,108,97,110,103,47,83,
+        116,97,99,107,84,114,97,99,101,69,108,101,109,101,110,116,59,76,0,20,115,
+        117,112,112,114,101,115,115,101,100,69,120,99,101,112,116,105,111,110,115,
+        116,0,16,76,106,97,118,97,47,117,116,105,108,47,76,105,115,116,59,120,112,
+        115,113,0,126,0,3,113,0,126,0,8,116,0,9,109,101,115,115,97,103,101,32,49,
+        117,114,0,30,91,76,106,97,118,97,46,108,97,110,103,46,83,116,97,99,107,84,
+        114,97,99,101,69,108,101,109,101,110,116,59,2,70,42,60,60,-3,34,57,2,0,0,
+        120,112,0,0,0,1,115,114,0,27,106,97,118,97,46,108,97,110,103,46,83,116,97,
+        99,107,84,114,97,99,101,69,108,101,109,101,110,116,97,9,-59,-102,38,54,-35,
+        -123,2,0,4,73,0,10,108,105,110,101,78,117,109,98,101,114,76,0,14,100,101,
+        99,108,97,114,105,110,103,67,108,97,115,115,113,0,126,0,4,76,0,8,102,105,
+        108,101,78,97,109,101,113,0,126,0,4,76,0,10,109,101,116,104,111,100,78,97,
+        109,101,113,0,126,0,4,120,112,0,0,0,19,116,0,23,88,80,97,116,104,69,120,
+        99,101,112,116,105,111,110,83,101,114,105,97,108,105,122,101,116,0,28,88,
+        80,97,116,104,69,120,99,101,112,116,105,111,110,83,101,114,105,97,108,105,
+        122,101,46,106,97,118,97,116,0,4,109,97,105,110,115,114,0,38,106,97,118,
+        97,46,117,116,105,108,46,67,111,108,108,101,99,116,105,111,110,115,36,85,
+        110,109,111,100,105,102,105,97,98,108,101,76,105,115,116,-4,15,37,49,-75,
+        -20,-114,16,2,0,1,76,0,4,108,105,115,116,113,0,126,0,6,120,114,0,44,106,
+        97,118,97,46,117,116,105,108,46,67,111,108,108,101,99,116,105,111,110,115,
+        36,85,110,109,111,100,105,102,105,97,98,108,101,67,111,108,108,101,99,116,
+        105,111,110,25,66,0,-128,-53,94,-9,30,2,0,1,76,0,1,99,116,0,22,76,106,97,
+        118,97,47,117,116,105,108,47,67,111,108,108,101,99,116,105,111,110,59,120,
+        112,115,114,0,19,106,97,118,97,46,117,116,105,108,46,65,114,114,97,121,76,
+        105,115,116,120,-127,-46,29,-103,-57,97,-99,3,0,1,73,0,4,115,105,122,101,
+        120,112,0,0,0,0,119,4,0,0,0,0,120,113,0,126,0,22,120,116,0,9,109,101,115,
+        115,97,103,101,32,50,117,113,0,126,0,10,0,0,0,1,115,113,0,126,0,12,0,0,0,
+        20,113,0,126,0,14,113,0,126,0,15,113,0,126,0,16,113,0,126,0,20,120,112
+    };
+
+    //Serialize XPathException
+    static byte [] pickleXPE(XPathException xpe) throws IOException {
+        ByteArrayOutputStream bos =  new ByteArrayOutputStream();
+        ObjectOutputStream xpeos = new ObjectOutputStream(bos);
+        xpeos.writeObject(xpe);
+        xpeos.close();
+        return bos.toByteArray();
+    }
+
+    //Deserialize XPathException with byte array as serial data source
+    static XPathException unpickleXPE(byte [] ser)
+            throws IOException, ClassNotFoundException {
+        XPathException xpe;
+        ByteArrayInputStream bis = new ByteArrayInputStream(ser);
+        ObjectInputStream xpeis = new ObjectInputStream(bis);
+        xpe = (XPathException) xpeis.readObject();
+        xpeis.close();
+        return xpe;
+    }
+
+    public static void main(String[] args) throws Exception {
+        Throwable cause = new Throwable("message 1");
+        XPathException xpathexcep = new XPathException("message 2");
+
+        //Test XPE initCause() method
+        xpathexcep.initCause(cause);
+        System.out.println("getCause() result: '" + xpathexcep.getCause()
+                + "' Cause itself: '" + cause + "'");
+        if (!xpathexcep.getCause().toString().equals(cause.toString())) {
+            throw new Exception("Incorrect cause is set by initCause()");
+        }
+
+        //Test serialization/deserialization of initialized XPE
+        byte [] xpeserial;
+        XPathException xpedeser;
+        xpeserial = pickleXPE(xpathexcep);
+        xpedeser = unpickleXPE(xpeserial);
+        System.out.println("Serialized XPE: message='" + xpathexcep.getMessage()
+                + "' cause='" + xpathexcep.getCause().toString() + "'");
+        System.out.println("Deserialized XPE: message='" + xpedeser.getMessage()
+                + "' cause='" + xpedeser.getCause().toString()+"'");
+        if(xpedeser.getCause() == null ||
+                !xpedeser.getCause().toString().equals(cause.toString()) ||
+                !xpedeser.getMessage().toString().equals("message 2") )
+            throw new Exception("XPathException incorrectly serialized/deserialized");
+
+        //Test serialization/deserialization of uninitialized cause in XPE
+        XPathException xpeuninit = new XPathException("uninitialized cause");
+        xpeserial = pickleXPE(xpeuninit);
+        xpedeser = unpickleXPE(xpeserial);
+        System.out.println("Serialized XPE: message='" + xpeuninit.getMessage()
+                + "' cause='" + xpeuninit.getCause()+"'");
+        System.out.println("Deserialized XPE: message='" + xpedeser.getMessage()
+                + "' cause='" + xpedeser.getCause()+"'");
+        if(xpedeser.getCause() != null ||
+                !xpedeser.getMessage().toString().equals("uninitialized cause") )
+            throw new Exception("XPathException incorrectly serialized/deserialized");
+
+        //Test deserialization of normal XPathException serialized by JDK7
+        XPathException xpejdk7 = unpickleXPE(NORMALJDK7SER);
+        if(xpejdk7 == null || xpejdk7.getCause() == null ||
+                !xpejdk7.getMessage().equals("message 2") ||
+                !xpejdk7.getCause().getMessage().equals("message 1"))
+            throw new Exception("XpathException serialized by JDK7 was "
+                    + "incorrectly deserialized.");
+
+        //Test deserialization of XPathException with two causes from JDK7.
+        //The serialization are done for the following XPathException object:
+        // new XPathException(new Exception()).initCause(null)
+        try {
+            xpejdk7 = unpickleXPE(TWOCAUSES);
+            throw new Exception("Expected InvalidClassException but it wasn't"
+                    + " observed");
+        } catch(InvalidClassException e) {
+            System.out.println("InvalidClassException caught as expected.");
+        }
+
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/xml/jaxp/XPath/8015978/XPathNegativeZero.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 8015978
+ * @summary Incorrect transformation of XPath expression "string(-0)"
+ * @run main XPathNegativeZero
+ * @author aleksej.efimov@oracle.com
+ */
+
+import java.io.File;
+import java.io.StringWriter;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.Templates;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.Source;
+import javax.xml.transform.Result;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.transform.stream.StreamResult;
+
+
+public class XPathNegativeZero {
+
+    static final String EXPECTEDXML = "<newtop>\"0\"</newtop>";
+
+    public static void main(final String[] args) throws Exception {
+        //file name of XML file to transform
+        final String xml = System.getProperty("test.src", ".")+"/dummy.xml";
+        //file name of XSL file w/ transformation
+        final String xsl = System.getProperty("test.src", ".")+"/negativezero.xsl";
+        final String result = xform(xml, xsl).trim();
+
+        System.out.println("transformed XML: '"+result+ "' expected XML: '"+EXPECTEDXML+"'");
+        if (!result.equals(EXPECTEDXML))
+            throw new Exception("Negative zero was incorrectly transformed");
+    }
+
+    private static String xform(final String xml, final String xsl) throws Exception {
+        final TransformerFactory tf = TransformerFactory.newInstance();
+        final Source xslsrc = new StreamSource(new File(xsl));
+        final Templates tmpl = tf.newTemplates(xslsrc);
+        final Transformer t = tmpl.newTransformer();
+
+        StringWriter writer = new StringWriter();
+        final Source src = new StreamSource(new File(xml));
+        final Result res = new StreamResult(writer);
+
+        t.transform(src, res);
+        return writer.toString();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/xml/jaxp/XPath/8015978/dummy.xml	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,1 @@
+<top/>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/xml/jaxp/XPath/8015978/negativezero.xsl	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,4 @@
+<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
+   <xsl:output method='xml' indent='yes' omit-xml-declaration='yes'/>
+   <xsl:template match='/'><newtop>"<xsl:value-of select='string(-0.0)'/>"</newtop></xsl:template>
+</xsl:stylesheet>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/lib/testlibrary/ClassFileInstaller.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+
+/**
+ * Dump a class file for a class on the class path in the current directory
+ */
+public class ClassFileInstaller {
+    /**
+     * @param args The names of the classes to dump
+     * @throws Exception
+     */
+    public static void main(String... args) throws Exception {
+        for (String arg : args) {
+            ClassLoader cl = ClassFileInstaller.class.getClassLoader();
+
+            // Convert dotted class name to a path to a class file
+            String pathName = arg.replace('.', '/').concat(".class");
+            InputStream is = cl.getResourceAsStream(pathName);
+
+            // Create the class file's package directory
+            Path p = Paths.get(pathName);
+            Files.createDirectories(p.getParent());
+            // Create the class file
+            Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/awt/AppContext/8012933/Test8012933.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 8012933
+ * @summary Tests (although somewhat indirectly) that createNewAppContext()
+ * immediately followed by dispose() works correctly
+ * @author Leonid Romanov
+ */
+
+import sun.awt.SunToolkit;
+import sun.awt.AppContext;
+
+public class Test8012933 {
+    private AppContext appContext = null;
+    final ThreadGroup threadGroup = new ThreadGroup("test thread group");
+    final Object lock = new Object();
+    boolean isCreated = false;
+
+    public static void main(String[] args) throws Exception {
+        SunToolkit.createNewAppContext();
+        new Test8012933().test();
+    }
+
+    private void test() throws Exception {
+        createAppContext();
+        long startTime = System.currentTimeMillis();
+        appContext.dispose();
+        long endTime = System.currentTimeMillis();
+
+        // In case of the bug, calling dispose() when there is no EQ
+        // dispatch thread running fails to create it, so it takes
+        // almost 10 sec to return from dispose(), which is spent
+        // waiting on the notificationLock.
+        if ((endTime - startTime) > 9000) {
+            throw new RuntimeException("Returning from dispose() took too much time, probably a bug");
+        }
+    }
+
+    private void createAppContext() {
+        isCreated = false;
+        final Runnable runnable = new Runnable() {
+                public void run() {
+                    appContext = SunToolkit.createNewAppContext();
+                    synchronized (lock) {
+                        isCreated = true;
+                        lock.notifyAll();
+                    }
+                }
+            };
+
+        final Thread thread = new Thread(threadGroup, runnable, "creates app context");
+        synchronized (lock) {
+            thread.start();
+            while (!isCreated) {
+                try {
+                    lock.wait();
+                } catch (InterruptedException ie) {
+                    ie.printStackTrace();
+                }
+            }
+        }
+
+        if (appContext == null) {
+            throw new RuntimeException("failed to create app context.");
+        } else {
+            System.out.println("app context was created.");
+        }
+    }
+
+}
--- a/jdk/test/sun/java2d/cmm/ColorConvertOp/ColConvCCMTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/java2d/cmm/ColorConvertOp/ColConvCCMTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -23,7 +23,7 @@
 
 /**
  * @test
- * @bug 6476665 7033534
+ * @bug 6476665 7033534 6830714
  * @summary Verifies color conversion of Component Color Model based images
  * @run main ColConvCCMTest
  */
@@ -57,9 +57,9 @@
     final static double [] ACCURACY = {
     // Accuracy for color conversions
         2.5,        // sRGB
-        6.5,        // LINEAR_RGB
+        (isOpenProfile() ? 45.0 : 10.1), // LINEAR_RGB
         10.5,       // GRAY
-        45.5,       // PYCC
+        (isOpenProfile() ? 207 : 45.5), // PYCC
         47.5        // CIEXYZ
     };
 
--- a/jdk/test/sun/java2d/cmm/ColorConvertOp/ColConvDCMTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/java2d/cmm/ColorConvertOp/ColConvDCMTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -62,7 +62,11 @@
         ColorSpace.CS_LINEAR_RGB,
     };
 
-    final static double ACCURACY = 2.5;
+    final static double [] ACCURACY = {
+        // Accuracy for color conversions
+        2.5, // sRGB
+        (isOpenProfile() ? 45.0 : 2.5), // LINEAR_RGB
+    };
 
     final static String [] gldImgNames = {
         "SRGB.png", "SRGB555.png", "SRGB565.png", "LRGB.png", "LRGB555.png",
@@ -142,7 +146,7 @@
 
             if (!testImage(imgTypes[i][0], imgTypes[i][1], imgTypes[i][2],
                            imgTypes[i][3], cSpaces[imgTypes[i][4]], gldImage,
-                           ACCURACY))
+                           ACCURACY[imgTypes[i][4]]))
             {
                 throw new RuntimeException(
                     "Invalid result of the ColorConvertOp for " +
@@ -154,7 +158,8 @@
 
             if (!testSubImage(SI_X, SI_Y, SI_W, SI_H, imgTypes[i][0],
                               imgTypes[i][1], imgTypes[i][2], imgTypes[i][3],
-                              cSpaces[imgTypes[i][4]], gldImage, ACCURACY))
+                              cSpaces[imgTypes[i][4]], gldImage,
+                              ACCURACY[imgTypes[i][4]]))
             {
                 throw new RuntimeException(
                     "Invalid result of the ColorConvertOp for " +
--- a/jdk/test/sun/java2d/cmm/ColorConvertOp/ColConvTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/java2d/cmm/ColorConvertOp/ColConvTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -22,6 +22,7 @@
  */
 
 import java.awt.color.ColorSpace;
+import java.awt.color.ICC_Profile;
 import java.awt.image.BufferedImage;
 import java.awt.image.DataBuffer;
 
@@ -126,4 +127,33 @@
     public boolean isPassed() {
         return passed;
     }
+
+    private static Boolean isOpenProfile = null;
+
+    public static boolean isOpenProfile() {
+        if (isOpenProfile == null) {
+            ICC_Profile p = ICC_Profile.getInstance(ColorSpace.CS_sRGB);
+
+            byte[] h = p.getData(ICC_Profile.icSigHead);
+
+            if (h == null || h.length < 128) {
+                throw new RuntimeException("Test failed: invalid sRGB header");
+            }
+
+            final byte[] lcmsID = new byte[] {
+                (byte)0x6c, // l
+                (byte)0x63, // c
+                (byte)0x6d, // m
+                (byte)0x73, // s
+            };
+
+            int off = ICC_Profile.icHdrCmmId;
+
+            isOpenProfile = ((h[off + 0] == lcmsID[0])
+                    && (h[off + 1] == lcmsID[1])
+                    && (h[off + 2] == lcmsID[2])
+                    && (h[off + 3] == lcmsID[3]));
+        }
+        return isOpenProfile;
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/misc/FloatingDecimal/OldFDBigIntForTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,491 @@
+/*
+ * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+//package sun.misc;
+
+/*
+ * A really, really simple bigint package
+ * tailored to the needs of floating base conversion.
+ */
+class OldFDBigIntForTest {
+    int nWords; // number of words used
+    int data[]; // value: data[0] is least significant
+
+
+    public OldFDBigIntForTest( int v ){
+        nWords = 1;
+        data = new int[1];
+        data[0] = v;
+    }
+
+    public OldFDBigIntForTest( long v ){
+        data = new int[2];
+        data[0] = (int)v;
+        data[1] = (int)(v>>>32);
+        nWords = (data[1]==0) ? 1 : 2;
+    }
+
+    public OldFDBigIntForTest( OldFDBigIntForTest other ){
+        data = new int[nWords = other.nWords];
+        System.arraycopy( other.data, 0, data, 0, nWords );
+    }
+
+    private OldFDBigIntForTest( int [] d, int n ){
+        data = d;
+        nWords = n;
+    }
+
+    public OldFDBigIntForTest( long seed, char digit[], int nd0, int nd ){
+        int n= (nd+8)/9;        // estimate size needed.
+        if ( n < 2 ) n = 2;
+        data = new int[n];      // allocate enough space
+        data[0] = (int)seed;    // starting value
+        data[1] = (int)(seed>>>32);
+        nWords = (data[1]==0) ? 1 : 2;
+        int i = nd0;
+        int limit = nd-5;       // slurp digits 5 at a time.
+        int v;
+        while ( i < limit ){
+            int ilim = i+5;
+            v = (int)digit[i++]-(int)'0';
+            while( i <ilim ){
+                v = 10*v + (int)digit[i++]-(int)'0';
+            }
+            multaddMe( 100000, v); // ... where 100000 is 10^5.
+        }
+        int factor = 1;
+        v = 0;
+        while ( i < nd ){
+            v = 10*v + (int)digit[i++]-(int)'0';
+            factor *= 10;
+        }
+        if ( factor != 1 ){
+            multaddMe( factor, v );
+        }
+    }
+
+    /*
+     * Left shift by c bits.
+     * Shifts this in place.
+     */
+    public void
+    lshiftMe( int c )throws IllegalArgumentException {
+        if ( c <= 0 ){
+            if ( c == 0 )
+                return; // silly.
+            else
+                throw new IllegalArgumentException("negative shift count");
+        }
+        int wordcount = c>>5;
+        int bitcount  = c & 0x1f;
+        int anticount = 32-bitcount;
+        int t[] = data;
+        int s[] = data;
+        if ( nWords+wordcount+1 > t.length ){
+            // reallocate.
+            t = new int[ nWords+wordcount+1 ];
+        }
+        int target = nWords+wordcount;
+        int src    = nWords-1;
+        if ( bitcount == 0 ){
+            // special hack, since an anticount of 32 won't go!
+            System.arraycopy( s, 0, t, wordcount, nWords );
+            target = wordcount-1;
+        } else {
+            t[target--] = s[src]>>>anticount;
+            while ( src >= 1 ){
+                t[target--] = (s[src]<<bitcount) | (s[--src]>>>anticount);
+            }
+            t[target--] = s[src]<<bitcount;
+        }
+        while( target >= 0 ){
+            t[target--] = 0;
+        }
+        data = t;
+        nWords += wordcount + 1;
+        // may have constructed high-order word of 0.
+        // if so, trim it
+        while ( nWords > 1 && data[nWords-1] == 0 )
+            nWords--;
+    }
+
+    /*
+     * normalize this number by shifting until
+     * the MSB of the number is at 0x08000000.
+     * This is in preparation for quoRemIteration, below.
+     * The idea is that, to make division easier, we want the
+     * divisor to be "normalized" -- usually this means shifting
+     * the MSB into the high words sign bit. But because we know that
+     * the quotient will be 0 < q < 10, we would like to arrange that
+     * the dividend not span up into another word of precision.
+     * (This needs to be explained more clearly!)
+     */
+    public int
+    normalizeMe() throws IllegalArgumentException {
+        int src;
+        int wordcount = 0;
+        int bitcount  = 0;
+        int v = 0;
+        for ( src= nWords-1 ; src >= 0 && (v=data[src]) == 0 ; src--){
+            wordcount += 1;
+        }
+        if ( src < 0 ){
+            // oops. Value is zero. Cannot normalize it!
+            throw new IllegalArgumentException("zero value");
+        }
+        /*
+         * In most cases, we assume that wordcount is zero. This only
+         * makes sense, as we try not to maintain any high-order
+         * words full of zeros. In fact, if there are zeros, we will
+         * simply SHORTEN our number at this point. Watch closely...
+         */
+        nWords -= wordcount;
+        /*
+         * Compute how far left we have to shift v s.t. its highest-
+         * order bit is in the right place. Then call lshiftMe to
+         * do the work.
+         */
+        if ( (v & 0xf0000000) != 0 ){
+            // will have to shift up into the next word.
+            // too bad.
+            for( bitcount = 32 ; (v & 0xf0000000) != 0 ; bitcount-- )
+                v >>>= 1;
+        } else {
+            while ( v <= 0x000fffff ){
+                // hack: byte-at-a-time shifting
+                v <<= 8;
+                bitcount += 8;
+            }
+            while ( v <= 0x07ffffff ){
+                v <<= 1;
+                bitcount += 1;
+            }
+        }
+        if ( bitcount != 0 )
+            lshiftMe( bitcount );
+        return bitcount;
+    }
+
+    /*
+     * Multiply a OldFDBigIntForTest by an int.
+     * Result is a new OldFDBigIntForTest.
+     */
+    public OldFDBigIntForTest
+    mult( int iv ) {
+        long v = iv;
+        int r[];
+        long p;
+
+        // guess adequate size of r.
+        r = new int[ ( v * ((long)data[nWords-1]&0xffffffffL) > 0xfffffffL ) ? nWords+1 : nWords ];
+        p = 0L;
+        for( int i=0; i < nWords; i++ ) {
+            p += v * ((long)data[i]&0xffffffffL);
+            r[i] = (int)p;
+            p >>>= 32;
+        }
+        if ( p == 0L){
+            return new OldFDBigIntForTest( r, nWords );
+        } else {
+            r[nWords] = (int)p;
+            return new OldFDBigIntForTest( r, nWords+1 );
+        }
+    }
+
+    /*
+     * Multiply a OldFDBigIntForTest by an int and add another int.
+     * Result is computed in place.
+     * Hope it fits!
+     */
+    public void
+    multaddMe( int iv, int addend ) {
+        long v = iv;
+        long p;
+
+        // unroll 0th iteration, doing addition.
+        p = v * ((long)data[0]&0xffffffffL) + ((long)addend&0xffffffffL);
+        data[0] = (int)p;
+        p >>>= 32;
+        for( int i=1; i < nWords; i++ ) {
+            p += v * ((long)data[i]&0xffffffffL);
+            data[i] = (int)p;
+            p >>>= 32;
+        }
+        if ( p != 0L){
+            data[nWords] = (int)p; // will fail noisily if illegal!
+            nWords++;
+        }
+    }
+
+    /*
+     * Multiply a OldFDBigIntForTest by another OldFDBigIntForTest.
+     * Result is a new OldFDBigIntForTest.
+     */
+    public OldFDBigIntForTest
+    mult( OldFDBigIntForTest other ){
+        // crudely guess adequate size for r
+        int r[] = new int[ nWords + other.nWords ];
+        int i;
+        // I think I am promised zeros...
+
+        for( i = 0; i < this.nWords; i++ ){
+            long v = (long)this.data[i] & 0xffffffffL; // UNSIGNED CONVERSION
+            long p = 0L;
+            int j;
+            for( j = 0; j < other.nWords; j++ ){
+                p += ((long)r[i+j]&0xffffffffL) + v*((long)other.data[j]&0xffffffffL); // UNSIGNED CONVERSIONS ALL 'ROUND.
+                r[i+j] = (int)p;
+                p >>>= 32;
+            }
+            r[i+j] = (int)p;
+        }
+        // compute how much of r we actually needed for all that.
+        for ( i = r.length-1; i> 0; i--)
+            if ( r[i] != 0 )
+                break;
+        return new OldFDBigIntForTest( r, i+1 );
+    }
+
+    /*
+     * Add one OldFDBigIntForTest to another. Return a OldFDBigIntForTest
+     */
+    public OldFDBigIntForTest
+    add( OldFDBigIntForTest other ){
+        int i;
+        int a[], b[];
+        int n, m;
+        long c = 0L;
+        // arrange such that a.nWords >= b.nWords;
+        // n = a.nWords, m = b.nWords
+        if ( this.nWords >= other.nWords ){
+            a = this.data;
+            n = this.nWords;
+            b = other.data;
+            m = other.nWords;
+        } else {
+            a = other.data;
+            n = other.nWords;
+            b = this.data;
+            m = this.nWords;
+        }
+        int r[] = new int[ n ];
+        for ( i = 0; i < n; i++ ){
+            c += (long)a[i] & 0xffffffffL;
+            if ( i < m ){
+                c += (long)b[i] & 0xffffffffL;
+            }
+            r[i] = (int) c;
+            c >>= 32; // signed shift.
+        }
+        if ( c != 0L ){
+            // oops -- carry out -- need longer result.
+            int s[] = new int[ r.length+1 ];
+            System.arraycopy( r, 0, s, 0, r.length );
+            s[i++] = (int)c;
+            return new OldFDBigIntForTest( s, i );
+        }
+        return new OldFDBigIntForTest( r, i );
+    }
+
+    /*
+     * Subtract one OldFDBigIntForTest from another. Return a OldFDBigIntForTest
+     * Assert that the result is positive.
+     */
+    public OldFDBigIntForTest
+    sub( OldFDBigIntForTest other ){
+        int r[] = new int[ this.nWords ];
+        int i;
+        int n = this.nWords;
+        int m = other.nWords;
+        int nzeros = 0;
+        long c = 0L;
+        for ( i = 0; i < n; i++ ){
+            c += (long)this.data[i] & 0xffffffffL;
+            if ( i < m ){
+                c -= (long)other.data[i] & 0xffffffffL;
+            }
+            if ( ( r[i] = (int) c ) == 0 )
+                nzeros++;
+            else
+                nzeros = 0;
+            c >>= 32; // signed shift
+        }
+        assert c == 0L : c; // borrow out of subtract
+        assert dataInRangeIsZero(i, m, other); // negative result of subtract
+        return new OldFDBigIntForTest( r, n-nzeros );
+    }
+
+    private static boolean dataInRangeIsZero(int i, int m, OldFDBigIntForTest other) {
+        while ( i < m )
+            if (other.data[i++] != 0)
+                return false;
+        return true;
+    }
+
+    /*
+     * Compare OldFDBigIntForTest with another OldFDBigIntForTest. Return an integer
+     * >0: this > other
+     *  0: this == other
+     * <0: this < other
+     */
+    public int
+    cmp( OldFDBigIntForTest other ){
+        int i;
+        if ( this.nWords > other.nWords ){
+            // if any of my high-order words is non-zero,
+            // then the answer is evident
+            int j = other.nWords-1;
+            for ( i = this.nWords-1; i > j ; i-- )
+                if ( this.data[i] != 0 ) return 1;
+        }else if ( this.nWords < other.nWords ){
+            // if any of other's high-order words is non-zero,
+            // then the answer is evident
+            int j = this.nWords-1;
+            for ( i = other.nWords-1; i > j ; i-- )
+                if ( other.data[i] != 0 ) return -1;
+        } else{
+            i = this.nWords-1;
+        }
+        for ( ; i > 0 ; i-- )
+            if ( this.data[i] != other.data[i] )
+                break;
+        // careful! want unsigned compare!
+        // use brute force here.
+        int a = this.data[i];
+        int b = other.data[i];
+        if ( a < 0 ){
+            // a is really big, unsigned
+            if ( b < 0 ){
+                return a-b; // both big, negative
+            } else {
+                return 1; // b not big, answer is obvious;
+            }
+        } else {
+            // a is not really big
+            if ( b < 0 ) {
+                // but b is really big
+                return -1;
+            } else {
+                return a - b;
+            }
+        }
+    }
+
+    /*
+     * Compute
+     * q = (int)( this / S )
+     * this = 10 * ( this mod S )
+     * Return q.
+     * This is the iteration step of digit development for output.
+     * We assume that S has been normalized, as above, and that
+     * "this" has been lshift'ed accordingly.
+     * Also assume, of course, that the result, q, can be expressed
+     * as an integer, 0 <= q < 10.
+     */
+    public int
+    quoRemIteration( OldFDBigIntForTest S )throws IllegalArgumentException {
+        // ensure that this and S have the same number of
+        // digits. If S is properly normalized and q < 10 then
+        // this must be so.
+        if ( nWords != S.nWords ){
+            throw new IllegalArgumentException("disparate values");
+        }
+        // estimate q the obvious way. We will usually be
+        // right. If not, then we're only off by a little and
+        // will re-add.
+        int n = nWords-1;
+        long q = ((long)data[n]&0xffffffffL) / (long)S.data[n];
+        long diff = 0L;
+        for ( int i = 0; i <= n ; i++ ){
+            diff += ((long)data[i]&0xffffffffL) -  q*((long)S.data[i]&0xffffffffL);
+            data[i] = (int)diff;
+            diff >>= 32; // N.B. SIGNED shift.
+        }
+        if ( diff != 0L ) {
+            // damn, damn, damn. q is too big.
+            // add S back in until this turns +. This should
+            // not be very many times!
+            long sum = 0L;
+            while ( sum ==  0L ){
+                sum = 0L;
+                for ( int i = 0; i <= n; i++ ){
+                    sum += ((long)data[i]&0xffffffffL) +  ((long)S.data[i]&0xffffffffL);
+                    data[i] = (int) sum;
+                    sum >>= 32; // Signed or unsigned, answer is 0 or 1
+                }
+                /*
+                 * Originally the following line read
+                 * "if ( sum !=0 && sum != -1 )"
+                 * but that would be wrong, because of the
+                 * treatment of the two values as entirely unsigned,
+                 * it would be impossible for a carry-out to be interpreted
+                 * as -1 -- it would have to be a single-bit carry-out, or
+                 * +1.
+                 */
+                assert sum == 0 || sum == 1 : sum; // carry out of division correction
+                q -= 1;
+            }
+        }
+        // finally, we can multiply this by 10.
+        // it cannot overflow, right, as the high-order word has
+        // at least 4 high-order zeros!
+        long p = 0L;
+        for ( int i = 0; i <= n; i++ ){
+            p += 10*((long)data[i]&0xffffffffL);
+            data[i] = (int)p;
+            p >>= 32; // SIGNED shift.
+        }
+        assert p == 0L : p; // Carry out of *10
+        return (int)q;
+    }
+
+    public long
+    longValue(){
+        // if this can be represented as a long, return the value
+        assert this.nWords > 0 : this.nWords; // longValue confused
+
+        if (this.nWords == 1)
+            return ((long)data[0]&0xffffffffL);
+
+        assert dataInRangeIsZero(2, this.nWords, this); // value too big
+        assert data[1] >= 0;  // value too big
+        return ((long)(data[1]) << 32) | ((long)data[0]&0xffffffffL);
+    }
+
+    public String
+    toString() {
+        StringBuffer r = new StringBuffer(30);
+        r.append('[');
+        int i = Math.min( nWords-1, data.length-1) ;
+        if ( nWords > data.length ){
+            r.append( "("+data.length+"<"+nWords+"!)" );
+        }
+        for( ; i> 0 ; i-- ){
+            r.append( Integer.toHexString( data[i] ) );
+            r.append(' ');
+        }
+        r.append( Integer.toHexString( data[0] ) );
+        r.append(']');
+        return new String( r );
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/misc/FloatingDecimal/OldFloatingDecimalForTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,2436 @@
+/*
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+//package sun.misc;
+
+import sun.misc.DoubleConsts;
+import sun.misc.FloatConsts;
+import java.util.regex.*;
+
+public class OldFloatingDecimalForTest{
+    boolean     isExceptional;
+    boolean     isNegative;
+    int         decExponent;
+    char        digits[];
+    int         nDigits;
+    int         bigIntExp;
+    int         bigIntNBits;
+    boolean     mustSetRoundDir = false;
+    boolean     fromHex = false;
+    int         roundDir = 0; // set by doubleValue
+
+    /*
+     * The fields below provides additional information about the result of
+     * the binary to decimal digits conversion done in dtoa() and roundup()
+     * methods. They are changed if needed by those two methods.
+     */
+
+    // True if the dtoa() binary to decimal conversion was exact.
+    boolean     exactDecimalConversion = false;
+
+    // True if the result of the binary to decimal conversion was rounded-up
+    // at the end of the conversion process, i.e. roundUp() method was called.
+    boolean     decimalDigitsRoundedUp = false;
+
+    private     OldFloatingDecimalForTest( boolean negSign, int decExponent, char []digits, int n,  boolean e )
+    {
+        isNegative = negSign;
+        isExceptional = e;
+        this.decExponent = decExponent;
+        this.digits = digits;
+        this.nDigits = n;
+    }
+
+    /*
+     * Constants of the implementation
+     * Most are IEEE-754 related.
+     * (There are more really boring constants at the end.)
+     */
+    static final long   signMask = 0x8000000000000000L;
+    static final long   expMask  = 0x7ff0000000000000L;
+    static final long   fractMask= ~(signMask|expMask);
+    static final int    expShift = 52;
+    static final int    expBias  = 1023;
+    static final long   fractHOB = ( 1L<<expShift ); // assumed High-Order bit
+    static final long   expOne   = ((long)expBias)<<expShift; // exponent of 1.0
+    static final int    maxSmallBinExp = 62;
+    static final int    minSmallBinExp = -( 63 / 3 );
+    static final int    maxDecimalDigits = 15;
+    static final int    maxDecimalExponent = 308;
+    static final int    minDecimalExponent = -324;
+    static final int    bigDecimalExponent = 324; // i.e. abs(minDecimalExponent)
+
+    static final long   highbyte = 0xff00000000000000L;
+    static final long   highbit  = 0x8000000000000000L;
+    static final long   lowbytes = ~highbyte;
+
+    static final int    singleSignMask =    0x80000000;
+    static final int    singleExpMask  =    0x7f800000;
+    static final int    singleFractMask =   ~(singleSignMask|singleExpMask);
+    static final int    singleExpShift  =   23;
+    static final int    singleFractHOB  =   1<<singleExpShift;
+    static final int    singleExpBias   =   127;
+    static final int    singleMaxDecimalDigits = 7;
+    static final int    singleMaxDecimalExponent = 38;
+    static final int    singleMinDecimalExponent = -45;
+
+    static final int    intDecimalDigits = 9;
+
+
+    /*
+     * count number of bits from high-order 1 bit to low-order 1 bit,
+     * inclusive.
+     */
+    private static int
+    countBits( long v ){
+        //
+        // the strategy is to shift until we get a non-zero sign bit
+        // then shift until we have no bits left, counting the difference.
+        // we do byte shifting as a hack. Hope it helps.
+        //
+        if ( v == 0L ) return 0;
+
+        while ( ( v & highbyte ) == 0L ){
+            v <<= 8;
+        }
+        while ( v > 0L ) { // i.e. while ((v&highbit) == 0L )
+            v <<= 1;
+        }
+
+        int n = 0;
+        while (( v & lowbytes ) != 0L ){
+            v <<= 8;
+            n += 8;
+        }
+        while ( v != 0L ){
+            v <<= 1;
+            n += 1;
+        }
+        return n;
+    }
+
+    /*
+     * Keep big powers of 5 handy for future reference.
+     */
+    private static OldFDBigIntForTest b5p[];
+
+    private static synchronized OldFDBigIntForTest
+    big5pow( int p ){
+        assert p >= 0 : p; // negative power of 5
+        if ( b5p == null ){
+            b5p = new OldFDBigIntForTest[ p+1 ];
+        }else if (b5p.length <= p ){
+            OldFDBigIntForTest t[] = new OldFDBigIntForTest[ p+1 ];
+            System.arraycopy( b5p, 0, t, 0, b5p.length );
+            b5p = t;
+        }
+        if ( b5p[p] != null )
+            return b5p[p];
+        else if ( p < small5pow.length )
+            return b5p[p] = new OldFDBigIntForTest( small5pow[p] );
+        else if ( p < long5pow.length )
+            return b5p[p] = new OldFDBigIntForTest( long5pow[p] );
+        else {
+            // construct the value.
+            // recursively.
+            int q, r;
+            // in order to compute 5^p,
+            // compute its square root, 5^(p/2) and square.
+            // or, let q = p / 2, r = p -q, then
+            // 5^p = 5^(q+r) = 5^q * 5^r
+            q = p >> 1;
+            r = p - q;
+            OldFDBigIntForTest bigq =  b5p[q];
+            if ( bigq == null )
+                bigq = big5pow ( q );
+            if ( r < small5pow.length ){
+                return (b5p[p] = bigq.mult( small5pow[r] ) );
+            }else{
+                OldFDBigIntForTest bigr = b5p[ r ];
+                if ( bigr == null )
+                    bigr = big5pow( r );
+                return (b5p[p] = bigq.mult( bigr ) );
+            }
+        }
+    }
+
+    //
+    // a common operation
+    //
+    private static OldFDBigIntForTest
+    multPow52( OldFDBigIntForTest v, int p5, int p2 ){
+        if ( p5 != 0 ){
+            if ( p5 < small5pow.length ){
+                v = v.mult( small5pow[p5] );
+            } else {
+                v = v.mult( big5pow( p5 ) );
+            }
+        }
+        if ( p2 != 0 ){
+            v.lshiftMe( p2 );
+        }
+        return v;
+    }
+
+    //
+    // another common operation
+    //
+    private static OldFDBigIntForTest
+    constructPow52( int p5, int p2 ){
+        OldFDBigIntForTest v = new OldFDBigIntForTest( big5pow( p5 ) );
+        if ( p2 != 0 ){
+            v.lshiftMe( p2 );
+        }
+        return v;
+    }
+
+    /*
+     * Make a floating double into a OldFDBigIntForTest.
+     * This could also be structured as a OldFDBigIntForTest
+     * constructor, but we'd have to build a lot of knowledge
+     * about floating-point representation into it, and we don't want to.
+     *
+     * AS A SIDE EFFECT, THIS METHOD WILL SET THE INSTANCE VARIABLES
+     * bigIntExp and bigIntNBits
+     *
+     */
+    private OldFDBigIntForTest
+    doubleToBigInt( double dval ){
+        long lbits = Double.doubleToLongBits( dval ) & ~signMask;
+        int binexp = (int)(lbits >>> expShift);
+        lbits &= fractMask;
+        if ( binexp > 0 ){
+            lbits |= fractHOB;
+        } else {
+            assert lbits != 0L : lbits; // doubleToBigInt(0.0)
+            binexp +=1;
+            while ( (lbits & fractHOB ) == 0L){
+                lbits <<= 1;
+                binexp -= 1;
+            }
+        }
+        binexp -= expBias;
+        int nbits = countBits( lbits );
+        /*
+         * We now know where the high-order 1 bit is,
+         * and we know how many there are.
+         */
+        int lowOrderZeros = expShift+1-nbits;
+        lbits >>>= lowOrderZeros;
+
+        bigIntExp = binexp+1-nbits;
+        bigIntNBits = nbits;
+        return new OldFDBigIntForTest( lbits );
+    }
+
+    /*
+     * Compute a number that is the ULP of the given value,
+     * for purposes of addition/subtraction. Generally easy.
+     * More difficult if subtracting and the argument
+     * is a normalized a power of 2, as the ULP changes at these points.
+     */
+    private static double ulp( double dval, boolean subtracting ){
+        long lbits = Double.doubleToLongBits( dval ) & ~signMask;
+        int binexp = (int)(lbits >>> expShift);
+        double ulpval;
+        if ( subtracting && ( binexp >= expShift ) && ((lbits&fractMask) == 0L) ){
+            // for subtraction from normalized, powers of 2,
+            // use next-smaller exponent
+            binexp -= 1;
+        }
+        if ( binexp > expShift ){
+            ulpval = Double.longBitsToDouble( ((long)(binexp-expShift))<<expShift );
+        } else if ( binexp == 0 ){
+            ulpval = Double.MIN_VALUE;
+        } else {
+            ulpval = Double.longBitsToDouble( 1L<<(binexp-1) );
+        }
+        if ( subtracting ) ulpval = - ulpval;
+
+        return ulpval;
+    }
+
+    /*
+     * Round a double to a float.
+     * In addition to the fraction bits of the double,
+     * look at the class instance variable roundDir,
+     * which should help us avoid double-rounding error.
+     * roundDir was set in hardValueOf if the estimate was
+     * close enough, but not exact. It tells us which direction
+     * of rounding is preferred.
+     */
+    float
+    stickyRound( double dval ){
+        long lbits = Double.doubleToLongBits( dval );
+        long binexp = lbits & expMask;
+        if ( binexp == 0L || binexp == expMask ){
+            // what we have here is special.
+            // don't worry, the right thing will happen.
+            return (float) dval;
+        }
+        lbits += (long)roundDir; // hack-o-matic.
+        return (float)Double.longBitsToDouble( lbits );
+    }
+
+
+    /*
+     * This is the easy subcase --
+     * all the significant bits, after scaling, are held in lvalue.
+     * negSign and decExponent tell us what processing and scaling
+     * has already been done. Exceptional cases have already been
+     * stripped out.
+     * In particular:
+     * lvalue is a finite number (not Inf, nor NaN)
+     * lvalue > 0L (not zero, nor negative).
+     *
+     * The only reason that we develop the digits here, rather than
+     * calling on Long.toString() is that we can do it a little faster,
+     * and besides want to treat trailing 0s specially. If Long.toString
+     * changes, we should re-evaluate this strategy!
+     */
+    private void
+    developLongDigits( int decExponent, long lvalue, long insignificant ){
+        char digits[];
+        int  ndigits;
+        int  digitno;
+        int  c;
+        //
+        // Discard non-significant low-order bits, while rounding,
+        // up to insignificant value.
+        int i;
+        for ( i = 0; insignificant >= 10L; i++ )
+            insignificant /= 10L;
+        if ( i != 0 ){
+            long pow10 = long5pow[i] << i; // 10^i == 5^i * 2^i;
+            long residue = lvalue % pow10;
+            lvalue /= pow10;
+            decExponent += i;
+            if ( residue >= (pow10>>1) ){
+                // round up based on the low-order bits we're discarding
+                lvalue++;
+            }
+        }
+        if ( lvalue <= Integer.MAX_VALUE ){
+            assert lvalue > 0L : lvalue; // lvalue <= 0
+            // even easier subcase!
+            // can do int arithmetic rather than long!
+            int  ivalue = (int)lvalue;
+            ndigits = 10;
+            digits = perThreadBuffer.get();
+            digitno = ndigits-1;
+            c = ivalue%10;
+            ivalue /= 10;
+            while ( c == 0 ){
+                decExponent++;
+                c = ivalue%10;
+                ivalue /= 10;
+            }
+            while ( ivalue != 0){
+                digits[digitno--] = (char)(c+'0');
+                decExponent++;
+                c = ivalue%10;
+                ivalue /= 10;
+            }
+            digits[digitno] = (char)(c+'0');
+        } else {
+            // same algorithm as above (same bugs, too )
+            // but using long arithmetic.
+            ndigits = 20;
+            digits = perThreadBuffer.get();
+            digitno = ndigits-1;
+            c = (int)(lvalue%10L);
+            lvalue /= 10L;
+            while ( c == 0 ){
+                decExponent++;
+                c = (int)(lvalue%10L);
+                lvalue /= 10L;
+            }
+            while ( lvalue != 0L ){
+                digits[digitno--] = (char)(c+'0');
+                decExponent++;
+                c = (int)(lvalue%10L);
+                lvalue /= 10;
+            }
+            digits[digitno] = (char)(c+'0');
+        }
+        char result [];
+        ndigits -= digitno;
+        result = new char[ ndigits ];
+        System.arraycopy( digits, digitno, result, 0, ndigits );
+        this.digits = result;
+        this.decExponent = decExponent+1;
+        this.nDigits = ndigits;
+    }
+
+    //
+    // add one to the least significant digit.
+    // in the unlikely event there is a carry out,
+    // deal with it.
+    // assert that this will only happen where there
+    // is only one digit, e.g. (float)1e-44 seems to do it.
+    //
+    private void
+    roundup(){
+        int i;
+        int q = digits[ i = (nDigits-1)];
+        if ( q == '9' ){
+            while ( q == '9' && i > 0 ){
+                digits[i] = '0';
+                q = digits[--i];
+            }
+            if ( q == '9' ){
+                // carryout! High-order 1, rest 0s, larger exp.
+                decExponent += 1;
+                digits[0] = '1';
+                return;
+            }
+            // else fall through.
+        }
+        digits[i] = (char)(q+1);
+        decimalDigitsRoundedUp = true;
+    }
+
+    public boolean digitsRoundedUp() {
+        return decimalDigitsRoundedUp;
+    }
+
+    /*
+     * FIRST IMPORTANT CONSTRUCTOR: DOUBLE
+     */
+    public OldFloatingDecimalForTest( double d )
+    {
+        long    dBits = Double.doubleToLongBits( d );
+        long    fractBits;
+        int     binExp;
+        int     nSignificantBits;
+
+        // discover and delete sign
+        if ( (dBits&signMask) != 0 ){
+            isNegative = true;
+            dBits ^= signMask;
+        } else {
+            isNegative = false;
+        }
+        // Begin to unpack
+        // Discover obvious special cases of NaN and Infinity.
+        binExp = (int)( (dBits&expMask) >> expShift );
+        fractBits = dBits&fractMask;
+        if ( binExp == (int)(expMask>>expShift) ) {
+            isExceptional = true;
+            if ( fractBits == 0L ){
+                digits =  infinity;
+            } else {
+                digits = notANumber;
+                isNegative = false; // NaN has no sign!
+            }
+            nDigits = digits.length;
+            return;
+        }
+        isExceptional = false;
+        // Finish unpacking
+        // Normalize denormalized numbers.
+        // Insert assumed high-order bit for normalized numbers.
+        // Subtract exponent bias.
+        if ( binExp == 0 ){
+            if ( fractBits == 0L ){
+                // not a denorm, just a 0!
+                decExponent = 0;
+                digits = zero;
+                nDigits = 1;
+                return;
+            }
+            while ( (fractBits&fractHOB) == 0L ){
+                fractBits <<= 1;
+                binExp -= 1;
+            }
+            nSignificantBits = expShift + binExp +1; // recall binExp is  - shift count.
+            binExp += 1;
+        } else {
+            fractBits |= fractHOB;
+            nSignificantBits = expShift+1;
+        }
+        binExp -= expBias;
+        // call the routine that actually does all the hard work.
+        dtoa( binExp, fractBits, nSignificantBits );
+    }
+
+    /*
+     * SECOND IMPORTANT CONSTRUCTOR: SINGLE
+     */
+    public OldFloatingDecimalForTest( float f )
+    {
+        int     fBits = Float.floatToIntBits( f );
+        int     fractBits;
+        int     binExp;
+        int     nSignificantBits;
+
+        // discover and delete sign
+        if ( (fBits&singleSignMask) != 0 ){
+            isNegative = true;
+            fBits ^= singleSignMask;
+        } else {
+            isNegative = false;
+        }
+        // Begin to unpack
+        // Discover obvious special cases of NaN and Infinity.
+        binExp = (fBits&singleExpMask) >> singleExpShift;
+        fractBits = fBits&singleFractMask;
+        if ( binExp == (singleExpMask>>singleExpShift) ) {
+            isExceptional = true;
+            if ( fractBits == 0L ){
+                digits =  infinity;
+            } else {
+                digits = notANumber;
+                isNegative = false; // NaN has no sign!
+            }
+            nDigits = digits.length;
+            return;
+        }
+        isExceptional = false;
+        // Finish unpacking
+        // Normalize denormalized numbers.
+        // Insert assumed high-order bit for normalized numbers.
+        // Subtract exponent bias.
+        if ( binExp == 0 ){
+            if ( fractBits == 0 ){
+                // not a denorm, just a 0!
+                decExponent = 0;
+                digits = zero;
+                nDigits = 1;
+                return;
+            }
+            while ( (fractBits&singleFractHOB) == 0 ){
+                fractBits <<= 1;
+                binExp -= 1;
+            }
+            nSignificantBits = singleExpShift + binExp +1; // recall binExp is  - shift count.
+            binExp += 1;
+        } else {
+            fractBits |= singleFractHOB;
+            nSignificantBits = singleExpShift+1;
+        }
+        binExp -= singleExpBias;
+        // call the routine that actually does all the hard work.
+        dtoa( binExp, ((long)fractBits)<<(expShift-singleExpShift), nSignificantBits );
+    }
+
+    private void
+    dtoa( int binExp, long fractBits, int nSignificantBits )
+    {
+        int     nFractBits; // number of significant bits of fractBits;
+        int     nTinyBits;  // number of these to the right of the point.
+        int     decExp;
+
+        // Examine number. Determine if it is an easy case,
+        // which we can do pretty trivially using float/long conversion,
+        // or whether we must do real work.
+        nFractBits = countBits( fractBits );
+        nTinyBits = Math.max( 0, nFractBits - binExp - 1 );
+        if ( binExp <= maxSmallBinExp && binExp >= minSmallBinExp ){
+            // Look more closely at the number to decide if,
+            // with scaling by 10^nTinyBits, the result will fit in
+            // a long.
+            if ( (nTinyBits < long5pow.length) && ((nFractBits + n5bits[nTinyBits]) < 64 ) ){
+                /*
+                 * We can do this:
+                 * take the fraction bits, which are normalized.
+                 * (a) nTinyBits == 0: Shift left or right appropriately
+                 *     to align the binary point at the extreme right, i.e.
+                 *     where a long int point is expected to be. The integer
+                 *     result is easily converted to a string.
+                 * (b) nTinyBits > 0: Shift right by expShift-nFractBits,
+                 *     which effectively converts to long and scales by
+                 *     2^nTinyBits. Then multiply by 5^nTinyBits to
+                 *     complete the scaling. We know this won't overflow
+                 *     because we just counted the number of bits necessary
+                 *     in the result. The integer you get from this can
+                 *     then be converted to a string pretty easily.
+                 */
+                long halfULP;
+                if ( nTinyBits == 0 ) {
+                    if ( binExp > nSignificantBits ){
+                        halfULP = 1L << ( binExp-nSignificantBits-1);
+                    } else {
+                        halfULP = 0L;
+                    }
+                    if ( binExp >= expShift ){
+                        fractBits <<= (binExp-expShift);
+                    } else {
+                        fractBits >>>= (expShift-binExp) ;
+                    }
+                    developLongDigits( 0, fractBits, halfULP );
+                    return;
+                }
+                /*
+                 * The following causes excess digits to be printed
+                 * out in the single-float case. Our manipulation of
+                 * halfULP here is apparently not correct. If we
+                 * better understand how this works, perhaps we can
+                 * use this special case again. But for the time being,
+                 * we do not.
+                 * else {
+                 *     fractBits >>>= expShift+1-nFractBits;
+                 *     fractBits *= long5pow[ nTinyBits ];
+                 *     halfULP = long5pow[ nTinyBits ] >> (1+nSignificantBits-nFractBits);
+                 *     developLongDigits( -nTinyBits, fractBits, halfULP );
+                 *     return;
+                 * }
+                 */
+            }
+        }
+        /*
+         * This is the hard case. We are going to compute large positive
+         * integers B and S and integer decExp, s.t.
+         *      d = ( B / S ) * 10^decExp
+         *      1 <= B / S < 10
+         * Obvious choices are:
+         *      decExp = floor( log10(d) )
+         *      B      = d * 2^nTinyBits * 10^max( 0, -decExp )
+         *      S      = 10^max( 0, decExp) * 2^nTinyBits
+         * (noting that nTinyBits has already been forced to non-negative)
+         * I am also going to compute a large positive integer
+         *      M      = (1/2^nSignificantBits) * 2^nTinyBits * 10^max( 0, -decExp )
+         * i.e. M is (1/2) of the ULP of d, scaled like B.
+         * When we iterate through dividing B/S and picking off the
+         * quotient bits, we will know when to stop when the remainder
+         * is <= M.
+         *
+         * We keep track of powers of 2 and powers of 5.
+         */
+
+        /*
+         * Estimate decimal exponent. (If it is small-ish,
+         * we could double-check.)
+         *
+         * First, scale the mantissa bits such that 1 <= d2 < 2.
+         * We are then going to estimate
+         *          log10(d2) ~=~  (d2-1.5)/1.5 + log(1.5)
+         * and so we can estimate
+         *      log10(d) ~=~ log10(d2) + binExp * log10(2)
+         * take the floor and call it decExp.
+         * FIXME -- use more precise constants here. It costs no more.
+         */
+        double d2 = Double.longBitsToDouble(
+            expOne | ( fractBits &~ fractHOB ) );
+        decExp = (int)Math.floor(
+            (d2-1.5D)*0.289529654D + 0.176091259 + (double)binExp * 0.301029995663981 );
+        int B2, B5; // powers of 2 and powers of 5, respectively, in B
+        int S2, S5; // powers of 2 and powers of 5, respectively, in S
+        int M2, M5; // powers of 2 and powers of 5, respectively, in M
+        int Bbits; // binary digits needed to represent B, approx.
+        int tenSbits; // binary digits needed to represent 10*S, approx.
+        OldFDBigIntForTest Sval, Bval, Mval;
+
+        B5 = Math.max( 0, -decExp );
+        B2 = B5 + nTinyBits + binExp;
+
+        S5 = Math.max( 0, decExp );
+        S2 = S5 + nTinyBits;
+
+        M5 = B5;
+        M2 = B2 - nSignificantBits;
+
+        /*
+         * the long integer fractBits contains the (nFractBits) interesting
+         * bits from the mantissa of d ( hidden 1 added if necessary) followed
+         * by (expShift+1-nFractBits) zeros. In the interest of compactness,
+         * I will shift out those zeros before turning fractBits into a
+         * OldFDBigIntForTest. The resulting whole number will be
+         *      d * 2^(nFractBits-1-binExp).
+         */
+        fractBits >>>= (expShift+1-nFractBits);
+        B2 -= nFractBits-1;
+        int common2factor = Math.min( B2, S2 );
+        B2 -= common2factor;
+        S2 -= common2factor;
+        M2 -= common2factor;
+
+        /*
+         * HACK!! For exact powers of two, the next smallest number
+         * is only half as far away as we think (because the meaning of
+         * ULP changes at power-of-two bounds) for this reason, we
+         * hack M2. Hope this works.
+         */
+        if ( nFractBits == 1 )
+            M2 -= 1;
+
+        if ( M2 < 0 ){
+            // oops.
+            // since we cannot scale M down far enough,
+            // we must scale the other values up.
+            B2 -= M2;
+            S2 -= M2;
+            M2 =  0;
+        }
+        /*
+         * Construct, Scale, iterate.
+         * Some day, we'll write a stopping test that takes
+         * account of the asymmetry of the spacing of floating-point
+         * numbers below perfect powers of 2
+         * 26 Sept 96 is not that day.
+         * So we use a symmetric test.
+         */
+        char digits[] = this.digits = new char[18];
+        int  ndigit = 0;
+        boolean low, high;
+        long lowDigitDifference;
+        int  q;
+
+        /*
+         * Detect the special cases where all the numbers we are about
+         * to compute will fit in int or long integers.
+         * In these cases, we will avoid doing OldFDBigIntForTest arithmetic.
+         * We use the same algorithms, except that we "normalize"
+         * our OldFDBigIntForTests before iterating. This is to make division easier,
+         * as it makes our fist guess (quotient of high-order words)
+         * more accurate!
+         *
+         * Some day, we'll write a stopping test that takes
+         * account of the asymmetry of the spacing of floating-point
+         * numbers below perfect powers of 2
+         * 26 Sept 96 is not that day.
+         * So we use a symmetric test.
+         */
+        Bbits = nFractBits + B2 + (( B5 < n5bits.length )? n5bits[B5] : ( B5*3 ));
+        tenSbits = S2+1 + (( (S5+1) < n5bits.length )? n5bits[(S5+1)] : ( (S5+1)*3 ));
+        if ( Bbits < 64 && tenSbits < 64){
+            if ( Bbits < 32 && tenSbits < 32){
+                // wa-hoo! They're all ints!
+                int b = ((int)fractBits * small5pow[B5] ) << B2;
+                int s = small5pow[S5] << S2;
+                int m = small5pow[M5] << M2;
+                int tens = s * 10;
+                /*
+                 * Unroll the first iteration. If our decExp estimate
+                 * was too high, our first quotient will be zero. In this
+                 * case, we discard it and decrement decExp.
+                 */
+                ndigit = 0;
+                q = b / s;
+                b = 10 * ( b % s );
+                m *= 10;
+                low  = (b <  m );
+                high = (b+m > tens );
+                assert q < 10 : q; // excessively large digit
+                if ( (q == 0) && ! high ){
+                    // oops. Usually ignore leading zero.
+                    decExp--;
+                } else {
+                    digits[ndigit++] = (char)('0' + q);
+                }
+                /*
+                 * HACK! Java spec sez that we always have at least
+                 * one digit after the . in either F- or E-form output.
+                 * Thus we will need more than one digit if we're using
+                 * E-form
+                 */
+                if ( decExp < -3 || decExp >= 8 ){
+                    high = low = false;
+                }
+                while( ! low && ! high ){
+                    q = b / s;
+                    b = 10 * ( b % s );
+                    m *= 10;
+                    assert q < 10 : q; // excessively large digit
+                    if ( m > 0L ){
+                        low  = (b <  m );
+                        high = (b+m > tens );
+                    } else {
+                        // hack -- m might overflow!
+                        // in this case, it is certainly > b,
+                        // which won't
+                        // and b+m > tens, too, since that has overflowed
+                        // either!
+                        low = true;
+                        high = true;
+                    }
+                    digits[ndigit++] = (char)('0' + q);
+                }
+                lowDigitDifference = (b<<1) - tens;
+                exactDecimalConversion  = (b == 0);
+            } else {
+                // still good! they're all longs!
+                long b = (fractBits * long5pow[B5] ) << B2;
+                long s = long5pow[S5] << S2;
+                long m = long5pow[M5] << M2;
+                long tens = s * 10L;
+                /*
+                 * Unroll the first iteration. If our decExp estimate
+                 * was too high, our first quotient will be zero. In this
+                 * case, we discard it and decrement decExp.
+                 */
+                ndigit = 0;
+                q = (int) ( b / s );
+                b = 10L * ( b % s );
+                m *= 10L;
+                low  = (b <  m );
+                high = (b+m > tens );
+                assert q < 10 : q; // excessively large digit
+                if ( (q == 0) && ! high ){
+                    // oops. Usually ignore leading zero.
+                    decExp--;
+                } else {
+                    digits[ndigit++] = (char)('0' + q);
+                }
+                /*
+                 * HACK! Java spec sez that we always have at least
+                 * one digit after the . in either F- or E-form output.
+                 * Thus we will need more than one digit if we're using
+                 * E-form
+                 */
+                if ( decExp < -3 || decExp >= 8 ){
+                    high = low = false;
+                }
+                while( ! low && ! high ){
+                    q = (int) ( b / s );
+                    b = 10 * ( b % s );
+                    m *= 10;
+                    assert q < 10 : q;  // excessively large digit
+                    if ( m > 0L ){
+                        low  = (b <  m );
+                        high = (b+m > tens );
+                    } else {
+                        // hack -- m might overflow!
+                        // in this case, it is certainly > b,
+                        // which won't
+                        // and b+m > tens, too, since that has overflowed
+                        // either!
+                        low = true;
+                        high = true;
+                    }
+                    digits[ndigit++] = (char)('0' + q);
+                }
+                lowDigitDifference = (b<<1) - tens;
+                exactDecimalConversion  = (b == 0);
+            }
+        } else {
+            OldFDBigIntForTest ZeroVal = new OldFDBigIntForTest(0);
+            OldFDBigIntForTest tenSval;
+            int  shiftBias;
+
+            /*
+             * We really must do OldFDBigIntForTest arithmetic.
+             * Fist, construct our OldFDBigIntForTest initial values.
+             */
+            Bval = multPow52( new OldFDBigIntForTest( fractBits  ), B5, B2 );
+            Sval = constructPow52( S5, S2 );
+            Mval = constructPow52( M5, M2 );
+
+
+            // normalize so that division works better
+            Bval.lshiftMe( shiftBias = Sval.normalizeMe() );
+            Mval.lshiftMe( shiftBias );
+            tenSval = Sval.mult( 10 );
+            /*
+             * Unroll the first iteration. If our decExp estimate
+             * was too high, our first quotient will be zero. In this
+             * case, we discard it and decrement decExp.
+             */
+            ndigit = 0;
+            q = Bval.quoRemIteration( Sval );
+            Mval = Mval.mult( 10 );
+            low  = (Bval.cmp( Mval ) < 0);
+            high = (Bval.add( Mval ).cmp( tenSval ) > 0 );
+            assert q < 10 : q; // excessively large digit
+            if ( (q == 0) && ! high ){
+                // oops. Usually ignore leading zero.
+                decExp--;
+            } else {
+                digits[ndigit++] = (char)('0' + q);
+            }
+            /*
+             * HACK! Java spec sez that we always have at least
+             * one digit after the . in either F- or E-form output.
+             * Thus we will need more than one digit if we're using
+             * E-form
+             */
+            if ( decExp < -3 || decExp >= 8 ){
+                high = low = false;
+            }
+            while( ! low && ! high ){
+                q = Bval.quoRemIteration( Sval );
+                Mval = Mval.mult( 10 );
+                assert q < 10 : q;  // excessively large digit
+                low  = (Bval.cmp( Mval ) < 0);
+                high = (Bval.add( Mval ).cmp( tenSval ) > 0 );
+                digits[ndigit++] = (char)('0' + q);
+            }
+            if ( high && low ){
+                Bval.lshiftMe(1);
+                lowDigitDifference = Bval.cmp(tenSval);
+            } else {
+                lowDigitDifference = 0L; // this here only for flow analysis!
+            }
+            exactDecimalConversion  = (Bval.cmp( ZeroVal ) == 0);
+        }
+        this.decExponent = decExp+1;
+        this.digits = digits;
+        this.nDigits = ndigit;
+        /*
+         * Last digit gets rounded based on stopping condition.
+         */
+        if ( high ){
+            if ( low ){
+                if ( lowDigitDifference == 0L ){
+                    // it's a tie!
+                    // choose based on which digits we like.
+                    if ( (digits[nDigits-1]&1) != 0 ) roundup();
+                } else if ( lowDigitDifference > 0 ){
+                    roundup();
+                }
+            } else {
+                roundup();
+            }
+        }
+    }
+
+    public boolean decimalDigitsExact() {
+        return exactDecimalConversion;
+    }
+
+    public String
+    toString(){
+        // most brain-dead version
+        StringBuffer result = new StringBuffer( nDigits+8 );
+        if ( isNegative ){ result.append( '-' ); }
+        if ( isExceptional ){
+            result.append( digits, 0, nDigits );
+        } else {
+            result.append( "0.");
+            result.append( digits, 0, nDigits );
+            result.append('e');
+            result.append( decExponent );
+        }
+        return new String(result);
+    }
+
+    public String toJavaFormatString() {
+        char result[] = perThreadBuffer.get();
+        int i = getChars(result);
+        return new String(result, 0, i);
+    }
+
+    private int getChars(char[] result) {
+        assert nDigits <= 19 : nDigits; // generous bound on size of nDigits
+        int i = 0;
+        if (isNegative) { result[0] = '-'; i = 1; }
+        if (isExceptional) {
+            System.arraycopy(digits, 0, result, i, nDigits);
+            i += nDigits;
+        } else {
+            if (decExponent > 0 && decExponent < 8) {
+                // print digits.digits.
+                int charLength = Math.min(nDigits, decExponent);
+                System.arraycopy(digits, 0, result, i, charLength);
+                i += charLength;
+                if (charLength < decExponent) {
+                    charLength = decExponent-charLength;
+                    System.arraycopy(zero, 0, result, i, charLength);
+                    i += charLength;
+                    result[i++] = '.';
+                    result[i++] = '0';
+                } else {
+                    result[i++] = '.';
+                    if (charLength < nDigits) {
+                        int t = nDigits - charLength;
+                        System.arraycopy(digits, charLength, result, i, t);
+                        i += t;
+                    } else {
+                        result[i++] = '0';
+                    }
+                }
+            } else if (decExponent <=0 && decExponent > -3) {
+                result[i++] = '0';
+                result[i++] = '.';
+                if (decExponent != 0) {
+                    System.arraycopy(zero, 0, result, i, -decExponent);
+                    i -= decExponent;
+                }
+                System.arraycopy(digits, 0, result, i, nDigits);
+                i += nDigits;
+            } else {
+                result[i++] = digits[0];
+                result[i++] = '.';
+                if (nDigits > 1) {
+                    System.arraycopy(digits, 1, result, i, nDigits-1);
+                    i += nDigits-1;
+                } else {
+                    result[i++] = '0';
+                }
+                result[i++] = 'E';
+                int e;
+                if (decExponent <= 0) {
+                    result[i++] = '-';
+                    e = -decExponent+1;
+                } else {
+                    e = decExponent-1;
+                }
+                // decExponent has 1, 2, or 3, digits
+                if (e <= 9) {
+                    result[i++] = (char)(e+'0');
+                } else if (e <= 99) {
+                    result[i++] = (char)(e/10 +'0');
+                    result[i++] = (char)(e%10 + '0');
+                } else {
+                    result[i++] = (char)(e/100+'0');
+                    e %= 100;
+                    result[i++] = (char)(e/10+'0');
+                    result[i++] = (char)(e%10 + '0');
+                }
+            }
+        }
+        return i;
+    }
+
+    // Per-thread buffer for string/stringbuffer conversion
+    private static ThreadLocal<char[]> perThreadBuffer = new ThreadLocal<char[]>() {
+            protected synchronized char[] initialValue() {
+                return new char[26];
+            }
+        };
+
+    public void appendTo(Appendable buf) {
+          char result[] = perThreadBuffer.get();
+          int i = getChars(result);
+        if (buf instanceof StringBuilder)
+            ((StringBuilder) buf).append(result, 0, i);
+        else if (buf instanceof StringBuffer)
+            ((StringBuffer) buf).append(result, 0, i);
+        else
+            assert false;
+    }
+
+    @SuppressWarnings("fallthrough")
+    public static OldFloatingDecimalForTest
+    readJavaFormatString( String in ) throws NumberFormatException {
+        boolean isNegative = false;
+        boolean signSeen   = false;
+        int     decExp;
+        char    c;
+
+    parseNumber:
+        try{
+            in = in.trim(); // don't fool around with white space.
+                            // throws NullPointerException if null
+            int l = in.length();
+            if ( l == 0 ) throw new NumberFormatException("empty String");
+            int i = 0;
+            switch ( c = in.charAt( i ) ){
+            case '-':
+                isNegative = true;
+                //FALLTHROUGH
+            case '+':
+                i++;
+                signSeen = true;
+            }
+
+            // Check for NaN and Infinity strings
+            c = in.charAt(i);
+            if(c == 'N' || c == 'I') { // possible NaN or infinity
+                boolean potentialNaN = false;
+                char targetChars[] = null;  // char array of "NaN" or "Infinity"
+
+                if(c == 'N') {
+                    targetChars = notANumber;
+                    potentialNaN = true;
+                } else {
+                    targetChars = infinity;
+                }
+
+                // compare Input string to "NaN" or "Infinity"
+                int j = 0;
+                while(i < l && j < targetChars.length) {
+                    if(in.charAt(i) == targetChars[j]) {
+                        i++; j++;
+                    }
+                    else // something is amiss, throw exception
+                        break parseNumber;
+                }
+
+                // For the candidate string to be a NaN or infinity,
+                // all characters in input string and target char[]
+                // must be matched ==> j must equal targetChars.length
+                // and i must equal l
+                if( (j == targetChars.length) && (i == l) ) { // return NaN or infinity
+                    return (potentialNaN ? new OldFloatingDecimalForTest(Double.NaN) // NaN has no sign
+                            : new OldFloatingDecimalForTest(isNegative?
+                                                  Double.NEGATIVE_INFINITY:
+                                                  Double.POSITIVE_INFINITY)) ;
+                }
+                else { // something went wrong, throw exception
+                    break parseNumber;
+                }
+
+            } else if (c == '0')  { // check for hexadecimal floating-point number
+                if (l > i+1 ) {
+                    char ch = in.charAt(i+1);
+                    if (ch == 'x' || ch == 'X' ) // possible hex string
+                        return parseHexString(in);
+                }
+            }  // look for and process decimal floating-point string
+
+            char[] digits = new char[ l ];
+            int    nDigits= 0;
+            boolean decSeen = false;
+            int decPt = 0;
+            int nLeadZero = 0;
+            int nTrailZero= 0;
+        digitLoop:
+            while ( i < l ){
+                switch ( c = in.charAt( i ) ){
+                case '0':
+                    if ( nDigits > 0 ){
+                        nTrailZero += 1;
+                    } else {
+                        nLeadZero += 1;
+                    }
+                    break; // out of switch.
+                case '1':
+                case '2':
+                case '3':
+                case '4':
+                case '5':
+                case '6':
+                case '7':
+                case '8':
+                case '9':
+                    while ( nTrailZero > 0 ){
+                        digits[nDigits++] = '0';
+                        nTrailZero -= 1;
+                    }
+                    digits[nDigits++] = c;
+                    break; // out of switch.
+                case '.':
+                    if ( decSeen ){
+                        // already saw one ., this is the 2nd.
+                        throw new NumberFormatException("multiple points");
+                    }
+                    decPt = i;
+                    if ( signSeen ){
+                        decPt -= 1;
+                    }
+                    decSeen = true;
+                    break; // out of switch.
+                default:
+                    break digitLoop;
+                }
+                i++;
+            }
+            /*
+             * At this point, we've scanned all the digits and decimal
+             * point we're going to see. Trim off leading and trailing
+             * zeros, which will just confuse us later, and adjust
+             * our initial decimal exponent accordingly.
+             * To review:
+             * we have seen i total characters.
+             * nLeadZero of them were zeros before any other digits.
+             * nTrailZero of them were zeros after any other digits.
+             * if ( decSeen ), then a . was seen after decPt characters
+             * ( including leading zeros which have been discarded )
+             * nDigits characters were neither lead nor trailing
+             * zeros, nor point
+             */
+            /*
+             * special hack: if we saw no non-zero digits, then the
+             * answer is zero!
+             * Unfortunately, we feel honor-bound to keep parsing!
+             */
+            if ( nDigits == 0 ){
+                digits = zero;
+                nDigits = 1;
+                if ( nLeadZero == 0 ){
+                    // we saw NO DIGITS AT ALL,
+                    // not even a crummy 0!
+                    // this is not allowed.
+                    break parseNumber; // go throw exception
+                }
+
+            }
+
+            /* Our initial exponent is decPt, adjusted by the number of
+             * discarded zeros. Or, if there was no decPt,
+             * then its just nDigits adjusted by discarded trailing zeros.
+             */
+            if ( decSeen ){
+                decExp = decPt - nLeadZero;
+            } else {
+                decExp = nDigits+nTrailZero;
+            }
+
+            /*
+             * Look for 'e' or 'E' and an optionally signed integer.
+             */
+            if ( (i < l) &&  (((c = in.charAt(i) )=='e') || (c == 'E') ) ){
+                int expSign = 1;
+                int expVal  = 0;
+                int reallyBig = Integer.MAX_VALUE / 10;
+                boolean expOverflow = false;
+                switch( in.charAt(++i) ){
+                case '-':
+                    expSign = -1;
+                    //FALLTHROUGH
+                case '+':
+                    i++;
+                }
+                int expAt = i;
+            expLoop:
+                while ( i < l  ){
+                    if ( expVal >= reallyBig ){
+                        // the next character will cause integer
+                        // overflow.
+                        expOverflow = true;
+                    }
+                    switch ( c = in.charAt(i++) ){
+                    case '0':
+                    case '1':
+                    case '2':
+                    case '3':
+                    case '4':
+                    case '5':
+                    case '6':
+                    case '7':
+                    case '8':
+                    case '9':
+                        expVal = expVal*10 + ( (int)c - (int)'0' );
+                        continue;
+                    default:
+                        i--;           // back up.
+                        break expLoop; // stop parsing exponent.
+                    }
+                }
+                int expLimit = bigDecimalExponent+nDigits+nTrailZero;
+                if ( expOverflow || ( expVal > expLimit ) ){
+                    //
+                    // The intent here is to end up with
+                    // infinity or zero, as appropriate.
+                    // The reason for yielding such a small decExponent,
+                    // rather than something intuitive such as
+                    // expSign*Integer.MAX_VALUE, is that this value
+                    // is subject to further manipulation in
+                    // doubleValue() and floatValue(), and I don't want
+                    // it to be able to cause overflow there!
+                    // (The only way we can get into trouble here is for
+                    // really outrageous nDigits+nTrailZero, such as 2 billion. )
+                    //
+                    decExp = expSign*expLimit;
+                } else {
+                    // this should not overflow, since we tested
+                    // for expVal > (MAX+N), where N >= abs(decExp)
+                    decExp = decExp + expSign*expVal;
+                }
+
+                // if we saw something not a digit ( or end of string )
+                // after the [Ee][+-], without seeing any digits at all
+                // this is certainly an error. If we saw some digits,
+                // but then some trailing garbage, that might be ok.
+                // so we just fall through in that case.
+                // HUMBUG
+                if ( i == expAt )
+                    break parseNumber; // certainly bad
+            }
+            /*
+             * We parsed everything we could.
+             * If there are leftovers, then this is not good input!
+             */
+            if ( i < l &&
+                ((i != l - 1) ||
+                (in.charAt(i) != 'f' &&
+                 in.charAt(i) != 'F' &&
+                 in.charAt(i) != 'd' &&
+                 in.charAt(i) != 'D'))) {
+                break parseNumber; // go throw exception
+            }
+
+            return new OldFloatingDecimalForTest( isNegative, decExp, digits, nDigits,  false );
+        } catch ( StringIndexOutOfBoundsException e ){ }
+        throw new NumberFormatException("For input string: \"" + in + "\"");
+    }
+
+    /*
+     * Take a FloatingDecimal, which we presumably just scanned in,
+     * and find out what its value is, as a double.
+     *
+     * AS A SIDE EFFECT, SET roundDir TO INDICATE PREFERRED
+     * ROUNDING DIRECTION in case the result is really destined
+     * for a single-precision float.
+     */
+
+    public strictfp double doubleValue(){
+        int     kDigits = Math.min( nDigits, maxDecimalDigits+1 );
+        long    lValue;
+        double  dValue;
+        double  rValue, tValue;
+
+        // First, check for NaN and Infinity values
+        if(digits == infinity || digits == notANumber) {
+            if(digits == notANumber)
+                return Double.NaN;
+            else
+                return (isNegative?Double.NEGATIVE_INFINITY:Double.POSITIVE_INFINITY);
+        }
+        else {
+            if (mustSetRoundDir) {
+                roundDir = 0;
+            }
+            /*
+             * convert the lead kDigits to a long integer.
+             */
+            // (special performance hack: start to do it using int)
+            int iValue = (int)digits[0]-(int)'0';
+            int iDigits = Math.min( kDigits, intDecimalDigits );
+            for ( int i=1; i < iDigits; i++ ){
+                iValue = iValue*10 + (int)digits[i]-(int)'0';
+            }
+            lValue = (long)iValue;
+            for ( int i=iDigits; i < kDigits; i++ ){
+                lValue = lValue*10L + (long)((int)digits[i]-(int)'0');
+            }
+            dValue = (double)lValue;
+            int exp = decExponent-kDigits;
+            /*
+             * lValue now contains a long integer with the value of
+             * the first kDigits digits of the number.
+             * dValue contains the (double) of the same.
+             */
+
+            if ( nDigits <= maxDecimalDigits ){
+                /*
+                 * possibly an easy case.
+                 * We know that the digits can be represented
+                 * exactly. And if the exponent isn't too outrageous,
+                 * the whole thing can be done with one operation,
+                 * thus one rounding error.
+                 * Note that all our constructors trim all leading and
+                 * trailing zeros, so simple values (including zero)
+                 * will always end up here
+                 */
+                if (exp == 0 || dValue == 0.0)
+                    return (isNegative)? -dValue : dValue; // small floating integer
+                else if ( exp >= 0 ){
+                    if ( exp <= maxSmallTen ){
+                        /*
+                         * Can get the answer with one operation,
+                         * thus one roundoff.
+                         */
+                        rValue = dValue * small10pow[exp];
+                        if ( mustSetRoundDir ){
+                            tValue = rValue / small10pow[exp];
+                            roundDir = ( tValue ==  dValue ) ? 0
+                                :( tValue < dValue ) ? 1
+                                : -1;
+                        }
+                        return (isNegative)? -rValue : rValue;
+                    }
+                    int slop = maxDecimalDigits - kDigits;
+                    if ( exp <= maxSmallTen+slop ){
+                        /*
+                         * We can multiply dValue by 10^(slop)
+                         * and it is still "small" and exact.
+                         * Then we can multiply by 10^(exp-slop)
+                         * with one rounding.
+                         */
+                        dValue *= small10pow[slop];
+                        rValue = dValue * small10pow[exp-slop];
+
+                        if ( mustSetRoundDir ){
+                            tValue = rValue / small10pow[exp-slop];
+                            roundDir = ( tValue ==  dValue ) ? 0
+                                :( tValue < dValue ) ? 1
+                                : -1;
+                        }
+                        return (isNegative)? -rValue : rValue;
+                    }
+                    /*
+                     * Else we have a hard case with a positive exp.
+                     */
+                } else {
+                    if ( exp >= -maxSmallTen ){
+                        /*
+                         * Can get the answer in one division.
+                         */
+                        rValue = dValue / small10pow[-exp];
+                        tValue = rValue * small10pow[-exp];
+                        if ( mustSetRoundDir ){
+                            roundDir = ( tValue ==  dValue ) ? 0
+                                :( tValue < dValue ) ? 1
+                                : -1;
+                        }
+                        return (isNegative)? -rValue : rValue;
+                    }
+                    /*
+                     * Else we have a hard case with a negative exp.
+                     */
+                }
+            }
+
+            /*
+             * Harder cases:
+             * The sum of digits plus exponent is greater than
+             * what we think we can do with one error.
+             *
+             * Start by approximating the right answer by,
+             * naively, scaling by powers of 10.
+             */
+            if ( exp > 0 ){
+                if ( decExponent > maxDecimalExponent+1 ){
+                    /*
+                     * Lets face it. This is going to be
+                     * Infinity. Cut to the chase.
+                     */
+                    return (isNegative)? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
+                }
+                if ( (exp&15) != 0 ){
+                    dValue *= small10pow[exp&15];
+                }
+                if ( (exp>>=4) != 0 ){
+                    int j;
+                    for( j = 0; exp > 1; j++, exp>>=1 ){
+                        if ( (exp&1)!=0)
+                            dValue *= big10pow[j];
+                    }
+                    /*
+                     * The reason for the weird exp > 1 condition
+                     * in the above loop was so that the last multiply
+                     * would get unrolled. We handle it here.
+                     * It could overflow.
+                     */
+                    double t = dValue * big10pow[j];
+                    if ( Double.isInfinite( t ) ){
+                        /*
+                         * It did overflow.
+                         * Look more closely at the result.
+                         * If the exponent is just one too large,
+                         * then use the maximum finite as our estimate
+                         * value. Else call the result infinity
+                         * and punt it.
+                         * ( I presume this could happen because
+                         * rounding forces the result here to be
+                         * an ULP or two larger than
+                         * Double.MAX_VALUE ).
+                         */
+                        t = dValue / 2.0;
+                        t *= big10pow[j];
+                        if ( Double.isInfinite( t ) ){
+                            return (isNegative)? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
+                        }
+                        t = Double.MAX_VALUE;
+                    }
+                    dValue = t;
+                }
+            } else if ( exp < 0 ){
+                exp = -exp;
+                if ( decExponent < minDecimalExponent-1 ){
+                    /*
+                     * Lets face it. This is going to be
+                     * zero. Cut to the chase.
+                     */
+                    return (isNegative)? -0.0 : 0.0;
+                }
+                if ( (exp&15) != 0 ){
+                    dValue /= small10pow[exp&15];
+                }
+                if ( (exp>>=4) != 0 ){
+                    int j;
+                    for( j = 0; exp > 1; j++, exp>>=1 ){
+                        if ( (exp&1)!=0)
+                            dValue *= tiny10pow[j];
+                    }
+                    /*
+                     * The reason for the weird exp > 1 condition
+                     * in the above loop was so that the last multiply
+                     * would get unrolled. We handle it here.
+                     * It could underflow.
+                     */
+                    double t = dValue * tiny10pow[j];
+                    if ( t == 0.0 ){
+                        /*
+                         * It did underflow.
+                         * Look more closely at the result.
+                         * If the exponent is just one too small,
+                         * then use the minimum finite as our estimate
+                         * value. Else call the result 0.0
+                         * and punt it.
+                         * ( I presume this could happen because
+                         * rounding forces the result here to be
+                         * an ULP or two less than
+                         * Double.MIN_VALUE ).
+                         */
+                        t = dValue * 2.0;
+                        t *= tiny10pow[j];
+                        if ( t == 0.0 ){
+                            return (isNegative)? -0.0 : 0.0;
+                        }
+                        t = Double.MIN_VALUE;
+                    }
+                    dValue = t;
+                }
+            }
+
+            /*
+             * dValue is now approximately the result.
+             * The hard part is adjusting it, by comparison
+             * with OldFDBigIntForTest arithmetic.
+             * Formulate the EXACT big-number result as
+             * bigD0 * 10^exp
+             */
+            OldFDBigIntForTest bigD0 = new OldFDBigIntForTest( lValue, digits, kDigits, nDigits );
+            exp   = decExponent - nDigits;
+
+            correctionLoop:
+            while(true){
+                /* AS A SIDE EFFECT, THIS METHOD WILL SET THE INSTANCE VARIABLES
+                 * bigIntExp and bigIntNBits
+                 */
+                OldFDBigIntForTest bigB = doubleToBigInt( dValue );
+
+                /*
+                 * Scale bigD, bigB appropriately for
+                 * big-integer operations.
+                 * Naively, we multiply by powers of ten
+                 * and powers of two. What we actually do
+                 * is keep track of the powers of 5 and
+                 * powers of 2 we would use, then factor out
+                 * common divisors before doing the work.
+                 */
+                int B2, B5; // powers of 2, 5 in bigB
+                int     D2, D5; // powers of 2, 5 in bigD
+                int Ulp2;   // powers of 2 in halfUlp.
+                if ( exp >= 0 ){
+                    B2 = B5 = 0;
+                    D2 = D5 = exp;
+                } else {
+                    B2 = B5 = -exp;
+                    D2 = D5 = 0;
+                }
+                if ( bigIntExp >= 0 ){
+                    B2 += bigIntExp;
+                } else {
+                    D2 -= bigIntExp;
+                }
+                Ulp2 = B2;
+                // shift bigB and bigD left by a number s. t.
+                // halfUlp is still an integer.
+                int hulpbias;
+                if ( bigIntExp+bigIntNBits <= -expBias+1 ){
+                    // This is going to be a denormalized number
+                    // (if not actually zero).
+                    // half an ULP is at 2^-(expBias+expShift+1)
+                    hulpbias = bigIntExp+ expBias + expShift;
+                } else {
+                    hulpbias = expShift + 2 - bigIntNBits;
+                }
+                B2 += hulpbias;
+                D2 += hulpbias;
+                // if there are common factors of 2, we might just as well
+                // factor them out, as they add nothing useful.
+                int common2 = Math.min( B2, Math.min( D2, Ulp2 ) );
+                B2 -= common2;
+                D2 -= common2;
+                Ulp2 -= common2;
+                // do multiplications by powers of 5 and 2
+                bigB = multPow52( bigB, B5, B2 );
+                OldFDBigIntForTest bigD = multPow52( new OldFDBigIntForTest( bigD0 ), D5, D2 );
+                //
+                // to recap:
+                // bigB is the scaled-big-int version of our floating-point
+                // candidate.
+                // bigD is the scaled-big-int version of the exact value
+                // as we understand it.
+                // halfUlp is 1/2 an ulp of bigB, except for special cases
+                // of exact powers of 2
+                //
+                // the plan is to compare bigB with bigD, and if the difference
+                // is less than halfUlp, then we're satisfied. Otherwise,
+                // use the ratio of difference to halfUlp to calculate a fudge
+                // factor to add to the floating value, then go 'round again.
+                //
+                OldFDBigIntForTest diff;
+                int cmpResult;
+                boolean overvalue;
+                if ( (cmpResult = bigB.cmp( bigD ) ) > 0 ){
+                    overvalue = true; // our candidate is too big.
+                    diff = bigB.sub( bigD );
+                    if ( (bigIntNBits == 1) && (bigIntExp > -expBias+1) ){
+                        // candidate is a normalized exact power of 2 and
+                        // is too big. We will be subtracting.
+                        // For our purposes, ulp is the ulp of the
+                        // next smaller range.
+                        Ulp2 -= 1;
+                        if ( Ulp2 < 0 ){
+                            // rats. Cannot de-scale ulp this far.
+                            // must scale diff in other direction.
+                            Ulp2 = 0;
+                            diff.lshiftMe( 1 );
+                        }
+                    }
+                } else if ( cmpResult < 0 ){
+                    overvalue = false; // our candidate is too small.
+                    diff = bigD.sub( bigB );
+                } else {
+                    // the candidate is exactly right!
+                    // this happens with surprising frequency
+                    break correctionLoop;
+                }
+                OldFDBigIntForTest halfUlp = constructPow52( B5, Ulp2 );
+                if ( (cmpResult = diff.cmp( halfUlp ) ) < 0 ){
+                    // difference is small.
+                    // this is close enough
+                    if (mustSetRoundDir) {
+                        roundDir = overvalue ? -1 : 1;
+                    }
+                    break correctionLoop;
+                } else if ( cmpResult == 0 ){
+                    // difference is exactly half an ULP
+                    // round to some other value maybe, then finish
+                    dValue += 0.5*ulp( dValue, overvalue );
+                    // should check for bigIntNBits == 1 here??
+                    if (mustSetRoundDir) {
+                        roundDir = overvalue ? -1 : 1;
+                    }
+                    break correctionLoop;
+                } else {
+                    // difference is non-trivial.
+                    // could scale addend by ratio of difference to
+                    // halfUlp here, if we bothered to compute that difference.
+                    // Most of the time ( I hope ) it is about 1 anyway.
+                    dValue += ulp( dValue, overvalue );
+                    if ( dValue == 0.0 || dValue == Double.POSITIVE_INFINITY )
+                        break correctionLoop; // oops. Fell off end of range.
+                    continue; // try again.
+                }
+
+            }
+            return (isNegative)? -dValue : dValue;
+        }
+    }
+
+    /*
+     * Take a FloatingDecimal, which we presumably just scanned in,
+     * and find out what its value is, as a float.
+     * This is distinct from doubleValue() to avoid the extremely
+     * unlikely case of a double rounding error, wherein the conversion
+     * to double has one rounding error, and the conversion of that double
+     * to a float has another rounding error, IN THE WRONG DIRECTION,
+     * ( because of the preference to a zero low-order bit ).
+     */
+
+    public strictfp float floatValue(){
+        int     kDigits = Math.min( nDigits, singleMaxDecimalDigits+1 );
+        int     iValue;
+        float   fValue;
+
+        // First, check for NaN and Infinity values
+        if(digits == infinity || digits == notANumber) {
+            if(digits == notANumber)
+                return Float.NaN;
+            else
+                return (isNegative?Float.NEGATIVE_INFINITY:Float.POSITIVE_INFINITY);
+        }
+        else {
+            /*
+             * convert the lead kDigits to an integer.
+             */
+            iValue = (int)digits[0]-(int)'0';
+            for ( int i=1; i < kDigits; i++ ){
+                iValue = iValue*10 + (int)digits[i]-(int)'0';
+            }
+            fValue = (float)iValue;
+            int exp = decExponent-kDigits;
+            /*
+             * iValue now contains an integer with the value of
+             * the first kDigits digits of the number.
+             * fValue contains the (float) of the same.
+             */
+
+            if ( nDigits <= singleMaxDecimalDigits ){
+                /*
+                 * possibly an easy case.
+                 * We know that the digits can be represented
+                 * exactly. And if the exponent isn't too outrageous,
+                 * the whole thing can be done with one operation,
+                 * thus one rounding error.
+                 * Note that all our constructors trim all leading and
+                 * trailing zeros, so simple values (including zero)
+                 * will always end up here.
+                 */
+                if (exp == 0 || fValue == 0.0f)
+                    return (isNegative)? -fValue : fValue; // small floating integer
+                else if ( exp >= 0 ){
+                    if ( exp <= singleMaxSmallTen ){
+                        /*
+                         * Can get the answer with one operation,
+                         * thus one roundoff.
+                         */
+                        fValue *= singleSmall10pow[exp];
+                        return (isNegative)? -fValue : fValue;
+                    }
+                    int slop = singleMaxDecimalDigits - kDigits;
+                    if ( exp <= singleMaxSmallTen+slop ){
+                        /*
+                         * We can multiply dValue by 10^(slop)
+                         * and it is still "small" and exact.
+                         * Then we can multiply by 10^(exp-slop)
+                         * with one rounding.
+                         */
+                        fValue *= singleSmall10pow[slop];
+                        fValue *= singleSmall10pow[exp-slop];
+                        return (isNegative)? -fValue : fValue;
+                    }
+                    /*
+                     * Else we have a hard case with a positive exp.
+                     */
+                } else {
+                    if ( exp >= -singleMaxSmallTen ){
+                        /*
+                         * Can get the answer in one division.
+                         */
+                        fValue /= singleSmall10pow[-exp];
+                        return (isNegative)? -fValue : fValue;
+                    }
+                    /*
+                     * Else we have a hard case with a negative exp.
+                     */
+                }
+            } else if ( (decExponent >= nDigits) && (nDigits+decExponent <= maxDecimalDigits) ){
+                /*
+                 * In double-precision, this is an exact floating integer.
+                 * So we can compute to double, then shorten to float
+                 * with one round, and get the right answer.
+                 *
+                 * First, finish accumulating digits.
+                 * Then convert that integer to a double, multiply
+                 * by the appropriate power of ten, and convert to float.
+                 */
+                long lValue = (long)iValue;
+                for ( int i=kDigits; i < nDigits; i++ ){
+                    lValue = lValue*10L + (long)((int)digits[i]-(int)'0');
+                }
+                double dValue = (double)lValue;
+                exp = decExponent-nDigits;
+                dValue *= small10pow[exp];
+                fValue = (float)dValue;
+                return (isNegative)? -fValue : fValue;
+
+            }
+            /*
+             * Harder cases:
+             * The sum of digits plus exponent is greater than
+             * what we think we can do with one error.
+             *
+             * Start by weeding out obviously out-of-range
+             * results, then convert to double and go to
+             * common hard-case code.
+             */
+            if ( decExponent > singleMaxDecimalExponent+1 ){
+                /*
+                 * Lets face it. This is going to be
+                 * Infinity. Cut to the chase.
+                 */
+                return (isNegative)? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
+            } else if ( decExponent < singleMinDecimalExponent-1 ){
+                /*
+                 * Lets face it. This is going to be
+                 * zero. Cut to the chase.
+                 */
+                return (isNegative)? -0.0f : 0.0f;
+            }
+
+            /*
+             * Here, we do 'way too much work, but throwing away
+             * our partial results, and going and doing the whole
+             * thing as double, then throwing away half the bits that computes
+             * when we convert back to float.
+             *
+             * The alternative is to reproduce the whole multiple-precision
+             * algorithm for float precision, or to try to parameterize it
+             * for common usage. The former will take about 400 lines of code,
+             * and the latter I tried without success. Thus the semi-hack
+             * answer here.
+             */
+            mustSetRoundDir = !fromHex;
+            double dValue = doubleValue();
+            return stickyRound( dValue );
+        }
+    }
+
+
+    /*
+     * All the positive powers of 10 that can be
+     * represented exactly in double/float.
+     */
+    private static final double small10pow[] = {
+        1.0e0,
+        1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,
+        1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10,
+        1.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15,
+        1.0e16, 1.0e17, 1.0e18, 1.0e19, 1.0e20,
+        1.0e21, 1.0e22
+    };
+
+    private static final float singleSmall10pow[] = {
+        1.0e0f,
+        1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
+        1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
+    };
+
+    private static final double big10pow[] = {
+        1e16, 1e32, 1e64, 1e128, 1e256 };
+    private static final double tiny10pow[] = {
+        1e-16, 1e-32, 1e-64, 1e-128, 1e-256 };
+
+    private static final int maxSmallTen = small10pow.length-1;
+    private static final int singleMaxSmallTen = singleSmall10pow.length-1;
+
+    private static final int small5pow[] = {
+        1,
+        5,
+        5*5,
+        5*5*5,
+        5*5*5*5,
+        5*5*5*5*5,
+        5*5*5*5*5*5,
+        5*5*5*5*5*5*5,
+        5*5*5*5*5*5*5*5,
+        5*5*5*5*5*5*5*5*5,
+        5*5*5*5*5*5*5*5*5*5,
+        5*5*5*5*5*5*5*5*5*5*5,
+        5*5*5*5*5*5*5*5*5*5*5*5,
+        5*5*5*5*5*5*5*5*5*5*5*5*5
+    };
+
+
+    private static final long long5pow[] = {
+        1L,
+        5L,
+        5L*5,
+        5L*5*5,
+        5L*5*5*5,
+        5L*5*5*5*5,
+        5L*5*5*5*5*5,
+        5L*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
+        5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
+    };
+
+    // approximately ceil( log2( long5pow[i] ) )
+    private static final int n5bits[] = {
+        0,
+        3,
+        5,
+        7,
+        10,
+        12,
+        14,
+        17,
+        19,
+        21,
+        24,
+        26,
+        28,
+        31,
+        33,
+        35,
+        38,
+        40,
+        42,
+        45,
+        47,
+        49,
+        52,
+        54,
+        56,
+        59,
+        61,
+    };
+
+    private static final char infinity[] = { 'I', 'n', 'f', 'i', 'n', 'i', 't', 'y' };
+    private static final char notANumber[] = { 'N', 'a', 'N' };
+    private static final char zero[] = { '0', '0', '0', '0', '0', '0', '0', '0' };
+
+
+    /*
+     * Grammar is compatible with hexadecimal floating-point constants
+     * described in section 6.4.4.2 of the C99 specification.
+     */
+    private static Pattern hexFloatPattern = null;
+    private static synchronized Pattern getHexFloatPattern() {
+        if (hexFloatPattern == null) {
+           hexFloatPattern = Pattern.compile(
+                   //1           234                   56                7                   8      9
+                    "([-+])?0[xX](((\\p{XDigit}+)\\.?)|((\\p{XDigit}*)\\.(\\p{XDigit}+)))[pP]([-+])?(\\p{Digit}+)[fFdD]?"
+                    );
+        }
+        return hexFloatPattern;
+    }
+
+    /*
+     * Convert string s to a suitable floating decimal; uses the
+     * double constructor and set the roundDir variable appropriately
+     * in case the value is later converted to a float.
+     */
+   static OldFloatingDecimalForTest parseHexString(String s) {
+        // Verify string is a member of the hexadecimal floating-point
+        // string language.
+        Matcher m = getHexFloatPattern().matcher(s);
+        boolean validInput = m.matches();
+
+        if (!validInput) {
+            // Input does not match pattern
+            throw new NumberFormatException("For input string: \"" + s + "\"");
+        } else { // validInput
+            /*
+             * We must isolate the sign, significand, and exponent
+             * fields.  The sign value is straightforward.  Since
+             * floating-point numbers are stored with a normalized
+             * representation, the significand and exponent are
+             * interrelated.
+             *
+             * After extracting the sign, we normalized the
+             * significand as a hexadecimal value, calculating an
+             * exponent adjust for any shifts made during
+             * normalization.  If the significand is zero, the
+             * exponent doesn't need to be examined since the output
+             * will be zero.
+             *
+             * Next the exponent in the input string is extracted.
+             * Afterwards, the significand is normalized as a *binary*
+             * value and the input value's normalized exponent can be
+             * computed.  The significand bits are copied into a
+             * double significand; if the string has more logical bits
+             * than can fit in a double, the extra bits affect the
+             * round and sticky bits which are used to round the final
+             * value.
+             */
+
+            //  Extract significand sign
+            String group1 = m.group(1);
+            double sign = (( group1 == null ) || group1.equals("+"))? 1.0 : -1.0;
+
+
+            //  Extract Significand magnitude
+            /*
+             * Based on the form of the significand, calculate how the
+             * binary exponent needs to be adjusted to create a
+             * normalized *hexadecimal* floating-point number; that
+             * is, a number where there is one nonzero hex digit to
+             * the left of the (hexa)decimal point.  Since we are
+             * adjusting a binary, not hexadecimal exponent, the
+             * exponent is adjusted by a multiple of 4.
+             *
+             * There are a number of significand scenarios to consider;
+             * letters are used in indicate nonzero digits:
+             *
+             * 1. 000xxxx       =>      x.xxx   normalized
+             *    increase exponent by (number of x's - 1)*4
+             *
+             * 2. 000xxx.yyyy =>        x.xxyyyy        normalized
+             *    increase exponent by (number of x's - 1)*4
+             *
+             * 3. .000yyy  =>   y.yy    normalized
+             *    decrease exponent by (number of zeros + 1)*4
+             *
+             * 4. 000.00000yyy => y.yy normalized
+             *    decrease exponent by (number of zeros to right of point + 1)*4
+             *
+             * If the significand is exactly zero, return a properly
+             * signed zero.
+             */
+
+            String significandString =null;
+            int signifLength = 0;
+            int exponentAdjust = 0;
+            {
+                int leftDigits  = 0; // number of meaningful digits to
+                                     // left of "decimal" point
+                                     // (leading zeros stripped)
+                int rightDigits = 0; // number of digits to right of
+                                     // "decimal" point; leading zeros
+                                     // must always be accounted for
+                /*
+                 * The significand is made up of either
+                 *
+                 * 1. group 4 entirely (integer portion only)
+                 *
+                 * OR
+                 *
+                 * 2. the fractional portion from group 7 plus any
+                 * (optional) integer portions from group 6.
+                 */
+                String group4;
+                if( (group4 = m.group(4)) != null) {  // Integer-only significand
+                    // Leading zeros never matter on the integer portion
+                    significandString = stripLeadingZeros(group4);
+                    leftDigits = significandString.length();
+                }
+                else {
+                    // Group 6 is the optional integer; leading zeros
+                    // never matter on the integer portion
+                    String group6 = stripLeadingZeros(m.group(6));
+                    leftDigits = group6.length();
+
+                    // fraction
+                    String group7 = m.group(7);
+                    rightDigits = group7.length();
+
+                    // Turn "integer.fraction" into "integer"+"fraction"
+                    significandString =
+                        ((group6 == null)?"":group6) + // is the null
+                        // check necessary?
+                        group7;
+                }
+
+                significandString = stripLeadingZeros(significandString);
+                signifLength  = significandString.length();
+
+                /*
+                 * Adjust exponent as described above
+                 */
+                if (leftDigits >= 1) {  // Cases 1 and 2
+                    exponentAdjust = 4*(leftDigits - 1);
+                } else {                // Cases 3 and 4
+                    exponentAdjust = -4*( rightDigits - signifLength + 1);
+                }
+
+                // If the significand is zero, the exponent doesn't
+                // matter; return a properly signed zero.
+
+                if (signifLength == 0) { // Only zeros in input
+                    return new OldFloatingDecimalForTest(sign * 0.0);
+                }
+            }
+
+            //  Extract Exponent
+            /*
+             * Use an int to read in the exponent value; this should
+             * provide more than sufficient range for non-contrived
+             * inputs.  If reading the exponent in as an int does
+             * overflow, examine the sign of the exponent and
+             * significand to determine what to do.
+             */
+            String group8 = m.group(8);
+            boolean positiveExponent = ( group8 == null ) || group8.equals("+");
+            long unsignedRawExponent;
+            try {
+                unsignedRawExponent = Integer.parseInt(m.group(9));
+            }
+            catch (NumberFormatException e) {
+                // At this point, we know the exponent is
+                // syntactically well-formed as a sequence of
+                // digits.  Therefore, if an NumberFormatException
+                // is thrown, it must be due to overflowing int's
+                // range.  Also, at this point, we have already
+                // checked for a zero significand.  Thus the signs
+                // of the exponent and significand determine the
+                // final result:
+                //
+                //                      significand
+                //                      +               -
+                // exponent     +       +infinity       -infinity
+                //              -       +0.0            -0.0
+                return new OldFloatingDecimalForTest(sign * (positiveExponent ?
+                                                   Double.POSITIVE_INFINITY : 0.0));
+            }
+
+            long rawExponent =
+                (positiveExponent ? 1L : -1L) * // exponent sign
+                unsignedRawExponent;            // exponent magnitude
+
+            // Calculate partially adjusted exponent
+            long exponent = rawExponent + exponentAdjust ;
+
+            // Starting copying non-zero bits into proper position in
+            // a long; copy explicit bit too; this will be masked
+            // later for normal values.
+
+            boolean round = false;
+            boolean sticky = false;
+            int bitsCopied=0;
+            int nextShift=0;
+            long significand=0L;
+            // First iteration is different, since we only copy
+            // from the leading significand bit; one more exponent
+            // adjust will be needed...
+
+            // IMPORTANT: make leadingDigit a long to avoid
+            // surprising shift semantics!
+            long leadingDigit = getHexDigit(significandString, 0);
+
+            /*
+             * Left shift the leading digit (53 - (bit position of
+             * leading 1 in digit)); this sets the top bit of the
+             * significand to 1.  The nextShift value is adjusted
+             * to take into account the number of bit positions of
+             * the leadingDigit actually used.  Finally, the
+             * exponent is adjusted to normalize the significand
+             * as a binary value, not just a hex value.
+             */
+            if (leadingDigit == 1) {
+                significand |= leadingDigit << 52;
+                nextShift = 52 - 4;
+                /* exponent += 0 */     }
+            else if (leadingDigit <= 3) { // [2, 3]
+                significand |= leadingDigit << 51;
+                nextShift = 52 - 5;
+                exponent += 1;
+            }
+            else if (leadingDigit <= 7) { // [4, 7]
+                significand |= leadingDigit << 50;
+                nextShift = 52 - 6;
+                exponent += 2;
+            }
+            else if (leadingDigit <= 15) { // [8, f]
+                significand |= leadingDigit << 49;
+                nextShift = 52 - 7;
+                exponent += 3;
+            } else {
+                throw new AssertionError("Result from digit conversion too large!");
+            }
+            // The preceding if-else could be replaced by a single
+            // code block based on the high-order bit set in
+            // leadingDigit.  Given leadingOnePosition,
+
+            // significand |= leadingDigit << (SIGNIFICAND_WIDTH - leadingOnePosition);
+            // nextShift = 52 - (3 + leadingOnePosition);
+            // exponent += (leadingOnePosition-1);
+
+
+            /*
+             * Now the exponent variable is equal to the normalized
+             * binary exponent.  Code below will make representation
+             * adjustments if the exponent is incremented after
+             * rounding (includes overflows to infinity) or if the
+             * result is subnormal.
+             */
+
+            // Copy digit into significand until the significand can't
+            // hold another full hex digit or there are no more input
+            // hex digits.
+            int i = 0;
+            for(i = 1;
+                i < signifLength && nextShift >= 0;
+                i++) {
+                long currentDigit = getHexDigit(significandString, i);
+                significand |= (currentDigit << nextShift);
+                nextShift-=4;
+            }
+
+            // After the above loop, the bulk of the string is copied.
+            // Now, we must copy any partial hex digits into the
+            // significand AND compute the round bit and start computing
+            // sticky bit.
+
+            if ( i < signifLength ) { // at least one hex input digit exists
+                long currentDigit = getHexDigit(significandString, i);
+
+                // from nextShift, figure out how many bits need
+                // to be copied, if any
+                switch(nextShift) { // must be negative
+                case -1:
+                    // three bits need to be copied in; can
+                    // set round bit
+                    significand |= ((currentDigit & 0xEL) >> 1);
+                    round = (currentDigit & 0x1L)  != 0L;
+                    break;
+
+                case -2:
+                    // two bits need to be copied in; can
+                    // set round and start sticky
+                    significand |= ((currentDigit & 0xCL) >> 2);
+                    round = (currentDigit &0x2L)  != 0L;
+                    sticky = (currentDigit & 0x1L) != 0;
+                    break;
+
+                case -3:
+                    // one bit needs to be copied in
+                    significand |= ((currentDigit & 0x8L)>>3);
+                    // Now set round and start sticky, if possible
+                    round = (currentDigit &0x4L)  != 0L;
+                    sticky = (currentDigit & 0x3L) != 0;
+                    break;
+
+                case -4:
+                    // all bits copied into significand; set
+                    // round and start sticky
+                    round = ((currentDigit & 0x8L) != 0);  // is top bit set?
+                    // nonzeros in three low order bits?
+                    sticky = (currentDigit & 0x7L) != 0;
+                    break;
+
+                default:
+                    throw new AssertionError("Unexpected shift distance remainder.");
+                    // break;
+                }
+
+                // Round is set; sticky might be set.
+
+                // For the sticky bit, it suffices to check the
+                // current digit and test for any nonzero digits in
+                // the remaining unprocessed input.
+                i++;
+                while(i < signifLength && !sticky) {
+                    currentDigit =  getHexDigit(significandString,i);
+                    sticky = sticky || (currentDigit != 0);
+                    i++;
+                }
+
+            }
+            // else all of string was seen, round and sticky are
+            // correct as false.
+
+
+            // Check for overflow and update exponent accordingly.
+
+            if (exponent > DoubleConsts.MAX_EXPONENT) {         // Infinite result
+                // overflow to properly signed infinity
+                return new OldFloatingDecimalForTest(sign * Double.POSITIVE_INFINITY);
+            } else {  // Finite return value
+                if (exponent <= DoubleConsts.MAX_EXPONENT && // (Usually) normal result
+                    exponent >= DoubleConsts.MIN_EXPONENT) {
+
+                    // The result returned in this block cannot be a
+                    // zero or subnormal; however after the
+                    // significand is adjusted from rounding, we could
+                    // still overflow in infinity.
+
+                    // AND exponent bits into significand; if the
+                    // significand is incremented and overflows from
+                    // rounding, this combination will update the
+                    // exponent correctly, even in the case of
+                    // Double.MAX_VALUE overflowing to infinity.
+
+                    significand = (( (exponent +
+                                     (long)DoubleConsts.EXP_BIAS) <<
+                                     (DoubleConsts.SIGNIFICAND_WIDTH-1))
+                                   & DoubleConsts.EXP_BIT_MASK) |
+                        (DoubleConsts.SIGNIF_BIT_MASK & significand);
+
+                }  else  {  // Subnormal or zero
+                    // (exponent < DoubleConsts.MIN_EXPONENT)
+
+                    if (exponent < (DoubleConsts.MIN_SUB_EXPONENT -1 )) {
+                        // No way to round back to nonzero value
+                        // regardless of significand if the exponent is
+                        // less than -1075.
+                        return new OldFloatingDecimalForTest(sign * 0.0);
+                    } else { //  -1075 <= exponent <= MIN_EXPONENT -1 = -1023
+                        /*
+                         * Find bit position to round to; recompute
+                         * round and sticky bits, and shift
+                         * significand right appropriately.
+                         */
+
+                        sticky = sticky || round;
+                        round = false;
+
+                        // Number of bits of significand to preserve is
+                        // exponent - abs_min_exp +1
+                        // check:
+                        // -1075 +1074 + 1 = 0
+                        // -1023 +1074 + 1 = 52
+
+                        int bitsDiscarded = 53 -
+                            ((int)exponent - DoubleConsts.MIN_SUB_EXPONENT + 1);
+                        assert bitsDiscarded >= 1 && bitsDiscarded <= 53;
+
+                        // What to do here:
+                        // First, isolate the new round bit
+                        round = (significand & (1L << (bitsDiscarded -1))) != 0L;
+                        if (bitsDiscarded > 1) {
+                            // create mask to update sticky bits; low
+                            // order bitsDiscarded bits should be 1
+                            long mask = ~((~0L) << (bitsDiscarded -1));
+                            sticky = sticky || ((significand & mask) != 0L ) ;
+                        }
+
+                        // Now, discard the bits
+                        significand = significand >> bitsDiscarded;
+
+                        significand = (( ((long)(DoubleConsts.MIN_EXPONENT -1) + // subnorm exp.
+                                          (long)DoubleConsts.EXP_BIAS) <<
+                                         (DoubleConsts.SIGNIFICAND_WIDTH-1))
+                                       & DoubleConsts.EXP_BIT_MASK) |
+                            (DoubleConsts.SIGNIF_BIT_MASK & significand);
+                    }
+                }
+
+                // The significand variable now contains the currently
+                // appropriate exponent bits too.
+
+                /*
+                 * Determine if significand should be incremented;
+                 * making this determination depends on the least
+                 * significant bit and the round and sticky bits.
+                 *
+                 * Round to nearest even rounding table, adapted from
+                 * table 4.7 in "Computer Arithmetic" by IsraelKoren.
+                 * The digit to the left of the "decimal" point is the
+                 * least significant bit, the digits to the right of
+                 * the point are the round and sticky bits
+                 *
+                 * Number       Round(x)
+                 * x0.00        x0.
+                 * x0.01        x0.
+                 * x0.10        x0.
+                 * x0.11        x1. = x0. +1
+                 * x1.00        x1.
+                 * x1.01        x1.
+                 * x1.10        x1. + 1
+                 * x1.11        x1. + 1
+                 */
+                boolean incremented = false;
+                boolean leastZero  = ((significand & 1L) == 0L);
+                if( (  leastZero  && round && sticky ) ||
+                    ((!leastZero) && round )) {
+                    incremented = true;
+                    significand++;
+                }
+
+                OldFloatingDecimalForTest fd = new OldFloatingDecimalForTest(Math.copySign(
+                                                              Double.longBitsToDouble(significand),
+                                                              sign));
+
+                /*
+                 * Set roundingDir variable field of fd properly so
+                 * that the input string can be properly rounded to a
+                 * float value.  There are two cases to consider:
+                 *
+                 * 1. rounding to double discards sticky bit
+                 * information that would change the result of a float
+                 * rounding (near halfway case between two floats)
+                 *
+                 * 2. rounding to double rounds up when rounding up
+                 * would not occur when rounding to float.
+                 *
+                 * For former case only needs to be considered when
+                 * the bits rounded away when casting to float are all
+                 * zero; otherwise, float round bit is properly set
+                 * and sticky will already be true.
+                 *
+                 * The lower exponent bound for the code below is the
+                 * minimum (normalized) subnormal exponent - 1 since a
+                 * value with that exponent can round up to the
+                 * minimum subnormal value and the sticky bit
+                 * information must be preserved (i.e. case 1).
+                 */
+                if ((exponent >= FloatConsts.MIN_SUB_EXPONENT-1) &&
+                    (exponent <= FloatConsts.MAX_EXPONENT ) ){
+                    // Outside above exponent range, the float value
+                    // will be zero or infinity.
+
+                    /*
+                     * If the low-order 28 bits of a rounded double
+                     * significand are 0, the double could be a
+                     * half-way case for a rounding to float.  If the
+                     * double value is a half-way case, the double
+                     * significand may have to be modified to round
+                     * the the right float value (see the stickyRound
+                     * method).  If the rounding to double has lost
+                     * what would be float sticky bit information, the
+                     * double significand must be incremented.  If the
+                     * double value's significand was itself
+                     * incremented, the float value may end up too
+                     * large so the increment should be undone.
+                     */
+                    if ((significand & 0xfffffffL) ==  0x0L) {
+                        // For negative values, the sign of the
+                        // roundDir is the same as for positive values
+                        // since adding 1 increasing the significand's
+                        // magnitude and subtracting 1 decreases the
+                        // significand's magnitude.  If neither round
+                        // nor sticky is true, the double value is
+                        // exact and no adjustment is required for a
+                        // proper float rounding.
+                        if( round || sticky) {
+                            if (leastZero) { // prerounding lsb is 0
+                                // If round and sticky were both true,
+                                // and the least significant
+                                // significand bit were 0, the rounded
+                                // significand would not have its
+                                // low-order bits be zero.  Therefore,
+                                // we only need to adjust the
+                                // significand if round XOR sticky is
+                                // true.
+                                if (round ^ sticky) {
+                                    fd.roundDir =  1;
+                                }
+                            }
+                            else { // prerounding lsb is 1
+                                // If the prerounding lsb is 1 and the
+                                // resulting significand has its
+                                // low-order bits zero, the significand
+                                // was incremented.  Here, we undo the
+                                // increment, which will ensure the
+                                // right guard and sticky bits for the
+                                // float rounding.
+                                if (round)
+                                    fd.roundDir =  -1;
+                            }
+                        }
+                    }
+                }
+
+                fd.fromHex = true;
+                return fd;
+            }
+        }
+    }
+
+    /**
+     * Return <code>s</code> with any leading zeros removed.
+     */
+    static String stripLeadingZeros(String s) {
+        return  s.replaceFirst("^0+", "");
+    }
+
+    /**
+     * Extract a hexadecimal digit from position <code>position</code>
+     * of string <code>s</code>.
+     */
+    static int getHexDigit(String s, int position) {
+        int value = Character.digit(s.charAt(position), 16);
+        if (value <= -1 || value >= 16) {
+            throw new AssertionError("Unexpected failure of digit conversion of " +
+                                     s.charAt(position));
+        }
+        return value;
+    }
+
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/misc/FloatingDecimal/TestFDBigInteger.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,426 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.math.BigInteger;
+import java.util.Random;
+import sun.misc.FDBigInteger;
+
+/**
+ * @test
+ * @bug 7032154
+ * @summary unit testys of sun.misc.FDBigInteger
+ * @author Dmitry Nadezhin
+ */
+public class TestFDBigInteger {
+
+    private static final int MAX_P5 = 413;
+    private static final int MAX_P2 = 65;
+    private static final long LONG_SIGN_MASK = (1L << 63);
+    private static final BigInteger FIVE = BigInteger.valueOf(5);
+    private static final FDBigInteger MUTABLE_ZERO = FDBigInteger.valueOfPow52(0, 0).leftInplaceSub(FDBigInteger.valueOfPow52(0, 0));
+    private static final FDBigInteger IMMUTABLE_ZERO = FDBigInteger.valueOfPow52(0, 0).leftInplaceSub(FDBigInteger.valueOfPow52(0, 0));
+    private static final FDBigInteger IMMUTABLE_MILLION = genMillion1();
+    private static final FDBigInteger IMMUTABLE_BILLION = genBillion1();
+    private static final FDBigInteger IMMUTABLE_TEN18 = genTen18();
+
+    static {
+        IMMUTABLE_ZERO.makeImmutable();
+        IMMUTABLE_MILLION.makeImmutable();
+        IMMUTABLE_BILLION.makeImmutable();
+        IMMUTABLE_TEN18.makeImmutable();
+    }
+
+    private static FDBigInteger mutable(String hex, int offset) {
+        char[] chars = new BigInteger(hex, 16).toString().toCharArray();
+        return new FDBigInteger(0, chars, 0, chars.length).multByPow52(0, offset * 32);
+    }
+
+    private static FDBigInteger immutable(String hex, int offset) {
+        FDBigInteger fd = mutable(hex, offset);
+        fd.makeImmutable();
+        return fd;
+    }
+
+    private static BigInteger biPow52(int p5, int p2) {
+        return FIVE.pow(p5).shiftLeft(p2);
+    }
+
+    // data.length == 1, nWords == 1, offset == 0
+    private static FDBigInteger genMillion1() {
+        return FDBigInteger.valueOfPow52(6, 0).leftShift(6);
+    }
+
+    // data.length == 2, nWords == 1, offset == 0
+    private static FDBigInteger genMillion2() {
+        return FDBigInteger.valueOfMulPow52(1000000L, 0, 0);
+    }
+
+    // data.length == 1, nWords == 1, offset == 0
+    private static FDBigInteger genBillion1() {
+        return FDBigInteger.valueOfPow52(9, 0).leftShift(9);
+    }
+
+    // data.length == 2, nWords == 2, offset == 0
+    private static FDBigInteger genTen18() {
+        return FDBigInteger.valueOfPow52(18, 0).leftShift(18);
+    }
+
+    private static void check(BigInteger expected, FDBigInteger actual, String message) throws Exception {
+        if (!expected.equals(actual.toBigInteger())) {
+            throw new Exception(message + " result " + actual.toHexString() + " expected " + expected.toString(16));
+        }
+    }
+
+    private static void testValueOfPow52(int p5, int p2) throws Exception {
+        check(biPow52(p5, p2), FDBigInteger.valueOfPow52(p5, p2),
+                "valueOfPow52(" + p5 + "," + p2 + ")");
+    }
+
+    private static void testValueOfPow52() throws Exception {
+        for (int p5 = 0; p5 <= MAX_P5; p5++) {
+            for (int p2 = 0; p2 <= MAX_P2; p2++) {
+                testValueOfPow52(p5, p2);
+            }
+        }
+    }
+
+    private static void testValueOfMulPow52(long value, int p5, int p2) throws Exception {
+        BigInteger bi = BigInteger.valueOf(value & ~LONG_SIGN_MASK);
+        if (value < 0) {
+            bi = bi.setBit(63);
+        }
+        check(biPow52(p5, p2).multiply(bi), FDBigInteger.valueOfMulPow52(value, p5, p2),
+                "valueOfMulPow52(" + Long.toHexString(value) + "." + p5 + "," + p2 + ")");
+    }
+
+    private static void testValueOfMulPow52(long value, int p5) throws Exception {
+        testValueOfMulPow52(value, p5, 0);
+        testValueOfMulPow52(value, p5, 1);
+        testValueOfMulPow52(value, p5, 30);
+        testValueOfMulPow52(value, p5, 31);
+        testValueOfMulPow52(value, p5, 33);
+        testValueOfMulPow52(value, p5, 63);
+    }
+
+    private static void testValueOfMulPow52() throws Exception {
+        for (int p5 = 0; p5 <= MAX_P5; p5++) {
+            testValueOfMulPow52(0xFFFFFFFFL, p5);
+            testValueOfMulPow52(0x123456789AL, p5);
+            testValueOfMulPow52(0x7FFFFFFFFFFFFFFFL, p5);
+            testValueOfMulPow52(0xFFFFFFFFFFF54321L, p5);
+        }
+    }
+
+    private static void testLeftShift(FDBigInteger t, int shift, boolean isImmutable) throws Exception {
+        BigInteger bt = t.toBigInteger();
+        FDBigInteger r = t.leftShift(shift);
+        if ((bt.signum() == 0 || shift == 0 || !isImmutable) && r != t) {
+            throw new Exception("leftShift doesn't reuse its argument");
+        }
+        if (isImmutable) {
+            check(bt, t, "leftShift corrupts its argument");
+        }
+        check(bt.shiftLeft(shift), r, "leftShift returns wrong result");
+    }
+
+    private static void testLeftShift() throws Exception {
+        testLeftShift(IMMUTABLE_ZERO, 0, true);
+        testLeftShift(IMMUTABLE_ZERO, 10, true);
+        testLeftShift(MUTABLE_ZERO, 0, false);
+        testLeftShift(MUTABLE_ZERO, 10, false);
+
+        testLeftShift(IMMUTABLE_MILLION, 0, true);
+        testLeftShift(IMMUTABLE_MILLION, 1, true);
+        testLeftShift(IMMUTABLE_MILLION, 12, true);
+        testLeftShift(IMMUTABLE_MILLION, 13, true);
+        testLeftShift(IMMUTABLE_MILLION, 32, true);
+        testLeftShift(IMMUTABLE_MILLION, 33, true);
+        testLeftShift(IMMUTABLE_MILLION, 44, true);
+        testLeftShift(IMMUTABLE_MILLION, 45, true);
+
+        testLeftShift(genMillion1(), 0, false);
+        testLeftShift(genMillion1(), 1, false);
+        testLeftShift(genMillion1(), 12, false);
+        testLeftShift(genMillion1(), 13, false);
+        testLeftShift(genMillion1(), 25, false);
+        testLeftShift(genMillion1(), 26, false);
+        testLeftShift(genMillion1(), 32, false);
+        testLeftShift(genMillion1(), 33, false);
+        testLeftShift(genMillion1(), 44, false);
+        testLeftShift(genMillion1(), 45, false);
+
+        testLeftShift(genMillion2(), 0, false);
+        testLeftShift(genMillion2(), 1, false);
+        testLeftShift(genMillion2(), 12, false);
+        testLeftShift(genMillion2(), 13, false);
+        testLeftShift(genMillion2(), 25, false);
+        testLeftShift(genMillion2(), 26, false);
+        testLeftShift(genMillion2(), 32, false);
+        testLeftShift(genMillion2(), 33, false);
+        testLeftShift(genMillion2(), 44, false);
+        testLeftShift(genMillion2(), 45, false);
+    }
+
+    private static void testQuoRemIteration(FDBigInteger t, FDBigInteger s) throws Exception {
+        BigInteger bt = t.toBigInteger();
+        BigInteger bs = s.toBigInteger();
+        int q = t.quoRemIteration(s);
+        BigInteger[] qr = bt.divideAndRemainder(bs);
+        if (!BigInteger.valueOf(q).equals(qr[0])) {
+            throw new Exception("quoRemIteration returns incorrect quo");
+        }
+        check(qr[1].multiply(BigInteger.TEN), t, "quoRemIteration returns incorrect rem");
+    }
+
+    private static void testQuoRemIteration() throws Exception {
+        // IMMUTABLE_TEN18 == 0de0b6b3a7640000
+        // q = 0
+        testQuoRemIteration(mutable("00000001", 0), IMMUTABLE_TEN18);
+        testQuoRemIteration(mutable("00000001", 1), IMMUTABLE_TEN18);
+        testQuoRemIteration(mutable("0de0b6b2", 1), IMMUTABLE_TEN18);
+        // q = 1 -> q = 0
+        testQuoRemIteration(mutable("0de0b6b3", 1), IMMUTABLE_TEN18);
+        testQuoRemIteration(mutable("0de0b6b3a763FFFF", 0), IMMUTABLE_TEN18);
+        // q = 1
+        testQuoRemIteration(mutable("0de0b6b3a7640000", 0), IMMUTABLE_TEN18);
+        testQuoRemIteration(mutable("0de0b6b3FFFFFFFF", 0), IMMUTABLE_TEN18);
+        testQuoRemIteration(mutable("8ac72304", 1), IMMUTABLE_TEN18);
+        testQuoRemIteration(mutable("0de0b6b400000000", 0), IMMUTABLE_TEN18);
+        testQuoRemIteration(mutable("8ac72305", 1), IMMUTABLE_TEN18);
+        // q = 18
+        testQuoRemIteration(mutable("FFFFFFFF", 1), IMMUTABLE_TEN18);
+    }
+
+    private static void testCmp(FDBigInteger t, FDBigInteger o) throws Exception {
+        BigInteger bt = t.toBigInteger();
+        BigInteger bo = o.toBigInteger();
+        int cmp = t.cmp(o);
+        int bcmp = bt.compareTo(bo);
+        if (bcmp != cmp) {
+            throw new Exception("cmp returns " + cmp + " expected " + bcmp);
+        }
+        check(bt, t, "cmp corrupts this");
+        check(bo, o, "cmp corrupts other");
+        if (o.cmp(t) != -cmp) {
+            throw new Exception("asymmetrical cmp");
+        }
+        check(bt, t, "cmp corrupts this");
+        check(bo, o, "cmp corrupts other");
+    }
+
+    private static void testCmp() throws Exception {
+        testCmp(mutable("FFFFFFFF", 0), mutable("100000000", 0));
+        testCmp(mutable("FFFFFFFF", 0), mutable("1", 1));
+        testCmp(mutable("5", 0), mutable("6", 0));
+        testCmp(mutable("5", 0), mutable("5", 0));
+        testCmp(mutable("5000000001", 0), mutable("500000001", 0));
+        testCmp(mutable("5000000001", 0), mutable("6", 1));
+        testCmp(mutable("5000000001", 0), mutable("5", 1));
+        testCmp(mutable("5000000000", 0), mutable("5", 1));
+    }
+
+    private static void testCmpPow52(FDBigInteger t, int p5, int p2) throws Exception {
+        FDBigInteger o = FDBigInteger.valueOfPow52(p5, p2);
+        BigInteger bt = t.toBigInteger();
+        BigInteger bo = biPow52(p5, p2);
+        int cmp = t.cmp(o);
+        int bcmp = bt.compareTo(bo);
+        if (bcmp != cmp) {
+            throw new Exception("cmpPow52 returns " + cmp + " expected " + bcmp);
+        }
+        check(bt, t, "cmpPow52 corrupts this");
+        check(bo, o, "cmpPow5 corrupts other");
+    }
+
+    private static void testCmpPow52() throws Exception {
+        testCmpPow52(mutable("00000002", 1), 0, 31);
+        testCmpPow52(mutable("00000002", 1), 0, 32);
+        testCmpPow52(mutable("00000002", 1), 0, 33);
+        testCmpPow52(mutable("00000002", 1), 0, 34);
+        testCmpPow52(mutable("00000002", 1), 0, 64);
+        testCmpPow52(mutable("00000003", 1), 0, 32);
+        testCmpPow52(mutable("00000003", 1), 0, 33);
+        testCmpPow52(mutable("00000003", 1), 0, 34);
+    }
+
+    private static void testAddAndCmp(FDBigInteger t, FDBigInteger x, FDBigInteger y) throws Exception {
+        BigInteger bt = t.toBigInteger();
+        BigInteger bx = x.toBigInteger();
+        BigInteger by = y.toBigInteger();
+        int cmp = t.addAndCmp(x, y);
+        int bcmp = bt.compareTo(bx.add(by));
+        if (bcmp != cmp) {
+            throw new Exception("addAndCmp returns " + cmp + " expected " + bcmp);
+        }
+        check(bt, t, "addAndCmp corrupts this");
+        check(bx, x, "addAndCmp corrupts x");
+        check(by, y, "addAndCmp corrupts y");
+    }
+
+    private static void testAddAndCmp() throws Exception {
+        testAddAndCmp(MUTABLE_ZERO, MUTABLE_ZERO, MUTABLE_ZERO);
+        testAddAndCmp(mutable("00000001", 0), MUTABLE_ZERO, MUTABLE_ZERO);
+        testAddAndCmp(mutable("00000001", 0), mutable("00000001", 0), MUTABLE_ZERO);
+        testAddAndCmp(mutable("00000001", 0), MUTABLE_ZERO, mutable("00000001", 0));
+        testAddAndCmp(mutable("00000001", 0), mutable("00000002", 0), MUTABLE_ZERO);
+        testAddAndCmp(mutable("00000001", 0), MUTABLE_ZERO, mutable("00000002", 0));
+        testAddAndCmp(mutable("00000001", 2), mutable("FFFFFFFF", 0), mutable("FFFFFFFF", 0));
+        testAddAndCmp(mutable("00000001", 0), mutable("00000001", 1), mutable("00000001", 0));
+
+        testAddAndCmp(mutable("00000001", 2), mutable("0F0F0F0F80000000", 1), mutable("F0F0F0F080000000", 1));
+        testAddAndCmp(mutable("00000001", 2), mutable("0F0F0F0E80000000", 1), mutable("F0F0F0F080000000", 1));
+
+        testAddAndCmp(mutable("00000002", 1), mutable("0000000180000000", 1), mutable("0000000280000000", 1));
+        testAddAndCmp(mutable("00000003", 1), mutable("0000000180000000", 1), mutable("0000000280000000", 1));
+        testAddAndCmp(mutable("00000004", 1), mutable("0000000180000000", 1), mutable("0000000280000000", 1));
+        testAddAndCmp(mutable("00000005", 1), mutable("0000000180000000", 1), mutable("0000000280000000", 1));
+
+        testAddAndCmp(mutable("00000001", 2), mutable("8000000000000000", 0), mutable("8000000000000000", 0));
+        testAddAndCmp(mutable("00000001", 2), mutable("8000000000000000", 0), mutable("8000000000000001", 0));
+        testAddAndCmp(mutable("00000002", 2), mutable("8000000000000000", 0), mutable("8000000000000000", 0));
+        testAddAndCmp(mutable("00000003", 2), mutable("8000000000000000", 0), mutable("8000000000000000", 0));
+    }
+
+    private static void testMultBy10(FDBigInteger t, boolean isImmutable) throws Exception {
+        BigInteger bt = t.toBigInteger();
+        FDBigInteger r = t.multBy10();
+        if ((bt.signum() == 0 || !isImmutable) && r != t) {
+            throw new Exception("multBy10 of doesn't reuse its argument");
+        }
+        if (isImmutable) {
+            check(bt, t, "multBy10 corrupts its argument");
+        }
+        check(bt.multiply(BigInteger.TEN), r, "multBy10 returns wrong result");
+    }
+
+    private static void testMultBy10() throws Exception {
+        for (int p5 = 0; p5 <= MAX_P5; p5++) {
+            for (int p2 = 0; p2 <= MAX_P2; p2++) {
+                // This strange way of creating a value ensures that it is mutable.
+                FDBigInteger value = FDBigInteger.valueOfPow52(0, 0).multByPow52(p5, p2);
+                testMultBy10(value, false);
+                value.makeImmutable();
+                testMultBy10(value, true);
+            }
+        }
+    }
+
+    private static void testMultByPow52(FDBigInteger t, int p5, int p2) throws Exception {
+        BigInteger bt = t.toBigInteger();
+        FDBigInteger r = t.multByPow52(p5, p2);
+        if (bt.signum() == 0 && r != t) {
+            throw new Exception("multByPow52 of doesn't reuse its argument");
+        }
+        check(bt.multiply(biPow52(p5, p2)), r, "multByPow52 returns wrong result");
+    }
+
+    private static void testMultByPow52() throws Exception {
+        for (int p5 = 0; p5 <= MAX_P5; p5++) {
+            for (int p2 = 0; p2 <= MAX_P2; p2++) {
+                // This strange way of creating a value ensures that it is mutable.
+                FDBigInteger value = FDBigInteger.valueOfPow52(0, 0).multByPow52(p5, p2);
+                testMultByPow52(value, p5, p2);
+            }
+        }
+    }
+
+    private static void testLeftInplaceSub(FDBigInteger left, FDBigInteger right, boolean isImmutable) throws Exception {
+        BigInteger biLeft = left.toBigInteger();
+        BigInteger biRight = right.toBigInteger();
+        FDBigInteger diff = left.leftInplaceSub(right);
+        if (!isImmutable && diff != left) {
+            throw new Exception("leftInplaceSub of doesn't reuse its argument");
+        }
+        check(biLeft.subtract(biRight), diff, "leftInplaceSub returns wrong result");
+    }
+
+    private static void testLeftInplaceSub() throws Exception {
+        for (int p5 = 0; p5 <= MAX_P5; p5++) {
+            for (int p2 = 0; p2 <= MAX_P2; p2++) {
+//                for (int p5r = 0; p5r <= p5; p5r += 10) {
+//                    for (int p2r = 0; p2r <= p2; p2r += 10) {
+                for (int p5r = 0; p5r <= p5; p5r++) {
+                    for (int p2r = 0; p2r <= p2; p2r++) {
+                        // This strange way of creating a value ensures that it is mutable.
+                        FDBigInteger left = FDBigInteger.valueOfPow52(0, 0).multByPow52(p5, p2);
+                        FDBigInteger right = FDBigInteger.valueOfPow52(0, 0).multByPow52(p5r, p2r);
+                        testLeftInplaceSub(left, right, false);
+                        left = FDBigInteger.valueOfPow52(0, 0).multByPow52(p5, p2);
+                        left.makeImmutable();
+                        testLeftInplaceSub(left, right, true);
+                    }
+                }
+            }
+        }
+    }
+
+    private static void testRightInplaceSub(FDBigInteger left, FDBigInteger right, boolean isImmutable) throws Exception {
+        BigInteger biLeft = left.toBigInteger();
+        BigInteger biRight = right.toBigInteger();
+        FDBigInteger diff = left.rightInplaceSub(right);
+        if (!isImmutable && diff != right) {
+            throw new Exception("rightInplaceSub of doesn't reuse its argument");
+        }
+        try {
+            check(biLeft.subtract(biRight), diff, "rightInplaceSub returns wrong result");
+        } catch (Exception e) {
+            System.out.println(biLeft+" - "+biRight+" = "+biLeft.subtract(biRight));
+            throw e;
+        }
+    }
+
+    private static void testRightInplaceSub() throws Exception {
+        for (int p5 = 0; p5 <= MAX_P5; p5++) {
+            for (int p2 = 0; p2 <= MAX_P2; p2++) {
+//                for (int p5r = 0; p5r <= p5; p5r += 10) {
+//                    for (int p2r = 0; p2r <= p2; p2r += 10) {
+                for (int p5r = 0; p5r <= p5; p5r++) {
+                    for (int p2r = 0; p2r <= p2; p2r++) {
+                        // This strange way of creating a value ensures that it is mutable.
+                        FDBigInteger left = FDBigInteger.valueOfPow52(0, 0).multByPow52(p5, p2);
+                        FDBigInteger right = FDBigInteger.valueOfPow52(0, 0).multByPow52(p5r, p2r);
+                        testRightInplaceSub(left, right, false);
+                        right = FDBigInteger.valueOfPow52(0, 0).multByPow52(p5r, p2r);
+                        right.makeImmutable();
+                        testRightInplaceSub(left, right, true);
+                    }
+                }
+            }
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        testValueOfPow52();
+        testValueOfMulPow52();
+        testLeftShift();
+        testQuoRemIteration();
+        testCmp();
+        testCmpPow52();
+        testAddAndCmp();
+        // Uncomment the following for more comprehensize but slow testing.
+        // testLeftInplaceSub();
+        // testMultBy10();
+        // testMultByPow52();
+        // testRightInplaceSub();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/misc/FloatingDecimal/TestFloatingDecimal.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,324 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.util.Random;
+import sun.misc.FloatingDecimal;
+
+/*
+OldFloatingDecimalForTest
+
+public class OldFloatingDecimalForTest {
+  public boolean digitsRoundedUp();
+  public OldFloatingDecimalForTest(double);
+  public OldFloatingDecimalForTest(float);
+  public boolean decimalDigitsExact();
+  public java.lang.String toString();
+  public java.lang.String toJavaFormatString();
+  public void appendTo(java.lang.Appendable);
+  public static OldFloatingDecimalForTest readJavaFormatString(java.lang.String) throws java.lang.NumberFormatException;
+  public strictfp double doubleValue();
+  public strictfp float floatValue();
+}
+
+sun.misc.FloatingDecimal
+
+public class sun.misc.FloatingDecimal {
+  public sun.misc.FloatingDecimal();
+  public static java.lang.String toJavaFormatString(double);
+  public static java.lang.String toJavaFormatString(float);
+  public static void appendTo(double, java.lang.Appendable);
+  public static void appendTo(float, java.lang.Appendable);
+  public static double parseDouble(java.lang.String) throws java.lang.NumberFormatException;
+  public static float parseFloat(java.lang.String) throws java.lang.NumberFormatException;
+  public static sun.misc.FloatingDecimal$AbstractD2ABuffer getD2ABuffer(double);
+}
+*/
+
+/**
+ * @test
+ * @bug 7032154
+ * @summary unit tests of sun.misc.FloatingDecimal
+ * @author Brian Burkhalter
+ */
+public class TestFloatingDecimal {
+    private static enum ResultType {
+        RESULT_EXCEPTION,
+        RESULT_PRINT
+    }
+
+    private static final ResultType RESULT_TYPE = ResultType.RESULT_PRINT;
+    private static final int NUM_RANDOM_TESTS = 100000;
+
+    private static final Random RANDOM = new Random();
+
+    private static void result(String message) {
+        switch (RESULT_TYPE) {
+            case RESULT_EXCEPTION:
+                throw new RuntimeException(message);
+            case RESULT_PRINT:
+                System.err.println(message);
+                break;
+            default:
+                assert false;
+        }
+    }
+
+    private static int check(String test, Object expected, Object actual) {
+        int failures = 0;
+        if(!actual.equals(expected)) {
+            failures++;
+            result("Test "+test+" expected "+expected+" but obtained "+actual);
+        }
+        return failures;
+    }
+
+    private static int testAppendToDouble() {
+        System.out.println("  testAppendToDouble");
+        int failures = 0;
+
+        for(int i = 0; i < NUM_RANDOM_TESTS; i++) {
+            double[] d = new double[] {
+                RANDOM.nextLong(),
+                RANDOM.nextGaussian(),
+                RANDOM.nextDouble()*Double.MAX_VALUE
+            };
+            for(int j = 0; j < d.length; j++) {
+                OldFloatingDecimalForTest ofd = new OldFloatingDecimalForTest(d[j]);
+                StringBuilder sb = new StringBuilder();
+                ofd.appendTo(sb);
+                String oldString = sb.toString();
+                sb = new StringBuilder();
+                FloatingDecimal.appendTo(d[j], sb);
+                String newString = sb.toString();
+                failures += check("testAppendToDouble", oldString, newString);
+            }
+        }
+
+        return failures;
+    }
+
+    private static int testAppendToFloat() {
+        System.out.println("  testAppendToFloat");
+        int failures = 0;
+
+        for(int i = 0; i < NUM_RANDOM_TESTS; i++) {
+            float[] f = new float[] {
+                RANDOM.nextLong(),
+                (float)RANDOM.nextGaussian(),
+                RANDOM.nextFloat()*Float.MAX_VALUE
+            };
+            for(int j = 0; j < f.length; j++) {
+                OldFloatingDecimalForTest ofd = new OldFloatingDecimalForTest(f[j]);
+                StringBuilder sb = new StringBuilder();
+                ofd.appendTo(sb);
+                String oldString = sb.toString();
+                sb = new StringBuilder();
+                FloatingDecimal.appendTo(f[j], sb);
+                String newString = sb.toString();
+                failures += check("testAppendToFloat", oldString, newString);
+            }
+        }
+
+        return failures;
+    }
+
+    private static int testAppendTo() {
+        System.out.println("testAppendTo");
+        int failures = 0;
+
+        failures += testAppendToDouble();
+        failures += testAppendToFloat();
+
+        return failures;
+    }
+
+    private static int testParseDouble() {
+        System.out.println("  testParseDouble");
+        int failures = 0;
+
+        for(int i = 0; i < NUM_RANDOM_TESTS; i++) {
+            double[] d = new double[] {
+                RANDOM.nextLong(),
+                RANDOM.nextGaussian(),
+                RANDOM.nextDouble()*Double.MAX_VALUE
+            };
+            for(int j = 0; j < d.length; j++) {
+                OldFloatingDecimalForTest ofd = new OldFloatingDecimalForTest(d[j]);
+                String javaFormatString = ofd.toJavaFormatString();
+                ofd = OldFloatingDecimalForTest.readJavaFormatString(javaFormatString);
+                double oldDouble = ofd.doubleValue();
+                double newDouble = FloatingDecimal.parseDouble(javaFormatString);
+                failures += check("testParseDouble", oldDouble, newDouble);
+            }
+        }
+
+        return failures;
+    }
+
+    private static int testParseFloat() {
+        System.out.println("  testParseFloat");
+        int failures = 0;
+
+        for(int i = 0; i < NUM_RANDOM_TESTS; i++) {
+            float[] f = new float[] {
+                RANDOM.nextInt(),
+                (float)RANDOM.nextGaussian(),
+                RANDOM.nextFloat()*Float.MAX_VALUE
+            };
+            for(int j = 0; j < f.length; j++) {
+                OldFloatingDecimalForTest ofd = new OldFloatingDecimalForTest(f[j]);
+                String javaFormatString = ofd.toJavaFormatString();
+                ofd = OldFloatingDecimalForTest.readJavaFormatString(javaFormatString);
+                float oldFloat = ofd.floatValue();
+                float newFloat = FloatingDecimal.parseFloat(javaFormatString);
+                failures += check("testParseFloat", oldFloat, newFloat);
+            }
+        }
+
+        return failures;
+    }
+
+    private static int testParse() {
+        System.out.println("testParse");
+        int failures = 0;
+
+        failures += testParseDouble();
+        failures += testParseFloat();
+
+        return failures;
+    }
+
+    private static int testToJavaFormatStringDoubleFixed() {
+        System.out.println("    testToJavaFormatStringDoubleFixed");
+        int failures = 0;
+
+        double[] d = new double [] {
+            -5.9522650387500933e18, // dtoa() fast path
+            0.872989018674569,      // dtoa() fast iterative - long
+            1.1317400099603851e308  // dtoa() slow iterative
+        };
+
+        for(int i = 0; i < d.length; i++) {
+            OldFloatingDecimalForTest ofd = new OldFloatingDecimalForTest(d[i]);
+            failures += check("testToJavaFormatStringDoubleFixed", ofd.toJavaFormatString(), FloatingDecimal.toJavaFormatString(d[i]));
+        }
+
+        return failures;
+    }
+
+    private static int testToJavaFormatStringDoubleRandom() {
+        System.out.println("    testToJavaFormatStringDoubleRandom");
+        int failures = 0;
+
+        for(int i = 0; i < NUM_RANDOM_TESTS; i++) {
+            double[] d = new double[] {
+                RANDOM.nextLong(),
+                RANDOM.nextGaussian(),
+                RANDOM.nextDouble()*Double.MAX_VALUE
+            };
+            for(int j = 0; j < d.length; j++) {
+                OldFloatingDecimalForTest ofd = new OldFloatingDecimalForTest(d[j]);
+                failures += check("testToJavaFormatStringDoubleRandom", ofd.toJavaFormatString(), FloatingDecimal.toJavaFormatString(d[j]));
+            }
+        }
+
+        return failures;
+    }
+
+    private static int testToJavaFormatStringDouble() {
+        System.out.println("  testToJavaFormatStringDouble");
+        int failures = 0;
+        failures += testToJavaFormatStringDoubleFixed();
+        failures += testToJavaFormatStringDoubleRandom();
+        return failures;
+    }
+
+    private static int testToJavaFormatStringFloatFixed() {
+        System.out.println("    testToJavaFormatStringFloatFixed");
+        int failures = 0;
+
+        float[] f = new float[] {
+            -9.8784166e8f, // dtoa() fast path
+            0.70443946f,   // dtoa() fast iterative - int
+            1.8254228e37f  // dtoa() slow iterative
+        };
+
+        for(int i = 0; i < f.length; i++) {
+            OldFloatingDecimalForTest ofd = new OldFloatingDecimalForTest(f[i]);
+            failures += check("testToJavaFormatStringFloatFixed", ofd.toJavaFormatString(), FloatingDecimal.toJavaFormatString(f[i]));
+        }
+
+        return failures;
+    }
+
+    private static int testToJavaFormatStringFloatRandom() {
+        System.out.println("    testToJavaFormatStringFloatRandom");
+        int failures = 0;
+
+        for(int i = 0; i < NUM_RANDOM_TESTS; i++) {
+            float[] f = new float[] {
+                RANDOM.nextInt(),
+                (float)RANDOM.nextGaussian(),
+                RANDOM.nextFloat()*Float.MAX_VALUE
+            };
+            for(int j = 0; j < f.length; j++) {
+                OldFloatingDecimalForTest ofd = new OldFloatingDecimalForTest(f[j]);
+                failures += check("testToJavaFormatStringFloatRandom", ofd.toJavaFormatString(), FloatingDecimal.toJavaFormatString(f[j]));
+            }
+        }
+
+        return failures;
+    }
+
+    private static int testToJavaFormatStringFloat() {
+        System.out.println("  testToJavaFormatStringFloat");
+        int failures = 0;
+
+        failures += testToJavaFormatStringFloatFixed();
+        failures += testToJavaFormatStringFloatRandom();
+
+        return failures;
+    }
+
+    private static int testToJavaFormatString() {
+        System.out.println("testToJavaFormatString");
+        int failures = 0;
+
+        failures += testToJavaFormatStringDouble();
+        failures += testToJavaFormatStringFloat();
+
+        return failures;
+    }
+
+    public static void main(String[] args) {
+        int failures = 0;
+
+        failures += testAppendTo();
+        failures += testParse();
+        failures += testToJavaFormatString();
+
+        if (failures != 0) {
+            throw new RuntimeException("" + failures + " failures while testing FloatingDecimal");
+        }
+    }
+}
--- a/jdk/test/sun/misc/Hashing.java	Mon Jun 24 14:26:58 2013 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,127 +0,0 @@
-/*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test @summary Ensure that Murmur3 hash performs according to specification.
- * @compile -XDignore.symbol.file Hashing.java
- */
-public class Hashing {
-
-    static final byte ONE_BYTE[] = {
-        (byte) 0x80};
-    static final byte TWO_BYTE[] = {
-        (byte) 0x80, (byte) 0x81};
-    static final char ONE_CHAR[] = {
-        (char) 0x8180};
-    static final byte THREE_BYTE[] = {
-        (byte) 0x80, (byte) 0x81, (byte) 0x82};
-    static final byte FOUR_BYTE[] = {
-        (byte) 0x80, (byte) 0x81, (byte) 0x82, (byte) 0x83};
-    static final char TWO_CHAR[] = {
-        (char) 0x8180, (char) 0x8382};
-    static final int ONE_INT[] = {
-        0x83828180};
-    static final byte SIX_BYTE[] = {
-        (byte) 0x80, (byte) 0x81, (byte) 0x82,
-        (byte) 0x83, (byte) 0x84, (byte) 0x85};
-    static final char THREE_CHAR[] = {
-        (char) 0x8180, (char) 0x8382, (char) 0x8584};
-    static final byte EIGHT_BYTE[] = {
-        (byte) 0x80, (byte) 0x81, (byte) 0x82,
-        (byte) 0x83, (byte) 0x84, (byte) 0x85,
-        (byte) 0x86, (byte) 0x87};
-    static final char FOUR_CHAR[] = {
-        (char) 0x8180, (char) 0x8382,
-        (char) 0x8584, (char) 0x8786};
-    static final int TWO_INT[] = {
-        0x83828180, 0x87868584};
-    // per  http://code.google.com/p/smhasher/source/browse/trunk/main.cpp, line:72
-    static final int MURMUR3_32_X86_CHECK_VALUE = 0xB0F57EE3;
-
-    public static void testMurmur3_32_ByteArray() {
-        System.out.println("testMurmur3_32_ByteArray");
-
-        byte[] vector = new byte[256];
-        byte[] hashes = new byte[4 * 256];
-
-        for (int i = 0; i < 256; i++) {
-            vector[i] = (byte) i;
-        }
-
-        // Hash subranges {}, {0}, {0,1}, {0,1,2}, ..., {0,...,255}
-        for (int i = 0; i < 256; i++) {
-            int hash = sun.misc.Hashing.murmur3_32(256 - i, vector, 0, i);
-
-            hashes[i * 4] = (byte) hash;
-            hashes[i * 4 + 1] = (byte) (hash >>> 8);
-            hashes[i * 4 + 2] = (byte) (hash >>> 16);
-            hashes[i * 4 + 3] = (byte) (hash >>> 24);
-        }
-
-        // hash to get final result.
-        int final_hash = sun.misc.Hashing.murmur3_32(0, hashes);
-
-        if (MURMUR3_32_X86_CHECK_VALUE != final_hash) {
-            throw new RuntimeException(
-                    String.format("Calculated hash result not as expected. Expected %08X got %08X",
-                    MURMUR3_32_X86_CHECK_VALUE,
-                    final_hash));
-        }
-    }
-
-    public static void testEquivalentHashes() {
-        int bytes, chars, ints;
-
-        System.out.println("testEquivalentHashes");
-
-        bytes = sun.misc.Hashing.murmur3_32(TWO_BYTE);
-        chars = sun.misc.Hashing.murmur3_32(ONE_CHAR);
-        if (bytes != chars) {
-            throw new RuntimeException(String.format("Hashes did not match. b:%08x != c:%08x", bytes, chars));
-        }
-
-        bytes = sun.misc.Hashing.murmur3_32(FOUR_BYTE);
-        chars = sun.misc.Hashing.murmur3_32(TWO_CHAR);
-        ints = sun.misc.Hashing.murmur3_32(ONE_INT);
-        if ((bytes != chars) || (bytes != ints)) {
-            throw new RuntimeException(String.format("Hashes did not match. b:%08x != c:%08x != i:%08x", bytes, chars, ints));
-        }
-        bytes = sun.misc.Hashing.murmur3_32(SIX_BYTE);
-        chars = sun.misc.Hashing.murmur3_32(THREE_CHAR);
-        if (bytes != chars) {
-            throw new RuntimeException(String.format("Hashes did not match. b:%08x != c:%08x", bytes, chars));
-        }
-
-        bytes = sun.misc.Hashing.murmur3_32(EIGHT_BYTE);
-        chars = sun.misc.Hashing.murmur3_32(FOUR_CHAR);
-        ints = sun.misc.Hashing.murmur3_32(TWO_INT);
-        if ((bytes != chars) || (bytes != ints)) {
-            throw new RuntimeException(String.format("Hashes did not match. b:%08x != c:%08x != i:%08x", bytes, chars, ints));
-        }
-    }
-
-    public static void main(String[] args) {
-        testMurmur3_32_ByteArray();
-        testEquivalentHashes();
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/net/www/http/HttpClient/B7025238.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import com.sun.net.httpserver.*;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.*;
+import java.util.concurrent.Executors;
+
+/*
+ * @test
+ * @bug 7025238
+ * @summary HttpURLConnection does not handle URLs with an empty path component
+ */
+public class B7025238 {
+
+    public static void main(String[] args) throws Exception {
+        new B7025238().runTest();
+    }
+
+    public void runTest() throws Exception {
+        Server s = null;
+        try {
+            s = new Server();
+            s.startServer();
+            URL url = new URL("http://localhost:" + s.getPort() + "?q=test");
+            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
+            urlConnection.setRequestMethod("GET");
+            urlConnection.connect();
+            int code = urlConnection.getResponseCode();
+
+            if (code != 200) {
+                throw new RuntimeException("Test failed!");
+            }
+        } finally {
+            s.stopServer();
+        }
+    }
+
+    class Server {
+        HttpServer server;
+
+        public void startServer() {
+            InetSocketAddress addr = new InetSocketAddress(0);
+            try {
+                server = HttpServer.create(addr, 0);
+            } catch (IOException ioe) {
+                throw new RuntimeException("Server could not be created");
+            }
+
+            server.createContext("/", new EmptyPathHandler());
+            server.start();
+        }
+
+        public int getPort() {
+            return server.getAddress().getPort();
+        }
+
+        public void stopServer() {
+            server.stop(0);
+        }
+    }
+
+    class EmptyPathHandler implements HttpHandler {
+
+        @Override
+        public void handle(HttpExchange exchange) throws IOException {
+            String requestMethod = exchange.getRequestMethod();
+
+            if (requestMethod.equalsIgnoreCase("GET")) {
+                Headers responseHeaders = exchange.getResponseHeaders();
+                responseHeaders.set("Content-Type", "text/plain");
+                exchange.sendResponseHeaders(200, 0);
+                OutputStream os = exchange.getResponseBody();
+                String str = "Hello from server!";
+                os.write(str.getBytes());
+                os.flush();
+                os.close();
+            }
+        }
+    }
+}
+
--- a/jdk/test/sun/security/krb5/auto/BasicKrb5Test.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/security/krb5/auto/BasicKrb5Test.java	Wed Jul 05 19:00:49 2017 +0200
@@ -59,6 +59,7 @@
 import org.ietf.jgss.GSSName;
 import sun.security.jgss.GSSUtil;
 import sun.security.krb5.Config;
+import sun.security.krb5.KrbException;
 import sun.security.krb5.internal.crypto.EType;
 
 /**
@@ -84,12 +85,10 @@
 
         // Creates and starts the KDC. This line must be put ahead of etype check
         // since the check needs a krb5.conf.
-        new OneKDC(etype).writeJAASConf();
-
-        System.out.println("Testing etype " + etype);
-        if (etype != null && !EType.isSupported(Config.getType(etype))) {
-            // aes256 is not enabled on all systems
-            System.out.println("Not supported.");
+        try {
+            new OneKDC(etype).writeJAASConf();
+        } catch (KrbException ke) {
+            System.out.println("Testing etype " + etype + "Not supported.");
             return;
         }
 
--- a/jdk/test/sun/security/krb5/auto/OneKDC.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/security/krb5/auto/OneKDC.java	Wed Jul 05 19:00:49 2017 +0200
@@ -67,10 +67,19 @@
         addPrincipalRandKey("krbtgt/" + REALM);
         addPrincipalRandKey(SERVER);
         addPrincipalRandKey(BACKEND);
+
+        String extraConfig = "";
+        if (etype != null) {
+            extraConfig += "default_tkt_enctypes=" + etype
+                    + "\ndefault_tgs_enctypes=" + etype;
+            if (etype.startsWith("des")) {
+                extraConfig += "\nallow_weak_crypto = true";
+            }
+        }
         KDC.saveConfig(KRB5_CONF, this,
                 "forwardable = true",
                 "default_keytab_name = " + KTAB,
-                etype == null ? "" : "default_tkt_enctypes=" + etype + "\ndefault_tgs_enctypes=" + etype);
+                extraConfig);
         System.setProperty("java.security.krb5.conf", KRB5_CONF);
         // Whatever krb5.conf had been loaded before, we reload ours now.
         Config.refresh();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/krb5/auto/OnlyDesLogin.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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 8014310
+ * @summary JAAS/Krb5LoginModule using des encytypes failure with NPE after JDK-8012679
+ * @compile -XDignore.symbol.file OnlyDesLogin.java
+ * @run main/othervm OnlyDesLogin
+ */
+
+import sun.security.krb5.Config;
+
+import javax.security.auth.login.LoginException;
+
+public class OnlyDesLogin {
+
+    public static void main(String[] args) throws Exception {
+
+        OneKDC kdc = new OneKDC(null);
+        kdc.writeJAASConf();
+
+        KDC.saveConfig(OneKDC.KRB5_CONF, kdc,
+                "default_tkt_enctypes=des-cbc-md5",
+                "default_tgs_enctypes=des-cbc-md5",
+                "permitted_enctypes=des-cbc-md5");
+        Config.refresh();
+
+        try {
+            Context.fromJAAS("client");
+            throw new Exception("What?");
+        } catch (LoginException le) {
+            // This is OK
+        }
+    }
+}
--- a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLEngineImpl/SSLEngineDeadlock.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLEngineImpl/SSLEngineDeadlock.java	Wed Jul 05 19:00:49 2017 +0200
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -21,15 +21,14 @@
  * questions.
  */
 
+// SunJSSE does not support dynamic system properties, no way to re-use
+// system properties in samevm/agentvm mode.
+
 /*
  * @test
  * @bug 6492872
  * @summary Deadlock in SSLEngine
  * @run main/othervm SSLEngineDeadlock
- *
- *     SunJSSE does not support dynamic system properties, no way to re-use
- *     system properties in samevm/agentvm mode.
- *
  * @author Brad R. Wetmore
  */
 
@@ -74,6 +73,7 @@
 import java.io.*;
 import java.security.*;
 import java.nio.*;
+import java.lang.management.*;
 
 public class SSLEngineDeadlock {
 
@@ -144,6 +144,8 @@
             }
             SSLEngineDeadlock test = new SSLEngineDeadlock();
             test.runTest();
+
+            detectDeadLock();
         }
         System.out.println("Test Passed.");
     }
@@ -361,6 +363,22 @@
     }
 
     /*
+     * Detect dead lock
+     */
+    private static void detectDeadLock() throws Exception {
+        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
+        long[] threadIds = threadBean.findDeadlockedThreads();
+        if (threadIds != null && threadIds.length != 0) {
+            for (long id : threadIds) {
+                ThreadInfo info =
+                    threadBean.getThreadInfo(id, Integer.MAX_VALUE);
+                System.out.println("Deadlocked ThreadInfo: " + info);
+            }
+            throw new Exception("Found Deadlock!");
+        }
+    }
+
+    /*
      * Logging code
      */
     private static boolean resultOnce = true;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/NoImpactServerRenego.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,310 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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.
+ */
+
+// SunJSSE does not support dynamic system properties, no way to re-use
+// system properties in samevm/agentvm mode.
+
+/*
+ * @test
+ * @bug 7188658
+ * @summary Add possibility to disable client initiated renegotiation
+ * @run main/othervm
+ *      -Djdk.tls.rejectClientInitializedRenego=true NoImpactServerRenego
+ */
+
+import java.io.*;
+import java.net.*;
+import javax.net.ssl.*;
+
+public class NoImpactServerRenego implements
+        HandshakeCompletedListener {
+
+    static byte handshakesCompleted = 0;
+
+    /*
+     * Define what happens when handshaking is completed
+     */
+    public void handshakeCompleted(HandshakeCompletedEvent event) {
+        synchronized (this) {
+            handshakesCompleted++;
+            System.out.println("Session: " + event.getSession().toString());
+            System.out.println("Seen handshake completed #" +
+                handshakesCompleted);
+        }
+    }
+
+    /*
+     * =============================================================
+     * Set the various variables needed for the tests, then
+     * specify what tests to run on each side.
+     */
+
+    /*
+     * Should we run the client or server in a separate thread?
+     * Both sides can throw exceptions, but do you have a preference
+     * as to which side should be the main thread.
+     */
+    static boolean separateServerThread = false;
+
+    /*
+     * Where do we find the keystores?
+     */
+    static String pathToStores = "../../../../../../../etc";
+    static String keyStoreFile = "keystore";
+    static String trustStoreFile = "truststore";
+    static String passwd = "passphrase";
+
+    /*
+     * Is the server ready to serve?
+     */
+    volatile static boolean serverReady = false;
+
+    /*
+     * Turn on SSL debugging?
+     */
+    static boolean debug = false;
+
+    /*
+     * If the client or server is doing some kind of object creation
+     * that the other side depends on, and that thread prematurely
+     * exits, you may experience a hang.  The test harness will
+     * terminate all hung threads after its timeout has expired,
+     * currently 3 minutes by default, but you might try to be
+     * smart about it....
+     */
+
+    /*
+     * Define the server side of the test.
+     *
+     * If the server prematurely exits, serverReady will be set to true
+     * to avoid infinite hangs.
+     */
+    void doServerSide() throws Exception {
+        SSLServerSocketFactory sslssf =
+            (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
+        SSLServerSocket sslServerSocket =
+            (SSLServerSocket) sslssf.createServerSocket(serverPort);
+
+        serverPort = sslServerSocket.getLocalPort();
+
+        /*
+         * Signal Client, we're ready for his connect.
+         */
+        serverReady = true;
+
+        SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
+        sslSocket.addHandshakeCompletedListener(this);
+        InputStream sslIS = sslSocket.getInputStream();
+        OutputStream sslOS = sslSocket.getOutputStream();
+
+        for (int i = 0; i < 10; i++) {
+            sslIS.read();
+            sslOS.write(85);
+            sslOS.flush();
+        }
+
+        System.out.println("invalidating");
+        sslSocket.getSession().invalidate();
+        System.out.println("starting new handshake");
+        sslSocket.startHandshake();
+
+        for (int i = 0; i < 10; i++) {
+            System.out.println("sending/receiving data, iteration: " + i);
+            sslIS.read();
+            sslOS.write(85);
+            sslOS.flush();
+        }
+
+        sslSocket.close();
+    }
+
+    /*
+     * Define the client side of the test.
+     *
+     * If the server prematurely exits, serverReady will be set to true
+     * to avoid infinite hangs.
+     */
+    void doClientSide() throws Exception {
+
+        /*
+         * Wait for server to get started.
+         */
+        while (!serverReady) {
+            Thread.sleep(50);
+        }
+
+        SSLSocketFactory sslsf =
+            (SSLSocketFactory) SSLSocketFactory.getDefault();
+        SSLSocket sslSocket = (SSLSocket)
+            sslsf.createSocket("localhost", serverPort);
+
+        InputStream sslIS = sslSocket.getInputStream();
+        OutputStream sslOS = sslSocket.getOutputStream();
+
+        for (int i = 0; i < 10; i++) {
+            sslOS.write(280);
+            sslOS.flush();
+            sslIS.read();
+        }
+
+        for (int i = 0; i < 10; i++) {
+            sslOS.write(280);
+            sslOS.flush();
+            sslIS.read();
+        }
+
+        sslSocket.close();
+    }
+
+    /*
+     * =============================================================
+     * The remainder is just support stuff
+     */
+
+    // use any free port by default
+    volatile int serverPort = 0;
+
+    volatile Exception serverException = null;
+    volatile Exception clientException = null;
+
+    public static void main(String[] args) throws Exception {
+        String keyFilename =
+            System.getProperty("test.src", "./") + "/" + pathToStores +
+                "/" + keyStoreFile;
+        String trustFilename =
+            System.getProperty("test.src", "./") + "/" + pathToStores +
+                "/" + trustStoreFile;
+
+        System.setProperty("javax.net.ssl.keyStore", keyFilename);
+        System.setProperty("javax.net.ssl.keyStorePassword", passwd);
+        System.setProperty("javax.net.ssl.trustStore", trustFilename);
+        System.setProperty("javax.net.ssl.trustStorePassword", passwd);
+
+        if (debug)
+            System.setProperty("javax.net.debug", "all");
+
+        /*
+         * Start the tests.
+         */
+        new NoImpactServerRenego();
+    }
+
+    Thread clientThread = null;
+    Thread serverThread = null;
+
+    /*
+     * Primary constructor, used to drive remainder of the test.
+     *
+     * Fork off the other side, then do your work.
+     */
+    NoImpactServerRenego() throws Exception {
+        if (separateServerThread) {
+            startServer(true);
+            startClient(false);
+        } else {
+            startClient(true);
+            startServer(false);
+        }
+
+        /*
+         * Wait for other side to close down.
+         */
+        if (separateServerThread) {
+            serverThread.join();
+        } else {
+            clientThread.join();
+        }
+
+        /*
+         * When we get here, the test is pretty much over.
+         *
+         * If the main thread excepted, that propagates back
+         * immediately.  If the other thread threw an exception, we
+         * should report back.
+         */
+        if (serverException != null) {
+            System.out.print("Server Exception:");
+            throw serverException;
+        }
+        if (clientException != null) {
+            System.out.print("Client Exception:");
+            throw clientException;
+        }
+
+        /*
+         * Give the Handshaker Thread a chance to run
+         */
+        Thread.sleep(1000);
+
+        synchronized (this) {
+            if (handshakesCompleted != 2) {
+                throw new Exception("Didn't see 2 handshake completed events.");
+            }
+        }
+    }
+
+    void startServer(boolean newThread) throws Exception {
+        if (newThread) {
+            serverThread = new Thread() {
+                public void run() {
+                    try {
+                        doServerSide();
+                    } catch (Exception e) {
+                        /*
+                         * Our server thread just died.
+                         *
+                         * Release the client, if not active already...
+                         */
+                        System.err.println("Server died...");
+                        serverReady = true;
+                        serverException = e;
+                    }
+                }
+            };
+            serverThread.start();
+        } else {
+            doServerSide();
+        }
+    }
+
+    void startClient(boolean newThread) throws Exception {
+        if (newThread) {
+            clientThread = new Thread() {
+                public void run() {
+                    try {
+                        doClientSide();
+                    } catch (Exception e) {
+                        /*
+                         * Our client thread just died.
+                         */
+                        System.err.println("Client died...");
+                        clientException = e;
+                    }
+                }
+            };
+            clientThread.start();
+        } else {
+            doClientSide();
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/RejectClientRenego.java	Wed Jul 05 19:00:49 2017 +0200
@@ -0,0 +1,322 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * 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.
+ */
+
+// SunJSSE does not support dynamic system properties, no way to re-use
+// system properties in samevm/agentvm mode.
+
+/*
+ * @test
+ * @bug 7188658
+ * @summary Add possibility to disable client initiated renegotiation
+ * @run main/othervm RejectClientRenego true
+ * @run main/othervm RejectClientRenego false
+ */
+
+import java.io.*;
+import java.net.*;
+import javax.net.ssl.*;
+
+public class RejectClientRenego implements
+        HandshakeCompletedListener {
+
+    static byte handshakesCompleted = 0;
+
+    /*
+     * Define what happens when handshaking is completed
+     */
+    public void handshakeCompleted(HandshakeCompletedEvent event) {
+        synchronized (this) {
+            handshakesCompleted++;
+            System.out.println("Session: " + event.getSession().toString());
+            System.out.println("Seen handshake completed #" +
+                handshakesCompleted);
+        }
+    }
+
+    /*
+     * =============================================================
+     * Set the various variables needed for the tests, then
+     * specify what tests to run on each side.
+     */
+
+    /*
+     * Should we run the client or server in a separate thread?
+     * Both sides can throw exceptions, but do you have a preference
+     * as to which side should be the main thread.
+     */
+    static boolean separateServerThread = false;
+
+    /*
+     * Where do we find the keystores?
+     */
+    static String pathToStores = "../../../../../../../etc";
+    static String keyStoreFile = "keystore";
+    static String trustStoreFile = "truststore";
+    static String passwd = "passphrase";
+
+    /*
+     * Is the server ready to serve?
+     */
+    volatile static boolean serverReady = false;
+
+    /*
+     * Turn on SSL debugging?
+     */
+    static boolean debug = false;
+
+    /*
+     * If the client or server is doing some kind of object creation
+     * that the other side depends on, and that thread prematurely
+     * exits, you may experience a hang.  The test harness will
+     * terminate all hung threads after its timeout has expired,
+     * currently 3 minutes by default, but you might try to be
+     * smart about it....
+     */
+
+    /*
+     * Define the server side of the test.
+     *
+     * If the server prematurely exits, serverReady will be set to true
+     * to avoid infinite hangs.
+     */
+    void doServerSide() throws Exception {
+        SSLServerSocketFactory sslssf =
+            (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
+        SSLServerSocket sslServerSocket =
+            (SSLServerSocket) sslssf.createServerSocket(serverPort);
+
+        serverPort = sslServerSocket.getLocalPort();
+
+        /*
+         * Signal Client, we're ready for his connect.
+         */
+        serverReady = true;
+
+        SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
+        sslSocket.addHandshakeCompletedListener(this);
+        InputStream sslIS = sslSocket.getInputStream();
+        OutputStream sslOS = sslSocket.getOutputStream();
+
+        for (int i = 0; i < 10; i++) {
+            sslIS.read();
+            sslOS.write(85);
+            sslOS.flush();
+        }
+
+        try {
+            for (int i = 0; i < 10; i++) {
+                System.out.println("sending/receiving data, iteration: " + i);
+                sslIS.read();
+                sslOS.write(85);
+                sslOS.flush();
+            }
+            throw new Exception("Not reject client initialized renegotiation");
+        } catch (SSLHandshakeException she) {
+            System.out.println("Got the expected exception");
+        } finally {
+            sslSocket.close();
+        }
+    }
+
+    /*
+     * Define the client side of the test.
+     *
+     * If the server prematurely exits, serverReady will be set to true
+     * to avoid infinite hangs.
+     */
+    void doClientSide() throws Exception {
+
+        /*
+         * Wait for server to get started.
+         */
+        while (!serverReady) {
+            Thread.sleep(50);
+        }
+
+        SSLSocketFactory sslsf =
+            (SSLSocketFactory) SSLSocketFactory.getDefault();
+        SSLSocket sslSocket = (SSLSocket)
+            sslsf.createSocket("localhost", serverPort);
+
+        InputStream sslIS = sslSocket.getInputStream();
+        OutputStream sslOS = sslSocket.getOutputStream();
+
+        for (int i = 0; i < 10; i++) {
+            sslOS.write(280);
+            sslOS.flush();
+            sslIS.read();
+        }
+
+        if (!isAbbreviated) {
+            System.out.println("invalidating");
+            sslSocket.getSession().invalidate();
+        }
+        System.out.println("starting new handshake");
+        sslSocket.startHandshake();
+
+        try {
+            for (int i = 0; i < 10; i++) {
+                sslOS.write(280);
+                sslOS.flush();
+                sslIS.read();
+            }
+            throw new Exception("Not reject client initialized renegotiation");
+        } catch (SSLHandshakeException she) {
+            System.out.println("Got the expected exception");
+        } finally {
+            sslSocket.close();
+        }
+    }
+
+    /*
+     * =============================================================
+     * The remainder is just support stuff
+     */
+
+    // use any free port by default
+    volatile int serverPort = 0;
+
+    volatile Exception serverException = null;
+    volatile Exception clientException = null;
+
+    // Is it abbreviated handshake?
+    private static boolean isAbbreviated = false;
+
+    public static void main(String[] args) throws Exception {
+        String keyFilename =
+            System.getProperty("test.src", "./") + "/" + pathToStores +
+                "/" + keyStoreFile;
+        String trustFilename =
+            System.getProperty("test.src", "./") + "/" + pathToStores +
+                "/" + trustStoreFile;
+
+        System.setProperty("javax.net.ssl.keyStore", keyFilename);
+        System.setProperty("javax.net.ssl.keyStorePassword", passwd);
+        System.setProperty("javax.net.ssl.trustStore", trustFilename);
+        System.setProperty("javax.net.ssl.trustStorePassword", passwd);
+
+        // reject client initialized SSL renegotiation.
+        System.setProperty("jdk.tls.rejectClientInitializedRenego", "true");
+
+        if (debug)
+            System.setProperty("javax.net.debug", "all");
+
+        // Is it abbreviated handshake?
+        if ("true".equals(args[0])) {
+            isAbbreviated = true;
+        }
+
+        /*
+         * Start the tests.
+         */
+        new RejectClientRenego();
+    }
+
+    Thread clientThread = null;
+    Thread serverThread = null;
+
+    /*
+     * Primary constructor, used to drive remainder of the test.
+     *
+     * Fork off the other side, then do your work.
+     */
+    RejectClientRenego() throws Exception {
+        if (separateServerThread) {
+            startServer(true);
+            startClient(false);
+        } else {
+            startClient(true);
+            startServer(false);
+        }
+
+        /*
+         * Wait for other side to close down.
+         */
+        if (separateServerThread) {
+            serverThread.join();
+        } else {
+            clientThread.join();
+        }
+
+        /*
+         * When we get here, the test is pretty much over.
+         *
+         * If the main thread excepted, that propagates back
+         * immediately.  If the other thread threw an exception, we
+         * should report back.
+         */
+        if (serverException != null) {
+            System.out.print("Server Exception:");
+            throw serverException;
+        }
+        if (clientException != null) {
+            System.out.print("Client Exception:");
+            throw clientException;
+        }
+    }
+
+    void startServer(boolean newThread) throws Exception {
+        if (newThread) {
+            serverThread = new Thread() {
+                public void run() {
+                    try {
+                        doServerSide();
+                    } catch (Exception e) {
+                        /*
+                         * Our server thread just died.
+                         *
+                         * Release the client, if not active already...
+                         */
+                        System.err.println("Server died...");
+                        serverReady = true;
+                        serverException = e;
+                    }
+                }
+            };
+            serverThread.start();
+        } else {
+            doServerSide();
+        }
+    }
+
+    void startClient(boolean newThread) throws Exception {
+        if (newThread) {
+            clientThread = new Thread() {
+                public void run() {
+                    try {
+                        doClientSide();
+                    } catch (Exception e) {
+                        /*
+                         * Our client thread just died.
+                         */
+                        System.err.println("Client died...");
+                        clientException = e;
+                    }
+                }
+            };
+            clientThread.start();
+        } else {
+            doClientSide();
+        }
+    }
+}
--- a/jdk/test/sun/security/tools/policytool/Alias.sh	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/security/tools/policytool/Alias.sh	Wed Jul 05 19:00:49 2017 +0200
@@ -52,6 +52,11 @@
     PS=":"
     FS="/"
     ;;
+  CYGWIN* )
+    NULL=/dev/null
+    PS=";"
+    FS="/"
+    ;;
   Windows* )
     NULL=NUL
     PS=";"
--- a/jdk/test/sun/security/tools/policytool/ChangeUI.html	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/security/tools/policytool/ChangeUI.html	Wed Jul 05 19:00:49 2017 +0200
@@ -17,7 +17,8 @@
 
 First, policytool will be invoked.<br><br>
 <ol start="0">
-<li>If testing on Windows, create a temporary directory. (Example: C:\foo\tmp)
+<li>Find (or create) a temporary directory that you have write access to.
+(Example: 'C:\foo\tmp' on Windows or '/tmp' on other systems)
 <li>Add new policy entry
 <li>Add permission:
     <pre>
@@ -63,9 +64,9 @@
 <li>Confirm there are 2 entries in the permission list
 <li>Press cancel
 <li>Save as "/tmp/p"<br>
-If testing on Windows, save in the temporary directory created in Step 0.
-(Example: Save as "C:\foo\tmp\p.policy")
-<li>Confirm that the file /tmp/p (or C:\foo\tmp\p.policy) looks like
+(Or use the temporary directory mentioned in Step 0 if it's not '/tmp'.
+         For example, "C:\foo\tmp\p" on Windows)
+<li>Confirm that the file created in the previous step looks like
 <pre>
 /* AUTOMATICALLY GENERATED ON Tue Jul 19 16:27:30 CST 2005*/
 /* DO NOT EDIT */
--- a/jdk/test/sun/security/tools/policytool/ChangeUI.sh	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/security/tools/policytool/ChangeUI.sh	Wed Jul 05 19:00:49 2017 +0200
@@ -22,7 +22,7 @@
 #
 
 # @test
-# @bug  6296772 6293981 6290216
+# @bug  6296772 6293981 6290216 8015276
 # @summary FilePermission and DelegationPermission, and cancel button
 #
 # @run applet/manual=done ChangeUI.html
@@ -51,6 +51,11 @@
     PS=":"
     FS="/"
     ;;
+  CYGWIN* )
+    NULL=/dev/null
+    PS=";"
+    FS="/"
+    ;;
   Windows* )
     NULL=NUL
     PS=";"
--- a/jdk/test/sun/security/tools/policytool/OpenPolicy.sh	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/security/tools/policytool/OpenPolicy.sh	Wed Jul 05 19:00:49 2017 +0200
@@ -51,6 +51,11 @@
     PS=":"
     FS="/"
     ;;
+  CYGWIN* )
+    NULL=/dev/null
+    PS=";"
+    FS="/"
+    ;;
   Windows* )
     NULL=NUL
     PS=";"
--- a/jdk/test/sun/security/tools/policytool/SaveAs.sh	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/security/tools/policytool/SaveAs.sh	Wed Jul 05 19:00:49 2017 +0200
@@ -52,6 +52,11 @@
     PS=":"
     FS="/"
     ;;
+  CYGWIN* )
+    NULL=/dev/null
+    PS=";"
+    FS="/"
+    ;;
   Windows* )
     NULL=NUL
     PS=";"
--- a/jdk/test/sun/security/tools/policytool/UpdatePermissions.html	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/security/tools/policytool/UpdatePermissions.html	Wed Jul 05 19:00:49 2017 +0200
@@ -10,8 +10,8 @@
 First, policytool will be invoked.<br><br>
 
 Then, follow these steps:<br>
-0) If testing on Windows, create a temporary directory.
-(Example: C:\foo\tmp)<br><br>
+0) Find (or create) a temporary directory that you have write access to.
+(Example: 'C:\foo\tmp' on Windows or '/tmp' on other systems)<br><br>
 1) Click on the "Add Policy Entry" button in the
 main policytool window.<br><br>
 
@@ -32,13 +32,10 @@
 
 8) In the SaveAs window, enter "/tmp/ptool.test" as the file name
 and click "OK".<br>
-If testing on Windows, use the temporary directory created in Step 0.
-(Example: Save as "C:\foo\tmp\ptool.test")<br><br>
+(Or use the temporary directory mentioned in Step 0 if it's not '/tmp'.
+For example, "C:\foo\tmp\ptool.test" on Windows)<br><br>
 
-9) cat /tmp/ptool.test<br>
-If testing on Windows, check the contents of the file created in the previous
-step.<br><br>
-
+9) Check the content of the file created in the previous step<br><br>
 
 10) check to make sure that the new entry is in the policy file.<br><br>
 
@@ -53,8 +50,8 @@
 
 In the confirmation dialog pop-up, click "OK".<br><br>
 
-Exit policytool. If testing on Windows, delete the temporary directory and its
-contents created during this test.<br><br>
+Exit policytool. Delete the files created during this test. If the
+temporary directory is also newly created, empty and delete it.<br><br>
 
 Press "Pass" if ... press "Fail" otherwise.<br><br>
 
--- a/jdk/test/sun/security/tools/policytool/UpdatePermissions.sh	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/security/tools/policytool/UpdatePermissions.sh	Wed Jul 05 19:00:49 2017 +0200
@@ -23,6 +23,7 @@
 
 # @test
 # @bug 4218206
+# @bug 8015276
 # @summary missing or invalid permission target names in policy tool
 #
 # @run applet/manual=done UpdatePermissions.html
@@ -51,6 +52,11 @@
     PS=":"
     FS="/"
     ;;
+  CYGWIN* )
+    NULL=/dev/null
+    PS=";"
+    FS="/"
+    ;;
   Windows* )
     NULL=NUL
     PS=";"
--- a/jdk/test/sun/security/tools/policytool/UsePolicy.sh	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/security/tools/policytool/UsePolicy.sh	Wed Jul 05 19:00:49 2017 +0200
@@ -51,6 +51,11 @@
     PS=":"
     FS="/"
     ;;
+  CYGWIN* )
+    NULL=/dev/null
+    PS=";"
+    FS="/"
+    ;;
   Windows* )
     NULL=NUL
     PS=";"
--- a/jdk/test/sun/security/tools/policytool/i18n.html	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/security/tools/policytool/i18n.html	Wed Jul 05 19:00:49 2017 +0200
@@ -15,10 +15,15 @@
 is incomprehensible, then the test failed.  Otherwise,
 the test passed.
 <p>
+<b>Preparation</b>: Find (or create) a temporary directory that you have write
+access to (Example: 'C:\tmp' on Windows or '/tmp' on other systems) and copy
+the files "ks", "good", "bad" from the scratch sub-directory of this test's
+working directory (the -w argument of jtreg) into the temporary directory.
+If 'policy1' or 'policy2' already exists in this directory, remove it.
+<p>
 Press "Pass" if ... press "Fail" otherwise.
 <p>
-<ol start="0">
-<li> If testing on Windows, create a temporary directory. (Example: C:\foo\tmp)
+<ol>
 <li> Pull down the 'File' and 'KeyStore' menus and check values
 <li> Pull down 'File' menu and select 'View Warning Log'.  Confirm FileNotFound.
 <li> Pull down 'File' menu and select 'New'.
@@ -46,65 +51,65 @@
 <li> Select "play" from Target menu.
 <li> Click OK, confirm changed permission.
 <li> Type "hello" for 'CodeBase', click on 'Done', and check error message
+<li> Clean up the 'CodeBase' textbox
 <li> Type "hello" for 'SignedBy', click on 'Done', and check warning message
-<li> Click, on 'Edit Policy Entry' and 'Remove Policy Entry'
+<li> Click on 'Edit Policy Entry' and 'Remove Policy Entry'
 	and check error messages
-<li> Select policy entry, click on 'Edit Policy Entry', and check pop-up window
+<li> Select policy entry, click on 'Edit Policy Entry', check pop-up window and close it
 <li> Select policy entry, click on 'Remove Policy Entry',
 	and check pop-up window
 <li> Do not remove the entry, click 'Cancel'.
 <li> Pull down 'File' menu and select 'Exit'.  Confirm Save option.
 	Click 'Cancel'.
-<li> Select 'File' menu value 'Save' and enter "/tmp/policy1" as the filename.<br>
-     If testing on Windows, use the temporary directory created in Step 0.
-        (Example: Save as "C:\foo\tmp\policy1")<br>
-     Check status message.
+<li> Select 'File' menu value 'Save' and save into file "policy1" in the
+    temporary directory. Check status message.<br>
 <li> Select 'File' menu value 'New'
 <li> Click 'Add Policy Entry', type in "hello" for 'SignedBy' field,
 	click 'Done'.  Confirm warning.
 <li> Select 'File' menu value 'Open' and confirm save option
-	(do not save changes)
-<li> Type "/tmp/policy1" (if Windows, "C:\foo\tmp\policy1") for the filename
-        and confirm warning message<br>
+	(Click 'Cancel', do not save changes)
 <li> Pull down 'File' menu, select 'View Warning Log'
 	and confirm KeyStore alias warning
 <li> Pull down 'KeyStore' menu and select 'Edit'
-<li> Enter 'foo' as KeyStore URL and check error
-<li> Using keytool create JKS keystore
-<li> Enter KeyStore URL but leave other fields empty.  Should succeed.
+<li> Enter 'foo' as KeyStore URL, click 'OK', and check error
+<li> Enter KeyStore URL "file:/tmp/ks" (Or use the temporary directory mentioned
+    in the preparation if it's not '/tmp'. For example, "file:/C:/tmp/ks" on Windows)
+    but leave other fields empty. Click 'OK'. Should succeed.
 <li> Pull down 'KeyStore' menu and select 'Edit'
-<li> Confirm URL and Type values.
-<li> Enter 'foo' as the provider and check error message.
-<li> Enter 'SUN' as the provider.  Should succeed.
+<li> Confirm URL and Type values. The Type should be "jks"
+<li> Enter 'foo' as the provider, click 'OK' and check error message.
+<li> Enter 'SUN' as the provider, click 'OK'.  Should succeed.
 <li> Pull down 'KeyStore' menu and select 'Edit'
 <li> Confirm URL, Type, and Provider values.
-<li> Enter 'foo' as the password URL and check error message.
-<li> Enter URL with bad password and check error message.
-<li> Enter URL with good password.  Should succeed.
+<li> Enter 'foo' as the password URL, click 'OK' and check error message.
+<li> Enter URL "file:/tmp/bad" (Or use the temporary directory mentioned in
+    the preparation if it's not '/tmp'. For example, "file:/C:/tmp/bad" on Windows),
+    click 'OK' and check error message.
+<li> Enter URL "file:/tmp/good" (Or use the temporary directory mentioned in
+    the preparation if it's not '/tmp'. For example, "file:/C:/tmp/good" on Windows)
+    and click 'OK'.  Should succeed.
 <li> Pull down 'KeyStore' menu and select 'Edit'
 <li> Confirm URL, Type, Provider, and Password URL values.
 <li> Click OK
-<li> Pull down 'File' menu and select 'Save As'.  Enter "/tmp/policy2"
-        (if Windows, "C:\foo\tmp\policy2").
-	Confirm status message.<br>
+<li> Pull down 'File' menu and select 'Save As' and save into file "policy2"
+    in the temporary directory. Confirm status message.<br>
 <li> Pull down 'File' menu and select 'New'.
-<li> Pull down 'File' menu and select 'Open'.  Enter "/tmp/policy2"
-        (if Windows, "C:\foo\tmp\policy2").
-	Confirm warning message.<br>
+<li> Pull down 'File' menu and select 'Open' and open "policy2" in the
+    temporary directory.<br>
 <li> Click on 'Add Policy Entry', enter Codebase 'http://foo',
 	SignedBy 'bar'.  Click on 'Done' and confirm alias warning.
 <li> Double-Click on just created policy entry, confirm edit window appears.
-<li> Change SignedBy to an alias in previously created keystore.
+<li> Change SignedBy to an 'hello'.
 <li> Click on Done and confirm it worked with no warning.
 <li> Double-Click on "SignedBy hello" policy entry and
 	confirm edit window appears.
 <li> Click on Edit/Remove Principal, confirm errors.
 <li> Click on 'Add Principal' and check new window.
 <li> Click on 'OK' and confirm error message (no principal name)
-<li> Enter valid KeyStore alias as principal name, click OK and
+<li> Enter 'hello' as principal name, click OK and
 	confirm status message.
 <li> Confirm new principal in Principals list.
-<li> Click on 'Done' (creating policy entry), confirm alias warning.
+<li> Click on 'Done' (creating policy entry).
 <li> View warning log and confirm X500Principal/KeyStore alias message.
 <li> Confirm principal added to policy entry in main window listing.
 <li> Double click on that entry.
@@ -116,14 +121,14 @@
 	Confirm name cleared.  Type 'foo' as name.  Click OK.  Confirm error.
 	type 'cn=foo' as name.  Click OK.  should succeed.
 <li> Confirm changed principal in list.
-<li> Click on 'Add Permission', and add any FilePermission.
-<li> Click on 'Done' in Policy Entry window.  Confirm alias warning.
+<li> Click on 'Add Permission', and add a FilePermission, choose a target and
+    an action. Click OK.
+<li> Click on 'Done' in Policy Entry window.
 <li> Confirm entries in main window listing.
 <li> Select 'File' menu value 'Exit'
 <li> Save Changes, confirm status message.
-<li> If testing on Windows, delete the temporary directory and its contents
-        created during this test.
-</ol>
+<li> Delete all files created during this test. If the temporary directory
+ is also newly created, empty and delete it.</ol>
 <p>
 
 </body>
--- a/jdk/test/sun/security/tools/policytool/i18n.sh	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/security/tools/policytool/i18n.sh	Wed Jul 05 19:00:49 2017 +0200
@@ -23,10 +23,13 @@
 
 # @test
 # @bug 4348370
+# @bug 8015274
+# @bug 8015276
+# @bug 8016158
 # @summary policytool not i18n compliant
 #
 # @run applet/manual=done i18n.html
-# @run shell i18n.sh
+# @run shell/timeout=1200 i18n.sh
 # @run applet/manual=yesno i18n.html
 
 # set a few environment variables so that the shell-script can run stand-alone
@@ -51,6 +54,11 @@
     PS=":"
     FS="/"
     ;;
+  CYGWIN* )
+    NULL=/dev/null
+    PS=";"
+    FS="/"
+    ;;
   Windows* )
     NULL=NUL
     PS=";"
@@ -66,6 +74,19 @@
 
 echo "HELLO!"
 
+echo "Checking for $HOME/.java.policy"
+
+# 8015274
+if [ -e $HOME/.java.policy ]; then
+    echo "You have a .java.policy file in your HOME directory"
+    echo "The file must be removed before running this test"
+    exit 1
+fi
+
+${TESTJAVA}${FS}bin${FS}keytool -genkeypair -alias hello -dname CN=Hello \
+        -storepass changeit -keypass changeit -keystore ks
+echo changeit > good
+echo badpass > bad
 ${TESTJAVA}${FS}bin${FS}policytool
 
 exit $?
--- a/jdk/test/sun/text/resources/LocaleData	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/text/resources/LocaleData	Wed Jul 05 19:00:49 2017 +0200
@@ -28,9 +28,6 @@
 FormatData/pt_BR/NumberElements/0=,
 FormatData/pt_BR/NumberElements/1=.
 FormatData/pt_BR/NumberElements/2=;
-FormatData/pt_BR/MonthAbbreviations/0=Jan
-FormatData/pt_BR/MonthAbbreviations/1=Fev
-FormatData/pt_BR/MonthAbbreviations/2=Mar
 FormatData/pt_BR/DayAbbreviations/0=Dom
 FormatData/pt_BR/DayAbbreviations/1=Seg
 FormatData/pt_BR/DayAbbreviations/2=Ter
@@ -7667,3 +7664,18 @@
 # bug 7074882
 FormatData/mt/MonthNames/7=Awwissu
 FormatData/mt/MonthAbbreviations/7=Aww
+
+# bug 7040556
+FormatData/pt/MonthAbbreviations/0=jan
+FormatData/pt/MonthAbbreviations/1=fev
+FormatData/pt/MonthAbbreviations/2=mar
+FormatData/pt/MonthAbbreviations/3=abr
+FormatData/pt/MonthAbbreviations/4=mai
+FormatData/pt/MonthAbbreviations/5=jun
+FormatData/pt/MonthAbbreviations/6=jul
+FormatData/pt/MonthAbbreviations/7=ago
+FormatData/pt/MonthAbbreviations/8=set
+FormatData/pt/MonthAbbreviations/9=out
+FormatData/pt/MonthAbbreviations/10=nov
+FormatData/pt/MonthAbbreviations/11=dez
+
--- a/jdk/test/sun/text/resources/LocaleDataTest.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/sun/text/resources/LocaleDataTest.java	Wed Jul 05 19:00:49 2017 +0200
@@ -35,7 +35,7 @@
  *      6645405 6650730 6910489 6573250 6870908 6585666 6716626 6914413 6916787
  *      6919624 6998391 7019267 7020960 7025837 7020583 7036905 7066203 7101495
  *      7003124 7085757 7028073 7171028 7189611 8000983 7195759 8004489 8006509
- *      7114053 7074882
+ *      7114053 7074882 7040556
  * @summary Verify locale data
  *
  */
--- a/jdk/test/tools/launcher/VersionCheck.java	Mon Jun 24 14:26:58 2013 -0700
+++ b/jdk/test/tools/launcher/VersionCheck.java	Wed Jul 05 19:00:49 2017 +0200
@@ -49,6 +49,7 @@
         "javaw",
         "javaws",
         "jcontrol",
+        "jmc",
         "jvisualvm",
         "packager",
         "unpack200",
@@ -72,6 +73,7 @@
         "jdeps",
         "jinfo",
         "jmap",
+        "jmc",
         "jps",
         "jrunscript",
         "jjs",