changeset 22463:cea98f929b79

Merge
author kvn
date Thu, 01 Aug 2013 17:24:26 -0700
parents eed978e4169a bbe43d712fe0
children f466b1e79df5
files jdk/src/share/classes/java/net/package.html nashorn/src/jdk/internal/dynalink/beans/SafeUnreflector.java nashorn/src/jdk/internal/dynalink/beans/SafeUnreflectorImpl.java nashorn/src/jdk/internal/dynalink/beans/SandboxClassLoader.java nashorn/src/jdk/internal/dynalink/beans/sandbox/Unreflector.java nashorn/src/jdk/nashorn/internal/runtime/linker/JavaAdapterGeneratorBase.java nashorn/test/script/representations/NASHORN-592a.js
diffstat 647 files changed, 29968 insertions(+), 8002 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Fri Jul 19 13:24:09 2013 -0700
+++ b/.hgtags	Thu Aug 01 17:24:26 2013 -0700
@@ -221,3 +221,5 @@
 0a85476a0b9cb876d5666d45097dac68bef3fce1 jdk8-b97
 711eb4aa87de68de78250e0549980936bab53d54 jdk8-b98
 2d3875b0d18b3ad1c2bebf385a697e309e4005a4 jdk8-b99
+3d34036aae4ea90b2ca59712d5a69db3221f0875 jdk8-b100
+edb01c460d4cab21ff0ff13512df7b746efaa0e7 jdk8-b101
--- a/.hgtags-top-repo	Fri Jul 19 13:24:09 2013 -0700
+++ b/.hgtags-top-repo	Thu Aug 01 17:24:26 2013 -0700
@@ -221,3 +221,5 @@
 a1c1e8bf71f354f3aec0214cf13d6668811e021d jdk8-b97
 0d0c983a817bbe8518a5ff201306334a8de267f2 jdk8-b98
 59dc9da813794c924a0383c2a6241af94defdfed jdk8-b99
+d2dcb110e9dbaf9903c05b211df800e78e4b394e jdk8-b100
+9f74a220677dc265a724515d8e2617548cef62f1 jdk8-b101
--- a/corba/.hgtags	Fri Jul 19 13:24:09 2013 -0700
+++ b/corba/.hgtags	Thu Aug 01 17:24:26 2013 -0700
@@ -221,3 +221,5 @@
 469995a8e97424f450c880606d689bf345277b19 jdk8-b97
 3370fb6146e47a6cc05a213fc213e12fc0a38d07 jdk8-b98
 3f67804ab61303782df57e54989ef5e0e4629beb jdk8-b99
+8d492f1dfd1b131a4c7886ee6b59528609f7e4fe jdk8-b100
+a013024b07475782f1fa8e196e950b34b4077663 jdk8-b101
--- a/hotspot/.hgtags	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/.hgtags	Thu Aug 01 17:24:26 2013 -0700
@@ -361,3 +361,7 @@
 2b9946e10587f74ef75ae8145bea484df4a2738b hs25-b41
 81b6cb70717c66375846b78bb174594ec3aa998e jdk8-b99
 9f71e36a471ae4a668e08827d33035963ed10c08 hs25-b42
+5787fac72e760c6a5fd9efa113b0c75caf554136 jdk8-b100
+46487ba40ff225654d0c51787ed3839bafcbd9f3 hs25-b43
+f6921c876db192bba389cec062855a66372da01c jdk8-b101
+530fe88b3b2c710f42810b3580d86a0d83ad6c1c hs25-b44
--- a/hotspot/make/bsd/makefiles/minimal1.make	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/make/bsd/makefiles/minimal1.make	Thu Aug 01 17:24:26 2013 -0700
@@ -24,16 +24,20 @@
 
 TYPE=MINIMAL1
 
-INCLUDE_JVMTI ?= false
-INCLUDE_FPROF ?= false
-INCLUDE_VM_STRUCTS ?= false
-INCLUDE_JNI_CHECK ?= false
-INCLUDE_SERVICES ?= false
-INCLUDE_MANAGEMENT ?= false
-INCLUDE_ALL_GCS ?= false
-INCLUDE_NMT ?= false
-INCLUDE_TRACE ?= false
-INCLUDE_CDS ?= false
+# Force all variables to false, overriding any other
+# setting that may have occurred in the makefiles. These
+# can still be overridden by passing the variable as an
+# argument to 'make'
+INCLUDE_JVMTI := false
+INCLUDE_FPROF := false
+INCLUDE_VM_STRUCTS := false
+INCLUDE_JNI_CHECK := false
+INCLUDE_SERVICES := false
+INCLUDE_MANAGEMENT := false
+INCLUDE_ALL_GCS := false
+INCLUDE_NMT := false
+INCLUDE_TRACE := false
+INCLUDE_CDS := false
 
 CXXFLAGS += -DMINIMAL_JVM -DCOMPILER1 -DVMTYPE=\"Minimal\"
 CFLAGS += -DMINIMAL_JVM -DCOMPILER1 -DVMTYPE=\"Minimal\"
--- a/hotspot/make/hotspot_version	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/make/hotspot_version	Thu Aug 01 17:24:26 2013 -0700
@@ -35,7 +35,7 @@
 
 HS_MAJOR_VER=25
 HS_MINOR_VER=0
-HS_BUILD_NUMBER=42
+HS_BUILD_NUMBER=44
 
 JDK_MAJOR_VER=1
 JDK_MINOR_VER=8
--- a/hotspot/make/linux/makefiles/minimal1.make	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/make/linux/makefiles/minimal1.make	Thu Aug 01 17:24:26 2013 -0700
@@ -24,16 +24,20 @@
 
 TYPE=MINIMAL1
 
-INCLUDE_JVMTI ?= false
-INCLUDE_FPROF ?= false
-INCLUDE_VM_STRUCTS ?= false
-INCLUDE_JNI_CHECK ?= false
-INCLUDE_SERVICES ?= false
-INCLUDE_MANAGEMENT ?= false
-INCLUDE_ALL_GCS ?= false
-INCLUDE_NMT ?= false
-INCLUDE_TRACE ?= false
-INCLUDE_CDS ?= false
+# Force all variables to false, overriding any other
+# setting that may have occurred in the makefiles. These
+# can still be overridden by passing the variable as an
+# argument to 'make'
+INCLUDE_JVMTI := false
+INCLUDE_FPROF := false
+INCLUDE_VM_STRUCTS := false
+INCLUDE_JNI_CHECK := false
+INCLUDE_SERVICES := false
+INCLUDE_MANAGEMENT := false
+INCLUDE_ALL_GCS := false
+INCLUDE_NMT := false
+INCLUDE_TRACE := false
+INCLUDE_CDS := false
 
 CXXFLAGS += -DMINIMAL_JVM -DCOMPILER1 -DVMTYPE=\"Minimal\"
 CFLAGS += -DMINIMAL_JVM -DCOMPILER1 -DVMTYPE=\"Minimal\"
--- a/hotspot/make/linux/makefiles/vm.make	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/make/linux/makefiles/vm.make	Thu Aug 01 17:24:26 2013 -0700
@@ -212,6 +212,12 @@
 Src_Files_EXCLUDE += \*x86_32\*
 endif
 
+# Alternate vm.make
+# This has to be included here to allow changes to the source
+# directories and excluded files before they are expanded
+# by the definition of Src_Files.
+-include $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/vm.make
+
 # Locate all source files in the given directory, excluding files in Src_Files_EXCLUDE.
 define findsrc
 	$(notdir $(shell find $(1)/. ! -name . -prune \
@@ -381,4 +387,4 @@
 
 install: install_jvm install_jsig install_saproc
 
-.PHONY: default build install install_jvm $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/$(BUILDARCH).make
+.PHONY: default build install install_jvm $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/$(BUILDARCH).make $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/vm.make
--- a/hotspot/make/windows/makefiles/compile.make	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/make/windows/makefiles/compile.make	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -110,6 +110,7 @@
 #      1400 is for VS2005
 #      1500 is for VS2008
 #      1600 is for VS2010
+#      1700 is for VS2012
 #    Do not confuse this MSC_VER with the predefined macro _MSC_VER that the
 #    compiler provides, when MSC_VER==1399, _MSC_VER will be 1400.
 #    Normally they are the same, but a pre-release of the VS2005 compilers
@@ -142,6 +143,9 @@
 !if "$(MSC_VER)" == "1600"
 COMPILER_NAME=VS2010
 !endif
+!if "$(MSC_VER)" == "1700"
+COMPILER_NAME=VS2012
+!endif
 !endif
 
 # By default, we do not want to use the debug version of the msvcrt.dll file
@@ -151,9 +155,13 @@
 MS_RUNTIME_OPTION = /MTd /D "_DEBUG"
 !endif
 
+# VS2012 and later won't work with:
+#     /D _STATIC_CPPLIB /D _DISABLE_DEPRECATE_STATIC_CPPLIB
+!if "$(MSC_VER)" < "1700"
 # Always add the _STATIC_CPPLIB flag
 STATIC_CPPLIB_OPTION = /D _STATIC_CPPLIB /D _DISABLE_DEPRECATE_STATIC_CPPLIB
 MS_RUNTIME_OPTION = $(MS_RUNTIME_OPTION) $(STATIC_CPPLIB_OPTION)
+!endif
 CXX_FLAGS=$(CXX_FLAGS) $(MS_RUNTIME_OPTION)
 
 # How /GX option is spelled
@@ -221,6 +229,22 @@
 !endif
 !endif
 
+!if "$(COMPILER_NAME)" == "VS2012"
+PRODUCT_OPT_OPTION   = /O2 /Oy-
+FASTDEBUG_OPT_OPTION = /O2 /Oy-
+DEBUG_OPT_OPTION     = /Od
+GX_OPTION = /EHsc
+LD_FLAGS = /manifest $(LD_FLAGS)
+# Manifest Tool - used in VS2005 and later to adjust manifests stored
+# as resources inside build artifacts.
+!if "x$(MT)" == "x"
+MT=mt.exe
+!endif
+!if "$(BUILDARCH)" == "i486"
+LD_FLAGS = /SAFESEH $(LD_FLAGS)
+!endif
+!endif
+
 # If NO_OPTIMIZATIONS is defined in the environment, turn everything off
 !ifdef NO_OPTIMIZATIONS
 PRODUCT_OPT_OPTION   = $(DEBUG_OPT_OPTION)
--- a/hotspot/make/windows/makefiles/sanity.make	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/make/windows/makefiles/sanity.make	Thu Aug 01 17:24:26 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2006, 2012, 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
@@ -27,9 +27,9 @@
 all: checkCL checkLink
 
 checkCL:
-	@ if "$(MSC_VER)" NEQ "1310" if "$(MSC_VER)" NEQ "1399" if "$(MSC_VER)" NEQ "1400" if "$(MSC_VER)" NEQ "1500" if "$(MSC_VER)" NEQ "1600" \
+	@ if "$(MSC_VER)" NEQ "1310" if "$(MSC_VER)" NEQ "1399" if "$(MSC_VER)" NEQ "1400" if "$(MSC_VER)" NEQ "1500" if "$(MSC_VER)" NEQ "1600" if "$(MSC_VER)" NEQ "1700" \
 	echo *** WARNING *** unrecognized cl.exe version $(MSC_VER) ($(RAW_MSC_VER)).  Use FORCE_MSC_VER to override automatic detection.
 
 checkLink:
-	@ if "$(LD_VER)" NEQ "710" if "$(LD_VER)" NEQ "800" if "$(LD_VER)" NEQ "900" if "$(LD_VER)" NEQ "1000" \
+	@ if "$(LD_VER)" NEQ "710" if "$(LD_VER)" NEQ "800" if "$(LD_VER)" NEQ "900" if "$(LD_VER)" NEQ "1000" if "$(LD_VER)" NEQ "1100" \
 	echo *** WARNING *** unrecognized link.exe version $(LD_VER) ($(RAW_LD_VER)).  Use FORCE_LD_VER to override automatic detection.
--- a/hotspot/make/windows/makefiles/vm.make	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/make/windows/makefiles/vm.make	Thu Aug 01 17:24:26 2013 -0700
@@ -132,6 +132,10 @@
 
 !if "$(USE_PRECOMPILED_HEADER)" != "0"
 CXX_USE_PCH=/Fp"vm.pch" /Yu"precompiled.hpp"
+!if "$(COMPILER_NAME)" == "VS2012"
+# VS2012 requires this object file to be listed:
+LD_FLAGS=$(LD_FLAGS) _build_pch_file.obj
+!endif
 !else
 CXX_USE_PCH=$(CXX_DONT_USE_PCH)
 !endif
--- a/hotspot/src/cpu/sparc/vm/c2_globals_sparc.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/c2_globals_sparc.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -42,7 +42,7 @@
 #else
 define_pd_global(bool, ProfileInterpreter,           true);
 #endif // CC_INTERP
-define_pd_global(bool, TieredCompilation,            false);
+define_pd_global(bool, TieredCompilation,            trueInTiered);
 define_pd_global(intx, CompileThreshold,             10000);
 define_pd_global(intx, BackEdgeThreshold,            140000);
 
--- a/hotspot/src/cpu/sparc/vm/frame_sparc.inline.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/cpu/sparc/vm/frame_sparc.inline.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -240,10 +240,10 @@
 #endif // CC_INTERP
 
 
-inline JavaCallWrapper* frame::entry_frame_call_wrapper() const {
+inline JavaCallWrapper** frame::entry_frame_call_wrapper_addr() const {
   // note: adjust this code if the link argument in StubGenerator::call_stub() changes!
   const Argument link = Argument(0, false);
-  return (JavaCallWrapper*)sp()[link.as_in().as_register()->sp_offset_in_saved_window()];
+  return (JavaCallWrapper**)&sp()[link.as_in().as_register()->sp_offset_in_saved_window()];
 }
 
 
--- a/hotspot/src/cpu/x86/vm/c2_globals_x86.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/c2_globals_x86.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -44,7 +44,7 @@
 #else
 define_pd_global(bool, ProfileInterpreter,           true);
 #endif // CC_INTERP
-define_pd_global(bool, TieredCompilation,            false);
+define_pd_global(bool, TieredCompilation,            trueInTiered);
 define_pd_global(intx, CompileThreshold,             10000);
 define_pd_global(intx, BackEdgeThreshold,            100000);
 
--- a/hotspot/src/cpu/x86/vm/frame_x86.inline.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/frame_x86.inline.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -272,11 +272,10 @@
 
 // Entry frames
 
-inline JavaCallWrapper* frame::entry_frame_call_wrapper() const {
- return (JavaCallWrapper*)at(entry_frame_call_wrapper_offset);
+inline JavaCallWrapper** frame::entry_frame_call_wrapper_addr() const {
+ return (JavaCallWrapper**)addr_at(entry_frame_call_wrapper_offset);
 }
 
-
 // Compiled frames
 
 inline int frame::local_offset_for_compiler(int local_index, int nof_args, int max_nof_locals, int max_nof_monitors) {
--- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -279,7 +279,7 @@
       __ stmxcsr(mxcsr_save);
       __ movl(rax, mxcsr_save);
       __ andl(rax, MXCSR_MASK);    // Only check control and mask bits
-      ExternalAddress mxcsr_std(StubRoutines::x86::mxcsr_std());
+      ExternalAddress mxcsr_std(StubRoutines::addr_mxcsr_std());
       __ cmp32(rax, mxcsr_std);
       __ jcc(Assembler::equal, skip_ldmx);
       __ ldmxcsr(mxcsr_std);
@@ -729,17 +729,18 @@
 
     if (CheckJNICalls) {
       Label ok_ret;
+      ExternalAddress mxcsr_std(StubRoutines::addr_mxcsr_std());
       __ push(rax);
       __ subptr(rsp, wordSize);      // allocate a temp location
       __ stmxcsr(mxcsr_save);
       __ movl(rax, mxcsr_save);
       __ andl(rax, MXCSR_MASK);    // Only check control and mask bits
-      __ cmpl(rax, *(int *)(StubRoutines::x86::mxcsr_std()));
+      __ cmp32(rax, mxcsr_std);
       __ jcc(Assembler::equal, ok_ret);
 
       __ warn("MXCSR changed by native JNI code, use -XX:+RestoreMXCSROnJNICall");
 
-      __ ldmxcsr(ExternalAddress(StubRoutines::x86::mxcsr_std()));
+      __ ldmxcsr(mxcsr_std);
 
       __ bind(ok_ret);
       __ addptr(rsp, wordSize);
@@ -3767,12 +3768,35 @@
     return stub->entry_point();
   }
 
+  void create_control_words() {
+    // Round to nearest, 53-bit mode, exceptions masked
+    StubRoutines::_fpu_cntrl_wrd_std   = 0x027F;
+    // Round to zero, 53-bit mode, exception mased
+    StubRoutines::_fpu_cntrl_wrd_trunc = 0x0D7F;
+    // Round to nearest, 24-bit mode, exceptions masked
+    StubRoutines::_fpu_cntrl_wrd_24    = 0x007F;
+    // Round to nearest, 64-bit mode, exceptions masked
+    StubRoutines::_fpu_cntrl_wrd_64    = 0x037F;
+    // Round to nearest, 64-bit mode, exceptions masked
+    StubRoutines::_mxcsr_std           = 0x1F80;
+    // Note: the following two constants are 80-bit values
+    //       layout is critical for correct loading by FPU.
+    // Bias for strict fp multiply/divide
+    StubRoutines::_fpu_subnormal_bias1[0]= 0x00000000; // 2^(-15360) == 0x03ff 8000 0000 0000 0000
+    StubRoutines::_fpu_subnormal_bias1[1]= 0x80000000;
+    StubRoutines::_fpu_subnormal_bias1[2]= 0x03ff;
+    // Un-Bias for strict fp multiply/divide
+    StubRoutines::_fpu_subnormal_bias2[0]= 0x00000000; // 2^(+15360) == 0x7bff 8000 0000 0000 0000
+    StubRoutines::_fpu_subnormal_bias2[1]= 0x80000000;
+    StubRoutines::_fpu_subnormal_bias2[2]= 0x7bff;
+  }
+
   // Initialization
   void generate_initial() {
     // Generates all stubs and initializes the entry points
 
-    // This platform-specific stub is needed by generate_call_stub()
-    StubRoutines::x86::_mxcsr_std        = generate_fp_mask("mxcsr_std",        0x0000000000001F80);
+    // This platform-specific settings are needed by generate_call_stub()
+    create_control_words();
 
     // entry points that exist in all platforms Note: This is code
     // that could be shared among different platforms - however the
--- a/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -42,4 +42,3 @@
 address StubRoutines::x86::_float_sign_flip = NULL;
 address StubRoutines::x86::_double_sign_mask = NULL;
 address StubRoutines::x86::_double_sign_flip = NULL;
-address StubRoutines::x86::_mxcsr_std = NULL;
--- a/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -52,7 +52,6 @@
   static address _float_sign_flip;
   static address _double_sign_mask;
   static address _double_sign_flip;
-  static address _mxcsr_std;
 
  public:
 
@@ -106,11 +105,6 @@
     return _double_sign_flip;
   }
 
-  static address mxcsr_std()
-  {
-    return _mxcsr_std;
-  }
-
 # include "stubRoutines_x86.hpp"
 
 };
--- a/hotspot/src/os/bsd/vm/attachListener_bsd.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os/bsd/vm/attachListener_bsd.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -437,6 +437,30 @@
   return op;
 }
 
+
+// Performs initialization at vm startup
+// For BSD we remove any stale .java_pid file which could cause
+// an attaching process to think we are ready to receive on the
+// domain socket before we are properly initialized
+
+void AttachListener::vm_start() {
+  char fn[UNIX_PATH_MAX];
+  struct stat64 st;
+  int ret;
+
+  int n = snprintf(fn, UNIX_PATH_MAX, "%s/.java_pid%d",
+           os::get_temp_directory(), os::current_process_id());
+  assert(n < (int)UNIX_PATH_MAX, "java_pid file name buffer overflow");
+
+  RESTARTABLE(::stat64(fn, &st), ret);
+  if (ret == 0) {
+    ret = ::unlink(fn);
+    if (ret == -1) {
+      debug_only(warning("failed to remove stale attach pid file at %s", fn));
+    }
+  }
+}
+
 int AttachListener::pd_init() {
   JavaThread* thread = JavaThread::current();
   ThreadBlockInVM tbivm(thread);
--- a/hotspot/src/os/linux/vm/attachListener_linux.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os/linux/vm/attachListener_linux.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2010, 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
@@ -432,6 +432,30 @@
   return op;
 }
 
+
+// Performs initialization at vm startup
+// For Linux we remove any stale .java_pid file which could cause
+// an attaching process to think we are ready to receive on the
+// domain socket before we are properly initialized
+
+void AttachListener::vm_start() {
+  char fn[UNIX_PATH_MAX];
+  struct stat64 st;
+  int ret;
+
+  int n = snprintf(fn, UNIX_PATH_MAX, "%s/.java_pid%d",
+           os::get_temp_directory(), os::current_process_id());
+  assert(n < (int)UNIX_PATH_MAX, "java_pid file name buffer overflow");
+
+  RESTARTABLE(::stat64(fn, &st), ret);
+  if (ret == 0) {
+    ret = ::unlink(fn);
+    if (ret == -1) {
+      debug_only(warning("failed to remove stale attach pid file at %s", fn));
+    }
+  }
+}
+
 int AttachListener::pd_init() {
   JavaThread* thread = JavaThread::current();
   ThreadBlockInVM tbivm(thread);
--- a/hotspot/src/os/linux/vm/jsig.c	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os/linux/vm/jsig.c	Thu Aug 01 17:24:26 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2010, 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
@@ -107,7 +107,7 @@
 
   signal_lock();
 
-  sigused = (MASK(sig) & jvmsigs) != 0;
+  sigused = (sig < MAXSIGNUM) && ((MASK(sig) & jvmsigs) != 0);
   if (jvm_signal_installed && sigused) {
     /* jvm has installed its signal handler for this signal. */
     /* Save the handler. Don't really install it. */
@@ -116,7 +116,7 @@
 
     signal_unlock();
     return oldhandler;
-  } else if (jvm_signal_installing) {
+  } else if (sig < MAXSIGNUM && jvm_signal_installing) {
     /* jvm is installing its signal handlers. Install the new
      * handlers and save the old ones. jvm uses sigaction().
      * Leave the piece here just in case. */
@@ -165,7 +165,7 @@
 
   signal_lock();
 
-  sigused = (MASK(sig) & jvmsigs) != 0;
+  sigused = (sig < MAXSIGNUM) && ((MASK(sig) & jvmsigs) != 0);
   if (jvm_signal_installed && sigused) {
     /* jvm has installed its signal handler for this signal. */
     /* Save the handler. Don't really install it. */
@@ -178,7 +178,7 @@
 
     signal_unlock();
     return 0;
-  } else if (jvm_signal_installing) {
+  } else if (sig < MAXSIGNUM && jvm_signal_installing) {
     /* jvm is installing its signal handlers. Install the new
      * handlers and save the old ones. */
     res = call_os_sigaction(sig, act, &oldAct);
--- a/hotspot/src/os/posix/vm/os_posix.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os/posix/vm/os_posix.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -259,3 +259,52 @@
 FILE* os::open(int fd, const char* mode) {
   return ::fdopen(fd, mode);
 }
+
+os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
+  assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
+}
+
+/*
+ * See the caveats for this class in os_posix.hpp
+ * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this
+ * method and returns false. If none of the signals are raised, returns true.
+ * The callback is supposed to provide the method that should be protected.
+ */
+bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
+  assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread");
+  assert(!WatcherThread::watcher_thread()->has_crash_protection(),
+      "crash_protection already set?");
+
+  if (sigsetjmp(_jmpbuf, 1) == 0) {
+    // make sure we can see in the signal handler that we have crash protection
+    // installed
+    WatcherThread::watcher_thread()->set_crash_protection(this);
+    cb.call();
+    // and clear the crash protection
+    WatcherThread::watcher_thread()->set_crash_protection(NULL);
+    return true;
+  }
+  // this happens when we siglongjmp() back
+  WatcherThread::watcher_thread()->set_crash_protection(NULL);
+  return false;
+}
+
+void os::WatcherThreadCrashProtection::restore() {
+  assert(WatcherThread::watcher_thread()->has_crash_protection(),
+      "must have crash protection");
+
+  siglongjmp(_jmpbuf, 1);
+}
+
+void os::WatcherThreadCrashProtection::check_crash_protection(int sig,
+    Thread* thread) {
+
+  if (thread != NULL &&
+      thread->is_Watcher_thread() &&
+      WatcherThread::watcher_thread()->has_crash_protection()) {
+
+    if (sig == SIGSEGV || sig == SIGBUS) {
+      WatcherThread::watcher_thread()->crash_protection()->restore();
+    }
+  }
+}
--- a/hotspot/src/os/posix/vm/os_posix.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os/posix/vm/os_posix.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -37,5 +37,24 @@
 
 };
 
+/*
+ * Crash protection for the watcher thread. Wrap the callback
+ * with a sigsetjmp and in case of a SIGSEGV/SIGBUS we siglongjmp
+ * back.
+ * To be able to use this - don't take locks, don't rely on destructors,
+ * don't make OS library calls, don't allocate memory, don't print,
+ * don't call code that could leave the heap / memory in an inconsistent state,
+ * or anything else where we are not in control if we suddenly jump out.
+ */
+class WatcherThreadCrashProtection : public StackObj {
+public:
+  WatcherThreadCrashProtection();
+  bool call(os::CrashProtectionCallback& cb);
+
+  static void check_crash_protection(int signal, Thread* thread);
+private:
+  void restore();
+  sigjmp_buf _jmpbuf;
+};
 
 #endif
--- a/hotspot/src/os/solaris/vm/attachListener_solaris.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os/solaris/vm/attachListener_solaris.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -576,6 +576,30 @@
   return op;
 }
 
+
+// Performs initialization at vm startup
+// For Solaris we remove any stale .java_pid file which could cause
+// an attaching process to think we are ready to receive a door_call
+// before we are properly initialized
+
+void AttachListener::vm_start() {
+  char fn[PATH_MAX+1];
+  struct stat64 st;
+  int ret;
+
+  int n = snprintf(fn, sizeof(fn), "%s/.java_pid%d",
+           os::get_temp_directory(), os::current_process_id());
+  assert(n < sizeof(fn), "java_pid file name buffer overflow");
+
+  RESTARTABLE(::stat64(fn, &st), ret);
+  if (ret == 0) {
+    ret = ::unlink(fn);
+    if (ret == -1) {
+      debug_only(warning("failed to remove stale attach pid file at %s", fn));
+    }
+  }
+}
+
 int AttachListener::pd_init() {
   JavaThread* thread = JavaThread::current();
   ThreadBlockInVM tbivm(thread);
--- a/hotspot/src/os/windows/vm/attachListener_windows.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os/windows/vm/attachListener_windows.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2010, 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
@@ -358,6 +358,10 @@
   return op;
 }
 
+void AttachListener::vm_start() {
+  // nothing to do
+}
+
 int AttachListener::pd_init() {
   return Win32AttachListener::init();
 }
--- a/hotspot/src/os/windows/vm/os_windows.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os/windows/vm/os_windows.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -4689,6 +4689,34 @@
   }
 }
 
+os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() {
+  assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread");
+}
+
+/*
+ * See the caveats for this class in os_windows.hpp
+ * Protects the callback call so that raised OS EXCEPTIONS causes a jump back
+ * into this method and returns false. If no OS EXCEPTION was raised, returns
+ * true.
+ * The callback is supposed to provide the method that should be protected.
+ */
+bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) {
+  assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread");
+  assert(!WatcherThread::watcher_thread()->has_crash_protection(),
+      "crash_protection already set?");
+
+  bool success = true;
+  __try {
+    WatcherThread::watcher_thread()->set_crash_protection(this);
+    cb.call();
+  } __except(EXCEPTION_EXECUTE_HANDLER) {
+    // only for protection, nothing to do
+    success = false;
+  }
+  WatcherThread::watcher_thread()->set_crash_protection(NULL);
+  return success;
+}
+
 // An Event wraps a win32 "CreateEvent" kernel handle.
 //
 // We have a number of choices regarding "CreateEvent" win32 handle leakage:
--- a/hotspot/src/os/windows/vm/os_windows.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os/windows/vm/os_windows.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -102,6 +102,20 @@
   static LONG WINAPI serialize_fault_filter(struct _EXCEPTION_POINTERS* e);
 };
 
+/*
+ * Crash protection for the watcher thread. Wrap the callback
+ * with a __try { call() }
+ * To be able to use this - don't take locks, don't rely on destructors,
+ * don't make OS library calls, don't allocate memory, don't print,
+ * don't call code that could leave the heap / memory in an inconsistent state,
+ * or anything else where we are not in control if we suddenly jump out.
+ */
+class WatcherThreadCrashProtection : public StackObj {
+public:
+  WatcherThreadCrashProtection();
+  bool call(os::CrashProtectionCallback& cb);
+};
+
 class PlatformEvent : public CHeapObj<mtInternal> {
   private:
     double CachePad [4] ;   // increase odds that _Event is sole occupant of cache line
--- a/hotspot/src/os_cpu/bsd_x86/vm/orderAccess_bsd_x86.inline.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os_cpu/bsd_x86/vm/orderAccess_bsd_x86.inline.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -72,7 +72,7 @@
 inline juint    OrderAccess::load_acquire(volatile juint*   p) { return *p; }
 inline julong   OrderAccess::load_acquire(volatile julong*  p) { return Atomic::load((volatile jlong*)p); }
 inline jfloat   OrderAccess::load_acquire(volatile jfloat*  p) { return *p; }
-inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return *p; }
+inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return jdouble_cast(Atomic::load((volatile jlong*)p)); }
 
 inline intptr_t OrderAccess::load_ptr_acquire(volatile intptr_t*   p) { return *p; }
 inline void*    OrderAccess::load_ptr_acquire(volatile void*       p) { return *(void* volatile *)p; }
@@ -87,7 +87,7 @@
 inline void     OrderAccess::release_store(volatile juint*   p, juint   v) { *p = v; }
 inline void     OrderAccess::release_store(volatile julong*  p, julong  v) { Atomic::store((jlong)v, (volatile jlong*)p); }
 inline void     OrderAccess::release_store(volatile jfloat*  p, jfloat  v) { *p = v; }
-inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { *p = v; }
+inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { release_store((volatile jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr(volatile intptr_t* p, intptr_t v) { *p = v; }
 inline void     OrderAccess::release_store_ptr(volatile void*     p, void*    v) { *(void* volatile *)p = v; }
@@ -190,7 +190,7 @@
 inline void     OrderAccess::release_store_fence(volatile julong*  p, julong  v) { release_store_fence((volatile jlong*)p,  (jlong)v);  }
 
 inline void     OrderAccess::release_store_fence(volatile jfloat*  p, jfloat  v) { *p = v; fence(); }
-inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { *p = v; fence(); }
+inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { release_store_fence((volatile jlong*)p, jdouble_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr_fence(volatile intptr_t* p, intptr_t v) {
 #ifdef AMD64
--- a/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -394,6 +394,10 @@
 
   Thread* t = ThreadLocalStorage::get_thread_slow();
 
+  // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away
+  // (no destructors can be run)
+  os::WatcherThreadCrashProtection::check_crash_protection(sig, t);
+
   SignalHandlerMark shm(t);
 
   // Note: it's not uncommon that JNI code uses signal/sigset to install
--- a/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -544,6 +544,10 @@
 
   Thread* t = ThreadLocalStorage::get_thread_slow();
 
+  // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away
+  // (no destructors can be run)
+  os::WatcherThreadCrashProtection::check_crash_protection(sig, t);
+
   SignalHandlerMark shm(t);
 
   // Note: it's not uncommon that JNI code uses signal/sigset to install
--- a/hotspot/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -72,7 +72,7 @@
 inline juint    OrderAccess::load_acquire(volatile juint*   p) { return *p; }
 inline julong   OrderAccess::load_acquire(volatile julong*  p) { return Atomic::load((volatile jlong*)p); }
 inline jfloat   OrderAccess::load_acquire(volatile jfloat*  p) { return *p; }
-inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return *p; }
+inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return jdouble_cast(Atomic::load((volatile jlong*)p)); }
 
 inline intptr_t OrderAccess::load_ptr_acquire(volatile intptr_t*   p) { return *p; }
 inline void*    OrderAccess::load_ptr_acquire(volatile void*       p) { return *(void* volatile *)p; }
@@ -87,7 +87,7 @@
 inline void     OrderAccess::release_store(volatile juint*   p, juint   v) { *p = v; }
 inline void     OrderAccess::release_store(volatile julong*  p, julong  v) { Atomic::store((jlong)v, (volatile jlong*)p); }
 inline void     OrderAccess::release_store(volatile jfloat*  p, jfloat  v) { *p = v; }
-inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { *p = v; }
+inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { release_store((volatile jlong *)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr(volatile intptr_t* p, intptr_t v) { *p = v; }
 inline void     OrderAccess::release_store_ptr(volatile void*     p, void*    v) { *(void* volatile *)p = v; }
@@ -129,7 +129,7 @@
 inline void     OrderAccess::store_fence(juint*   p, juint   v) { store_fence((jint*)p,   (jint)v);   }
 inline void     OrderAccess::store_fence(julong*  p, julong  v) { store_fence((jlong*)p,  (jlong)v);  }
 inline void     OrderAccess::store_fence(jfloat*  p, jfloat  v) { *p = v; fence(); }
-inline void     OrderAccess::store_fence(jdouble* p, jdouble v) { *p = v; fence(); }
+inline void     OrderAccess::store_fence(jdouble* p, jdouble v) { store_fence((jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::store_ptr_fence(intptr_t* p, intptr_t v) {
 #ifdef AMD64
@@ -190,7 +190,7 @@
 inline void     OrderAccess::release_store_fence(volatile julong*  p, julong  v) { release_store_fence((volatile jlong*)p,  (jlong)v);  }
 
 inline void     OrderAccess::release_store_fence(volatile jfloat*  p, jfloat  v) { *p = v; fence(); }
-inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { *p = v; fence(); }
+inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { release_store_fence((volatile jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr_fence(volatile intptr_t* p, intptr_t v) {
 #ifdef AMD64
--- a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -218,6 +218,10 @@
 
   Thread* t = ThreadLocalStorage::get_thread_slow();
 
+  // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away
+  // (no destructors can be run)
+  os::WatcherThreadCrashProtection::check_crash_protection(sig, t);
+
   SignalHandlerMark shm(t);
 
   // Note: it's not uncommon that JNI code uses signal/sigset to install
--- a/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -310,6 +310,10 @@
 
   Thread* t = ThreadLocalStorage::get_thread_slow();
 
+  // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away
+  // (no destructors can be run)
+  os::WatcherThreadCrashProtection::check_crash_protection(sig, t);
+
   SignalHandlerMark shm(t);
 
   if(sig == SIGPIPE || sig == SIGXFSZ) {
--- a/hotspot/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -88,7 +88,7 @@
 inline juint    OrderAccess::load_acquire(volatile juint*   p) { return *p; }
 inline julong   OrderAccess::load_acquire(volatile julong*  p) { return Atomic::load((volatile jlong*)p); }
 inline jfloat   OrderAccess::load_acquire(volatile jfloat*  p) { return *p; }
-inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return *p; }
+inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return jdouble_cast(Atomic::load((volatile jlong*)p)); }
 
 inline intptr_t OrderAccess::load_ptr_acquire(volatile intptr_t*   p) { return *p; }
 inline void*    OrderAccess::load_ptr_acquire(volatile void*       p) { return *(void* volatile *)p; }
@@ -103,7 +103,7 @@
 inline void     OrderAccess::release_store(volatile juint*   p, juint   v) { *p = v; }
 inline void     OrderAccess::release_store(volatile julong*  p, julong  v) { Atomic::store((jlong)v, (volatile jlong*)p); }
 inline void     OrderAccess::release_store(volatile jfloat*  p, jfloat  v) { *p = v; }
-inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { *p = v; }
+inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { release_store((volatile jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr(volatile intptr_t* p, intptr_t v) { *p = v; }
 inline void     OrderAccess::release_store_ptr(volatile void*     p, void*    v) { *(void* volatile *)p = v; }
@@ -129,9 +129,9 @@
 inline void     OrderAccess::release_store_fence(volatile jubyte*  p, jubyte  v) { *p = v; fence(); }
 inline void     OrderAccess::release_store_fence(volatile jushort* p, jushort v) { *p = v; fence(); }
 inline void     OrderAccess::release_store_fence(volatile juint*   p, juint   v) { *p = v; fence(); }
-inline void     OrderAccess::release_store_fence(volatile julong*  p, julong  v) { release_store(p, v); fence(); }
+inline void     OrderAccess::release_store_fence(volatile julong*  p, julong  v) { release_store((jlong *)p, (jlong)v); fence(); }
 inline void     OrderAccess::release_store_fence(volatile jfloat*  p, jfloat  v) { *p = v; fence(); }
-inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { *p = v; fence(); }
+inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { release_store_fence((volatile jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr_fence(volatile intptr_t* p, intptr_t v) { *p = v; fence(); }
 inline void     OrderAccess::release_store_ptr_fence(volatile void*     p, void*    v) { *(void* volatile *)p = v; fence(); }
--- a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -367,6 +367,10 @@
 
   Thread* t = ThreadLocalStorage::get_thread_slow();  // slow & steady
 
+  // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away
+  // (no destructors can be run)
+  os::WatcherThreadCrashProtection::check_crash_protection(sig, t);
+
   SignalHandlerMark shm(t);
 
   if(sig == SIGPIPE || sig == SIGXFSZ) {
--- a/hotspot/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -71,7 +71,7 @@
 inline juint    OrderAccess::load_acquire(volatile juint*   p) { return *p; }
 inline julong   OrderAccess::load_acquire(volatile julong*  p) { return Atomic::load((volatile jlong*)p); }
 inline jfloat   OrderAccess::load_acquire(volatile jfloat*  p) { return *p; }
-inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return *p; }
+inline jdouble  OrderAccess::load_acquire(volatile jdouble* p) { return jdouble_cast(Atomic::load((volatile jlong*)p)); }
 
 inline intptr_t OrderAccess::load_ptr_acquire(volatile intptr_t*   p) { return *p; }
 inline void*    OrderAccess::load_ptr_acquire(volatile void*       p) { return *(void* volatile *)p; }
@@ -86,7 +86,7 @@
 inline void     OrderAccess::release_store(volatile juint*   p, juint   v) { *p = v; }
 inline void     OrderAccess::release_store(volatile julong*  p, julong  v) { Atomic::store((jlong)v, (volatile jlong*)p); }
 inline void     OrderAccess::release_store(volatile jfloat*  p, jfloat  v) { *p = v; }
-inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { *p = v; }
+inline void     OrderAccess::release_store(volatile jdouble* p, jdouble v) { release_store((volatile jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr(volatile intptr_t* p, intptr_t v) { *p = v; }
 inline void     OrderAccess::release_store_ptr(volatile void*     p, void*    v) { *(void* volatile *)p = v; }
@@ -195,7 +195,7 @@
 inline void     OrderAccess::release_store_fence(volatile juint*   p, juint   v) { release_store_fence((volatile jint*)p,   (jint)v);   }
 inline void     OrderAccess::release_store_fence(volatile julong*  p, julong  v) { release_store_fence((volatile jlong*)p,  (jlong)v);  }
 inline void     OrderAccess::release_store_fence(volatile jfloat*  p, jfloat  v) { *p = v; fence(); }
-inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { *p = v; fence(); }
+inline void     OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { release_store_fence((volatile jlong*)p, jlong_cast(v)); }
 
 inline void     OrderAccess::release_store_ptr_fence(volatile intptr_t* p, intptr_t v) {
 #ifdef AMD64
--- a/hotspot/src/os_cpu/windows_x86/vm/unwind_windows_x86.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/os_cpu/windows_x86/vm/unwind_windows_x86.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 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,10 +29,15 @@
 #ifdef AMD64
 typedef unsigned char UBYTE;
 
+#if _MSC_VER < 1700
+
+/* Not needed for VS2012 compiler, comes from winnt.h. */
 #define UNW_FLAG_EHANDLER  0x01
 #define UNW_FLAG_UHANDLER  0x02
 #define UNW_FLAG_CHAININFO 0x04
 
+#endif
+
 // This structure is used to define an UNWIND_INFO that
 // only has an ExceptionHandler.  There are no UnwindCodes
 // declared.
@@ -59,6 +64,9 @@
 } RUNTIME_FUNCTION, *PRUNTIME_FUNCTION;
 */
 
+#if _MSC_VER < 1700
+
+/* Not needed for VS2012 compiler, comes from winnt.h. */
 typedef struct _DISPATCHER_CONTEXT {
     ULONG64 ControlPc;
     ULONG64 ImageBase;
@@ -71,6 +79,8 @@
     PVOID HandlerData;
 } DISPATCHER_CONTEXT, *PDISPATCHER_CONTEXT;
 
+#endif
+
 #if _MSC_VER < 1500
 
 /* Not needed for VS2008 compiler, comes from winnt.h. */
--- a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -138,6 +138,16 @@
   return false;
 }
 
+// return true if all argument elements of vars are returned
+bool BCEscapeAnalyzer::returns_all(ArgumentMap vars) {
+  for (int i = 0; i < _arg_size; i++) {
+    if (vars.contains(i) && !_arg_returned.test(i)) {
+      return false;
+    }
+  }
+  return true;
+}
+
 void BCEscapeAnalyzer::clear_bits(ArgumentMap vars, VectorSet &bm) {
   for (int i = 0; i < _arg_size; i++) {
     if (vars.contains(i)) {
@@ -166,6 +176,11 @@
     if (vars.contains_unknown() || vars.contains_vars()) {
       _return_allocated = false;
     }
+    if (_return_local && vars.contains_vars() && !returns_all(vars)) {
+      // Return result should be invalidated if args in new
+      // state are not recorded in return state.
+      _return_local = false;
+    }
   }
 }
 
--- a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -80,6 +80,7 @@
   void set_returned(ArgumentMap vars);
   bool is_argument(ArgumentMap vars);
   bool is_arg_stack(ArgumentMap vars);
+  bool returns_all(ArgumentMap vars);
   void clear_bits(ArgumentMap vars, VectorSet &bs);
   void set_method_escape(ArgumentMap vars);
   void set_global_escape(ArgumentMap vars, bool merge = false);
--- a/hotspot/src/share/vm/ci/ciReplay.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/ci/ciReplay.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -299,7 +299,7 @@
     Symbol* method_signature = parse_symbol(CHECK_NULL);
     Method* m = k->find_method(method_name, method_signature);
     if (m == NULL) {
-      report_error("can't find method");
+      report_error("Can't find method");
     }
     return m;
   }
@@ -398,8 +398,8 @@
 
   // compile <klass> <name> <signature> <entry_bci> <comp_level>
   void process_compile(TRAPS) {
-    // methodHandle method;
     Method* method = parse_method(CHECK);
+    if (had_error()) return;
     int entry_bci = parse_int("entry_bci");
     const char* comp_level_label = "comp_level";
     int comp_level = parse_int(comp_level_label);
@@ -440,6 +440,7 @@
   //
   void process_ciMethod(TRAPS) {
     Method* method = parse_method(CHECK);
+    if (had_error()) return;
     ciMethodRecord* rec = new_ciMethod(method);
     rec->invocation_counter = parse_int("invocation_counter");
     rec->backedge_counter = parse_int("backedge_counter");
@@ -451,6 +452,7 @@
   // ciMethodData <klass> <name> <signature> <state> <current mileage> orig <length> # # ... data <length> # # ... oops <length>
   void process_ciMethodData(TRAPS) {
     Method* method = parse_method(CHECK);
+    if (had_error()) return;
     /* jsut copied from Method, to build interpret data*/
     if (InstanceRefKlass::owns_pending_list_lock((JavaThread*)THREAD)) {
       return;
--- a/hotspot/src/share/vm/classfile/classFileParser.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/classfile/classFileParser.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -3647,8 +3647,7 @@
   // If RedefineClasses() was used before the retransformable
   // agent attached, then the cached class bytes may not be the
   // original class bytes.
-  unsigned char *cached_class_file_bytes = NULL;
-  jint cached_class_file_length;
+  JvmtiCachedClassFileData *cached_class_file = NULL;
   Handle class_loader(THREAD, loader_data->class_loader());
   bool has_default_methods = false;
   ResourceMark rm(THREAD);
@@ -3680,10 +3679,7 @@
       if (h_class_being_redefined != NULL) {
         instanceKlassHandle ikh_class_being_redefined =
           instanceKlassHandle(THREAD, (*h_class_being_redefined)());
-        cached_class_file_bytes =
-          ikh_class_being_redefined->get_cached_class_file_bytes();
-        cached_class_file_length =
-          ikh_class_being_redefined->get_cached_class_file_len();
+        cached_class_file = ikh_class_being_redefined->get_cached_class_file();
       }
     }
 
@@ -3691,9 +3687,7 @@
     unsigned char* end_ptr = cfs->buffer() + cfs->length();
 
     JvmtiExport::post_class_file_load_hook(name, class_loader(), protection_domain,
-                                           &ptr, &end_ptr,
-                                           &cached_class_file_bytes,
-                                           &cached_class_file_length);
+                                           &ptr, &end_ptr, &cached_class_file);
 
     if (ptr != cfs->buffer()) {
       // JVMTI agent has modified class file data.
@@ -4011,10 +4005,9 @@
       }
     }
 
-    if (cached_class_file_bytes != NULL) {
+    if (cached_class_file != NULL) {
       // JVMTI: we have an InstanceKlass now, tell it about the cached bytes
-      this_klass->set_cached_class_file(cached_class_file_bytes,
-                                        cached_class_file_length);
+      this_klass->set_cached_class_file(cached_class_file);
     }
 
     // Fill in field values obtained by parse_classfile_attributes
--- a/hotspot/src/share/vm/classfile/vmSymbols.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -53,8 +53,6 @@
   template(java_lang_Object,                          "java/lang/Object")                         \
   template(java_lang_Class,                           "java/lang/Class")                          \
   template(java_lang_String,                          "java/lang/String")                         \
-  template(java_lang_StringValue,                     "java/lang/StringValue")                    \
-  template(java_lang_StringCache,                     "java/lang/StringValue$StringCache")        \
   template(java_lang_Thread,                          "java/lang/Thread")                         \
   template(java_lang_ThreadGroup,                     "java/lang/ThreadGroup")                    \
   template(java_lang_Cloneable,                       "java/lang/Cloneable")                      \
@@ -106,7 +104,6 @@
   template(java_util_Vector,                          "java/util/Vector")                         \
   template(java_util_AbstractList,                    "java/util/AbstractList")                   \
   template(java_util_Hashtable,                       "java/util/Hashtable")                      \
-  template(java_util_HashMap,                         "java/util/HashMap")                        \
   template(java_lang_Compiler,                        "java/lang/Compiler")                       \
   template(sun_misc_Signal,                           "sun/misc/Signal")                          \
   template(java_lang_AssertionStatusDirectives,       "java/lang/AssertionStatusDirectives")      \
@@ -367,8 +364,6 @@
   template(offset_name,                               "offset")                                   \
   template(count_name,                                "count")                                    \
   template(hash_name,                                 "hash")                                     \
-  template(frontCacheEnabled_name,                    "frontCacheEnabled")                        \
-  template(stringCacheEnabled_name,                   "stringCacheEnabled")                       \
   template(numberOfLeadingZeros_name,                 "numberOfLeadingZeros")                     \
   template(numberOfTrailingZeros_name,                "numberOfTrailingZeros")                    \
   template(bitCount_name,                             "bitCount")                                 \
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -122,6 +122,22 @@
   }
 };
 
+class Par_MarkRefsIntoClosure: public CMSOopsInGenClosure {
+ private:
+  const MemRegion _span;
+  CMSBitMap*      _bitMap;
+ protected:
+  DO_OOP_WORK_DEFN
+ public:
+  Par_MarkRefsIntoClosure(MemRegion span, CMSBitMap* bitMap);
+  virtual void do_oop(oop* p);
+  virtual void do_oop(narrowOop* p);
+
+  Prefetch::style prefetch_style() {
+    return Prefetch::do_read;
+  }
+};
+
 // A variant of the above used in certain kinds of CMS
 // marking verification.
 class MarkRefsIntoVerifyClosure: public CMSOopsInGenClosure {
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -569,6 +569,7 @@
   _restart_addr(NULL),
   _overflow_list(NULL),
   _stats(cmsGen),
+  _eden_chunk_lock(new Mutex(Mutex::leaf + 1, "CMS_eden_chunk_lock", true)),
   _eden_chunk_array(NULL),     // may be set in ctor body
   _eden_chunk_capacity(0),     // -- ditto --
   _eden_chunk_index(0),        // -- ditto --
@@ -732,7 +733,7 @@
   assert(_eden_chunk_array != NULL || _eden_chunk_capacity == 0, "Error");
 
   // Support for parallelizing survivor space rescan
-  if (CMSParallelRemarkEnabled && CMSParallelSurvivorRemarkEnabled) {
+  if ((CMSParallelRemarkEnabled && CMSParallelSurvivorRemarkEnabled) || CMSParallelInitialMarkEnabled) {
     const size_t max_plab_samples =
       ((DefNewGeneration*)_young_gen)->max_survivor_size()/MinTLABSize;
 
@@ -2137,6 +2138,39 @@
 }
 
 
+void CMSCollector::print_eden_and_survivor_chunk_arrays() {
+  DefNewGeneration* dng = _young_gen->as_DefNewGeneration();
+  EdenSpace* eden_space = dng->eden();
+  ContiguousSpace* from_space = dng->from();
+  ContiguousSpace* to_space   = dng->to();
+  // Eden
+  if (_eden_chunk_array != NULL) {
+    gclog_or_tty->print_cr("eden " PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "(" SIZE_FORMAT ")",
+                           eden_space->bottom(), eden_space->top(),
+                           eden_space->end(), eden_space->capacity());
+    gclog_or_tty->print_cr("_eden_chunk_index=" SIZE_FORMAT ", "
+                           "_eden_chunk_capacity=" SIZE_FORMAT,
+                           _eden_chunk_index, _eden_chunk_capacity);
+    for (size_t i = 0; i < _eden_chunk_index; i++) {
+      gclog_or_tty->print_cr("_eden_chunk_array[" SIZE_FORMAT "]=" PTR_FORMAT,
+                             i, _eden_chunk_array[i]);
+    }
+  }
+  // Survivor
+  if (_survivor_chunk_array != NULL) {
+    gclog_or_tty->print_cr("survivor " PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "(" SIZE_FORMAT ")",
+                           from_space->bottom(), from_space->top(),
+                           from_space->end(), from_space->capacity());
+    gclog_or_tty->print_cr("_survivor_chunk_index=" SIZE_FORMAT ", "
+                           "_survivor_chunk_capacity=" SIZE_FORMAT,
+                           _survivor_chunk_index, _survivor_chunk_capacity);
+    for (size_t i = 0; i < _survivor_chunk_index; i++) {
+      gclog_or_tty->print_cr("_survivor_chunk_array[" SIZE_FORMAT "]=" PTR_FORMAT,
+                             i, _survivor_chunk_array[i]);
+    }
+  }
+}
+
 void CMSCollector::getFreelistLocks() const {
   // Get locks for all free lists in all generations that this
   // collector is responsible for
@@ -3549,6 +3583,31 @@
 
 // CMS work
 
+// The common parts of CMSParInitialMarkTask and CMSParRemarkTask.
+class CMSParMarkTask : public AbstractGangTask {
+ protected:
+  CMSCollector*     _collector;
+  int               _n_workers;
+  CMSParMarkTask(const char* name, CMSCollector* collector, int n_workers) :
+      AbstractGangTask(name),
+      _collector(collector),
+      _n_workers(n_workers) {}
+  // Work method in support of parallel rescan ... of young gen spaces
+  void do_young_space_rescan(uint worker_id, OopsInGenClosure* cl,
+                             ContiguousSpace* space,
+                             HeapWord** chunk_array, size_t chunk_top);
+  void work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl);
+};
+
+// Parallel initial mark task
+class CMSParInitialMarkTask: public CMSParMarkTask {
+ public:
+  CMSParInitialMarkTask(CMSCollector* collector, int n_workers) :
+      CMSParMarkTask("Scan roots and young gen for initial mark in parallel",
+                     collector, n_workers) {}
+  void work(uint worker_id);
+};
+
 // Checkpoint the roots into this generation from outside
 // this generation. [Note this initial checkpoint need only
 // be approximate -- we'll do a catch up phase subsequently.]
@@ -3646,19 +3705,42 @@
   // the klasses. The claimed marks need to be cleared before marking starts.
   ClassLoaderDataGraph::clear_claimed_marks();
 
-  CMKlassClosure klass_closure(&notOlder);
+  if (CMSPrintEdenSurvivorChunks) {
+    print_eden_and_survivor_chunk_arrays();
+  }
+
   {
     COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
-    gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
-    gch->gen_process_strong_roots(_cmsGen->level(),
-                                  true,   // younger gens are roots
-                                  true,   // activate StrongRootsScope
-                                  false,  // not scavenging
-                                  SharedHeap::ScanningOption(roots_scanning_options()),
-                                  &notOlder,
-                                  true,   // walk all of code cache if (so & SO_CodeCache)
-                                  NULL,
-                                  &klass_closure);
+    if (CMSParallelInitialMarkEnabled && CollectedHeap::use_parallel_gc_threads()) {
+      // The parallel version.
+      FlexibleWorkGang* workers = gch->workers();
+      assert(workers != NULL, "Need parallel worker threads.");
+      int n_workers = workers->active_workers();
+      CMSParInitialMarkTask tsk(this, n_workers);
+      gch->set_par_threads(n_workers);
+      initialize_sequential_subtasks_for_young_gen_rescan(n_workers);
+      if (n_workers > 1) {
+        GenCollectedHeap::StrongRootsScope srs(gch);
+        workers->run_task(&tsk);
+      } else {
+        GenCollectedHeap::StrongRootsScope srs(gch);
+        tsk.work(0);
+      }
+      gch->set_par_threads(0);
+    } else {
+      // The serial version.
+      CMKlassClosure klass_closure(&notOlder);
+      gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
+      gch->gen_process_strong_roots(_cmsGen->level(),
+                                    true,   // younger gens are roots
+                                    true,   // activate StrongRootsScope
+                                    false,  // not scavenging
+                                    SharedHeap::ScanningOption(roots_scanning_options()),
+                                    &notOlder,
+                                    true,   // walk all of code cache if (so & SO_CodeCache)
+                                    NULL,
+                                    &klass_closure);
+    }
   }
 
   // Clear mod-union table; it will be dirtied in the prologue of
@@ -4417,7 +4499,9 @@
   verify_overflow_empty();
   _abort_preclean = false;
   if (CMSPrecleaningEnabled) {
-    _eden_chunk_index = 0;
+    if (!CMSEdenChunksRecordAlways) {
+      _eden_chunk_index = 0;
+    }
     size_t used = get_eden_used();
     size_t capacity = get_eden_capacity();
     // Don't start sampling unless we will get sufficiently
@@ -4526,7 +4610,9 @@
   if (!_start_sampling) {
     return;
   }
-  if (_eden_chunk_array) {
+  // When CMSEdenChunksRecordAlways is true, the eden chunk array
+  // is populated by the young generation.
+  if (_eden_chunk_array != NULL && !CMSEdenChunksRecordAlways) {
     if (_eden_chunk_index < _eden_chunk_capacity) {
       _eden_chunk_array[_eden_chunk_index] = *_top_addr;   // take sample
       assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr,
@@ -5010,6 +5096,10 @@
     // Update the saved marks which may affect the root scans.
     gch->save_marks();
 
+    if (CMSPrintEdenSurvivorChunks) {
+      print_eden_and_survivor_chunk_arrays();
+    }
+
     {
       COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
 
@@ -5116,10 +5206,53 @@
   }
 }
 
+void CMSParInitialMarkTask::work(uint worker_id) {
+  elapsedTimer _timer;
+  ResourceMark rm;
+  HandleMark   hm;
+
+  // ---------- scan from roots --------------
+  _timer.start();
+  GenCollectedHeap* gch = GenCollectedHeap::heap();
+  Par_MarkRefsIntoClosure par_mri_cl(_collector->_span, &(_collector->_markBitMap));
+  CMKlassClosure klass_closure(&par_mri_cl);
+
+  // ---------- young gen roots --------------
+  {
+    work_on_young_gen_roots(worker_id, &par_mri_cl);
+    _timer.stop();
+    if (PrintCMSStatistics != 0) {
+      gclog_or_tty->print_cr(
+        "Finished young gen initial mark scan work in %dth thread: %3.3f sec",
+        worker_id, _timer.seconds());
+    }
+  }
+
+  // ---------- remaining roots --------------
+  _timer.reset();
+  _timer.start();
+  gch->gen_process_strong_roots(_collector->_cmsGen->level(),
+                                false,     // yg was scanned above
+                                false,     // this is parallel code
+                                false,     // not scavenging
+                                SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
+                                &par_mri_cl,
+                                true,   // walk all of code cache if (so & SO_CodeCache)
+                                NULL,
+                                &klass_closure);
+  assert(_collector->should_unload_classes()
+         || (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_CodeCache),
+         "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
+  _timer.stop();
+  if (PrintCMSStatistics != 0) {
+    gclog_or_tty->print_cr(
+      "Finished remaining root initial mark scan work in %dth thread: %3.3f sec",
+      worker_id, _timer.seconds());
+  }
+}
+
 // Parallel remark task
-class CMSParRemarkTask: public AbstractGangTask {
-  CMSCollector* _collector;
-  int           _n_workers;
+class CMSParRemarkTask: public CMSParMarkTask {
   CompactibleFreeListSpace* _cms_space;
 
   // The per-thread work queues, available here for stealing.
@@ -5133,10 +5266,9 @@
                    CompactibleFreeListSpace* cms_space,
                    int n_workers, FlexibleWorkGang* workers,
                    OopTaskQueueSet* task_queues):
-    AbstractGangTask("Rescan roots and grey objects in parallel"),
-    _collector(collector),
+    CMSParMarkTask("Rescan roots and grey objects in parallel",
+                   collector, n_workers),
     _cms_space(cms_space),
-    _n_workers(n_workers),
     _task_queues(task_queues),
     _term(n_workers, task_queues) { }
 
@@ -5150,11 +5282,6 @@
   void work(uint worker_id);
 
  private:
-  // Work method in support of parallel rescan ... of young gen spaces
-  void do_young_space_rescan(int i, Par_MarkRefsIntoAndScanClosure* cl,
-                             ContiguousSpace* space,
-                             HeapWord** chunk_array, size_t chunk_top);
-
   // ... of  dirty cards in old space
   void do_dirty_card_rescan_tasks(CompactibleFreeListSpace* sp, int i,
                                   Par_MarkRefsIntoAndScanClosure* cl);
@@ -5186,6 +5313,25 @@
   }
 };
 
+void CMSParMarkTask::work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl) {
+  DefNewGeneration* dng = _collector->_young_gen->as_DefNewGeneration();
+  EdenSpace* eden_space = dng->eden();
+  ContiguousSpace* from_space = dng->from();
+  ContiguousSpace* to_space   = dng->to();
+
+  HeapWord** eca = _collector->_eden_chunk_array;
+  size_t     ect = _collector->_eden_chunk_index;
+  HeapWord** sca = _collector->_survivor_chunk_array;
+  size_t     sct = _collector->_survivor_chunk_index;
+
+  assert(ect <= _collector->_eden_chunk_capacity, "out of bounds");
+  assert(sct <= _collector->_survivor_chunk_capacity, "out of bounds");
+
+  do_young_space_rescan(worker_id, cl, to_space, NULL, 0);
+  do_young_space_rescan(worker_id, cl, from_space, sca, sct);
+  do_young_space_rescan(worker_id, cl, eden_space, eca, ect);
+}
+
 // work_queue(i) is passed to the closure
 // Par_MarkRefsIntoAndScanClosure.  The "i" parameter
 // also is passed to do_dirty_card_rescan_tasks() and to
@@ -5210,23 +5356,7 @@
   // work first.
   // ---------- young gen roots --------------
   {
-    DefNewGeneration* dng = _collector->_young_gen->as_DefNewGeneration();
-    EdenSpace* eden_space = dng->eden();
-    ContiguousSpace* from_space = dng->from();
-    ContiguousSpace* to_space   = dng->to();
-
-    HeapWord** eca = _collector->_eden_chunk_array;
-    size_t     ect = _collector->_eden_chunk_index;
-    HeapWord** sca = _collector->_survivor_chunk_array;
-    size_t     sct = _collector->_survivor_chunk_index;
-
-    assert(ect <= _collector->_eden_chunk_capacity, "out of bounds");
-    assert(sct <= _collector->_survivor_chunk_capacity, "out of bounds");
-
-    do_young_space_rescan(worker_id, &par_mrias_cl, to_space, NULL, 0);
-    do_young_space_rescan(worker_id, &par_mrias_cl, from_space, sca, sct);
-    do_young_space_rescan(worker_id, &par_mrias_cl, eden_space, eca, ect);
-
+    work_on_young_gen_roots(worker_id, &par_mrias_cl);
     _timer.stop();
     if (PrintCMSStatistics != 0) {
       gclog_or_tty->print_cr(
@@ -5334,8 +5464,8 @@
 
 // Note that parameter "i" is not used.
 void
-CMSParRemarkTask::do_young_space_rescan(int i,
-  Par_MarkRefsIntoAndScanClosure* cl, ContiguousSpace* space,
+CMSParMarkTask::do_young_space_rescan(uint worker_id,
+  OopsInGenClosure* cl, ContiguousSpace* space,
   HeapWord** chunk_array, size_t chunk_top) {
   // Until all tasks completed:
   // . claim an unclaimed task
@@ -5530,6 +5660,32 @@
          "Else our work is not yet done");
 }
 
+// Record object boundaries in _eden_chunk_array by sampling the eden
+// top in the slow-path eden object allocation code path and record
+// the boundaries, if CMSEdenChunksRecordAlways is true. If
+// CMSEdenChunksRecordAlways is false, we use the other asynchronous
+// sampling in sample_eden() that activates during the part of the
+// preclean phase.
+void CMSCollector::sample_eden_chunk() {
+  if (CMSEdenChunksRecordAlways && _eden_chunk_array != NULL) {
+    if (_eden_chunk_lock->try_lock()) {
+      // Record a sample. This is the critical section. The contents
+      // of the _eden_chunk_array have to be non-decreasing in the
+      // address order.
+      _eden_chunk_array[_eden_chunk_index] = *_top_addr;
+      assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr,
+             "Unexpected state of Eden");
+      if (_eden_chunk_index == 0 ||
+          ((_eden_chunk_array[_eden_chunk_index] > _eden_chunk_array[_eden_chunk_index-1]) &&
+           (pointer_delta(_eden_chunk_array[_eden_chunk_index],
+                          _eden_chunk_array[_eden_chunk_index-1]) >= CMSSamplingGrain))) {
+        _eden_chunk_index++;  // commit sample
+      }
+      _eden_chunk_lock->unlock();
+    }
+  }
+}
+
 // Return a thread-local PLAB recording array, as appropriate.
 void* CMSCollector::get_data_recorder(int thr_num) {
   if (_survivor_plab_array != NULL &&
@@ -5553,12 +5709,13 @@
 
 // Merge the per-thread plab arrays into the global survivor chunk
 // array which will provide the partitioning of the survivor space
-// for CMS rescan.
+// for CMS initial scan and rescan.
 void CMSCollector::merge_survivor_plab_arrays(ContiguousSpace* surv,
                                               int no_of_gc_threads) {
   assert(_survivor_plab_array  != NULL, "Error");
   assert(_survivor_chunk_array != NULL, "Error");
-  assert(_collectorState == FinalMarking, "Error");
+  assert(_collectorState == FinalMarking ||
+         (CMSParallelInitialMarkEnabled && _collectorState == InitialMarking), "Error");
   for (int j = 0; j < no_of_gc_threads; j++) {
     _cursor[j] = 0;
   }
@@ -5621,7 +5778,7 @@
 }
 
 // Set up the space's par_seq_tasks structure for work claiming
-// for parallel rescan of young gen.
+// for parallel initial scan and rescan of young gen.
 // See ParRescanTask where this is currently used.
 void
 CMSCollector::
@@ -6748,6 +6905,28 @@
 void MarkRefsIntoClosure::do_oop(oop* p)       { MarkRefsIntoClosure::do_oop_work(p); }
 void MarkRefsIntoClosure::do_oop(narrowOop* p) { MarkRefsIntoClosure::do_oop_work(p); }
 
+Par_MarkRefsIntoClosure::Par_MarkRefsIntoClosure(
+  MemRegion span, CMSBitMap* bitMap):
+    _span(span),
+    _bitMap(bitMap)
+{
+    assert(_ref_processor == NULL, "deliberately left NULL");
+    assert(_bitMap->covers(_span), "_bitMap/_span mismatch");
+}
+
+void Par_MarkRefsIntoClosure::do_oop(oop obj) {
+  // if p points into _span, then mark corresponding bit in _markBitMap
+  assert(obj->is_oop(), "expected an oop");
+  HeapWord* addr = (HeapWord*)obj;
+  if (_span.contains(addr)) {
+    // this should be made more efficient
+    _bitMap->par_mark(addr);
+  }
+}
+
+void Par_MarkRefsIntoClosure::do_oop(oop* p)       { Par_MarkRefsIntoClosure::do_oop_work(p); }
+void Par_MarkRefsIntoClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoClosure::do_oop_work(p); }
+
 // A variant of the above, used for CMS marking verification.
 MarkRefsIntoVerifyClosure::MarkRefsIntoVerifyClosure(
   MemRegion span, CMSBitMap* verification_bm, CMSBitMap* cms_bm):
@@ -9305,7 +9484,6 @@
     return;
   }
 }
-
 // Transfer some number of overflown objects to usual marking
 // stack. Return true if some objects were transferred.
 bool MarkRefsIntoAndScanClosure::take_from_overflow_list() {
@@ -9377,4 +9555,3 @@
       ShouldNotReachHere();
   }
 }
-
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -515,6 +515,8 @@
   friend class ConcurrentMarkSweepThread;
   friend class ConcurrentMarkSweepGeneration;
   friend class CompactibleFreeListSpace;
+  friend class CMSParMarkTask;
+  friend class CMSParInitialMarkTask;
   friend class CMSParRemarkTask;
   friend class CMSConcMarkingTask;
   friend class CMSRefProcTaskProxy;
@@ -749,6 +751,7 @@
   Generation* _young_gen;  // the younger gen
   HeapWord** _top_addr;    // ... Top of Eden
   HeapWord** _end_addr;    // ... End of Eden
+  Mutex*     _eden_chunk_lock;
   HeapWord** _eden_chunk_array; // ... Eden partitioning array
   size_t     _eden_chunk_index; // ... top (exclusive) of array
   size_t     _eden_chunk_capacity;  // ... max entries in array
@@ -950,6 +953,7 @@
 
   // Support for parallel remark of survivor space
   void* get_data_recorder(int thr_num);
+  void sample_eden_chunk();
 
   CMSBitMap* markBitMap()  { return &_markBitMap; }
   void directAllocated(HeapWord* start, size_t size);
@@ -1027,6 +1031,8 @@
 
   // Initialization errors
   bool completed_initialization() { return _completed_initialization; }
+
+  void print_eden_and_survivor_chunk_arrays();
 };
 
 class CMSExpansionCause : public AllStatic  {
@@ -1317,6 +1323,10 @@
     //Delegate to collector
     return collector()->get_data_recorder(thr_num);
   }
+  void sample_eden_chunk() {
+    //Delegate to collector
+    return collector()->sample_eden_chunk();
+  }
 
   // Printing
   const char* name() const;
--- a/hotspot/src/share/vm/gc_implementation/g1/g1_globals.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1_globals.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -96,11 +96,6 @@
           "the buffer will be enqueued for processing. A value of 0 "       \
           "specifies that mutator threads should not do such filtering.")   \
                                                                             \
-  develop(intx, G1ExtraRegionSurvRate, 33,                                  \
-          "If the young survival rate is S, and there's room left in "      \
-          "to-space, we will allow regions whose survival rate is up to "   \
-          "S + (1 - S)*X, where X is this parameter (as a fraction.)")      \
-                                                                            \
   develop(bool, G1SATBPrintStubs, false,                                    \
           "If true, print generated stubs for the SATB barrier")            \
                                                                             \
@@ -110,9 +105,6 @@
   develop(bool, G1RSBarrierRegionFilter, true,                              \
           "If true, generate region filtering code in RS barrier")          \
                                                                             \
-  develop(bool, G1RSBarrierNullFilter, true,                                \
-          "If true, generate null-pointer filtering code in RS barrier")    \
-                                                                            \
   develop(bool, G1DeferredRSUpdate, true,                                   \
           "If true, use deferred RS updates")                               \
                                                                             \
@@ -120,9 +112,6 @@
           "If true, verify that no dirty cards remain after RS log "        \
           "processing.")                                                    \
                                                                             \
-  develop(bool, G1RSCountHisto, false,                                      \
-          "If true, print a histogram of RS occupancies after each pause")  \
-                                                                            \
   diagnostic(bool, G1PrintRegionLivenessInfo, false,                        \
             "Prints the liveness information for all regions in the heap "  \
             "at the end of a marking cycle.")                               \
@@ -169,9 +158,6 @@
   product(uintx, G1ConcRSHotCardLimit, 4,                                   \
           "The threshold that defines (>=) a hot card.")                    \
                                                                             \
-  develop(bool, G1PrintOopAppls, false,                                     \
-          "When true, print applications of closures to external locs.")    \
-                                                                            \
   develop(intx, G1RSetRegionEntriesBase, 256,                               \
           "Max number of regions in a fine-grain table per MB.")            \
                                                                             \
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegion.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -314,6 +314,11 @@
     region_size = MAX_REGION_SIZE;
   }
 
+  if (region_size != G1HeapRegionSize) {
+    // Update the flag to make sure that PrintFlagsFinal logs the correct value
+    FLAG_SET_ERGO(uintx, G1HeapRegionSize, region_size);
+  }
+
   // And recalculate the log.
   region_size_log = log2_long((jlong) region_size);
 
--- a/hotspot/src/share/vm/memory/defNewGeneration.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/memory/defNewGeneration.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -1033,6 +1033,9 @@
   // have to use it here, as well.
   HeapWord* result = eden()->par_allocate(word_size);
   if (result != NULL) {
+    if (CMSEdenChunksRecordAlways && _next_gen != NULL) {
+      _next_gen->sample_eden_chunk();
+    }
     return result;
   }
   do {
@@ -1063,13 +1066,19 @@
   // circular dependency at compile time.
   if (result == NULL) {
     result = allocate_from_space(word_size);
+  } else if (CMSEdenChunksRecordAlways && _next_gen != NULL) {
+    _next_gen->sample_eden_chunk();
   }
   return result;
 }
 
 HeapWord* DefNewGeneration::par_allocate(size_t word_size,
                                          bool is_tlab) {
-  return eden()->par_allocate(word_size);
+  HeapWord* res = eden()->par_allocate(word_size);
+  if (CMSEdenChunksRecordAlways && _next_gen != NULL) {
+    _next_gen->sample_eden_chunk();
+  }
+  return res;
 }
 
 void DefNewGeneration::gc_prologue(bool full) {
--- a/hotspot/src/share/vm/memory/generation.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/memory/generation.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -455,6 +455,7 @@
   // expected to be GC worker thread-local, with the worker index
   // indicated by "thr_num".
   virtual void* get_data_recorder(int thr_num) { return NULL; }
+  virtual void sample_eden_chunk() {}
 
   // Some generations may require some cleanup actions before allowing
   // a verification.
--- a/hotspot/src/share/vm/memory/metaspace.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/memory/metaspace.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -2254,10 +2254,11 @@
 
 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
   assert_lock_strong(_lock);
+  size_t raw_word_size = get_raw_word_size(word_size);
   size_t min_size = TreeChunk<Metablock, FreeList>::min_size();
-  assert(word_size >= min_size,
+  assert(raw_word_size >= min_size,
     err_msg("Should not deallocate dark matter " SIZE_FORMAT, word_size));
-  block_freelists()->return_block(p, word_size);
+  block_freelists()->return_block(p, raw_word_size);
 }
 
 // Adds a chunk to the list of chunks in use.
--- a/hotspot/src/share/vm/memory/resourceArea.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/memory/resourceArea.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -83,6 +83,10 @@
   Chunk *_chunk;                // saved arena chunk
   char *_hwm, *_max;
   size_t _size_in_bytes;
+#ifdef ASSERT
+  Thread* _thread;
+  ResourceMark* _previous_resource_mark;
+#endif //ASSERT
 
   void initialize(Thread *thread) {
     _area = thread->resource_area();
@@ -92,6 +96,11 @@
     _size_in_bytes = _area->size_in_bytes();
     debug_only(_area->_nesting++;)
     assert( _area->_nesting > 0, "must stack allocate RMs" );
+#ifdef ASSERT
+    _thread = thread;
+    _previous_resource_mark = thread->current_resource_mark();
+    thread->set_current_resource_mark(this);
+#endif // ASSERT
   }
  public:
 
@@ -111,6 +120,17 @@
     _size_in_bytes = r->_size_in_bytes;
     debug_only(_area->_nesting++;)
     assert( _area->_nesting > 0, "must stack allocate RMs" );
+#ifdef ASSERT
+    Thread* thread = ThreadLocalStorage::thread();
+    if (thread != NULL) {
+      _thread = thread;
+      _previous_resource_mark = thread->current_resource_mark();
+      thread->set_current_resource_mark(this);
+    } else {
+      _thread = NULL;
+      _previous_resource_mark = NULL;
+    }
+#endif // ASSERT
   }
 
   void reset_to_mark() {
@@ -137,6 +157,11 @@
     assert( _area->_nesting > 0, "must stack allocate RMs" );
     debug_only(_area->_nesting--;)
     reset_to_mark();
+#ifdef ASSERT
+    if (_thread != NULL) {
+      _thread->set_current_resource_mark(_previous_resource_mark);
+    }
+#endif // ASSERT
   }
 
 
--- a/hotspot/src/share/vm/memory/sharedHeap.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/memory/sharedHeap.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -65,7 +65,8 @@
   }
   _sh = this;  // ch is static, should be set only once.
   if ((UseParNewGC ||
-      (UseConcMarkSweepGC && CMSParallelRemarkEnabled) ||
+      (UseConcMarkSweepGC && (CMSParallelInitialMarkEnabled ||
+                              CMSParallelRemarkEnabled)) ||
        UseG1GC) &&
       ParallelGCThreads > 0) {
     _workers = new FlexibleWorkGang("Parallel GC Threads", ParallelGCThreads,
--- a/hotspot/src/share/vm/oops/cpCache.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/oops/cpCache.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -140,8 +140,15 @@
     _f1 = f1;
   }
   void release_set_f1(Metadata* f1);
-  void set_f2(intx f2)                           { assert(_f2 == 0 || _f2 == f2,            "illegal field change"); _f2 = f2; }
-  void set_f2_as_vfinal_method(Method* f2)     { assert(_f2 == 0 || _f2 == (intptr_t) f2, "illegal field change"); assert(is_vfinal(), "flags must be set"); _f2 = (intptr_t) f2; }
+  void set_f2(intx f2) {
+    intx existing_f2 = _f2; // read once
+    assert(existing_f2 == 0 || existing_f2 == f2, "illegal field change");
+    _f2 = f2;
+  }
+  void set_f2_as_vfinal_method(Method* f2) {
+    assert(is_vfinal(), "flags must be set");
+    set_f2((intx)f2);
+  }
   int make_flags(TosState state, int option_bits, int field_index_or_method_params);
   void set_flags(intx flags)                     { _flags = flags; }
   bool init_flags_atomic(intx flags);
--- a/hotspot/src/share/vm/oops/instanceKlass.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/oops/instanceKlass.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -48,6 +48,7 @@
 #include "oops/symbol.hpp"
 #include "prims/jvmtiExport.hpp"
 #include "prims/jvmtiRedefineClassesTrace.hpp"
+#include "prims/jvmtiRedefineClasses.hpp"
 #include "prims/methodComparator.hpp"
 #include "runtime/fieldDescriptor.hpp"
 #include "runtime/handles.inline.hpp"
@@ -291,7 +292,7 @@
   set_initial_method_idnum(0);
   _dependencies = NULL;
   set_jvmti_cached_class_field_map(NULL);
-  set_cached_class_file(NULL, 0);
+  set_cached_class_file(NULL);
   set_initial_method_idnum(0);
   set_minor_version(0);
   set_major_version(0);
@@ -2357,10 +2358,9 @@
   }
 
   // deallocate the cached class file
-  if (_cached_class_file_bytes != NULL) {
-    os::free(_cached_class_file_bytes, mtClass);
-    _cached_class_file_bytes = NULL;
-    _cached_class_file_len = 0;
+  if (_cached_class_file != NULL) {
+    os::free(_cached_class_file, mtClass);
+    _cached_class_file = NULL;
   }
 
   // Decrement symbol reference counts associated with the unloaded class.
@@ -3530,6 +3530,14 @@
   return m;
 }
 
+jint InstanceKlass::get_cached_class_file_len() {
+  return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
+}
+
+unsigned char * InstanceKlass::get_cached_class_file_bytes() {
+  return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
+}
+
 
 // Construct a PreviousVersionNode entry for the array hung off
 // the InstanceKlass.
--- a/hotspot/src/share/vm/oops/instanceKlass.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/oops/instanceKlass.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -133,6 +133,8 @@
   uint _count;
 };
 
+struct JvmtiCachedClassFileData;
+
 class InstanceKlass: public Klass {
   friend class VMStructs;
   friend class ClassFileParser;
@@ -249,8 +251,8 @@
   // InstanceKlass. See PreviousVersionWalker below.
   GrowableArray<PreviousVersionNode *>* _previous_versions;
   // JVMTI fields can be moved to their own structure - see 6315920
-  unsigned char * _cached_class_file_bytes;       // JVMTI: cached class file, before retransformable agent modified it in CFLH
-  jint            _cached_class_file_len;         // JVMTI: length of above
+  // JVMTI: cached class file, before retransformable agent modified it in CFLH
+  JvmtiCachedClassFileData* _cached_class_file;
 
   volatile u2     _idnum_allocated_count;         // JNI/JVMTI: increments with the addition of methods, old ids don't change
 
@@ -615,11 +617,12 @@
   static void purge_previous_versions(InstanceKlass* ik);
 
   // JVMTI: Support for caching a class file before it is modified by an agent that can do retransformation
-  void set_cached_class_file(unsigned char *class_file_bytes,
-                             jint class_file_len)     { _cached_class_file_len = class_file_len;
-                                                        _cached_class_file_bytes = class_file_bytes; }
-  jint get_cached_class_file_len()                    { return _cached_class_file_len; }
-  unsigned char * get_cached_class_file_bytes()       { return _cached_class_file_bytes; }
+  void set_cached_class_file(JvmtiCachedClassFileData *data) {
+    _cached_class_file = data;
+  }
+  JvmtiCachedClassFileData * get_cached_class_file() { return _cached_class_file; }
+  jint get_cached_class_file_len();
+  unsigned char * get_cached_class_file_bytes();
 
   // JVMTI: Support for caching of field indices, types, and offsets
   void set_jvmti_cached_class_field_map(JvmtiCachedClassFieldMap* descriptor) {
--- a/hotspot/src/share/vm/oops/method.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/oops/method.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -1163,6 +1163,7 @@
   newm->constMethod()->set_constMethod_size(new_const_method_size);
   newm->set_method_size(new_method_size);
   assert(newm->code_size() == new_code_length, "check");
+  assert(newm->method_parameters_length() == method_parameters_len, "check");
   assert(newm->checked_exceptions_length() == checked_exceptions_len, "check");
   assert(newm->exception_table_length() == exception_table_len, "check");
   assert(newm->localvariable_table_length() == localvariable_len, "check");
@@ -1174,6 +1175,12 @@
            new_compressed_linenumber_table,
            new_compressed_linenumber_size);
   }
+  // Copy method_parameters
+  if (method_parameters_len > 0) {
+    memcpy(newm->method_parameters_start(),
+           m->method_parameters_start(),
+           method_parameters_len * sizeof(MethodParametersElement));
+  }
   // Copy checked_exceptions
   if (checked_exceptions_len > 0) {
     memcpy(newm->checked_exceptions_start(),
--- a/hotspot/src/share/vm/opto/bytecodeInfo.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/opto/bytecodeInfo.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -297,15 +297,6 @@
     }
   }
 
-  if (UseStringCache) {
-    // Do not inline StringCache::profile() method used only at the beginning.
-    if (callee_method->name() == ciSymbol::profile_name() &&
-        callee_method->holder()->name() == ciSymbol::java_lang_StringCache()) {
-      set_msg("profiling method");
-      return true;
-    }
-  }
-
   // use frequency-based objections only for non-trivial methods
   if (callee_method->code_size() <= MaxTrivialSize) {
     return false;
--- a/hotspot/src/share/vm/opto/matcher.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/opto/matcher.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -2305,26 +2305,26 @@
 // atomic instruction acting as a store_load barrier without any
 // intervening volatile load, and thus we don't need a barrier here.
 // We retain the Node to act as a compiler ordering barrier.
-bool Matcher::post_store_load_barrier(const Node *vmb) {
-  Compile *C = Compile::current();
-  assert( vmb->is_MemBar(), "" );
-  assert( vmb->Opcode() != Op_MemBarAcquire, "" );
-  const MemBarNode *mem = (const MemBarNode*)vmb;
+bool Matcher::post_store_load_barrier(const Node* vmb) {
+  Compile* C = Compile::current();
+  assert(vmb->is_MemBar(), "");
+  assert(vmb->Opcode() != Op_MemBarAcquire, "");
+  const MemBarNode* membar = vmb->as_MemBar();
 
-  // Get the Proj node, ctrl, that can be used to iterate forward
-  Node *ctrl = NULL;
-  DUIterator_Fast imax, i = mem->fast_outs(imax);
-  while( true ) {
-    ctrl = mem->fast_out(i);            // Throw out-of-bounds if proj not found
-    assert( ctrl->is_Proj(), "only projections here" );
-    ProjNode *proj = (ProjNode*)ctrl;
-    if( proj->_con == TypeFunc::Control &&
-        !C->node_arena()->contains(ctrl) ) // Unmatched old-space only
+  // Get the Ideal Proj node, ctrl, that can be used to iterate forward
+  Node* ctrl = NULL;
+  for (DUIterator_Fast imax, i = membar->fast_outs(imax); i < imax; i++) {
+    Node* p = membar->fast_out(i);
+    assert(p->is_Proj(), "only projections here");
+    if ((p->as_Proj()->_con == TypeFunc::Control) &&
+        !C->node_arena()->contains(p)) { // Unmatched old-space only
+      ctrl = p;
       break;
-    i++;
+    }
   }
+  assert((ctrl != NULL), "missing control projection");
 
-  for( DUIterator_Fast jmax, j = ctrl->fast_outs(jmax); j < jmax; j++ ) {
+  for (DUIterator_Fast jmax, j = ctrl->fast_outs(jmax); j < jmax; j++) {
     Node *x = ctrl->fast_out(j);
     int xop = x->Opcode();
 
@@ -2336,37 +2336,36 @@
     // that a monitor exit operation contains a serializing instruction.
 
     if (xop == Op_MemBarVolatile ||
-        xop == Op_FastLock ||
         xop == Op_CompareAndSwapL ||
         xop == Op_CompareAndSwapP ||
         xop == Op_CompareAndSwapN ||
-        xop == Op_CompareAndSwapI)
+        xop == Op_CompareAndSwapI) {
       return true;
+    }
+
+    // Op_FastLock previously appeared in the Op_* list above.
+    // With biased locking we're no longer guaranteed that a monitor
+    // enter operation contains a serializing instruction.
+    if ((xop == Op_FastLock) && !UseBiasedLocking) {
+      return true;
+    }
 
     if (x->is_MemBar()) {
       // We must retain this membar if there is an upcoming volatile
-      // load, which will be preceded by acquire membar.
-      if (xop == Op_MemBarAcquire)
+      // load, which will be followed by acquire membar.
+      if (xop == Op_MemBarAcquire) {
         return false;
-      // For other kinds of barriers, check by pretending we
-      // are them, and seeing if we can be removed.
-      else
-        return post_store_load_barrier((const MemBarNode*)x);
+      } else {
+        // For other kinds of barriers, check by pretending we
+        // are them, and seeing if we can be removed.
+        return post_store_load_barrier(x->as_MemBar());
+      }
     }
 
-    // Delicate code to detect case of an upcoming fastlock block
-    if( x->is_If() && x->req() > 1 &&
-        !C->node_arena()->contains(x) ) { // Unmatched old-space only
-      Node *iff = x;
-      Node *bol = iff->in(1);
-      // The iff might be some random subclass of If or bol might be Con-Top
-      if (!bol->is_Bool())  return false;
-      assert( bol->req() > 1, "" );
-      return (bol->in(1)->Opcode() == Op_FastUnlock);
+    // probably not necessary to check for these
+    if (x->is_Call() || x->is_SafePoint() || x->is_block_proj()) {
+      return false;
     }
-    // probably not necessary to check for these
-    if (x->is_Call() || x->is_SafePoint() || x->is_block_proj())
-      return false;
   }
   return false;
 }
--- a/hotspot/src/share/vm/opto/parse3.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/opto/parse3.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -294,25 +294,7 @@
   // If reference is volatile, prevent following volatiles ops from
   // floating up before the volatile write.
   if (is_vol) {
-    // First place the specific membar for THIS volatile index. This first
-    // membar is dependent on the store, keeping any other membars generated
-    // below from floating up past the store.
-    int adr_idx = C->get_alias_index(adr_type);
-    insert_mem_bar_volatile(Op_MemBarVolatile, adr_idx, store);
-
-    // Now place a membar for AliasIdxBot for the unknown yet-to-be-parsed
-    // volatile alias indices. Skip this if the membar is redundant.
-    if (adr_idx != Compile::AliasIdxBot) {
-      insert_mem_bar_volatile(Op_MemBarVolatile, Compile::AliasIdxBot, store);
-    }
-
-    // Finally, place alias-index-specific membars for each volatile index
-    // that isn't the adr_idx membar. Typically there's only 1 or 2.
-    for( int i = Compile::AliasIdxRaw; i < C->num_alias_types(); i++ ) {
-      if (i != adr_idx && C->alias_type(i)->is_volatile()) {
-        insert_mem_bar_volatile(Op_MemBarVolatile, i, store);
-      }
-    }
+    insert_mem_bar(Op_MemBarVolatile); // Use fat membar
   }
 
   // If the field is final, the rules of Java say we are in <init> or <clinit>.
--- a/hotspot/src/share/vm/prims/forte.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/prims/forte.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -31,6 +31,7 @@
 #include "oops/oop.inline.hpp"
 #include "oops/oop.inline2.hpp"
 #include "prims/forte.hpp"
+#include "runtime/javaCalls.hpp"
 #include "runtime/thread.hpp"
 #include "runtime/vframe.hpp"
 #include "runtime/vframeArray.hpp"
@@ -308,10 +309,14 @@
 
   for (loop_count = 0; loop_count < loop_max; loop_count++) {
 
-    if (candidate.is_first_frame()) {
+    if (candidate.is_entry_frame()) {
+      // jcw is NULL if the java call wrapper couldn't be found
+      JavaCallWrapper *jcw = candidate.entry_frame_call_wrapper_if_safe(thread);
       // If initial frame is frame from StubGenerator and there is no
       // previous anchor, there are no java frames associated with a method
-      return false;
+      if (jcw == NULL || jcw->is_first_frame()) {
+        return false;
+      }
     }
 
     if (candidate.is_interpreted_frame()) {
--- a/hotspot/src/share/vm/prims/jniCheck.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/prims/jniCheck.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -126,6 +126,7 @@
 static const char * fatal_non_weak_method = "non-weak methodID passed to JNI call";
 static const char * fatal_unknown_array_object = "Unknown array object passed to JNI array operations";
 static const char * fatal_object_array_expected = "Object array expected but not received for JNI array operation";
+static const char * fatal_prim_type_array_expected = "Primitive type array expected but not received for JNI array operation";
 static const char * fatal_non_array  = "Non-array passed to JNI array operations";
 static const char * fatal_element_type_mismatch = "Array element type mismatch in JNI";
 static const char * fatal_should_be_static = "Non-static field ID passed to JNI";
@@ -278,30 +279,49 @@
     ReportJNIFatalError(thr, fatal_non_string);
 }
 
-static inline void
-checkArray(JavaThread* thr, jarray jArray, int elementType)
+static inline arrayOop
+check_is_array(JavaThread* thr, jarray jArray)
 {
   ASSERT_OOPS_ALLOWED;
   arrayOop aOop;
 
   aOop = (arrayOop)jniCheck::validate_object(thr, jArray);
-  if (aOop == NULL || !aOop->is_array())
+  if (aOop == NULL || !aOop->is_array()) {
     ReportJNIFatalError(thr, fatal_non_array);
+  }
+  return aOop;
+}
 
-  if (elementType != -1) {
-    if (aOop->is_typeArray()) {
-      BasicType array_type = TypeArrayKlass::cast(aOop->klass())->element_type();
-      if (array_type != elementType)
-        ReportJNIFatalError(thr, fatal_element_type_mismatch);
-      } else if (aOop->is_objArray()) {
-        if ( T_OBJECT != elementType)
-          ReportJNIFatalError(thr, fatal_object_array_expected);
-      } else {
-        ReportJNIFatalError(thr, fatal_unknown_array_object);
-    }
+static inline arrayOop
+check_is_primitive_array(JavaThread* thr, jarray jArray) {
+  arrayOop aOop = check_is_array(thr, jArray);
+
+  if (!aOop->is_typeArray()) {
+     ReportJNIFatalError(thr, fatal_prim_type_array_expected);
+  }
+  return aOop;
+}
+
+static inline void
+check_primitive_array_type(JavaThread* thr, jarray jArray, BasicType elementType)
+{
+  BasicType array_type;
+  arrayOop aOop;
+
+  aOop = check_is_primitive_array(thr, jArray);
+  array_type = TypeArrayKlass::cast(aOop->klass())->element_type();
+  if (array_type != elementType) {
+    ReportJNIFatalError(thr, fatal_element_type_mismatch);
   }
 }
 
+static inline void
+check_is_obj_array(JavaThread* thr, jarray jArray) {
+  arrayOop aOop = check_is_array(thr, jArray);
+  if (!aOop->is_objArray()) {
+    ReportJNIFatalError(thr, fatal_object_array_expected);
+  }
+}
 
 oop jniCheck::validate_handle(JavaThread* thr, jobject obj) {
   if (JNIHandles::is_frame_handle(thr, obj) ||
@@ -1417,7 +1437,7 @@
                              jarray array))
     functionEnter(thr);
     IN_VM(
-      checkArray(thr, array, -1);
+      check_is_array(thr, array);
     )
     jsize result = UNCHECKED()->GetArrayLength(env,array);
     functionExit(env);
@@ -1441,7 +1461,7 @@
                                     jsize index))
     functionEnter(thr);
     IN_VM(
-      checkArray(thr, array, T_OBJECT);
+      check_is_obj_array(thr, array);
     )
     jobject result = UNCHECKED()->GetObjectArrayElement(env,array,index);
     functionExit(env);
@@ -1455,7 +1475,7 @@
                                     jobject val))
     functionEnter(thr);
     IN_VM(
-      checkArray(thr, array, T_OBJECT);
+      check_is_obj_array(thr, array);
     )
     UNCHECKED()->SetObjectArrayElement(env,array,index,val);
     functionExit(env);
@@ -1487,7 +1507,7 @@
                                          jboolean *isCopy)) \
     functionEnter(thr); \
     IN_VM( \
-      checkArray(thr, array, ElementTag); \
+      check_primitive_array_type(thr, array, ElementTag); \
     ) \
     ElementType *result = UNCHECKED()->Get##Result##ArrayElements(env, \
                                                                   array, \
@@ -1513,7 +1533,7 @@
                                              jint mode)) \
     functionEnterExceptionAllowed(thr); \
     IN_VM( \
-      checkArray(thr, array, ElementTag); \
+      check_primitive_array_type(thr, array, ElementTag); \
       ASSERT_OOPS_ALLOWED; \
       typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(array)); \
       /* cannot check validity of copy, unless every request is logged by
@@ -1543,7 +1563,7 @@
                                        ElementType *buf)) \
     functionEnter(thr); \
     IN_VM( \
-      checkArray(thr, array, ElementTag); \
+      check_primitive_array_type(thr, array, ElementTag); \
     ) \
     UNCHECKED()->Get##Result##ArrayRegion(env,array,start,len,buf); \
     functionExit(env); \
@@ -1567,7 +1587,7 @@
                                        const ElementType *buf)) \
     functionEnter(thr); \
     IN_VM( \
-      checkArray(thr, array, ElementTag); \
+      check_primitive_array_type(thr, array, ElementTag); \
     ) \
     UNCHECKED()->Set##Result##ArrayRegion(env,array,start,len,buf); \
     functionExit(env); \
@@ -1669,7 +1689,7 @@
                                         jboolean *isCopy))
     functionEnterCritical(thr);
     IN_VM(
-      checkArray(thr, array, -1);
+      check_is_primitive_array(thr, array);
     )
     void *result = UNCHECKED()->GetPrimitiveArrayCritical(env, array, isCopy);
     functionExit(env);
@@ -1683,7 +1703,7 @@
                                             jint mode))
     functionEnterCriticalExceptionAllowed(thr);
     IN_VM(
-      checkArray(thr, array, -1);
+      check_is_primitive_array(thr, array);
     )
     /* The Hotspot JNI code does not use the parameters, so just check the
      * array parameter as a minor sanity check
--- a/hotspot/src/share/vm/prims/jvmtiExport.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiExport.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -41,6 +41,7 @@
 #include "prims/jvmtiRawMonitor.hpp"
 #include "prims/jvmtiTagMap.hpp"
 #include "prims/jvmtiThreadState.inline.hpp"
+#include "prims/jvmtiRedefineClasses.hpp"
 #include "runtime/arguments.hpp"
 #include "runtime/handles.hpp"
 #include "runtime/interfaceSupport.hpp"
@@ -516,8 +517,7 @@
   jint                 _curr_len;
   unsigned char *      _curr_data;
   JvmtiEnv *           _curr_env;
-  jint *               _cached_length_ptr;
-  unsigned char **     _cached_data_ptr;
+  JvmtiCachedClassFileData ** _cached_class_file_ptr;
   JvmtiThreadState *   _state;
   KlassHandle *        _h_class_being_redefined;
   JvmtiClassLoadKind   _load_kind;
@@ -526,8 +526,7 @@
   inline JvmtiClassFileLoadHookPoster(Symbol* h_name, Handle class_loader,
                                       Handle h_protection_domain,
                                       unsigned char **data_ptr, unsigned char **end_ptr,
-                                      unsigned char **cached_data_ptr,
-                                      jint *cached_length_ptr) {
+                                      JvmtiCachedClassFileData **cache_ptr) {
     _h_name = h_name;
     _class_loader = class_loader;
     _h_protection_domain = h_protection_domain;
@@ -537,8 +536,7 @@
     _curr_len = *end_ptr - *data_ptr;
     _curr_data = *data_ptr;
     _curr_env = NULL;
-    _cached_length_ptr = cached_length_ptr;
-    _cached_data_ptr = cached_data_ptr;
+    _cached_class_file_ptr = cache_ptr;
 
     _state = _thread->jvmti_thread_state();
     if (_state != NULL) {
@@ -615,15 +613,20 @@
     }
     if (new_data != NULL) {
       // this agent has modified class data.
-      if (caching_needed && *_cached_data_ptr == NULL) {
+      if (caching_needed && *_cached_class_file_ptr == NULL) {
         // data has been changed by the new retransformable agent
         // and it hasn't already been cached, cache it
-        *_cached_data_ptr = (unsigned char *)os::malloc(_curr_len, mtInternal);
-        if (*_cached_data_ptr == NULL) {
-          vm_exit_out_of_memory(_curr_len, OOM_MALLOC_ERROR, "unable to allocate cached copy of original class bytes");
+        JvmtiCachedClassFileData *p;
+        p = (JvmtiCachedClassFileData *)os::malloc(
+          offset_of(JvmtiCachedClassFileData, data) + _curr_len, mtInternal);
+        if (p == NULL) {
+          vm_exit_out_of_memory(offset_of(JvmtiCachedClassFileData, data) + _curr_len,
+            OOM_MALLOC_ERROR,
+            "unable to allocate cached copy of original class bytes");
         }
-        memcpy(*_cached_data_ptr, _curr_data, _curr_len);
-        *_cached_length_ptr = _curr_len;
+        p->length = _curr_len;
+        memcpy(p->data, _curr_data, _curr_len);
+        *_cached_class_file_ptr = p;
       }
 
       if (_curr_data != *_data_ptr) {
@@ -662,13 +665,11 @@
                                             Handle h_protection_domain,
                                             unsigned char **data_ptr,
                                             unsigned char **end_ptr,
-                                            unsigned char **cached_data_ptr,
-                                            jint *cached_length_ptr) {
+                                            JvmtiCachedClassFileData **cache_ptr) {
   JvmtiClassFileLoadHookPoster poster(h_name, class_loader,
                                       h_protection_domain,
                                       data_ptr, end_ptr,
-                                      cached_data_ptr,
-                                      cached_length_ptr);
+                                      cache_ptr);
   poster.post();
 }
 
--- a/hotspot/src/share/vm/prims/jvmtiExport.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiExport.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -323,8 +323,7 @@
   static void post_class_file_load_hook(Symbol* h_name, Handle class_loader,
                                         Handle h_protection_domain,
                                         unsigned char **data_ptr, unsigned char **end_ptr,
-                                        unsigned char **cached_data_ptr,
-                                        jint *cached_length_ptr) NOT_JVMTI_RETURN;
+                                        JvmtiCachedClassFileData **cache_ptr) NOT_JVMTI_RETURN;
   static void post_native_method_bind(Method* method, address* function_ptr) NOT_JVMTI_RETURN;
   static void post_compiled_method_load(nmethod *nm) NOT_JVMTI_RETURN;
   static void post_dynamic_code_generated(const char *name, const void *code_begin, const void *code_end) NOT_JVMTI_RETURN;
--- a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -3342,9 +3342,7 @@
   // should get cleared in the_class too.
   if (the_class->get_cached_class_file_bytes() == 0) {
     // the_class doesn't have a cache yet so copy it
-    the_class->set_cached_class_file(
-      scratch_class->get_cached_class_file_bytes(),
-      scratch_class->get_cached_class_file_len());
+    the_class->set_cached_class_file(scratch_class->get_cached_class_file());
   }
 #ifndef PRODUCT
   else {
@@ -3357,7 +3355,7 @@
 
   // NULL out in scratch class to not delete twice.  The class to be redefined
   // always owns these bytes.
-  scratch_class->set_cached_class_file(NULL, 0);
+  scratch_class->set_cached_class_file(NULL);
 
   // Replace inner_classes
   Array<u2>* old_inner_classes = the_class->inner_classes();
--- a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -331,6 +331,11 @@
 //   coordinate a cleanup of these constants with Runtime.
 //
 
+struct JvmtiCachedClassFileData {
+  jint length;
+  unsigned char data[1];
+};
+
 class VM_RedefineClasses: public VM_Operation {
  private:
   // These static fields are needed by ClassLoaderDataGraph::classes_do()
@@ -509,5 +514,12 @@
   // Modifiable test must be shared between IsModifiableClass query
   // and redefine implementation
   static bool is_modifiable_class(oop klass_mirror);
+
+  static jint get_cached_class_file_len(JvmtiCachedClassFileData *cache) {
+    return cache == NULL ? 0 : cache->length;
+  }
+  static unsigned char * get_cached_class_file_bytes(JvmtiCachedClassFileData *cache) {
+    return cache == NULL ? NULL : cache->data;
+  }
 };
 #endif // SHARE_VM_PRIMS_JVMTIREDEFINECLASSES_HPP
--- a/hotspot/src/share/vm/runtime/arguments.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/runtime/arguments.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -263,6 +263,7 @@
   { "UseISM",                        JDK_Version::jdk(8), JDK_Version::jdk(9) },
   { "UsePermISM",                    JDK_Version::jdk(8), JDK_Version::jdk(9) },
   { "UseMPSS",                       JDK_Version::jdk(8), JDK_Version::jdk(9) },
+  { "UseStringCache",                JDK_Version::jdk(8), JDK_Version::jdk(9) },
 #ifdef PRODUCT
   { "DesiredMethodLimit",
                            JDK_Version::jdk_update(7, 2), JDK_Version::jdk(8) },
@@ -1890,6 +1891,10 @@
     warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"
             "and will likely be removed in future release");
   }
+  if (FLAG_IS_CMDLINE(DefaultMaxRAMFraction)) {
+    warning("DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. "
+        "Use MaxRAMFraction instead.");
+  }
 }
 
 // Check stack pages settings
--- a/hotspot/src/share/vm/runtime/frame.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/runtime/frame.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -221,9 +221,20 @@
 
 
 bool frame::entry_frame_is_first() const {
-  return entry_frame_call_wrapper()->anchor()->last_Java_sp() == NULL;
+  return entry_frame_call_wrapper()->is_first_frame();
 }
 
+JavaCallWrapper* frame::entry_frame_call_wrapper_if_safe(JavaThread* thread) const {
+  JavaCallWrapper** jcw = entry_frame_call_wrapper_addr();
+  address addr = (address) jcw;
+
+  // addr must be within the usable part of the stack
+  if (thread->is_in_usable_stack(addr)) {
+    return *jcw;
+  }
+
+  return NULL;
+}
 
 bool frame::should_be_deoptimized() const {
   if (_deopt_state == is_deoptimized ||
--- a/hotspot/src/share/vm/runtime/frame.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/runtime/frame.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -353,7 +353,9 @@
 
  public:
   // Entry frames
-  JavaCallWrapper* entry_frame_call_wrapper() const;
+  JavaCallWrapper* entry_frame_call_wrapper() const { return *entry_frame_call_wrapper_addr(); }
+  JavaCallWrapper* entry_frame_call_wrapper_if_safe(JavaThread* thread) const;
+  JavaCallWrapper** entry_frame_call_wrapper_addr() const;
   intptr_t* entry_frame_argument_at(int offset) const;
 
   // tells whether there is another chunk of Delta stack above
--- a/hotspot/src/share/vm/runtime/globals.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/runtime/globals.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -1689,6 +1689,9 @@
   product(bool, CMSAbortSemantics, false,                                   \
           "Whether abort-on-overflow semantics is implemented")             \
                                                                             \
+  product(bool, CMSParallelInitialMarkEnabled, true,                        \
+          "Use the parallel initial mark.")                                 \
+                                                                            \
   product(bool, CMSParallelRemarkEnabled, true,                             \
           "Whether parallel remark enabled (only if ParNewGC)")             \
                                                                             \
@@ -1700,6 +1703,14 @@
           "Whether to always record survivor space PLAB bdries"             \
           " (effective only if CMSParallelSurvivorRemarkEnabled)")          \
                                                                             \
+  product(bool, CMSEdenChunksRecordAlways, true,                            \
+          "Whether to always record eden chunks used for "                  \
+          "the parallel initial mark or remark of eden" )                   \
+                                                                            \
+  product(bool, CMSPrintEdenSurvivorChunks, false,                          \
+          "Print the eden and the survivor chunks used for the parallel "   \
+          "initial mark or remark of the eden/survivor spaces")             \
+                                                                            \
   product(bool, CMSConcurrentMTEnabled, true,                               \
           "Whether multi-threaded concurrent work enabled (if ParNewGC)")   \
                                                                             \
@@ -2589,9 +2600,6 @@
   product(bool, AggressiveOpts, false,                                      \
           "Enable aggressive optimizations - see arguments.cpp")            \
                                                                             \
-  product(bool, UseStringCache, false,                                      \
-          "Enable String cache capabilities on String.java")                \
-                                                                            \
   /* statistics */                                                          \
   develop(bool, CountCompiledCalls, false,                                  \
           "counts method invocations")                                      \
--- a/hotspot/src/share/vm/runtime/javaCalls.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/runtime/javaCalls.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -80,6 +80,8 @@
   oop              receiver()               { return _receiver; }
   void             oops_do(OopClosure* f);
 
+  bool             is_first_frame() const   { return _anchor.last_Java_sp() == NULL; }
+
 };
 
 
--- a/hotspot/src/share/vm/runtime/mutex.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/runtime/mutex.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -1370,6 +1370,10 @@
     debug_only(if (rank() != Mutex::special) \
       thread->check_for_valid_safepoint_state(false);)
   }
+  if (thread->is_Watcher_thread()) {
+    assert(!WatcherThread::watcher_thread()->has_crash_protection(),
+        "locking not allowed when crash protection is set");
+  }
 }
 
 void Monitor::check_block_state(Thread *thread) {
--- a/hotspot/src/share/vm/runtime/os.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/runtime/os.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -595,6 +595,22 @@
   NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
   NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
 
+#ifdef ASSERT
+  // checking for the WatcherThread and crash_protection first
+  // since os::malloc can be called when the libjvm.{dll,so} is
+  // first loaded and we don't have a thread yet.
+  // try to find the thread after we see that the watcher thread
+  // exists and has crash protection.
+  WatcherThread *wt = WatcherThread::watcher_thread();
+  if (wt != NULL && wt->has_crash_protection()) {
+    Thread* thread = ThreadLocalStorage::get_thread_slow();
+    if (thread == wt) {
+      assert(!wt->has_crash_protection(),
+          "Can't malloc with crash protection from WatcherThread");
+    }
+  }
+#endif
+
   if (size == 0) {
     // return a valid pointer if size is zero
     // if NULL is returned the calling functions assume out of memory.
--- a/hotspot/src/share/vm/runtime/os.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/runtime/os.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -32,15 +32,18 @@
 #include "utilities/top.hpp"
 #ifdef TARGET_OS_FAMILY_linux
 # include "jvm_linux.h"
+# include <setjmp.h>
 #endif
 #ifdef TARGET_OS_FAMILY_solaris
 # include "jvm_solaris.h"
+# include <setjmp.h>
 #endif
 #ifdef TARGET_OS_FAMILY_windows
 # include "jvm_windows.h"
 #endif
 #ifdef TARGET_OS_FAMILY_bsd
 # include "jvm_bsd.h"
+# include <setjmp.h>
 #endif
 
 // os defines the interface to operating system; this includes traditional
@@ -730,6 +733,10 @@
 #include "runtime/os_ext.hpp"
 
  public:
+  class CrashProtectionCallback : public StackObj {
+  public:
+    virtual void call() = 0;
+  };
 
   // Platform dependent stuff
 #ifdef TARGET_OS_FAMILY_linux
@@ -908,6 +915,7 @@
                                 char pathSep);
   static bool set_boot_path(char fileSep, char pathSep);
   static char** split_path(const char* path, int* n);
+
 };
 
 // Note that "PAUSE" is almost always used with synchronization
--- a/hotspot/src/share/vm/runtime/thread.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/runtime/thread.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -218,6 +218,7 @@
   // allocated data structures
   set_osthread(NULL);
   set_resource_area(new (mtThread)ResourceArea());
+  DEBUG_ONLY(_current_resource_mark = NULL;)
   set_handle_area(new (mtThread) HandleArea(NULL));
   set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true));
   set_active_handles(NULL);
@@ -953,6 +954,14 @@
 }
 
 
+bool Thread::is_in_usable_stack(address adr) const {
+  size_t stack_guard_size = os::uses_stack_guard_pages() ? (StackYellowPages + StackRedPages) * os::vm_page_size() : 0;
+  size_t usable_stack_size = _stack_size - stack_guard_size;
+
+  return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size));
+}
+
+
 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
 // used for compilation in the future. If that change is made, the need for these methods
@@ -1217,7 +1226,7 @@
 bool WatcherThread::_startable = false;
 volatile bool  WatcherThread::_should_terminate = false;
 
-WatcherThread::WatcherThread() : Thread() {
+WatcherThread::WatcherThread() : Thread(), _crash_protection(NULL) {
   assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
   if (os::create_thread(this, os::watcher_thread)) {
     _watcher_thread = this;
@@ -3481,44 +3490,6 @@
 
     initialize_class(vmSymbols::java_lang_String(), CHECK_0);
 
-    if (AggressiveOpts) {
-      {
-        // Forcibly initialize java/util/HashMap and mutate the private
-        // static final "frontCacheEnabled" field before we start creating instances
-#ifdef ASSERT
-        Klass* tmp_k = SystemDictionary::find(vmSymbols::java_util_HashMap(), Handle(), Handle(), CHECK_0);
-        assert(tmp_k == NULL, "java/util/HashMap should not be loaded yet");
-#endif
-        Klass* k_o = SystemDictionary::resolve_or_null(vmSymbols::java_util_HashMap(), Handle(), Handle(), CHECK_0);
-        KlassHandle k = KlassHandle(THREAD, k_o);
-        guarantee(k.not_null(), "Must find java/util/HashMap");
-        instanceKlassHandle ik = instanceKlassHandle(THREAD, k());
-        ik->initialize(CHECK_0);
-        fieldDescriptor fd;
-        // Possible we might not find this field; if so, don't break
-        if (ik->find_local_field(vmSymbols::frontCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) {
-          k()->java_mirror()->bool_field_put(fd.offset(), true);
-        }
-      }
-
-      if (UseStringCache) {
-        // Forcibly initialize java/lang/StringValue and mutate the private
-        // static final "stringCacheEnabled" field before we start creating instances
-        Klass* k_o = SystemDictionary::resolve_or_null(vmSymbols::java_lang_StringValue(), Handle(), Handle(), CHECK_0);
-        // Possible that StringValue isn't present: if so, silently don't break
-        if (k_o != NULL) {
-          KlassHandle k = KlassHandle(THREAD, k_o);
-          instanceKlassHandle ik = instanceKlassHandle(THREAD, k());
-          ik->initialize(CHECK_0);
-          fieldDescriptor fd;
-          // Possible we might not find this field: if so, silently don't break
-          if (ik->find_local_field(vmSymbols::stringCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) {
-            k()->java_mirror()->bool_field_put(fd.offset(), true);
-          }
-        }
-      }
-    }
-
     // Initialize java_lang.System (needed before creating the thread)
     initialize_class(vmSymbols::java_lang_System(), CHECK_0);
     initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0);
@@ -3636,6 +3607,7 @@
 
   // Start Attach Listener if +StartAttachListener or it can't be started lazily
   if (!DisableAttachMechanism) {
+    AttachListener::vm_start();
     if (StartAttachListener || AttachListener::init_at_startup()) {
       AttachListener::init();
     }
--- a/hotspot/src/share/vm/runtime/thread.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/runtime/thread.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -86,6 +86,8 @@
 class ThreadClosure;
 class IdealGraphPrinter;
 
+DEBUG_ONLY(class ResourceMark;)
+
 class WorkerThread;
 
 // Class hierarchy
@@ -519,6 +521,9 @@
   // Check if address is in the stack of the thread (not just for locks).
   // Warning: the method can only be used on the running thread
   bool is_in_stack(address adr) const;
+  // Check if address is in the usable part of the stack (excludes protected
+  // guard pages)
+  bool is_in_usable_stack(address adr) const;
 
   // Sets this thread as starting thread. Returns failure if thread
   // creation fails due to lack of memory, too many threads etc.
@@ -531,6 +536,8 @@
   // Thread local resource area for temporary allocation within the VM
   ResourceArea* _resource_area;
 
+  DEBUG_ONLY(ResourceMark* _current_resource_mark;)
+
   // Thread local handle area for allocation of handles within the VM
   HandleArea* _handle_area;
   GrowableArray<Metadata*>* _metadata_handles;
@@ -585,6 +592,8 @@
 
   // Deadlock detection
   bool allow_allocation()                        { return _allow_allocation_count == 0; }
+  ResourceMark* current_resource_mark()          { return _current_resource_mark; }
+  void set_current_resource_mark(ResourceMark* rm) { _current_resource_mark = rm; }
 #endif
 
   void check_for_valid_safepoint_state(bool potential_vm_operation) PRODUCT_RETURN;
@@ -724,6 +733,8 @@
 
   static bool _startable;
   volatile static bool _should_terminate; // updated without holding lock
+
+  os::WatcherThreadCrashProtection* _crash_protection;
  public:
   enum SomeConstants {
     delay_interval = 10                          // interrupt delay in milliseconds
@@ -751,6 +762,14 @@
   // Otherwise the first task to enroll will trigger the start
   static void make_startable();
 
+  void set_crash_protection(os::WatcherThreadCrashProtection* crash_protection) {
+    assert(Thread::current()->is_Watcher_thread(), "Can only be set by WatcherThread");
+    _crash_protection = crash_protection;
+  }
+
+  bool has_crash_protection() const { return _crash_protection != NULL; }
+  os::WatcherThreadCrashProtection* crash_protection() const { return _crash_protection; }
+
  private:
   int sleep() const;
 };
--- a/hotspot/src/share/vm/services/attachListener.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/services/attachListener.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -50,6 +50,7 @@
 
 class AttachListener: AllStatic {
  public:
+  static void vm_start() NOT_SERVICES_RETURN;
   static void init()  NOT_SERVICES_RETURN;
   static void abort() NOT_SERVICES_RETURN;
 
--- a/hotspot/src/share/vm/services/memTracker.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/services/memTracker.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -385,6 +385,7 @@
 #define SAFE_SEQUENCE_THRESHOLD    30
 #define HIGH_GENERATION_THRESHOLD  60
 #define MAX_RECORDER_THREAD_RATIO  30
+#define MAX_RECORDER_PER_THREAD    100
 
 void MemTracker::sync() {
   assert(_tracking_level > NMT_off, "NMT is not enabled");
@@ -437,6 +438,11 @@
         // means that worker thread is lagging behind in processing them.
         if (!AutoShutdownNMT) {
           _slowdown_calling_thread = (MemRecorder::_instance_count > MAX_RECORDER_THREAD_RATIO * _thread_count);
+        } else {
+          // If auto shutdown is on, enforce MAX_RECORDER_PER_THREAD threshold to prevent OOM
+          if (MemRecorder::_instance_count >= _thread_count * MAX_RECORDER_PER_THREAD) {
+            shutdown(NMT_out_of_memory);
+          }
         }
 
         // check _worker_thread with lock to avoid racing condition
--- a/hotspot/src/share/vm/trace/traceDataTypes.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/trace/traceDataTypes.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -63,5 +63,7 @@
 typedef u8 methodid;
 typedef u8 fieldid;
 
+class TraceUnicodeString;
+
 #endif // SHARE_VM_TRACE_TRACEDATATYPES_HPP
 
--- a/hotspot/src/share/vm/trace/tracetypes.xml	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/trace/tracetypes.xml	Thu Aug 01 17:24:26 2013 -0700
@@ -55,18 +55,6 @@
               type="u8" sizeop="sizeof(u1)"/>
 
 Now we can use the content + data type in declaring event fields.
-Remember however, that for us to be able to resolve the value later we must also add
-creating the constant pool data in  VM_JFRCheckpoint::write_checkpoint
-
-   ...
-   //CGMODE
-   w->be_uint(CONTENT_TYPE_GCMODE);
-   w->be_uint(MM_GC_MODE_UNINITIALIZED);
-   for (i = 0; i < MM_GC_MODE_UNINITIALIZED; i++) {
-      w->uchar(i);
-      w->write_utf8(gcModeGetName(i));
-   }
-
  -->
 
  <types>
@@ -81,10 +69,6 @@
       <value type="OSTHREAD" field="thread" label="VM Thread"/>
     </content_type>
 
-    <!-- The first argument ("JavaThread") is misleading, it's really a
-         java.lang.Thread id (long), but Mission Control depends on the name
-         being "JavaThread" so it shouldn't be changed.
-    -->
     <content_type id="JavaThread" hr_name="Java thread"
                   type="U8" builtin_type="JAVALANGTHREAD">
       <value type="OSTHREAD" field="thread" label="OS Thread ID"/>
@@ -285,6 +269,10 @@
     <primary_type symbol="UTF8" datatype="UTF8" contenttype="NONE"
                   type="const char *" sizeop="sizeof_utf(%)"/>
 
+    <!-- UTF-16 encoded (Unicode) string, max length maxjuint -->
+    <primary_type symbol="STRING" datatype="STRING" contenttype="NONE"
+                  type="TraceUnicodeString*" sizeop="sizeof_unicode(%)"/>
+
     <!-- Symbol* constant. Note that this may currently ONLY be used by
           classes, methods fields.  This restriction might be lifted. -->
     <primary_type symbol="SYMBOL" datatype="U8" contenttype="SYMBOL"
--- a/hotspot/src/share/vm/trace/xinclude.mod	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/trace/xinclude.mod	Thu Aug 01 17:24:26 2013 -0700
@@ -22,30 +22,6 @@
  questions.
   
 -->
-
-<!--
- 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
- 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.
-  
--->
 <!ELEMENT xi:include (xi:fallback?) >
 <!ATTLIST xi:include
     xmlns:xi   CDATA       #FIXED    "http://www.w3.org/2001/XInclude"
--- a/hotspot/src/share/vm/utilities/ostream.cpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/utilities/ostream.cpp	Thu Aug 01 17:24:26 2013 -0700
@@ -296,6 +296,7 @@
   buffer        = NEW_RESOURCE_ARRAY(char, buffer_length);
   buffer_pos    = 0;
   buffer_fixed  = false;
+  DEBUG_ONLY(rm = Thread::current()->current_resource_mark();)
 }
 
 // useful for output to fixed chunks of memory, such as performance counters
@@ -321,6 +322,8 @@
         end = buffer_length * 2;
       }
       char* oldbuf = buffer;
+      assert(rm == NULL || Thread::current()->current_resource_mark() == rm,
+             "stringStream is re-allocated with a different ResourceMark");
       buffer = NEW_RESOURCE_ARRAY(char, end);
       strncpy(buffer, oldbuf, buffer_pos);
       buffer_length = end;
--- a/hotspot/src/share/vm/utilities/ostream.hpp	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/src/share/vm/utilities/ostream.hpp	Thu Aug 01 17:24:26 2013 -0700
@@ -28,6 +28,8 @@
 #include "memory/allocation.hpp"
 #include "runtime/timer.hpp"
 
+DEBUG_ONLY(class ResourceMark;)
+
 // Output streams for printing
 //
 // Printing guidelines:
@@ -177,6 +179,7 @@
   size_t buffer_pos;
   size_t buffer_length;
   bool   buffer_fixed;
+  DEBUG_ONLY(ResourceMark* rm;)
  public:
   stringStream(size_t initial_bufsize = 256);
   stringStream(char* fixed_buffer, size_t fixed_buffer_size);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/EscapeAnalysis/Test8020215.java	Thu Aug 01 17:24:26 2013 -0700
@@ -0,0 +1,82 @@
+/*
+ * 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 8020215
+ * @summary Different execution plan when using JIT vs interpreter
+ * @run main Test8020215
+ */
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Test8020215 {
+    public static class NamedObject {
+        public int id;
+        public String name;
+        public NamedObject(int id, String name) {
+            this.id = id;
+            this.name = name;
+        }
+    }
+
+    public static class NamedObjectList {
+        public List<NamedObject> namedObjectList = new ArrayList<NamedObject>();
+
+        public NamedObject getBest(int id) {
+            NamedObject bestObject = null;
+            for (NamedObject o : namedObjectList) {
+                bestObject = id==o.id ? getBetter(bestObject, o) : bestObject;
+            }
+            return (bestObject != null) ? bestObject : null;
+        }
+
+        private static NamedObject getBetter(NamedObject p1, NamedObject p2) {
+            return (p1 == null) ? p2 : (p2 == null) ? p1 : (p2.name.compareTo(p1.name) >= 0) ? p2 : p1;
+        }
+    }
+
+    static void test(NamedObjectList b, int i) {
+        NamedObject x = b.getBest(2);
+        // test
+        if (x == null) {
+            throw new RuntimeException("x should never be null here! (i=" + i + ")");
+        }
+    }
+
+    public static void main(String[] args) {
+        // setup
+        NamedObjectList b = new NamedObjectList();
+        for (int i = 0; i < 10000; i++) {
+            b.namedObjectList.add(new NamedObject(1, "2012-12-31"));
+        }
+        b.namedObjectList.add(new NamedObject(2, "2013-12-31"));
+
+        // execution
+        for (int i = 0; i < 12000; i++) {
+            test(b, i);
+        }
+        System.out.println("PASSED");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/cpuflags/RestoreMXCSR.java	Thu Aug 01 17:24:26 2013 -0700
@@ -0,0 +1,42 @@
+/*
+ * 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 8020433
+ * @summary Crash when using -XX:+RestoreMXCSROnJNICalls
+ * @library /testlibrary
+ *
+ */
+import com.oracle.java.testlibrary.*;
+
+public class RestoreMXCSR {
+  public static void main(String[] args) throws Exception {
+    ProcessBuilder pb;
+    OutputAnalyzer out;
+
+    pb = ProcessTools.createJavaProcessBuilder("-XX:+RestoreMXCSROnJNICalls", "-version");
+    out = new OutputAnalyzer(pb.start());
+    out.shouldHaveExitValue(0);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/membars/DekkerTest.java	Thu Aug 01 17:24:26 2013 -0700
@@ -0,0 +1,163 @@
+/*
+ * Copyright 2013 SAP AG.  All Rights Reserved.
+ * 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 8007898
+ * @summary Incorrect optimization of Memory Barriers in Matcher::post_store_load_barrier().
+ * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:CICompilerCount=1 -XX:+StressGCM -XX:+StressLCM DekkerTest
+ * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:CICompilerCount=1 -XX:+StressGCM -XX:+StressLCM DekkerTest
+ * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:CICompilerCount=1 -XX:+StressGCM -XX:+StressLCM DekkerTest
+ * @author Martin Doerr martin DOT doerr AT sap DOT com
+ *
+ * Run 3 times since the failure is intermittent.
+ */
+
+public class DekkerTest {
+
+    /*
+      Read After Write Test (basically a simple Dekker test with volatile variables)
+      Derived from the original jcstress test, available at:
+        http://hg.openjdk.java.net/code-tools/jcstress/file/6c339a5aa00d/
+        tests-custom/src/main/java/org/openjdk/jcstress/tests/volatiles/DekkerTest.java
+     */
+
+    static final int ITERATIONS = 1000000;
+
+    static class TestData {
+        public volatile int a;
+        public volatile int b;
+    }
+
+    static class ResultData {
+        public int a;
+        public int b;
+    }
+
+    TestData[]   testDataArray;
+    ResultData[] results;
+
+    volatile boolean start;
+
+    public DekkerTest() {
+        testDataArray = new TestData[ITERATIONS];
+        results = new ResultData[ITERATIONS];
+        for (int i = 0; i < ITERATIONS; ++i) {
+            testDataArray[i] = new TestData();
+            results[i] = new ResultData();
+        }
+        start = false;
+    }
+
+    public void reset() {
+        for (int i = 0; i < ITERATIONS; ++i) {
+            testDataArray[i].a = 0;
+            testDataArray[i].b = 0;
+            results[i].a = 0;
+            results[i].b = 0;
+        }
+        start = false;
+    }
+
+    int actor1(TestData t) {
+        t.a = 1;
+        return t.b;
+    }
+
+    int actor2(TestData t) {
+        t.b = 1;
+        return t.a;
+    }
+
+    class Runner1 extends Thread {
+        public void run() {
+            do {} while (!start);
+            for (int i = 0; i < ITERATIONS; ++i) {
+                results[i].a = actor1(testDataArray[i]);
+            }
+        }
+    }
+
+    class Runner2 extends Thread {
+        public void run() {
+            do {} while (!start);
+            for (int i = 0; i < ITERATIONS; ++i) {
+                results[i].b = actor2(testDataArray[i]);
+            }
+        }
+    }
+
+    void testRunner() {
+        Thread thread1 = new Runner1();
+        Thread thread2 = new Runner2();
+        thread1.start();
+        thread2.start();
+        do {} while (!thread1.isAlive());
+        do {} while (!thread2.isAlive());
+        start = true;
+        Thread.yield();
+        try {
+            thread1.join();
+            thread2.join();
+        } catch (InterruptedException e) {
+            System.out.println("interrupted!");
+            System.exit(1);
+        }
+    }
+
+    boolean printResult() {
+        int[] count = new int[4];
+        for (int i = 0; i < ITERATIONS; ++i) {
+            int event_kind = (results[i].a << 1) + results[i].b;
+            ++count[event_kind];
+        }
+        if (count[0] == 0 && count[3] == 0) {
+            System.out.println("[not interesting]");
+            return false; // not interesting
+        }
+        String error = (count[0] == 0) ? " ok" : " disallowed!";
+        System.out.println("[0,0] " + count[0] + error);
+        System.out.println("[0,1] " + count[1]);
+        System.out.println("[1,0] " + count[2]);
+        System.out.println("[1,1] " + count[3]);
+        return (count[0] != 0);
+    }
+
+    public static void main(String args[]) {
+        DekkerTest test = new DekkerTest();
+        final int runs = 30;
+        int failed = 0;
+        for (int c = 0; c < runs; ++c) {
+            test.testRunner();
+            if (test.printResult()) {
+                failed++;
+            }
+            test.reset();
+        }
+        if (failed > 0) {
+            throw new InternalError("FAILED. Got " + failed + " failed ITERATIONS");
+        }
+        System.out.println("PASSED.");
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/gc/arguments/TestG1HeapRegionSize.java	Thu Aug 01 17:24:26 2013 -0700
@@ -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.
+*/
+
+/*
+ * @test TestG1HeapRegionSize
+ * @key gc
+ * @bug 8021879
+ * @summary Verify that the flag G1HeapRegionSize is updated properly
+ * @run main/othervm -Xmx64m TestG1HeapRegionSize 1048576
+ * @run main/othervm -XX:G1HeapRegionSize=2m -Xmx64m TestG1HeapRegionSize 2097152
+ * @run main/othervm -XX:G1HeapRegionSize=3m -Xmx64m TestG1HeapRegionSize 2097152
+ * @run main/othervm -XX:G1HeapRegionSize=64m -Xmx256m TestG1HeapRegionSize 33554432
+ */
+
+import sun.management.ManagementFactoryHelper;
+import com.sun.management.HotSpotDiagnosticMXBean;
+import com.sun.management.VMOption;
+
+public class TestG1HeapRegionSize {
+
+  public static void main(String[] args) {
+    HotSpotDiagnosticMXBean diagnostic = ManagementFactoryHelper.getDiagnosticMXBean();
+
+    VMOption option = diagnostic.getVMOption("UseG1GC");
+    if (option.getValue().equals("false")) {
+      System.out.println("Skipping this test. It is only a G1 test.");
+      return;
+    }
+
+    String expectedValue = getExpectedValue(args);
+    option = diagnostic.getVMOption("G1HeapRegionSize");
+    if (!expectedValue.equals(option.getValue())) {
+      throw new RuntimeException("Wrong value for G1HeapRegionSize. Expected " + expectedValue + " but got " + option.getValue());
+    }
+  }
+
+  private static String getExpectedValue(String[] args) {
+    if (args.length != 1) {
+      throw new RuntimeException("Wrong number of arguments. Expected 1 but got " + args.length);
+    }
+    return args[0];
+  }
+
+}
--- a/hotspot/test/gc/g1/TestPrintRegionRememberedSetInfo.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/test/gc/g1/TestPrintRegionRememberedSetInfo.java	Thu Aug 01 17:24:26 2013 -0700
@@ -27,7 +27,7 @@
  * @bug 8014240
  * @summary Test output of G1PrintRegionRememberedSetInfo
  * @library /testlibrary
- * @build TestPrintRegionRememberedSetInfo
+ * @run main TestPrintRegionRememberedSetInfo
  * @author thomas.schatzl@oracle.com
  */
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/gc/startup_warnings/TestDefaultMaxRAMFraction.java	Thu Aug 01 17:24:26 2013 -0700
@@ -0,0 +1,44 @@
+/*
+* 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 TestDefaultMaxRAMFraction
+* @key gc
+* @bug 8021967
+* @summary Test that the deprecated TestDefaultMaxRAMFraction flag print a warning message
+* @library /testlibrary
+*/
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+public class TestDefaultMaxRAMFraction {
+  public static void main(String[] args) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:DefaultMaxRAMFraction=4", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("warning: DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. Use MaxRAMFraction instead.");
+    output.shouldNotContain("error");
+    output.shouldHaveExitValue(0);
+  }
+
+}
--- a/hotspot/test/runtime/6929067/Test6929067.sh	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/test/runtime/6929067/Test6929067.sh	Thu Aug 01 17:24:26 2013 -0700
@@ -3,6 +3,7 @@
 ##
 ## @test Test6929067.sh
 ## @bug 6929067
+## @bug 8021296
 ## @summary Stack guard pages should be removed when thread is detached
 ## @compile T.java
 ## @run shell Test6929067.sh
@@ -21,6 +22,11 @@
 OS=`uname -s`
 case "$OS" in
   Linux)
+    gcc_cmd=`which gcc`
+    if [ "x$gcc_cmd" == "x" ]; then
+        echo "WARNING: gcc not found. Cannot execute test." 2>&1
+        exit 0;
+    fi
     NULL=/dev/null
     PS=":"
     FS="/"
@@ -119,10 +125,10 @@
 # Check to ensure you have a /usr/lib/libpthread.so if you don't please look
 # for /usr/lib/`uname -m`-linux-gnu version ensure to add that path to below compilation.
 
-gcc -DLINUX ${COMP_FLAG} -o invoke \
-  -I${COMPILEJAVA}/include -I${COMPILEJAVA}/include/linux \
-  -L${COMPILEJAVA}/jre/lib/${ARCH}/${VMTYPE} \
-  -ljvm -lpthread invoke.c
+$gcc_cmd -DLINUX ${COMP_FLAG} -o invoke \
+    -I${COMPILEJAVA}/include -I${COMPILEJAVA}/include/linux \
+    -L${COMPILEJAVA}/jre/lib/${ARCH}/${VMTYPE} \
+    -ljvm -lpthread invoke.c
 
 ./invoke
 exit $?
--- a/hotspot/test/runtime/7107135/Test7107135.sh	Fri Jul 19 13:24:09 2013 -0700
+++ b/hotspot/test/runtime/7107135/Test7107135.sh	Thu Aug 01 17:24:26 2013 -0700
@@ -27,6 +27,7 @@
 ##
 ## @test Test7107135.sh
 ## @bug 7107135
+## @bug 8021296
 ## @summary Stack guard pages lost after loading library with executable stack.
 ## @run shell Test7107135.sh
 ##
@@ -45,6 +46,11 @@
 case "$OS" in
   Linux)
     echo "Testing on Linux"
+    gcc_cmd=`which gcc`
+    if [ "x$gcc_cmd" == "x" ]; then
+        echo "WARNING: gcc not found. Cannot execute test." 2>&1
+        exit 0;
+    fi
     ;;
   *)
     NULL=NUL
@@ -62,7 +68,10 @@
 cp ${TESTSRC}${FS}*.java ${THIS_DIR}
 ${TESTJAVA}${FS}bin${FS}javac *.java
 
-gcc -fPIC -shared -c -o test.o -I${TESTJAVA}${FS}include -I${TESTJAVA}${FS}include${FS}linux ${TESTSRC}${FS}test.c
+$gcc_cmd -fPIC -shared -c -o test.o \
+    -I${TESTJAVA}${FS}include -I${TESTJAVA}${FS}include${FS}linux \
+    ${TESTSRC}${FS}test.c
+
 ld -shared -z   execstack -o libtest-rwx.so test.o
 ld -shared -z noexecstack -o libtest-rw.so  test.o
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/jsig/Test8017498.sh	Thu Aug 01 17:24:26 2013 -0700
@@ -0,0 +1,94 @@
+#!/bin/sh
+
+#
+#  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 Test8017498.sh
+## @bug 8017498
+## @bug 8020791
+## @bug 8021296
+## @summary sigaction(sig) results in process hang/timed-out if sig is much greater than SIGRTMAX
+## @run shell/timeout=30 Test8017498.sh
+##
+
+if [ "${TESTSRC}" = "" ]
+then
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
+fi
+echo "TESTSRC=${TESTSRC}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
+
+# set platform-dependent variables
+OS=`uname -s`
+case "$OS" in
+  Linux)
+    echo "Testing on Linux"
+    gcc_cmd=`which gcc`
+    if [ "x$gcc_cmd" == "x" ]; then
+        echo "WARNING: gcc not found. Cannot execute test." 2>&1
+        exit 0;
+    fi
+    if [ "$VM_BITS" = "64" ]
+    then
+        MY_LD_PRELOAD=${TESTJAVA}${FS}jre${FS}lib${FS}amd64${FS}libjsig.so
+    else
+        MY_LD_PRELOAD=${TESTJAVA}${FS}jre${FS}lib${FS}i386${FS}libjsig.so
+    fi
+    echo MY_LD_PRELOAD = ${MY_LD_PRELOAD}
+    ;;
+  *)
+    echo "Test passed; only valid for Linux"
+    exit 0;
+    ;;
+esac
+
+THIS_DIR=.
+
+cp ${TESTSRC}${FS}*.java ${THIS_DIR}
+${TESTJAVA}${FS}bin${FS}javac *.java
+
+$gcc_cmd -DLINUX -fPIC -shared \
+    -o ${TESTSRC}${FS}libTestJNI.so \
+    -I${TESTJAVA}${FS}include \
+    -I${TESTJAVA}${FS}include${FS}linux \
+    ${TESTSRC}${FS}TestJNI.c
+
+# run the java test in the background
+cmd="LD_PRELOAD=$MY_LD_PRELOAD \
+    ${TESTJAVA}${FS}bin${FS}java \
+    -Djava.library.path=${TESTSRC}${FS} -server TestJNI 100"
+echo "$cmd > test.out 2>&1"
+eval $cmd > test.out 2>&1
+
+grep "old handler" test.out > ${NULL}
+if [ $? = 0 ]
+then
+    echo "Test Passed"
+    exit 0
+fi
+
+echo "Test Failed"
+exit 1
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/jsig/TestJNI.c	Thu Aug 01 17:24:26 2013 -0700
@@ -0,0 +1,55 @@
+/*
+ * 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.
+ */
+
+#include <stdio.h>
+#include <jni.h>
+#include <signal.h>
+#include <sys/ucontext.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void sig_handler(int sig, siginfo_t *info, ucontext_t *context) {
+
+    printf( " HANDLER (1) " );
+}
+
+JNIEXPORT void JNICALL Java_TestJNI_doSomething(JNIEnv *env, jclass klass, jint val) {
+    struct sigaction act;
+    struct sigaction oact;
+
+    act.sa_flags = SA_ONSTACK|SA_RESTART|SA_SIGINFO;
+    sigfillset(&act.sa_mask);
+    act.sa_handler = SIG_DFL;
+    act.sa_sigaction = (void (*)())sig_handler;
+    sigaction(0x20+val, &act, &oact);
+
+    printf( " doSomething(%d) " , val);
+    printf( " old handler = %p " , oact.sa_handler);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/runtime/jsig/TestJNI.java	Thu Aug 01 17:24:26 2013 -0700
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+public class TestJNI {
+    static {
+        System.loadLibrary("TestJNI");
+    }
+    public static native void doSomething(int val);
+    public static void main(String[] args) {
+        int intArg = 43;
+        if (args.length > 0) {
+            try {
+                intArg = Integer.parseInt(args[0]);
+            } catch (NumberFormatException e) {
+                System.err.println("arg " + args[0] + " must be an integer");
+                System.exit(1);
+            }
+        }
+        TestJNI.doSomething(intArg);
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/serviceability/attach/AttachWithStalePidFile.java	Thu Aug 01 17:24:26 2013 -0700
@@ -0,0 +1,139 @@
+/*
+ * 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 7162400
+ * @key regression
+ * @summary Regression test for attach issue where stale pid files in /tmp lead to connection issues
+ * @library /testlibrary
+ * @compile AttachWithStalePidFileTarget.java
+ * @run main AttachWithStalePidFile
+ */
+
+import com.oracle.java.testlibrary.*;
+import com.sun.tools.attach.VirtualMachine;
+import sun.tools.attach.HotSpotVirtualMachine;
+import java.lang.reflect.Field;
+import java.nio.file.*;
+import java.nio.file.attribute.*;
+import java.io.*;
+
+public class AttachWithStalePidFile {
+  public static void main(String... args) throws Exception {
+
+    // this test is only valid on non-Windows platforms
+    if(Platform.isWindows()) {
+      System.out.println("This test is only valid on non-Windows platforms.");
+      return;
+    }
+
+    // Since there might be stale pid-files owned by different
+    // users on the system we may need to retry the test in case we
+    // are unable to remove the existing file.
+    int retries = 5;
+    while(!runTest() && --retries > 0);
+
+    if(retries == 0) {
+      throw new RuntimeException("Test failed after 5 retries. " +
+        "Remove any /tmp/.java_pid* files and retry.");
+    }
+  }
+
+  public static boolean runTest() throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+      "-XX:+UnlockDiagnosticVMOptions", "-XX:+PauseAtStartup", "AttachWithStalePidFileTarget");
+    Process target = pb.start();
+    Path pidFile = null;
+
+    try {
+      int pid = getUnixProcessId(target);
+
+      // create the stale .java_pid file. use hard-coded /tmp path as in th VM
+      pidFile = createJavaPidFile(pid);
+      if(pidFile == null) {
+        return false;
+      }
+
+      // wait for vm.paused file to be created and delete it once we find it.
+      waitForAndResumeVM(pid);
+
+      // unfortunately there's no reliable way to know the VM is ready to receive the
+      // attach request so we have to do an arbitrary sleep.
+      Thread.sleep(5000);
+
+      HotSpotVirtualMachine vm = (HotSpotVirtualMachine)VirtualMachine.attach(((Integer)pid).toString());
+      BufferedReader remoteDataReader = new BufferedReader(new InputStreamReader(vm.remoteDataDump()));
+      String line = null;
+      while((line = remoteDataReader.readLine()) != null);
+
+      vm.detach();
+      return true;
+    }
+    finally {
+      target.destroy();
+      target.waitFor();
+
+      if(pidFile != null && Files.exists(pidFile)) {
+        Files.delete(pidFile);
+      }
+    }
+  }
+
+  private static Path createJavaPidFile(int pid) throws Exception {
+    Path pidFile = Paths.get("/tmp/.java_pid" + pid);
+    if(Files.exists(pidFile)) {
+      try {
+        Files.delete(pidFile);
+      }
+      catch(FileSystemException e) {
+        if(e.getReason().equals("Operation not permitted")) {
+          System.out.println("Unable to remove exisiting stale PID file" + pidFile);
+          return null;
+        }
+        throw e;
+      }
+    }
+    return Files.createFile(pidFile,
+      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
+  }
+
+  private static void waitForAndResumeVM(int pid) throws Exception {
+    Path pauseFile = Paths.get("vm.paused." + pid);
+    int retries = 60;
+    while(!Files.exists(pauseFile) && --retries > 0) {
+      Thread.sleep(1000);
+    }
+    if(retries == 0) {
+      throw new RuntimeException("Timeout waiting for VM to start. " +
+        "vm.paused file not created within 60 seconds.");
+    }
+    Files.delete(pauseFile);
+  }
+
+  private static int getUnixProcessId(Process unixProcess) throws Exception {
+    Field pidField = unixProcess.getClass().getDeclaredField("pid");
+    pidField.setAccessible(true);
+    return (Integer)pidField.get(unixProcess);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/serviceability/attach/AttachWithStalePidFileTarget.java	Thu Aug 01 17:24:26 2013 -0700
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+public class AttachWithStalePidFileTarget {
+  public static void main(String... args) throws Exception {
+    Thread.sleep(2*60*1000);
+  }
+}
--- a/jaxp/.hgtags	Fri Jul 19 13:24:09 2013 -0700
+++ b/jaxp/.hgtags	Thu Aug 01 17:24:26 2013 -0700
@@ -221,3 +221,5 @@
 6c830db28d21108f32af990ecf4d80a75887980d jdk8-b97
 15e5bb51bc0cd89304dc2f7f29b4c8002e632353 jdk8-b98
 adf49c3ef83c160d53ece623049b2cdccaf78fc7 jdk8-b99
+5d1974c1d7b9a86431bc253dc5a6a52d4586622e jdk8-b100
+0a7432f898e579ea35e8c51e3edab37f949168e4 jdk8-b101
--- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/SAXParserImpl.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/SAXParserImpl.java	Thu Aug 01 17:24:26 2013 -0700
@@ -112,7 +112,7 @@
     /** Initial EntityResolver */
     private final EntityResolver fInitEntityResolver;
 
-    private XMLSecurityPropertyManager fSecurityPropertyMgr;
+    private final XMLSecurityPropertyManager fSecurityPropertyMgr;
 
     /**
      * Create a SAX parser with the associated features
@@ -130,8 +130,10 @@
     SAXParserImpl(SAXParserFactoryImpl spf, Hashtable features, boolean secureProcessing)
         throws SAXException
     {
+        fSecurityPropertyMgr = new XMLSecurityPropertyManager();
+
         // Instantiate a SAXParser directly and not through SAX so that we use the right ClassLoader
-        xmlReader = new JAXPSAXParser(this);
+        xmlReader = new JAXPSAXParser(this, fSecurityPropertyMgr);
 
         // JAXP "namespaceAware" == SAX Namespaces feature
         // Note: there is a compatibility problem here with default values:
@@ -150,7 +152,6 @@
             xmlReader.setFeature0(XINCLUDE_FEATURE, true);
         }
 
-        fSecurityPropertyMgr = new XMLSecurityPropertyManager();
         xmlReader.setProperty0(XML_SECURITY_PROPERTY_MANAGER, fSecurityPropertyMgr);
 
         // If the secure processing feature is on set a security manager.
@@ -397,14 +398,30 @@
         private final HashMap fInitFeatures = new HashMap();
         private final HashMap fInitProperties = new HashMap();
         private final SAXParserImpl fSAXParser;
+        private XMLSecurityPropertyManager fSecurityPropertyMgr;
+
 
         public JAXPSAXParser() {
-            this(null);
+            this(null, null);
         }
 
-        JAXPSAXParser(SAXParserImpl saxParser) {
+        JAXPSAXParser(SAXParserImpl saxParser, XMLSecurityPropertyManager spm) {
             super();
             fSAXParser = saxParser;
+            fSecurityPropertyMgr = spm;
+
+            /**
+             * This class may be used directly. So initialize the security manager if
+             * it is null.
+             */
+            if (fSecurityPropertyMgr == null) {
+                fSecurityPropertyMgr = new XMLSecurityPropertyManager();
+                try {
+                    super.setProperty(XML_SECURITY_PROPERTY_MANAGER, fSecurityPropertyMgr);
+                } catch (Exception ex) {
+                    //shall not happen
+                }
+            }
         }
 
         /**
@@ -542,9 +559,9 @@
                 setSchemaValidatorProperty(name, value);
             }
             /** Check to see if the property is managed by the property manager **/
-            int index = fSAXParser.fSecurityPropertyMgr.getIndex(name);
+            int index = (fSecurityPropertyMgr != null) ? fSecurityPropertyMgr.getIndex(name) : -1;
             if (index > -1) {
-                fSAXParser.fSecurityPropertyMgr.setValue(index,
+                fSecurityPropertyMgr.setValue(index,
                         XMLSecurityPropertyManager.State.APIPROPERTY, (String)value);
             } else {
                 if (!fInitProperties.containsKey(name)) {
@@ -564,9 +581,9 @@
                 // JAXP 1.2 support
                 return fSAXParser.schemaLanguage;
             }
-            int index = fSAXParser.fSecurityPropertyMgr.getIndex(name);
+            int index = (fSecurityPropertyMgr != null) ? fSecurityPropertyMgr.getIndex(name) : -1;
             if (index > -1) {
-                return fSAXParser.fSecurityPropertyMgr.getValueByIndex(index);
+                return fSecurityPropertyMgr.getValueByIndex(index);
             }
 
             return super.getProperty(name);
--- a/jaxws/.hgtags	Fri Jul 19 13:24:09 2013 -0700
+++ b/jaxws/.hgtags	Thu Aug 01 17:24:26 2013 -0700
@@ -221,3 +221,5 @@
 dcde7f049111353ad23175f54985a4f6bfea720c jdk8-b97
 b1fb4612a2caea52b5661b87509e560fa044b194 jdk8-b98
 8ef83d4b23c933935e28f59b282cea920b1b1f5f jdk8-b99
+4fd722afae5c02f00bbd44c3a34425ee474afb1c jdk8-b100
+60b623a361642a0f5aef5f06dad9e5f279b9d9a9 jdk8-b101
--- a/jdk/.hgtags	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/.hgtags	Thu Aug 01 17:24:26 2013 -0700
@@ -221,3 +221,5 @@
 978a95239044f26dcc8a6d59246be07ad6ca6be2 jdk8-b97
 c4908732fef5235f1b98cafe0ce507771ef7892c jdk8-b98
 6a099a36589bd933957272ba63e5263bede29971 jdk8-b99
+5be9c5bfcfe9b2a40412b4fb364377d49de014eb jdk8-b100
+6901612328239fbd471d20823113c1cf3fdaebee jdk8-b101
--- a/jdk/src/macosx/classes/com/apple/eawt/_AppMenuBarHandler.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/macosx/classes/com/apple/eawt/_AppMenuBarHandler.java	Thu Aug 01 17:24:26 2013 -0700
@@ -31,6 +31,7 @@
 import javax.swing.*;
 import javax.swing.plaf.MenuBarUI;
 
+import com.apple.laf.ScreenMenuBar;
 import sun.lwawt.macosx.CMenuBar;
 
 import com.apple.laf.AquaMenuBarUI;
@@ -72,12 +73,15 @@
         // scan the current frames, and see if any are foreground
         final Frame[] frames = Frame.getFrames();
         for (final Frame frame : frames) {
-            if (frame.isVisible() && !isFrameMinimized(frame)) return;
+            if (frame.isVisible() && !isFrameMinimized(frame)) {
+                return;
+            }
         }
 
         // if we have no foreground frames, then we have to "kick" the menubar
         final JFrame pingFrame = new JFrame();
         pingFrame.getRootPane().putClientProperty("Window.alpha", new Float(0.0f));
+        pingFrame.setUndecorated(true);
         pingFrame.setVisible(true);
         pingFrame.toFront();
         pingFrame.setVisible(false);
@@ -101,7 +105,6 @@
             // Aqua was not installed
             throw new IllegalStateException("Application.setDefaultMenuBar() only works with the Aqua Look and Feel");
         }
-/* TODO: disabled until ScreenMenuBar is working
 
         final AquaMenuBarUI aquaUI = (AquaMenuBarUI)ui;
         final ScreenMenuBar screenMenuBar = aquaUI.getScreenMenuBar();
@@ -118,8 +121,7 @@
         }
 
         // grab the pointer to the CMenuBar, and retain it in native
-        nativeSetDefaultMenuBar(((CMenuBar)peer).getNativeMenuBarPeer());
-*/
+        nativeSetDefaultMenuBar(((CMenuBar)peer).getModel());
     }
 
     void setAboutMenuItemVisible(final boolean present) {
--- a/jdk/src/macosx/classes/sun/font/CStrike.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/macosx/classes/sun/font/CStrike.java	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -31,7 +31,7 @@
 
 import sun.awt.SunHints;
 
-public class CStrike extends FontStrike {
+public final class CStrike extends FontStrike {
 
     // Creates the native strike
     private static native long createNativeStrikePtr(long nativeFontPtr,
@@ -68,10 +68,10 @@
                                                          Rectangle2D.Float result,
                                                          double x, double y);
 
-    private CFont nativeFont;
+    private final CFont nativeFont;
     private AffineTransform invDevTx;
-    private GlyphInfoCache glyphInfoCache;
-    private GlyphAdvanceCache glyphAdvanceCache;
+    private final GlyphInfoCache glyphInfoCache;
+    private final GlyphAdvanceCache glyphAdvanceCache;
     private long nativeStrikePtr;
 
     CStrike(final CFont font, final FontStrikeDesc inDesc) {
@@ -84,11 +84,11 @@
         // Normally the device transform should be the identity transform
         // for screen operations.  The device transform only becomes
         // interesting when we are outputting between different dpi surfaces,
-        // like when we are printing to postscript.
+        // like when we are printing to postscript or use retina.
         if (inDesc.devTx != null && !inDesc.devTx.isIdentity()) {
             try {
                 invDevTx = inDesc.devTx.createInverse();
-            } catch (NoninvertibleTransformException e) {
+            } catch (NoninvertibleTransformException ignored) {
                 // ignored, since device transforms should not be that
                 // complicated, and if they are - there is nothing we can do,
                 // so we won't worry about it.
@@ -134,15 +134,13 @@
         nativeStrikePtr = 0;
     }
 
-    // the fractional metrics default on our platform is OFF
-    private boolean useFractionalMetrics() {
-        return desc.fmHint == SunHints.INTVAL_FRACTIONALMETRICS_ON;
-    }
 
+    @Override
     public int getNumGlyphs() {
         return nativeFont.getNumGlyphs();
     }
 
+    @Override
     StrikeMetrics getFontMetrics() {
         if (strikeMetrics == null) {
             StrikeMetrics metrics = getFontMetrics(getNativeStrikePtr());
@@ -155,74 +153,24 @@
         return strikeMetrics;
     }
 
-    float getGlyphAdvance(int glyphCode) {
-        return getScaledAdvanceForAdvance(getCachedNativeGlyphAdvance(glyphCode));
+    @Override
+    float getGlyphAdvance(final int glyphCode) {
+        return getCachedNativeGlyphAdvance(glyphCode);
     }
 
-    float getCodePointAdvance(int cp) {
-        float advance = getCachedNativeGlyphAdvance(nativeFont.getMapper().charToGlyph(cp));
-
-        double glyphScaleX = desc.glyphTx.getScaleX();
-        double devScaleX = desc.devTx.getScaleX();
-
-        if (devScaleX == 0) {
-            glyphScaleX = Math.sqrt(desc.glyphTx.getDeterminant());
-            devScaleX = Math.sqrt(desc.devTx.getDeterminant());
-        }
-
-        if (devScaleX == 0) {
-            devScaleX = Double.NaN; // this an undefined graphics state
-        }
-        advance = (float) (advance * glyphScaleX / devScaleX);
-        return useFractionalMetrics() ? advance : Math.round(advance);
+    @Override
+    float getCodePointAdvance(final int cp) {
+        return getGlyphAdvance(nativeFont.getMapper().charToGlyph(cp));
     }
 
-    // calculate an advance, and round if not using fractional metrics
-    private float getScaledAdvanceForAdvance(float advance) {
-        if (invDevTx != null) {
-            advance *= invDevTx.getScaleX();
-        }
-        advance *= desc.glyphTx.getScaleX();
-        return useFractionalMetrics() ? advance : Math.round(advance);
+    @Override
+    Point2D.Float getCharMetrics(final char ch) {
+        return getGlyphMetrics(nativeFont.getMapper().charToGlyph(ch));
     }
 
-    Point2D.Float getCharMetrics(char ch) {
-        return getScaledPointForAdvance(getCachedNativeGlyphAdvance(nativeFont.getMapper().charToGlyph(ch)));
-    }
-
-    Point2D.Float getGlyphMetrics(int glyphCode) {
-        return getScaledPointForAdvance(getCachedNativeGlyphAdvance(glyphCode));
-    }
-
-    // calculate an advance point, and round if not using fractional metrics
-    private Point2D.Float getScaledPointForAdvance(float advance) {
-        Point2D.Float pt = new Point2D.Float(advance, 0);
-
-        if (!desc.glyphTx.isIdentity()) {
-            return scalePoint(pt);
-        }
-
-        if (!useFractionalMetrics()) {
-            pt.x = Math.round(pt.x);
-        }
-        return pt;
-    }
-
-    private Point2D.Float scalePoint(Point2D.Float pt) {
-        if (invDevTx != null) {
-            // transform the point out of the device space first
-            invDevTx.transform(pt, pt);
-        }
-        desc.glyphTx.transform(pt, pt);
-        pt.x -= desc.glyphTx.getTranslateX();
-        pt.y -= desc.glyphTx.getTranslateY();
-
-        if (!useFractionalMetrics()) {
-            pt.x = Math.round(pt.x);
-            pt.y = Math.round(pt.y);
-        }
-
-        return pt;
+    @Override
+    Point2D.Float getGlyphMetrics(final int glyphCode) {
+        return new Point2D.Float(getGlyphAdvance(glyphCode), 0.0f);
     }
 
     Rectangle2D.Float getGlyphOutlineBounds(int glyphCode) {
@@ -414,9 +362,7 @@
         private SparseBitShiftingTwoLayerArray secondLayerCache;
         private HashMap<Integer, Long> generalCache;
 
-        public GlyphInfoCache(final Font2D nativeFont,
-                              final FontStrikeDesc desc)
-        {
+        GlyphInfoCache(final Font2D nativeFont, final FontStrikeDesc desc) {
             super(nativeFont, desc);
             firstLayerCache = new long[FIRST_LAYER_SIZE];
         }
@@ -527,7 +473,7 @@
             final int shift;
             final int secondLayerLength;
 
-            public SparseBitShiftingTwoLayerArray(final int size, final int shift) {
+            SparseBitShiftingTwoLayerArray(final int size, final int shift) {
                 this.shift = shift;
                 this.cache = new long[1 << shift][];
                 this.secondLayerLength = size >> shift;
@@ -559,6 +505,12 @@
         private SparseBitShiftingTwoLayerArray secondLayerCache;
         private HashMap<Integer, Float> generalCache;
 
+        // Empty non private constructor was added because access to this
+        // class shouldn't be emulated by a synthetic accessor method.
+        GlyphAdvanceCache() {
+            super();
+        }
+
         public synchronized float get(final int index) {
             if (index < 0) {
                 if (-index < SECOND_LAYER_SIZE) {
@@ -609,9 +561,7 @@
             final int shift;
             final int secondLayerLength;
 
-            public SparseBitShiftingTwoLayerArray(final int size,
-                                                  final int shift)
-            {
+            SparseBitShiftingTwoLayerArray(final int size, final int shift) {
                 this.shift = shift;
                 this.cache = new float[1 << shift][];
                 this.secondLayerLength = size >> shift;
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java	Thu Aug 01 17:24:26 2013 -0700
@@ -182,7 +182,11 @@
         Long format = predefinedClipboardNameMap.get(str);
 
         if (format == null) {
-            format = new Long(registerFormatWithPasteboard(str));
+            if (java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().isHeadlessInstance()) {
+                // Do not try to access native system for the unknown format
+                return -1L;
+            }
+            format = registerFormatWithPasteboard(str);
             predefinedClipboardNameMap.put(str, format);
             predefinedClipboardFormatMap.put(format, str);
         }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CMenuComponent.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CMenuComponent.java	Thu Aug 01 17:24:26 2013 -0700
@@ -43,7 +43,7 @@
         return target;
     }
 
-    long getModel() {
+    public long getModel() {
         return modelPtr;
     }
 
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Thu Aug 01 17:24:26 2013 -0700
@@ -47,7 +47,7 @@
 import com.sun.awt.AWTUtilities;
 
 public class CPlatformWindow extends CFRetainedResource implements PlatformWindow {
-    private native long nativeCreateNSWindow(long nsViewPtr, long styleBits, double x, double y, double w, double h);
+    private native long nativeCreateNSWindow(long nsViewPtr,long ownerPtr, long styleBits, double x, double y, double w, double h);
     private static native void nativeSetNSWindowStyleBits(long nsWindowPtr, int mask, int data);
     private static native void nativeSetNSWindowMenuBar(long nsWindowPtr, long menuBarPtr);
     private static native Insets nativeGetNSWindowInsets(long nsWindowPtr);
@@ -230,7 +230,8 @@
         contentView = createContentView();
         contentView.initialize(peer, responder);
 
-        final long nativeWindowPtr = nativeCreateNSWindow(contentView.getAWTView(), styleBits, 0, 0, 0, 0);
+        final long ownerPtr = owner != null ? owner.getNSWindowPtr() : 0L;
+        final long nativeWindowPtr = nativeCreateNSWindow(contentView.getAWTView(), ownerPtr, styleBits, 0, 0, 0, 0);
         setPtr(nativeWindowPtr);
 
         if (target instanceof javax.swing.RootPaneContainer) {
--- a/jdk/src/macosx/native/sun/awt/AWTWindow.h	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/macosx/native/sun/awt/AWTWindow.h	Thu Aug 01 17:24:26 2013 -0700
@@ -44,6 +44,7 @@
     jint styleBits;
     BOOL isEnabled;
     NSWindow *nsWindow;
+    AWTWindow *ownerWindow;
 }
 
 // An instance of either AWTWindow_Normal or AWTWindow_Panel
@@ -51,12 +52,15 @@
 
 @property (nonatomic, retain) JNFWeakJObjectWrapper *javaPlatformWindow;
 @property (nonatomic, retain) CMenuBar *javaMenuBar;
+@property (nonatomic, retain) AWTWindow *ownerWindow;
 @property (nonatomic) NSSize javaMinSize;
 @property (nonatomic) NSSize javaMaxSize;
 @property (nonatomic) jint styleBits;
 @property (nonatomic) BOOL isEnabled;
 
+
 - (id) initWithPlatformWindow:(JNFWeakJObjectWrapper *)javaPlatformWindow
+                  ownerWindow:owner
                     styleBits:(jint)styleBits
                     frameRect:(NSRect)frameRect
                   contentView:(NSView *)contentView;
--- a/jdk/src/macosx/native/sun/awt/AWTWindow.m	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/macosx/native/sun/awt/AWTWindow.m	Thu Aug 01 17:24:26 2013 -0700
@@ -30,6 +30,7 @@
 #import "sun_lwawt_macosx_CPlatformWindow.h"
 #import "com_apple_eawt_event_GestureHandler.h"
 #import "com_apple_eawt_FullScreenHandler.h"
+#import "ApplicationDelegate.h"
 
 #import "AWTWindow.h"
 #import "AWTView.h"
@@ -55,7 +56,7 @@
 // doesn't provide information about "opposite" window, so we
 // have to do a bit of tracking. This variable points to a window
 // which had been the key window just before a new key window
-// was set. It would be nil if the new key window isn't an AWT 
+// was set. It would be nil if the new key window isn't an AWT
 // window or the app currently has no key window.
 static AWTWindow* lastKeyWindow = nil;
 
@@ -120,6 +121,7 @@
 @synthesize javaMaxSize;
 @synthesize styleBits;
 @synthesize isEnabled;
+@synthesize ownerWindow;
 
 - (void) updateMinMaxSize:(BOOL)resizable {
     if (resizable) {
@@ -201,6 +203,7 @@
 }
 
 - (id) initWithPlatformWindow:(JNFWeakJObjectWrapper *)platformWindow
+                  ownerWindow:owner
                     styleBits:(jint)bits
                     frameRect:(NSRect)rect
                   contentView:(NSView *)view
@@ -245,6 +248,7 @@
     self.isEnabled = YES;
     self.javaPlatformWindow = platformWindow;
     self.styleBits = bits;
+    self.ownerWindow = owner;
     [self setPropertiesForStyleBits:styleBits mask:MASK(_METHOD_PROP_BITMASK)];
 
     return self;
@@ -350,7 +354,7 @@
     [self.javaPlatformWindow setJObject:nil withEnv:env];
 
     self.nsWindow = nil;
-
+    self.ownerWindow = nil;
     [super dealloc];
 }
 
@@ -539,11 +543,27 @@
 AWT_ASSERT_APPKIT_THREAD;
     [AWTToolkit eventCountPlusPlus];
     AWTWindow *opposite = [AWTWindow lastKeyWindow];
-    if (!IS(self.styleBits, IS_DIALOG)) {
-        [CMenuBar activate:self.javaMenuBar modallyDisabled:NO];
-    } else if ((opposite != NULL) && IS(self.styleBits, IS_MODAL)) {
-        [CMenuBar activate:opposite->javaMenuBar modallyDisabled:YES];        
+
+    // Finds appropriate menubar in our hierarchy,
+    AWTWindow *awtWindow = self;
+    while (awtWindow.ownerWindow != nil) {
+        awtWindow = awtWindow.ownerWindow;
     }
+
+    CMenuBar *menuBar = nil;
+    BOOL isDisabled = NO;
+    if ([awtWindow.nsWindow isVisible]){
+        menuBar = awtWindow.javaMenuBar;
+        isDisabled = !awtWindow.isEnabled;
+    }
+
+    if (menuBar == nil) {
+        menuBar = [[ApplicationDelegate sharedDelegate] defaultMenuBar];
+        isDisabled = NO;
+    }
+
+    [CMenuBar activate:menuBar modallyDisabled:isDisabled];
+
     [AWTWindow setLastKeyWindow:nil];
 
     [self _deliverWindowFocusEvent:YES oppositeWindow: opposite];
@@ -555,6 +575,14 @@
     [AWTToolkit eventCountPlusPlus];
     [self.javaMenuBar deactivate];
 
+    // In theory, this might cause flickering if the window gaining focus
+    // has its own menu. However, I couldn't reproduce it on practice, so
+    // perhaps this is a non issue.
+    CMenuBar* defaultMenu = [[ApplicationDelegate sharedDelegate] defaultMenuBar];
+    if (defaultMenu != nil) {
+        [CMenuBar activate:defaultMenu modallyDisabled:NO];
+    }
+
     // the new key window
     NSWindow *keyWindow = [NSApp keyWindow];
     AWTWindow *opposite = nil;
@@ -741,7 +769,7 @@
  * Signature: (JJIIII)J
  */
 JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeCreateNSWindow
-(JNIEnv *env, jobject obj, jlong contentViewPtr, jlong styleBits, jdouble x, jdouble y, jdouble w, jdouble h)
+(JNIEnv *env, jobject obj, jlong contentViewPtr, jlong ownerPtr, jlong styleBits, jdouble x, jdouble y, jdouble w, jdouble h)
 {
     __block AWTWindow *window = nil;
 
@@ -750,13 +778,14 @@
     JNFWeakJObjectWrapper *platformWindow = [JNFWeakJObjectWrapper wrapperWithJObject:obj withEnv:env];
     NSView *contentView = OBJC(contentViewPtr);
     NSRect frameRect = NSMakeRect(x, y, w, h);
-
+    AWTWindow *owner = [OBJC(ownerPtr) delegate];
     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
 
         window = [[AWTWindow alloc] initWithPlatformWindow:platformWindow
-                                                  styleBits:styleBits
-                                                  frameRect:frameRect
-                                                contentView:contentView];
+                                               ownerWindow:owner
+                                                 styleBits:styleBits
+                                                 frameRect:frameRect
+                                               contentView:contentView];
         // the window is released is CPlatformWindow.nativeDispose()
 
         if (window) CFRetain(window.nsWindow);
@@ -818,11 +847,19 @@
 
         AWTWindow *window = (AWTWindow*)[nsWindow delegate];
 
-        if ([nsWindow isKeyWindow]) [window.javaMenuBar deactivate];
+        if ([nsWindow isKeyWindow]) {
+            [window.javaMenuBar deactivate];
+        }
+
         window.javaMenuBar = menuBar;
 
+        CMenuBar* actualMenuBar = menuBar;
+        if (actualMenuBar == nil) {
+            actualMenuBar = [[ApplicationDelegate sharedDelegate] defaultMenuBar];
+        }
+
         if ([nsWindow isKeyWindow]) {
-            [CMenuBar activate:window.javaMenuBar modallyDisabled:NO];
+            [CMenuBar activate:actualMenuBar modallyDisabled:NO];
         }
     }];
 
--- a/jdk/src/macosx/native/sun/awt/CMenuBar.m	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/macosx/native/sun/awt/CMenuBar.m	Thu Aug 01 17:24:26 2013 -0700
@@ -63,7 +63,7 @@
         if (excludingAppleMenu && ![currMenu isJavaMenu]) {
             continue;
         }
-
+        [currItem setSubmenu:nil];
         [theMainMenu removeItemAtIndex:index];
     }
 
@@ -154,7 +154,10 @@
     // Clean up extra items
     NSUInteger removedIndex, removedCount = [removedMenuArray count];
     for (removedIndex=removedCount; removedIndex > 0; removedIndex--) {
-        [theMainMenu removeItemAtIndex:[[removedMenuArray objectAtIndex:(removedIndex-1)] integerValue]];
+        NSUInteger index = [[removedMenuArray objectAtIndex:(removedIndex-1)] integerValue];
+        NSMenuItem *currItem = [theMainMenu itemAtIndex:index];
+        [currItem setSubmenu:nil];
+        [theMainMenu removeItemAtIndex:index];
     }
 
     i = cmenuIndex;
--- a/jdk/src/macosx/native/sun/awt/CMenuItem.m	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/macosx/native/sun/awt/CMenuItem.m	Thu Aug 01 17:24:26 2013 -0700
@@ -70,9 +70,15 @@
     JNIEnv *env = [ThreadUtilities getJNIEnv];
 JNF_COCOA_ENTER(env);
 
-    // If we are called as a result of user pressing a shorcut, do nothing,
+    // If we are called as a result of user pressing a shortcut, do nothing,
     // because AVTView has already sent corresponding key event to the Java
-    // layer from performKeyEquivalent
+    // layer from performKeyEquivalent.
+    // There is an exception from the rule above, though: if a window with
+    // a menu gets minimized by user and there are no other windows to take
+    // focus, the window's menu won't be removed from the global menu bar.
+    // However, the Java layer won't handle invocation by a shortcut coming
+    // from this "frameless" menu, because there are no active windows. This
+    // means we have to handle it here.
     NSEvent *currEvent = [[NSApplication sharedApplication] currentEvent];
     if ([currEvent type] == NSKeyDown) {
         NSString *menuKey = [sender keyEquivalent];
@@ -91,7 +97,8 @@
             eventKey = [NSString stringWithCharacters: &newChar length: 1];
         }
 
-        if ([menuKey isEqualToString:eventKey]) {
+        NSWindow *keyWindow = [NSApp keyWindow];
+        if ([menuKey isEqualToString:eventKey] && keyWindow != nil) {
             return;
         }
     }
--- a/jdk/src/macosx/native/sun/font/AWTStrike.h	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/macosx/native/sun/font/AWTStrike.h	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -31,11 +31,12 @@
 @interface AWTStrike : NSObject {
 @public
     AWTFont *                fAWTFont;
-    CGFloat                    fSize;
+    CGFloat                  fSize;
     JRSFontRenderingStyle    fStyle;
-    jint                    fAAStyle;
+    jint                     fAAStyle;
 
     CGAffineTransform        fTx;
+    CGAffineTransform        fDevTx;
     CGAffineTransform        fAltTx; // alternate strike tx used for Sun2D
     CGAffineTransform        fFontTx;
 }
--- a/jdk/src/macosx/native/sun/font/AWTStrike.m	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/macosx/native/sun/font/AWTStrike.m	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -65,6 +65,7 @@
         invDevTx.b *= -1;
         invDevTx.c *= -1;
         fFontTx = CGAffineTransformConcat(CGAffineTransformConcat(tx, invDevTx), sInverseTX);
+        fDevTx = CGAffineTransformInvert(invDevTx);
 
         // the "font size" is the square root of the determinant of the matrix
         fSize = sqrt(abs(fFontTx.a * fFontTx.d - fFontTx.b * fFontTx.c));
@@ -148,7 +149,8 @@
 {
     CGSize advance;
 JNF_COCOA_ENTER(env);
-    AWTFont *awtFont = ((AWTStrike *)jlong_to_ptr(awtStrikePtr))->fAWTFont;
+    AWTStrike *awtStrike = (AWTStrike *)jlong_to_ptr(awtStrikePtr);
+    AWTFont *awtFont = awtStrike->fAWTFont;
 
     // negative glyph codes are really unicodes, which were placed there by the mapper
     // to indicate we should use CoreText to substitute the character
@@ -156,6 +158,10 @@
     const CTFontRef fallback = CTS_CopyCTFallbackFontAndGlyphForJavaGlyphCode(awtFont, glyphCode, &glyph);
     CTFontGetAdvancesForGlyphs(fallback, kCTFontDefaultOrientation, &glyph, &advance, 1);
     CFRelease(fallback);
+    advance = CGSizeApplyAffineTransform(advance, awtStrike->fFontTx);
+    if (!JRSFontStyleUsesFractionalMetrics(awtStrike->fStyle)) {
+        advance.width = round(advance.width);
+    }
 
 JNF_COCOA_EXIT(env);
     return advance.width;
--- a/jdk/src/macosx/native/sun/font/CGGlyphImages.m	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/macosx/native/sun/font/CGGlyphImages.m	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -455,6 +455,7 @@
 #define CGGI_GLYPH_BBOX_PADDING 2.0f
 static inline GlyphInfo *
 CGGI_CreateNewGlyphInfoFrom(CGSize advance, CGRect bbox,
+                            const AWTStrike *strike,
                             const CGGI_RenderingMode *mode)
 {
     size_t pixelSize = mode->glyphDescriptor->pixelSize;
@@ -477,6 +478,12 @@
         width = 1;
         height = 1;
     }
+    advance = CGSizeApplyAffineTransform(advance, strike->fFontTx);
+    if (!JRSFontStyleUsesFractionalMetrics(strike->fStyle)) {
+        advance.width = round(advance.width);
+        advance.height = round(advance.height);
+    }
+    advance = CGSizeApplyAffineTransform(advance, strike->fDevTx);
 
 #ifdef USE_IMAGE_ALIGNED_MEMORY
     // create separate memory
@@ -564,10 +571,10 @@
     JRSFontGetBoundingBoxesForGlyphsAndStyle(fallback, &tx, style, &glyph, 1, &bbox);
 
     CGSize advance;
-    JRSFontGetAdvancesForGlyphsAndStyle(fallback, &tx, strike->fStyle, &glyph, 1, &advance);
+    CTFontGetAdvancesForGlyphs(fallback, kCTFontDefaultOrientation, &glyph, &advance, 1);
 
     // create the Sun2D GlyphInfo we are going to strike into
-    GlyphInfo *info = CGGI_CreateNewGlyphInfoFrom(advance, bbox, mode);
+    GlyphInfo *info = CGGI_CreateNewGlyphInfoFrom(advance, bbox, strike, mode);
 
     // fix the context size, just in case the substituted character is unexpectedly large
     CGGI_SizeCanvas(canvas, info->width, info->height, mode->cgFontMode);
@@ -715,7 +722,7 @@
     JRSFontRenderingStyle bboxCGMode = JRSFontAlignStyleForFractionalMeasurement(strike->fStyle);
 
     JRSFontGetBoundingBoxesForGlyphsAndStyle((CTFontRef)font->fFont, &tx, bboxCGMode, glyphs, len, bboxes);
-    JRSFontGetAdvancesForGlyphsAndStyle((CTFontRef)font->fFont, &tx, strike->fStyle, glyphs, len, advances);
+    CTFontGetAdvancesForGlyphs((CTFontRef)font->fFont, kCTFontDefaultOrientation, glyphs, advances, len);
 
     size_t maxWidth = 1;
     size_t maxHeight = 1;
@@ -732,7 +739,7 @@
         CGSize advance = advances[i];
         CGRect bbox = bboxes[i];
 
-        GlyphInfo *glyphInfo = CGGI_CreateNewGlyphInfoFrom(advance, bbox, mode);
+        GlyphInfo *glyphInfo = CGGI_CreateNewGlyphInfoFrom(advance, bbox, strike, mode);
 
         if (maxWidth < glyphInfo->width)   maxWidth = glyphInfo->width;
         if (maxHeight < glyphInfo->height) maxHeight = glyphInfo->height;
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/resources/gtk.properties	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/resources/gtk.properties	Thu Aug 01 17:24:26 2013 -0700
@@ -1,54 +1,54 @@
-# Refer to the note in basic.properties for a description as to what
-# the mnemonics correspond to and how to calculate them.
-
-
-
-# GTK specific properties
-
-# GTK color chooser properties:
-GTKColorChooserPanel.textAndMnemonic=&GTK Color Chooser
-# mnemonic as a VK_ constant
-
-GTKColorChooserPanel.hue.textAndMnemonic=&Hue:
-
-GTKColorChooserPanel.red.textAndMnemonic=R&ed:
-
-GTKColorChooserPanel.saturation.textAndMnemonic=&Saturation:
-
-GTKColorChooserPanel.green.textAndMnemonic=&Green:
-
-GTKColorChooserPanel.value.textAndMnemonic=&Value:
-
-GTKColorChooserPanel.blue.textAndMnemonic=&Blue:
-
-GTKColorChooserPanel.color.textAndMnemonic=Color &Name:
-
-
-
-############ FILE CHOOSER STRINGS #############
-
-FileChooser.acceptAllFileFilter.textAndMnemonic=All Files
-FileChooser.newFolderButton.textAndMnemonic=&New Folder
-FileChooser.newFolderDialog.textAndMnemonic=Folder name:
-FileChooser.newFolderNoDirectoryErrorTitle.textAndMnemonic=Error
-FileChooser.newFolderNoDirectoryError.textAndMnemonic=Error creating directory "{0}": No such file or directory
-FileChooser.deleteFileButton.textAndMnemonic=De&lete File
-FileChooser.renameFileButton.textAndMnemonic=&Rename File
-FileChooser.cancelButton.textAndMnemonic=&Cancel
-FileChooser.saveButton.textAndMnemonic=&OK
-FileChooser.openButton.textAndMnemonic=&OK
-FileChooser.saveDialogTitle.textAndMnemonic=Save
-FileChooser.openDialogTitle.textAndMnemonic=Open
-FileChooser.pathLabel.textAndMnemonic=&Selection:
-FileChooser.filterLabel.textAndMnemonic=Filter:
-FileChooser.foldersLabel.textAndMnemonic=Fol&ders
-FileChooser.filesLabel.textAndMnemonic=&Files
-
-FileChooser.cancelButtonToolTip.textAndMnemonic=Abort file chooser dialog.
-FileChooser.saveButtonToolTip.textAndMnemonic=Save selected file.
-FileChooser.openButtonToolTip.textAndMnemonic=Open selected file.
-
-FileChooser.renameFileDialog.textAndMnemonic=Rename file "{0}" to
-FileChooser.renameFileError.titleAndMnemonic=Error
-FileChooser.renameFileError.textAndMnemonic=Error renaming file "{0}" to "{1}"
-
+# Refer to the note in basic.properties for a description as to what
+# the mnemonics correspond to and how to calculate them.
+
+
+
+# GTK specific properties
+
+# GTK color chooser properties:
+GTKColorChooserPanel.textAndMnemonic=&GTK Color Chooser
+# mnemonic as a VK_ constant
+
+GTKColorChooserPanel.hue.textAndMnemonic=&Hue:
+
+GTKColorChooserPanel.red.textAndMnemonic=R&ed:
+
+GTKColorChooserPanel.saturation.textAndMnemonic=&Saturation:
+
+GTKColorChooserPanel.green.textAndMnemonic=&Green:
+
+GTKColorChooserPanel.value.textAndMnemonic=&Value:
+
+GTKColorChooserPanel.blue.textAndMnemonic=&Blue:
+
+GTKColorChooserPanel.color.textAndMnemonic=Color &Name:
+
+
+
+############ FILE CHOOSER STRINGS #############
+
+FileChooser.acceptAllFileFilter.textAndMnemonic=All Files
+FileChooser.newFolderButton.textAndMnemonic=&New Folder
+FileChooser.newFolderDialog.textAndMnemonic=Folder name:
+FileChooser.newFolderNoDirectoryErrorTitle.textAndMnemonic=Error
+FileChooser.newFolderNoDirectoryError.textAndMnemonic=Error creating directory "{0}": No such file or directory
+FileChooser.deleteFileButton.textAndMnemonic=De&lete File
+FileChooser.renameFileButton.textAndMnemonic=&Rename File
+FileChooser.cancelButton.textAndMnemonic=&Cancel
+FileChooser.saveButton.textAndMnemonic=&OK
+FileChooser.openButton.textAndMnemonic=&OK
+FileChooser.saveDialogTitle.textAndMnemonic=Save
+FileChooser.openDialogTitle.textAndMnemonic=Open
+FileChooser.pathLabel.textAndMnemonic=&Selection:
+FileChooser.filterLabel.textAndMnemonic=Filter:
+FileChooser.foldersLabel.textAndMnemonic=Fol&ders
+FileChooser.filesLabel.textAndMnemonic=&Files
+
+FileChooser.cancelButtonToolTip.textAndMnemonic=Abort file chooser dialog.
+FileChooser.saveButtonToolTip.textAndMnemonic=Save selected file.
+FileChooser.openButtonToolTip.textAndMnemonic=Open selected file.
+
+FileChooser.renameFileDialog.textAndMnemonic=Rename file "{0}" to
+FileChooser.renameFileError.titleAndMnemonic=Error
+FileChooser.renameFileError.textAndMnemonic=Error renaming file "{0}" to "{1}"
+
--- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsComboBoxUI.java	Thu Aug 01 17:24:26 2013 -0700
@@ -499,7 +499,8 @@
 
         public void setItem(Object item) {
             super.setItem(item);
-            if (editor.hasFocus()) {
+            Object focus = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
+            if ((focus == editor) || (focus == editor.getParent())) {
                 editor.selectAll();
             }
         }
--- a/jdk/src/share/classes/com/sun/swing/internal/plaf/synth/resources/synth.properties	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/com/sun/swing/internal/plaf/synth/resources/synth.properties	Thu Aug 01 17:24:26 2013 -0700
@@ -1,45 +1,45 @@
-# This properties file is used to create a PropertyResourceBundle
-# It contains Locale specific strings used be the Synth Look and Feel.
-# Currently, the following components need this for support:
-#
-#    FileChooser
-#
-# When this file is read in, the strings are put into the
-# defaults table.  This is an implementation detail of the current
-# workings of Swing.  DO NOT DEPEND ON THIS.
-# This may change in future versions of Swing as we improve localization
-# support.
-#
-# Refer to the note in basic.properties for a description as to what
-# the mnemonics correspond to and how to calculate them.
-#
-# @author Steve Wilson
-
-
-############ FILE CHOOSER STRINGS #############
-
-FileChooser.lookInLabel.textAndMnemonic=Look &In:
-FileChooser.saveInLabel.textAndMnemonic=Save In:
-FileChooser.fileNameLabel.textAndMnemonic=File &Name:
-FileChooser.folderNameLabel.textAndMnemonic=Folder &Name:
-FileChooser.filesOfTypeLabel.textAndMnemonic=Files of &Type:
-FileChooser.upFolderToolTip.textAndMnemonic=Up One Level
-FileChooser.upFolderAccessibleName=Up
-FileChooser.homeFolderToolTip.textAndMnemonic=Home
-FileChooser.homeFolderAccessibleName=Home
-FileChooser.newFolderToolTip.textAndMnemonic=Create New Folder
-FileChooser.newFolderAccessibleName=New Folder
-FileChooser.newFolderActionLabel.textAndMnemonic=New Folder
-FileChooser.listViewButtonToolTip.textAndMnemonic=List
-FileChooser.listViewButtonAccessibleName=List
-FileChooser.listViewActionLabel.textAndMnemonic=List
-FileChooser.detailsViewButtonToolTip.textAndMnemonic=Details
-FileChooser.detailsViewButtonAccessibleName=Details
-FileChooser.detailsViewActionLabel.textAndMnemonic=Details
-FileChooser.refreshActionLabel.textAndMnemonic=Refresh
-FileChooser.viewMenuLabel.textAndMnemonic=View
-FileChooser.fileNameHeader.textAndMnemonic=Name
-FileChooser.fileSizeHeader.textAndMnemonic=Size
-FileChooser.fileTypeHeader.textAndMnemonic=Type
-FileChooser.fileDateHeader.textAndMnemonic=Modified
-FileChooser.fileAttrHeader.textAndMnemonic=Attributes
+# This properties file is used to create a PropertyResourceBundle
+# It contains Locale specific strings used be the Synth Look and Feel.
+# Currently, the following components need this for support:
+#
+#    FileChooser
+#
+# When this file is read in, the strings are put into the
+# defaults table.  This is an implementation detail of the current
+# workings of Swing.  DO NOT DEPEND ON THIS.
+# This may change in future versions of Swing as we improve localization
+# support.
+#
+# Refer to the note in basic.properties for a description as to what
+# the mnemonics correspond to and how to calculate them.
+#
+# @author Steve Wilson
+
+
+############ FILE CHOOSER STRINGS #############
+
+FileChooser.lookInLabel.textAndMnemonic=Look &In:
+FileChooser.saveInLabel.textAndMnemonic=Save In:
+FileChooser.fileNameLabel.textAndMnemonic=File &Name:
+FileChooser.folderNameLabel.textAndMnemonic=Folder &Name:
+FileChooser.filesOfTypeLabel.textAndMnemonic=Files of &Type:
+FileChooser.upFolderToolTip.textAndMnemonic=Up One Level
+FileChooser.upFolderAccessibleName=Up
+FileChooser.homeFolderToolTip.textAndMnemonic=Home
+FileChooser.homeFolderAccessibleName=Home
+FileChooser.newFolderToolTip.textAndMnemonic=Create New Folder
+FileChooser.newFolderAccessibleName=New Folder
+FileChooser.newFolderActionLabel.textAndMnemonic=New Folder
+FileChooser.listViewButtonToolTip.textAndMnemonic=List
+FileChooser.listViewButtonAccessibleName=List
+FileChooser.listViewActionLabel.textAndMnemonic=List
+FileChooser.detailsViewButtonToolTip.textAndMnemonic=Details
+FileChooser.detailsViewButtonAccessibleName=Details
+FileChooser.detailsViewActionLabel.textAndMnemonic=Details
+FileChooser.refreshActionLabel.textAndMnemonic=Refresh
+FileChooser.viewMenuLabel.textAndMnemonic=View
+FileChooser.fileNameHeader.textAndMnemonic=Name
+FileChooser.fileSizeHeader.textAndMnemonic=Size
+FileChooser.fileTypeHeader.textAndMnemonic=Type
+FileChooser.fileDateHeader.textAndMnemonic=Modified
+FileChooser.fileAttrHeader.textAndMnemonic=Attributes
--- a/jdk/src/share/classes/com/sun/tools/script/shell/init.js	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/com/sun/tools/script/shell/init.js	Thu Aug 01 17:24:26 2013 -0700
@@ -332,7 +332,7 @@
  * @param str input from which script is loaded and evaluated
  */
 if (typeof(load) == 'undefined') {
-    var load = function(str) {
+    this.load = function(str) {
         var stream = inStream(str);
         var bstream = new BufferedInputStream(stream);
         var reader = new BufferedReader(new InputStreamReader(bstream));
@@ -712,7 +712,7 @@
      * @param exitCode integer code returned to OS shell.
      * optional, defaults to 0
      */
-    var exit = function (code) {
+    this.exit = function (code) {
         if (code) {
             java.lang.System.exit(code + 0);
         } else {
@@ -725,7 +725,7 @@
     /**
      * synonym for exit
      */
-    var quit = function (code) {
+    this.quit = function (code) {
         exit(code);
     }
 }
@@ -881,7 +881,7 @@
      * @param format string to format the rest of the print items
      * @param args variadic argument list
      */
-    var printf = function (format, args/*, more args*/) {  
+    this.printf = function (format, args/*, more args*/) {  
         var array = java.lang.reflect.Array.newInstance(java.lang.Object, 
                     arguments.length - 1);
         for (var i = 0; i < array.length; i++) {
@@ -921,25 +921,7 @@
 }
 
 if (typeof(println) == 'undefined') {
-    var print = function(str, newline) {
-        if (typeof(str) == 'undefined') {
-            str = 'undefined';
-        } else if (str == null) {
-            str = 'null';
-        }
+    // just synonym to print
+    this.println = print;
+}
 
-        if (!(out instanceof java.io.PrintWriter)) {
-            out = new java.io.PrintWriter(out);
-        }
-
-        out.print(String(str));
-        if (newline) {
-            out.print('\n');
-        }
-        out.flush();
-    }
-
-    var println = function(str) {
-        print(str, true);
-    };
-}
--- a/jdk/src/share/classes/java/awt/AWTException.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/awt/AWTException.java	Thu Aug 01 17:24:26 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 1997, 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
@@ -26,7 +26,7 @@
 
 
 /**
- * Signals that an Absract Window Toolkit exception has occurred.
+ * Signals that an Abstract Window Toolkit exception has occurred.
  *
  * @author      Arthur van Hoff
  */
--- a/jdk/src/share/classes/java/io/DataInput.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/io/DataInput.java	Thu Aug 01 17:24:26 2013 -0700
@@ -48,132 +48,87 @@
  * may be thrown if the input stream has been
  * closed.
  *
- * <h4><a name="modified-utf-8">Modified UTF-8</a></h4>
+ * <h3><a name="modified-utf-8">Modified UTF-8</a></h3>
  * <p>
  * Implementations of the DataInput and DataOutput interfaces represent
  * Unicode strings in a format that is a slight modification of UTF-8.
  * (For information regarding the standard UTF-8 format, see section
  * <i>3.9 Unicode Encoding Forms</i> of <i>The Unicode Standard, Version
  * 4.0</i>).
- * Note that in the following tables, the most significant bit appears in the
+ * Note that in the following table, the most significant bit appears in the
  * far left-hand column.
- * <p>
- * All characters in the range {@code '\u005Cu0001'} to
- * {@code '\u005Cu007F'} are represented by a single byte:
  *
  * <blockquote>
- *   <table border="1" cellspacing="0" cellpadding="8" width="50%"
+ *   <table border="1" cellspacing="0" cellpadding="8"
  *          summary="Bit values and bytes">
  *     <tr>
+ *       <th colspan="9"><span style="font-weight:normal">
+ *         All characters in the range {@code '\u005Cu0001'} to
+ *         {@code '\u005Cu007F'} are represented by a single byte:</span></th>
+ *     </tr>
+ *     <tr>
  *       <td></td>
- *       <th id="bit_a">Bit Values</th>
+ *       <th colspan="8" id="bit_a">Bit Values</th>
  *     </tr>
  *     <tr>
  *       <th id="byte1_a">Byte 1</th>
- *       <td>
- *         <table border="1" cellspacing="0" width="100%">
- *           <tr>
- *             <td width="12%"><center>0</center>
- *             <td colspan="7"><center>bits 6-0</center>
- *           </tr>
- *         </table>
- *       </td>
+ *       <td><center>0</center>
+ *       <td colspan="7"><center>bits 6-0</center>
+ *     </tr>
+ *     <tr>
+ *       <th colspan="9"><span style="font-weight:normal">
+ *         The null character {@code '\u005Cu0000'} and characters
+ *         in the range {@code '\u005Cu0080'} to {@code '\u005Cu07FF'} are
+ *         represented by a pair of bytes:</span></th>
+ *     </tr>
+ *     <tr>
+ *       <td></td>
+ *       <th colspan="8" id="bit_b">Bit Values</th>
+ *     </tr>
+ *     <tr>
+ *       <th id="byte1_b">Byte 1</th>
+ *       <td><center>1</center>
+ *       <td><center>1</center>
+ *       <td><center>0</center>
+ *       <td colspan="5"><center>bits 10-6</center>
+ *     </tr>
+ *     <tr>
+ *       <th id="byte2_a">Byte 2</th>
+ *       <td><center>1</center>
+ *       <td><center>0</center>
+ *       <td colspan="6"><center>bits 5-0</center>
+ *     </tr>
+ *     <tr>
+ *       <th colspan="9"><span style="font-weight:normal">
+ *         {@code char} values in the range {@code '\u005Cu0800'}
+ *         to {@code '\u005CuFFFF'} are represented by three bytes:</span></th>
+ *     </tr>
+ *     <tr>
+ *       <td></td>
+ *       <th colspan="8"id="bit_c">Bit Values</th>
+ *     </tr>
+ *     <tr>
+ *       <th id="byte1_c">Byte 1</th>
+ *       <td><center>1</center>
+ *       <td><center>1</center>
+ *       <td><center>1</center>
+ *       <td><center>0</center>
+ *       <td colspan="4"><center>bits 15-12</center>
+ *     </tr>
+ *     <tr>
+ *       <th id="byte2_b">Byte 2</th>
+ *       <td><center>1</center>
+ *       <td><center>0</center>
+ *       <td colspan="6"><center>bits 11-6</center>
+ *     </tr>
+ *     <tr>
+ *       <th id="byte3">Byte 3</th>
+ *       <td><center>1</center>
+ *       <td><center>0</center>
+ *       <td colspan="6"><center>bits 5-0</center>
  *     </tr>
  *   </table>
  * </blockquote>
- *
- * <p>
- * The null character {@code '\u005Cu0000'} and characters in the
- * range {@code '\u005Cu0080'} to {@code '\u005Cu07FF'} are
- * represented by a pair of bytes:
- *
- * <blockquote>
- *   <table border="1" cellspacing="0" cellpadding="8" width="50%"
- *          summary="Bit values and bytes">
- *     <tr>
- *       <td></td>
- *       <th id="bit_b">Bit Values</th>
- *     </tr>
- *     <tr>
- *       <th id="byte1_b">Byte 1</th>
- *       <td>
- *         <table border="1" cellspacing="0" width="100%">
- *           <tr>
- *             <td width="12%"><center>1</center>
- *             <td width="13%"><center>1</center>
- *             <td width="12%"><center>0</center>
- *             <td colspan="5"><center>bits 10-6</center>
- *           </tr>
- *         </table>
- *       </td>
- *     </tr>
- *     <tr>
- *       <th id="byte2_a">Byte 2</th>
- *       <td>
- *         <table border="1" cellspacing="0" width="100%">
- *           <tr>
- *             <td width="12%"><center>1</center>
- *             <td width="13%"><center>0</center>
- *             <td colspan="6"><center>bits 5-0</center>
- *           </tr>
- *         </table>
- *       </td>
- *     </tr>
- *   </table>
- *  </blockquote>
- *
- * <br>
- * {@code char} values in the range {@code '\u005Cu0800'} to
- * {@code '\u005CuFFFF'} are represented by three bytes:
- *
- * <blockquote>
- *   <table border="1" cellspacing="0" cellpadding="8" width="50%"
- *          summary="Bit values and bytes">
- *     <tr>
- *       <td></td>
- *       <th id="bit_c">Bit Values</th>
- *     </tr>
- *     <tr>
- *       <th id="byte1_c">Byte 1</th>
- *       <td>
- *         <table border="1" cellspacing="0" width="100%">
- *           <tr>
- *             <td width="12%"><center>1</center>
- *             <td width="13%"><center>1</center>
- *             <td width="12%"><center>1</center>
- *             <td width="13%"><center>0</center>
- *             <td colspan="4"><center>bits 15-12</center>
- *           </tr>
- *         </table>
- *       </td>
- *     </tr>
- *     <tr>
- *       <th id="byte2_b">Byte 2</th>
- *       <td>
- *         <table border="1" cellspacing="0" width="100%">
- *           <tr>
- *             <td width="12%"><center>1</center>
- *             <td width="13%"><center>0</center>
- *             <td colspan="6"><center>bits 11-6</center>
- *           </tr>
- *         </table>
- *       </td>
- *     </tr>
- *     <tr>
- *       <th id="byte3">Byte 3</th>
- *       <td>
- *         <table border="1" cellspacing="0" width="100%">
- *           <tr>
- *             <td width="12%"><center>1</center>
- *             <td width="13%"><center>0</center>
- *             <td colspan="6"><center>bits 5-0</center>
- *           </tr>
- *         </table>
- *       </td>
- *     </tr>
- *   </table>
- *  </blockquote>
- *
  * <p>
  * The differences between this format and the
  * standard UTF-8 format are the following:
--- a/jdk/src/share/classes/java/io/File.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/io/File.java	Thu Aug 01 17:24:26 2013 -0700
@@ -129,7 +129,7 @@
  * created, the abstract pathname represented by a <code>File</code> object
  * will never change.
  *
- * <h4>Interoperability with {@code java.nio.file} package</h4>
+ * <h3>Interoperability with {@code java.nio.file} package</h3>
  *
  * <p> The <a href="../../java/nio/file/package-summary.html">{@code java.nio.file}</a>
  * package defines interfaces and classes for the Java virtual machine to access
--- a/jdk/src/share/classes/java/io/ObjectInputStream.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/io/ObjectInputStream.java	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -313,6 +313,7 @@
      * @throws  SecurityException if a security manager exists and its
      *          <code>checkPermission</code> method denies enabling
      *          subclassing.
+     * @throws  IOException if an I/O error occurs while creating this stream
      * @see SecurityManager#checkPermission
      * @see java.io.SerializablePermission
      */
--- a/jdk/src/share/classes/java/io/ObjectOutputStream.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/io/ObjectOutputStream.java	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -265,6 +265,7 @@
      * @throws  SecurityException if a security manager exists and its
      *          <code>checkPermission</code> method denies enabling
      *          subclassing.
+     * @throws  IOException if an I/O error occurs while creating this stream
      * @see SecurityManager#checkPermission
      * @see java.io.SerializablePermission
      */
--- a/jdk/src/share/classes/java/io/ObjectStreamField.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/io/ObjectStreamField.java	Thu Aug 01 17:24:26 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, 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
@@ -240,6 +240,8 @@
      * Returns boolean value indicating whether or not the serializable field
      * represented by this ObjectStreamField instance is unshared.
      *
+     * @return {@code true} if this field is unshared
+     *
      * @since 1.4
      */
     public boolean isUnshared() {
--- a/jdk/src/share/classes/java/io/RandomAccessFile.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/io/RandomAccessFile.java	Thu Aug 01 17:24:26 2013 -0700
@@ -128,7 +128,7 @@
      * meanings are:
      *
      * <table summary="Access mode permitted values and meanings">
-     * <tr><th><p align="left">Value</p></th><th><p align="left">Meaning</p></th></tr>
+     * <tr><th align="left">Value</th><th align="left">Meaning</th></tr>
      * <tr><td valign="top"><tt>"r"</tt></td>
      *     <td> Open for reading only.  Invoking any of the <tt>write</tt>
      *     methods of the resulting object will cause an {@link
--- a/jdk/src/share/classes/java/lang/Class.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/lang/Class.java	Thu Aug 01 17:24:26 2013 -0700
@@ -157,10 +157,10 @@
      *
      * The string is formatted as a list of type modifiers, if any,
      * followed by the kind of type (empty string for primitive types
-     * and {@code class}, {@code enum}, {@code interface}, or {@code
-     * &#64;interface}, as appropriate), followed by the type's name,
-     * followed by an angle-bracketed comma-separated list of the
-     * type's type parameters, if any.
+     * and {@code class}, {@code enum}, {@code interface}, or
+     * <code>&#64;</code>{@code interface}, as appropriate), followed
+     * by the type's name, followed by an angle-bracketed
+     * comma-separated list of the type's type parameters, if any.
      *
      * A space is used to separate modifiers from one another and to
      * separate any modifiers from the kind of type. The modifiers
--- a/jdk/src/share/classes/java/lang/invoke/LambdaConversionException.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/lang/invoke/LambdaConversionException.java	Thu Aug 01 17:24:26 2013 -0700
@@ -29,6 +29,8 @@
  * LambdaConversionException
  */
 public class LambdaConversionException extends Exception {
+    private static final long serialVersionUID = 292L + 8L;
+
     /**
      * Constructs a {@code LambdaConversionException}.
      */
--- a/jdk/src/share/classes/java/lang/ref/FinalReference.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/lang/ref/FinalReference.java	Thu Aug 01 17:24:26 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2003, 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
@@ -25,13 +25,12 @@
 
 package java.lang.ref;
 
-
-/* Final references, used to implement finalization */
-
+/**
+ * Final references, used to implement finalization
+ */
 class FinalReference<T> extends Reference<T> {
 
     public FinalReference(T referent, ReferenceQueue<? super T> q) {
         super(referent, q);
     }
-
 }
--- a/jdk/src/share/classes/java/lang/ref/Finalizer.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/lang/ref/Finalizer.java	Thu Aug 01 17:24:26 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2008, 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
@@ -29,16 +29,16 @@
 import java.security.AccessController;
 
 
-final class Finalizer extends FinalReference { /* Package-private; must be in
-                                                  same package as the Reference
-                                                  class */
+final class Finalizer extends FinalReference<Object> { /* Package-private; must be in
+                                                          same package as the Reference
+                                                          class */
 
     /* A native method that invokes an arbitrary object's finalize method is
        required since the finalize method is protected
      */
     static native void invokeFinalizeMethod(Object o) throws Throwable;
 
-    private static ReferenceQueue queue = new ReferenceQueue();
+    private static ReferenceQueue<Object> queue = new ReferenceQueue<>();
     private static Finalizer unfinalized = null;
     private static final Object lock = new Object();
 
--- a/jdk/src/share/classes/java/lang/ref/Reference.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/lang/ref/Reference.java	Thu Aug 01 17:24:26 2013 -0700
@@ -96,6 +96,7 @@
      *    Enqueued:   next reference in queue (or this if last)
      *    Inactive:   this
      */
+    @SuppressWarnings("rawtypes")
     Reference next;
 
     /* When active:   next element in a discovered reference list maintained by GC (or this if last)
@@ -119,7 +120,7 @@
      * them.  This list is protected by the above lock object. The
      * list uses the discovered field to link its elements.
      */
-    private static Reference pending = null;
+    private static Reference<Object> pending = null;
 
     /* High-priority thread to enqueue pending References
      */
@@ -131,7 +132,7 @@
 
         public void run() {
             for (;;) {
-                Reference r;
+                Reference<Object> r;
                 synchronized (lock) {
                     if (pending != null) {
                         r = pending;
@@ -166,7 +167,7 @@
                     continue;
                 }
 
-                ReferenceQueue q = r.queue;
+                ReferenceQueue<Object> q = r.queue;
                 if (q != ReferenceQueue.NULL) q.enqueue(r);
             }
         }
--- a/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java	Thu Aug 01 17:24:26 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2005, 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
@@ -40,14 +40,14 @@
      */
     public ReferenceQueue() { }
 
-    private static class Null extends ReferenceQueue {
-        boolean enqueue(Reference r) {
+    private static class Null<S> extends ReferenceQueue<S> {
+        boolean enqueue(Reference<? extends S> r) {
             return false;
         }
     }
 
-    static ReferenceQueue NULL = new Null();
-    static ReferenceQueue ENQUEUED = new Null();
+    static ReferenceQueue<Object> NULL = new Null<>();
+    static ReferenceQueue<Object> ENQUEUED = new Null<>();
 
     static private class Lock { };
     private Lock lock = new Lock();
@@ -58,7 +58,7 @@
         synchronized (lock) {
             // Check that since getting the lock this reference hasn't already been
             // enqueued (and even then removed)
-            ReferenceQueue queue = r.queue;
+            ReferenceQueue<?> queue = r.queue;
             if ((queue == NULL) || (queue == ENQUEUED)) {
                 return false;
             }
@@ -75,10 +75,13 @@
         }
     }
 
+    @SuppressWarnings("unchecked")
     private Reference<? extends T> reallyPoll() {       /* Must hold lock */
         Reference<? extends T> r = head;
         if (r != null) {
-            head = (r.next == r) ? null : r.next;
+            head = (r.next == r) ?
+                null :
+                r.next; // Unchecked due to the next field having a raw type in Reference
             r.queue = NULL;
             r.next = r;
             queueLength--;
--- a/jdk/src/share/classes/java/lang/reflect/Parameter.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/lang/reflect/Parameter.java	Thu Aug 01 17:24:26 2013 -0700
@@ -162,7 +162,7 @@
 
     /**
      * Returns the name of the parameter.  If the parameter's name is
-     * {@linkplain isNamePresent() present}, then this method returns
+     * {@linkplain #isNamePresent() present}, then this method returns
      * the name provided by the class file. Otherwise, this method
      * synthesizes a name of the form argN, where N is the index of
      * the parameter in the descriptor of the method which declares
--- a/jdk/src/share/classes/java/math/BigInteger.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/math/BigInteger.java	Thu Aug 01 17:24:26 2013 -0700
@@ -33,7 +33,6 @@
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.io.ObjectStreamField;
-import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Random;
 import sun.misc.DoubleConsts;
@@ -101,6 +100,7 @@
  * @author  Josh Bloch
  * @author  Michael McCloskey
  * @author  Alan Eliasen
+ * @author  Timothy Buktu
  * @since JDK1.1
  */
 
@@ -215,6 +215,14 @@
     private static final int TOOM_COOK_SQUARE_THRESHOLD = 140;
 
     /**
+     * The threshold value for using Burnikel-Ziegler division.  If the number
+     * of ints in the number are larger than this value,
+     * Burnikel-Ziegler division will be used.   This value is found
+     * experimentally to work well.
+     */
+    static final int BURNIKEL_ZIEGLER_THRESHOLD = 50;
+
+    /**
      * The threshold value for using Schoenhage recursive base conversion. If
      * the number of ints in the number are larger than this value,
      * the Schoenhage algorithm will be used.  In practice, it appears that the
@@ -290,7 +298,7 @@
         if (signum < -1 || signum > 1)
             throw(new NumberFormatException("Invalid signum value"));
 
-        if (this.mag.length==0) {
+        if (this.mag.length == 0) {
             this.signum = 0;
         } else {
             if (signum == 0)
@@ -311,7 +319,7 @@
         if (signum < -1 || signum > 1)
             throw(new NumberFormatException("Invalid signum value"));
 
-        if (this.mag.length==0) {
+        if (this.mag.length == 0) {
             this.signum = 0;
         } else {
             if (signum == 0)
@@ -364,8 +372,10 @@
 
         // Skip leading zeros and compute number of digits in magnitude
         while (cursor < len &&
-               Character.digit(val.charAt(cursor), radix) == 0)
+               Character.digit(val.charAt(cursor), radix) == 0) {
             cursor++;
+        }
+
         if (cursor == len) {
             signum = 0;
             mag = ZERO.mag;
@@ -455,7 +465,7 @@
         if (result == -1)
             throw new NumberFormatException(new String(source));
 
-        for (int index = start; index<end; index++) {
+        for (int index = start; index < end; index++) {
             int nextVal = Character.digit(source[index], 10);
             if (nextVal == -1)
                 throw new NumberFormatException(new String(source));
@@ -622,9 +632,9 @@
         int highBit = 1 << ((bitLength+31) & 0x1f);  // High bit of high int
         int highMask = (highBit << 1) - 1;  // Bits to keep in high int
 
-        while(true) {
+        while (true) {
             // Construct a candidate
-            for (int i=0; i<magLen; i++)
+            for (int i=0; i < magLen; i++)
                 temp[i] = rnd.nextInt();
             temp[0] = (temp[0] & highMask) | highBit;  // Ensure exact length
             if (bitLength > 2)
@@ -710,7 +720,7 @@
             if (!result.testBit(0))
                 result = result.add(ONE);
 
-            while(true) {
+            while (true) {
                 // Do cheap "pre-test" if applicable
                 if (result.bitLength() > 6) {
                     long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();
@@ -741,7 +751,7 @@
         // Looking for the next large prime
         int searchLen = (result.bitLength() / 20) * 64;
 
-        while(true) {
+        while (true) {
            BitSieve searchSieve = new BitSieve(result, searchLen);
            BigInteger candidate = searchSieve.retrieve(result,
                                                  DEFAULT_PRIME_CERTAINTY, null);
@@ -808,7 +818,7 @@
         int d = 5;
         while (jacobiSymbol(d, this) != -1) {
             // 5, -7, 9, -11, ...
-            d = (d<0) ? Math.abs(d)+2 : -(d+2);
+            d = (d < 0) ? Math.abs(d)+2 : -(d+2);
         }
 
         // Step 2
@@ -881,7 +891,7 @@
         BigInteger u = ONE; BigInteger u2;
         BigInteger v = ONE; BigInteger v2;
 
-        for (int i=k.bitLength()-2; i>=0; i--) {
+        for (int i=k.bitLength()-2; i >= 0; i--) {
             u2 = u.multiply(v).mod(n);
 
             v2 = v.square().add(d.multiply(u.square())).mod(n);
@@ -937,7 +947,7 @@
         if (rnd == null) {
             rnd = getSecureRandom();
         }
-        for (int i=0; i<iterations; i++) {
+        for (int i=0; i < iterations; i++) {
             // Generate a uniform random on (1, this)
             BigInteger b;
             do {
@@ -946,8 +956,8 @@
 
             int j = 0;
             BigInteger z = b.modPow(m, this);
-            while(!((j==0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
-                if (j>0 && z.equals(ONE) || ++j==a)
+            while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
+                if (j > 0 && z.equals(ONE) || ++j == a)
                     return false;
                 z = z.modPow(TWO, this);
             }
@@ -961,7 +971,7 @@
      * arguments are correct, and it doesn't copy the magnitude array.
      */
     BigInteger(int[] magnitude, int signum) {
-        this.signum = (magnitude.length==0 ? 0 : signum);
+        this.signum = (magnitude.length == 0 ? 0 : signum);
         this.mag = magnitude;
     }
 
@@ -970,7 +980,7 @@
      * arguments are correct.
      */
     private BigInteger(byte[] magnitude, int signum) {
-        this.signum = (magnitude.length==0 ? 0 : signum);
+        this.signum = (magnitude.length == 0 ? 0 : signum);
         this.mag = stripLeadingZeroBytes(magnitude);
     }
 
@@ -1009,7 +1019,7 @@
         }
 
         int highWord = (int)(val >>> 32);
-        if (highWord==0) {
+        if (highWord == 0) {
             mag = new int[1];
             mag[0] = (int)val;
         } else {
@@ -1025,7 +1035,7 @@
      * BigInteger will reference the input array if feasible).
      */
     private static BigInteger valueOf(int val[]) {
-        return (val[0]>0 ? new BigInteger(val, 1) : new BigInteger(val));
+        return (val[0] > 0 ? new BigInteger(val, 1) : new BigInteger(val));
     }
 
     // Constants
@@ -1066,8 +1076,7 @@
         powerCache = new BigInteger[Character.MAX_RADIX+1][];
         logCache = new double[Character.MAX_RADIX+1];
 
-        for (int i=Character.MIN_RADIX; i<=Character.MAX_RADIX; i++)
-        {
+        for (int i=Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) {
             powerCache[i] = new BigInteger[] { BigInteger.valueOf(i) };
             logCache[i] = Math.log(i);
         }
@@ -1161,7 +1170,7 @@
         int xIndex = x.length;
         int[] result;
         int highWord = (int)(val >>> 32);
-        if (highWord==0) {
+        if (highWord == 0) {
             result = new int[xIndex];
             sum = (x[--xIndex] & LONG_MASK) + val;
             result[xIndex] = (int)sum;
@@ -1214,12 +1223,12 @@
         int yIndex = y.length;
         int result[] = new int[xIndex];
         long sum = 0;
-        if(yIndex==1) {
+        if (yIndex == 1) {
             sum = (x[--xIndex] & LONG_MASK) + (y[0] & LONG_MASK) ;
             result[xIndex] = (int)sum;
         } else {
             // Add common parts of both numbers
-            while(yIndex > 0) {
+            while (yIndex > 0) {
                 sum = (x[--xIndex] & LONG_MASK) +
                       (y[--yIndex] & LONG_MASK) + (sum >>> 32);
                 result[xIndex] = (int)sum;
@@ -1246,24 +1255,24 @@
 
     private static int[] subtract(long val, int[] little) {
         int highWord = (int)(val >>> 32);
-        if (highWord==0) {
+        if (highWord == 0) {
             int result[] = new int[1];
             result[0] = (int)(val - (little[0] & LONG_MASK));
             return result;
         } else {
             int result[] = new int[2];
-            if(little.length==1) {
+            if (little.length == 1) {
                 long difference = ((int)val & LONG_MASK) - (little[0] & LONG_MASK);
                 result[1] = (int)difference;
                 // Subtract remainder of longer number while borrow propagates
                 boolean borrow = (difference >> 32 != 0);
-                if(borrow) {
+                if (borrow) {
                     result[0] = highWord - 1;
                 } else {        // Copy remainder of longer number
                     result[0] = highWord;
                 }
                 return result;
-            } else { // little.length==2
+            } else { // little.length == 2
                 long difference = ((int)val & LONG_MASK) - (little[1] & LONG_MASK);
                 result[1] = (int)difference;
                 difference = (highWord & LONG_MASK) - (little[0] & LONG_MASK) + (difference >> 32);
@@ -1286,7 +1295,7 @@
         int result[] = new int[bigIndex];
         long difference = 0;
 
-        if (highWord==0) {
+        if (highWord == 0) {
             difference = (big[--bigIndex] & LONG_MASK) - val;
             result[bigIndex] = (int)difference;
         } else {
@@ -1296,7 +1305,6 @@
             result[bigIndex] = (int)difference;
         }
 
-
         // Subtract remainder of longer number while borrow propagates
         boolean borrow = (difference >> 32 != 0);
         while (bigIndex > 0 && borrow)
@@ -1345,7 +1353,7 @@
         long difference = 0;
 
         // Subtract common parts of both numbers
-        while(littleIndex > 0) {
+        while (littleIndex > 0) {
             difference = (big[--bigIndex] & LONG_MASK) -
                          (little[--littleIndex] & LONG_MASK) +
                          (difference >> 32);
@@ -1377,29 +1385,29 @@
         int xlen = mag.length;
         int ylen = val.mag.length;
 
-        if ((xlen < KARATSUBA_THRESHOLD) || (ylen < KARATSUBA_THRESHOLD))
-        {
+        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) {
+            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);
+        } else {
+            if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) {
+                return multiplyKaratsuba(this, val);
+            } else {
+                return multiplyToomCook3(this, val);
+            }
         }
-        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) {
-        if(Integer.bitCount(y)==1) {
+        if (Integer.bitCount(y) == 1) {
             return new BigInteger(shiftLeft(x,Integer.numberOfTrailingZeros(y)), sign);
         }
         int xlen = x.length;
@@ -1474,7 +1482,7 @@
             z = new int[xlen+ylen];
 
         long carry = 0;
-        for (int j=ystart, k=ystart+1+xstart; j>=0; j--, k--) {
+        for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) {
             long product = (y[j] & LONG_MASK) *
                            (x[xstart] & LONG_MASK) + carry;
             z[k] = (int)product;
@@ -1484,7 +1492,7 @@
 
         for (int i = xstart-1; i >= 0; i--) {
             carry = 0;
-            for (int j=ystart, k=ystart+1+i; j>=0; j--, k--) {
+            for (int j=ystart, k=ystart+1+i; j >= 0; j--, k--) {
                 long product = (y[j] & LONG_MASK) *
                                (x[i] & LONG_MASK) +
                                (z[k] & LONG_MASK) + carry;
@@ -1511,8 +1519,7 @@
      *
      * See:  http://en.wikipedia.org/wiki/Karatsuba_algorithm
      */
-    private static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y)
-    {
+    private static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y) {
         int xlen = x.mag.length;
         int ylen = y.mag.length;
 
@@ -1535,10 +1542,11 @@
         // 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)
+        if (x.signum != y.signum) {
             return result.negate();
-        else
+        } else {
             return result;
+        }
     }
 
     /**
@@ -1569,8 +1577,7 @@
      * LNCS #4547. Springer, Madrid, Spain, June 21-22, 2007.
      *
      */
-    private static BigInteger multiplyToomCook3(BigInteger a, BigInteger b)
-    {
+    private static BigInteger multiplyToomCook3(BigInteger a, BigInteger b) {
         int alen = a.mag.length;
         int blen = b.mag.length;
 
@@ -1605,12 +1612,12 @@
              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. */
+        // 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);
@@ -1624,10 +1631,11 @@
 
         BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
 
-        if (a.signum != b.signum)
+        if (a.signum != b.signum) {
             return result.negate();
-        else
+        } else {
             return result;
+        }
     }
 
 
@@ -1645,38 +1653,38 @@
      * numbers.
      */
     private BigInteger getToomSlice(int lowerSize, int upperSize, int slice,
-                                    int fullsize)
-    {
+                                    int fullsize) {
         int start, end, sliceSize, len, offset;
 
         len = mag.length;
         offset = fullsize - len;
 
-        if (slice == 0)
-        {
+        if (slice == 0) {
             start = 0 - offset;
             end = upperSize - 1 - offset;
-        }
-        else
-        {
+        } else {
             start = upperSize + (slice-1)*lowerSize - offset;
             end = start + lowerSize - 1;
         }
 
-        if (start < 0)
+        if (start < 0) {
             start = 0;
-        if (end < 0)
+        }
+        if (end < 0) {
            return ZERO;
+        }
 
         sliceSize = (end-start) + 1;
 
-        if (sliceSize <= 0)
+        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)
+        if (start == 0 && sliceSize >= len) {
             return this.abs();
+        }
 
         int intSlice[] = new int[sliceSize];
         System.arraycopy(mag, start, intSlice, 0, sliceSize);
@@ -1692,20 +1700,19 @@
      * undefined.  Note that this is expected to be called with positive
      * arguments only.
      */
-    private BigInteger exactDivideBy3()
-    {
+    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--)
-        {
+        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?
+            if (borrow > x) {      // Did we make the number go negative?
                 borrow = 1L;
-            else
+            } 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).
@@ -1715,8 +1722,7 @@
 
             // Now check the borrow. The second check can of course be
             // eliminated if the first fails.
-            if (q >= 0x55555556L)
-            {
+            if (q >= 0x55555556L) {
                 borrow++;
                 if (q >= 0xAAAAAAABL)
                     borrow++;
@@ -1733,8 +1739,9 @@
     private BigInteger getLower(int n) {
         int len = mag.length;
 
-        if (len <= n)
+        if (len <= n) {
             return this;
+        }
 
         int lowerInts[] = new int[n];
         System.arraycopy(mag, len-n, lowerInts, 0, n);
@@ -1750,8 +1757,9 @@
     private BigInteger getUpper(int n) {
         int len = mag.length;
 
-        if (len <= n)
+        if (len <= n) {
             return ZERO;
+        }
 
         int upperLen = len - n;
         int upperInts[] = new int[upperLen];
@@ -1768,20 +1776,21 @@
      * @return {@code this<sup>2</sup>}
      */
     private BigInteger square() {
-        if (signum == 0)
+        if (signum == 0) {
             return ZERO;
+        }
         int len = mag.length;
 
-        if (len < KARATSUBA_SQUARE_THRESHOLD)
-        {
+        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();
+            }
         }
-        else
-            if (len < TOOM_COOK_SQUARE_THRESHOLD)
-                return squareKaratsuba();
-            else
-               return squareToomCook3();
     }
 
     /**
@@ -1829,7 +1838,7 @@
 
         // Store the squares, right shifted one bit (i.e., divided by 2)
         int lastProductLowWord = 0;
-        for (int j=0, i=0; j<len; j++) {
+        for (int j=0, i=0; j < len; j++) {
             long piece = (x[j] & LONG_MASK);
             long product = piece * piece;
             z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33);
@@ -1838,7 +1847,7 @@
         }
 
         // Add in off-diagonal sums
-        for (int i=len, offset=1; i>0; i--, offset+=2) {
+        for (int i=len, offset=1; i > 0; i--, offset+=2) {
             int t = x[i-1];
             t = mulAdd(z, x, offset, i-1, t);
             addOne(z, offset-1, i, t);
@@ -1858,8 +1867,7 @@
      * has better asymptotic performance than the algorithm used in
      * squareToLen.
      */
-    private BigInteger squareKaratsuba()
-    {
+    private BigInteger squareKaratsuba() {
         int half = (mag.length+1) / 2;
 
         BigInteger xl = getLower(half);
@@ -1879,8 +1887,7 @@
      * that has better asymptotic performance than the algorithm used in
      * squareToLen or squareKaratsuba.
      */
-    private BigInteger squareToomCook3()
-    {
+    private BigInteger squareToomCook3() {
         int len = mag.length;
 
         // k is the size (in ints) of the lower-order slices.
@@ -1905,13 +1912,12 @@
         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.
-        */
+        // 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);
@@ -1936,11 +1942,28 @@
      * @throws ArithmeticException if {@code val} is zero.
      */
     public BigInteger divide(BigInteger val) {
+        if (mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
+                val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD) {
+            return divideKnuth(val);
+        } else {
+            return divideBurnikelZiegler(val);
+        }
+    }
+
+    /**
+     * Returns a BigInteger whose value is {@code (this / val)} using an O(n^2) algorithm from Knuth.
+     *
+     * @param  val value by which this BigInteger is to be divided.
+     * @return {@code this / val}
+     * @throws ArithmeticException if {@code val} is zero.
+     * @see MutableBigInteger#divideKnuth(MutableBigInteger, MutableBigInteger, boolean)
+     */
+    private BigInteger divideKnuth(BigInteger val) {
         MutableBigInteger q = new MutableBigInteger(),
                           a = new MutableBigInteger(this.mag),
                           b = new MutableBigInteger(val.mag);
 
-        a.divide(b, q, false);
+        a.divideKnuth(b, q, false);
         return q.toBigInteger(this.signum * val.signum);
     }
 
@@ -1956,11 +1979,21 @@
      * @throws ArithmeticException if {@code val} is zero.
      */
     public BigInteger[] divideAndRemainder(BigInteger val) {
+        if (mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
+                val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD) {
+            return divideAndRemainderKnuth(val);
+        } else {
+            return divideAndRemainderBurnikelZiegler(val);
+        }
+    }
+
+    /** Long division */
+    private BigInteger[] divideAndRemainderKnuth(BigInteger val) {
         BigInteger[] result = new BigInteger[2];
         MutableBigInteger q = new MutableBigInteger(),
                           a = new MutableBigInteger(this.mag),
                           b = new MutableBigInteger(val.mag);
-        MutableBigInteger r = a.divide(b, q);
+        MutableBigInteger r = a.divideKnuth(b, q);
         result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1);
         result[1] = r.toBigInteger(this.signum);
         return result;
@@ -1975,11 +2008,53 @@
      * @throws ArithmeticException if {@code val} is zero.
      */
     public BigInteger remainder(BigInteger val) {
+        if (mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
+                val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD) {
+            return remainderKnuth(val);
+        } else {
+            return remainderBurnikelZiegler(val);
+        }
+    }
+
+    /** Long division */
+    private BigInteger remainderKnuth(BigInteger val) {
         MutableBigInteger q = new MutableBigInteger(),
                           a = new MutableBigInteger(this.mag),
                           b = new MutableBigInteger(val.mag);
 
-        return a.divide(b, q).toBigInteger(this.signum);
+        return a.divideKnuth(b, q).toBigInteger(this.signum);
+    }
+
+    /**
+     * Calculates {@code this / val} using the Burnikel-Ziegler algorithm.
+     * @param  val the divisor
+     * @return {@code this / val}
+     */
+    private BigInteger divideBurnikelZiegler(BigInteger val) {
+        return divideAndRemainderBurnikelZiegler(val)[0];
+    }
+
+    /**
+     * Calculates {@code this % val} using the Burnikel-Ziegler algorithm.
+     * @param val the divisor
+     * @return {@code this % val}
+     */
+    private BigInteger remainderBurnikelZiegler(BigInteger val) {
+        return divideAndRemainderBurnikelZiegler(val)[1];
+    }
+
+    /**
+     * Computes {@code this / val} and {@code this % val} using the
+     * Burnikel-Ziegler algorithm.
+     * @param val the divisor
+     * @return an array containing the quotient and remainder
+     */
+    private BigInteger[] divideAndRemainderBurnikelZiegler(BigInteger val) {
+        MutableBigInteger q = new MutableBigInteger();
+        MutableBigInteger r = new MutableBigInteger(this).divideAndRemainderBurnikelZiegler(new MutableBigInteger(val), q);
+        BigInteger qBigInt = q.isZero() ? ZERO : q.toBigInteger(signum*val.signum);
+        BigInteger rBigInt = r.isZero() ? ZERO : r.toBigInteger(signum);
+        return new BigInteger[] {qBigInt, rBigInt};
     }
 
     /**
@@ -1992,10 +2067,12 @@
      *         cause the operation to yield a non-integer value.)
      */
     public BigInteger pow(int exponent) {
-        if (exponent < 0)
+        if (exponent < 0) {
             throw new ArithmeticException("Negative exponent");
-        if (signum==0)
-            return (exponent==0 ? ONE : this);
+        }
+        if (signum == 0) {
+            return (exponent == 0 ? ONE : this);
+        }
 
         BigInteger partToSquare = this.abs();
 
@@ -2008,24 +2085,25 @@
         int remainingBits;
 
         // Factor the powers of two out quickly by shifting right, if needed.
-        if (powersOfTwo > 0)
-        {
+        if (powersOfTwo > 0) {
             partToSquare = partToSquare.shiftRight(powersOfTwo);
             remainingBits = partToSquare.bitLength();
-            if (remainingBits == 1)  // Nothing left but +/- 1?
-                if (signum<0 && (exponent&1)==1)
+            if (remainingBits == 1) {  // Nothing left but +/- 1?
+                if (signum < 0 && (exponent&1) == 1) {
                     return NEGATIVE_ONE.shiftLeft(powersOfTwo*exponent);
-                else
+                } else {
                     return ONE.shiftLeft(powersOfTwo*exponent);
-        }
-        else
-        {
+                }
+            }
+        } else {
             remainingBits = partToSquare.bitLength();
-            if (remainingBits == 1)  // Nothing left but +/- 1?
-                if (signum<0 && (exponent&1)==1)
+            if (remainingBits == 1) { // Nothing left but +/- 1?
+                if (signum < 0  && (exponent&1) == 1) {
                     return NEGATIVE_ONE;
-                else
+                } else {
                     return ONE;
+                }
+            }
         }
 
         // This is a quick way to approximate the size of the result,
@@ -2035,10 +2113,9 @@
 
         // 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)
-        {
+        if (partToSquare.mag.length == 1 && scaleFactor <= 62) {
             // Small number algorithm.  Everything fits into a long.
-            int newSign = (signum<0 && (exponent&1)==1 ? -1 : 1);
+            int newSign = (signum <0  && (exponent&1) == 1 ? -1 : 1);
             long result = 1;
             long baseToPow2 = partToSquare.mag[0] & LONG_MASK;
 
@@ -2046,27 +2123,28 @@
 
             // Perform exponentiation using repeated squaring trick
             while (workingExponent != 0) {
-                if ((workingExponent & 1)==1)
+                if ((workingExponent & 1) == 1) {
                     result = result * baseToPow2;
-
-                if ((workingExponent >>>= 1) != 0)
+                }
+
+                if ((workingExponent >>>= 1) != 0) {
                     baseToPow2 = baseToPow2 * baseToPow2;
+                }
             }
 
             // Multiply back the powers of two (quickly, by shifting left)
-            if (powersOfTwo > 0)
-            {
+            if (powersOfTwo > 0) {
                 int bitsToShift = powersOfTwo*exponent;
-                if (bitsToShift + scaleFactor <= 62) // Fits in long?
+                if (bitsToShift + scaleFactor <= 62) { // Fits in long?
                     return valueOf((result << bitsToShift) * newSign);
-                else
+                } else {
                     return valueOf(result*newSign).shiftLeft(bitsToShift);
+                }
             }
-            else
+            else {
                 return valueOf(result*newSign);
-        }
-        else
-        {
+            }
+        } 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.
@@ -2075,28 +2153,32 @@
             int workingExponent = exponent;
             // Perform exponentiation using repeated squaring trick
             while (workingExponent != 0) {
-                if ((workingExponent & 1)==1)
+                if ((workingExponent & 1) == 1) {
                     answer = answer.multiply(partToSquare);
-
-                if ((workingExponent >>>= 1) != 0)
+                }
+
+                if ((workingExponent >>>= 1) != 0) {
                     partToSquare = partToSquare.square();
+                }
             }
             // Multiply back the (exponentiated) powers of two (quickly,
             // by shifting left)
-            if (powersOfTwo > 0)
+            if (powersOfTwo > 0) {
                 answer = answer.shiftLeft(powersOfTwo*exponent);
-
-            if (signum<0 && (exponent&1)==1)
+            }
+
+            if (signum < 0 && (exponent&1) == 1) {
                 return answer.negate();
-            else
+            } else {
                 return answer;
+            }
         }
     }
 
     /**
      * Returns a BigInteger whose value is the greatest common divisor of
      * {@code abs(this)} and {@code abs(val)}.  Returns 0 if
-     * {@code this==0 && val==0}.
+     * {@code this == 0 && val == 0}.
      *
      * @param  val value with which the GCD is to be computed.
      * @return {@code GCD(abs(this), abs(val))}
@@ -2153,7 +2235,7 @@
     // shifts a up to len right n bits assumes no leading zeros, 0<n<32
     static void primitiveRightShift(int[] a, int len, int n) {
         int n2 = 32 - n;
-        for (int i=len-1, c=a[i]; i>0; i--) {
+        for (int i=len-1, c=a[i]; i > 0; i--) {
             int b = c;
             c = a[i-1];
             a[i] = (c << n2) | (b >>> n);
@@ -2167,7 +2249,7 @@
             return;
 
         int n2 = 32 - n;
-        for (int i=0, c=a[i], m=i+len-1; i<m; i++) {
+        for (int i=0, c=a[i], m=i+len-1; i < m; i++) {
             int b = c;
             c = a[i+1];
             a[i] = (b << n) | (c >>> n2);
@@ -2378,7 +2460,7 @@
             return this;
 
         // Special case for base of zero
-        if (signum==0)
+        if (signum == 0)
             return ZERO;
 
         int[] base = mag.clone();
@@ -2401,7 +2483,7 @@
 
         // Allocate table for precomputed odd powers of base in Montgomery form
         int[][] table = new int[tblmask][];
-        for (int i=0; i<tblmask; i++)
+        for (int i=0; i < tblmask; i++)
             table[i] = new int[modLen];
 
         // Compute the modular inverse
@@ -2421,7 +2503,7 @@
         if (table[0].length < modLen) {
            int offset = modLen - table[0].length;
            int[] t2 = new int[modLen];
-           for (int i=0; i<table[0].length; i++)
+           for (int i=0; i < table[0].length; i++)
                t2[i+offset] = table[0][i];
            table[0] = t2;
         }
@@ -2434,7 +2516,7 @@
         int[] t = Arrays.copyOf(b, modLen);
 
         // Fill in the table with odd powers of the base
-        for (int i=1; i<tblmask; i++) {
+        for (int i=1; i < tblmask; i++) {
             int[] prod = multiplyToLen(t, modLen, table[i-1], modLen, null);
             table[i] = montReduce(prod, mod, modLen, inv);
         }
@@ -2474,7 +2556,7 @@
             isone = false;
 
         // The main loop
-        while(true) {
+        while (true) {
             ebits--;
             // Advance the window
             buf <<= 1;
@@ -2551,9 +2633,9 @@
             int carry = mulAdd(n, mod, offset, mlen, inv * nEnd);
             c += addOne(n, offset, mlen, carry);
             offset++;
-        } while(--len > 0);
-
-        while(c>0)
+        } while (--len > 0);
+
+        while (c > 0)
             c += subN(n, mod, mlen);
 
         while (intArrayCmpToLen(n, mod, mlen) >= 0)
@@ -2568,7 +2650,7 @@
      * equal to, or greater than arg2 up to length len.
      */
     private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) {
-        for (int i=0; i<len; i++) {
+        for (int i=0; i < len; i++) {
             long b1 = arg1[i] & LONG_MASK;
             long b2 = arg2[i] & LONG_MASK;
             if (b1 < b2)
@@ -2585,7 +2667,7 @@
     private static int subN(int[] a, int[] b, int len) {
         long sum = 0;
 
-        while(--len >= 0) {
+        while (--len >= 0) {
             sum = (a[len] & LONG_MASK) -
                  (b[len] & LONG_MASK) + (sum >> 32);
             a[len] = (int)sum;
@@ -2679,7 +2761,7 @@
         int excessBits = (numInts << 5) - p;
         mag[0] &= (1L << (32-excessBits)) - 1;
 
-        return (mag[0]==0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));
+        return (mag[0] == 0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));
     }
 
     /**
@@ -2730,9 +2812,9 @@
     public BigInteger shiftLeft(int n) {
         if (signum == 0)
             return ZERO;
-        if (n==0)
+        if (n == 0)
             return this;
-        if (n<0) {
+        if (n < 0) {
             if (n == Integer.MIN_VALUE) {
                 throw new ArithmeticException("Shift distance of Integer.MIN_VALUE not supported.");
             } else {
@@ -2784,9 +2866,9 @@
      * @see #shiftLeft
      */
     public BigInteger shiftRight(int n) {
-        if (n==0)
+        if (n == 0)
             return this;
-        if (n<0) {
+        if (n < 0) {
             if (n == Integer.MIN_VALUE) {
                 throw new ArithmeticException("Shift distance of Integer.MIN_VALUE not supported.");
             } else {
@@ -2825,7 +2907,7 @@
         if (signum < 0) {
             // Find out whether any one-bits were shifted off the end.
             boolean onesLost = false;
-            for (int i=magLen-1, j=magLen-nInts; i>=j && !onesLost; i--)
+            for (int i=magLen-1, j=magLen-nInts; i >= j && !onesLost; i--)
                 onesLost = (mag[i] != 0);
             if (!onesLost && nBits != 0)
                 onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);
@@ -2860,7 +2942,7 @@
      */
     public BigInteger and(BigInteger val) {
         int[] result = new int[Math.max(intLength(), val.intLength())];
-        for (int i=0; i<result.length; i++)
+        for (int i=0; i < result.length; i++)
             result[i] = (getInt(result.length-i-1)
                          & val.getInt(result.length-i-1));
 
@@ -2877,7 +2959,7 @@
      */
     public BigInteger or(BigInteger val) {
         int[] result = new int[Math.max(intLength(), val.intLength())];
-        for (int i=0; i<result.length; i++)
+        for (int i=0; i < result.length; i++)
             result[i] = (getInt(result.length-i-1)
                          | val.getInt(result.length-i-1));
 
@@ -2894,7 +2976,7 @@
      */
     public BigInteger xor(BigInteger val) {
         int[] result = new int[Math.max(intLength(), val.intLength())];
-        for (int i=0; i<result.length; i++)
+        for (int i=0; i < result.length; i++)
             result[i] = (getInt(result.length-i-1)
                          ^ val.getInt(result.length-i-1));
 
@@ -2910,7 +2992,7 @@
      */
     public BigInteger not() {
         int[] result = new int[intLength()];
-        for (int i=0; i<result.length; i++)
+        for (int i=0; i < result.length; i++)
             result[i] = ~getInt(result.length-i-1);
 
         return valueOf(result);
@@ -2928,7 +3010,7 @@
      */
     public BigInteger andNot(BigInteger val) {
         int[] result = new int[Math.max(intLength(), val.intLength())];
-        for (int i=0; i<result.length; i++)
+        for (int i=0; i < result.length; i++)
             result[i] = (getInt(result.length-i-1)
                          & ~val.getInt(result.length-i-1));
 
@@ -2947,7 +3029,7 @@
      * @throws ArithmeticException {@code n} is negative.
      */
     public boolean testBit(int n) {
-        if (n<0)
+        if (n < 0)
             throw new ArithmeticException("Negative bit address");
 
         return (getInt(n >>> 5) & (1 << (n & 31))) != 0;
@@ -2962,13 +3044,13 @@
      * @throws ArithmeticException {@code n} is negative.
      */
     public BigInteger setBit(int n) {
-        if (n<0)
+        if (n < 0)
             throw new ArithmeticException("Negative bit address");
 
         int intNum = n >>> 5;
         int[] result = new int[Math.max(intLength(), intNum+2)];
 
-        for (int i=0; i<result.length; i++)
+        for (int i=0; i < result.length; i++)
             result[result.length-i-1] = getInt(i);
 
         result[result.length-intNum-1] |= (1 << (n & 31));
@@ -2986,13 +3068,13 @@
      * @throws ArithmeticException {@code n} is negative.
      */
     public BigInteger clearBit(int n) {
-        if (n<0)
+        if (n < 0)
             throw new ArithmeticException("Negative bit address");
 
         int intNum = n >>> 5;
         int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)];
 
-        for (int i=0; i<result.length; i++)
+        for (int i=0; i < result.length; i++)
             result[result.length-i-1] = getInt(i);
 
         result[result.length-intNum-1] &= ~(1 << (n & 31));
@@ -3010,13 +3092,13 @@
      * @throws ArithmeticException {@code n} is negative.
      */
     public BigInteger flipBit(int n) {
-        if (n<0)
+        if (n < 0)
             throw new ArithmeticException("Negative bit address");
 
         int intNum = n >>> 5;
         int[] result = new int[Math.max(intLength(), intNum+2)];
 
-        for (int i=0; i<result.length; i++)
+        for (int i=0; i < result.length; i++)
             result[result.length-i-1] = getInt(i);
 
         result[result.length-intNum-1] ^= (1 << (n & 31));
@@ -3028,7 +3110,7 @@
      * Returns the index of the rightmost (lowest-order) one bit in this
      * BigInteger (the number of zero bits to the right of the rightmost
      * one bit).  Returns -1 if this BigInteger contains no one bits.
-     * (Computes {@code (this==0? -1 : log2(this & -this))}.)
+     * (Computes {@code (this == 0? -1 : log2(this & -this))}.)
      *
      * @return index of the rightmost one bit in this BigInteger.
      */
@@ -3041,7 +3123,7 @@
             } else {
                 // Search for lowest order nonzero int
                 int i,b;
-                for (i=0; (b = getInt(i))==0; i++)
+                for (i=0; (b = getInt(i)) == 0; i++)
                     ;
                 lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
             }
@@ -3102,12 +3184,12 @@
         if (bc == -1) {  // bitCount not initialized yet
             bc = 0;      // offset by one to initialize
             // Count the bits in the magnitude
-            for (int i=0; i<mag.length; i++)
+            for (int i=0; i < mag.length; i++)
                 bc += Integer.bitCount(mag[i]);
             if (signum < 0) {
                 // Count the trailing zeros in the magnitude
                 int magTrailingZeroCount = 0, j;
-                for (j=mag.length-1; mag[j]==0; j--)
+                for (j=mag.length-1; mag[j] == 0; j--)
                     magTrailingZeroCount += 32;
                 magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
                 bc += magTrailingZeroCount - 1;
@@ -3208,14 +3290,14 @@
         assert val != Long.MIN_VALUE;
         int[] m1 = mag;
         int len = m1.length;
-        if(len > 2) {
+        if (len > 2) {
             return 1;
         }
         if (val < 0) {
             val = -val;
         }
         int highWord = (int)(val >>> 32);
-        if (highWord==0) {
+        if (highWord == 0) {
             if (len < 1)
                 return -1;
             if (len > 1)
@@ -3283,7 +3365,7 @@
      *         {@code val}.  If they are equal, either may be returned.
      */
     public BigInteger min(BigInteger val) {
-        return (compareTo(val)<0 ? this : val);
+        return (compareTo(val) < 0 ? this : val);
     }
 
     /**
@@ -3294,7 +3376,7 @@
      *         {@code val}.  If they are equal, either may be returned.
      */
     public BigInteger max(BigInteger val) {
-        return (compareTo(val)>0 ? this : val);
+        return (compareTo(val) > 0 ? this : val);
     }
 
 
@@ -3308,7 +3390,7 @@
     public int hashCode() {
         int hashCode = 0;
 
-        for (int i=0; i<mag.length; i++)
+        for (int i=0; i < mag.length; i++)
             hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK));
 
         return hashCode * signum;
@@ -3356,8 +3438,9 @@
 
     /** This method is used to perform toString when arguments are small. */
     private String smallToString(int radix) {
-        if (signum == 0)
+        if (signum == 0) {
             return "0";
+        }
 
         // Compute upper bound on number of digit groups and allocate space
         int maxNumDigitGroups = (4*mag.length + 6)/7;
@@ -3382,16 +3465,18 @@
 
         // Put sign (if any) and first digit group into result buffer
         StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1);
-        if (signum<0)
+        if (signum < 0) {
             buf.append('-');
+        }
         buf.append(digitGroup[numGroups-1]);
 
         // Append remaining digit groups padded with leading zeros
-        for (int i=numGroups-2; i>=0; i--) {
+        for (int i=numGroups-2; i >= 0; i--) {
             // Prepend (any) leading zeros for this digit group
             int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length();
-            if (numLeadingZeros != 0)
+            if (numLeadingZeros != 0) {
                 buf.append(zeros[numLeadingZeros]);
+            }
             buf.append(digitGroup[i]);
         }
         return buf.toString();
@@ -3399,7 +3484,7 @@
 
     /**
      * Converts the specified BigInteger to a string and appends to
-     * <code>sb</code>.  This implements the recursive Schoenhage algorithm
+     * {@code sb}.  This implements the recursive Schoenhage algorithm
      * for base conversions.
      * <p/>
      * See Knuth, Donald,  _The Art of Computer Programming_, Vol. 2,
@@ -3419,9 +3504,11 @@
 
             // Pad with internal zeros if necessary.
             // Don't pad if we're at the beginning of the string.
-            if ((s.length() < digits) && (sb.length() > 0))
-                for (int i=s.length(); i<digits; i++) // May be a faster way to
+            if ((s.length() < digits) && (sb.length() > 0)) {
+                for (int i=s.length(); i < digits; i++) { // May be a faster way to
                     sb.append('0');                    // do this?
+                }
+            }
 
             sb.append(s);
             return;
@@ -3450,7 +3537,7 @@
      * If this value doesn't already exist in the cache, it is added.
      * <p/>
      * This could be changed to a more complicated caching method using
-     * <code>Future</code>.
+     * {@code Future}.
      */
     private static BigInteger getRadixConversionCache(int radix, int exponent) {
         BigInteger[] cacheLine = powerCache[radix]; // volatile read
@@ -3478,7 +3565,7 @@
     static {
         zeros[63] =
             "000000000000000000000000000000000000000000000000000000000000000";
-        for (int i=0; i<63; i++)
+        for (int i=0; i < 63; i++)
             zeros[i] = zeros[63].substring(0, i);
     }
 
@@ -3516,7 +3603,7 @@
         int byteLen = bitLength()/8 + 1;
         byte[] byteArray = new byte[byteLen];
 
-        for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i>=0; i--) {
+        for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) {
             if (bytesCopied == 4) {
                 nextInt = getInt(intIndex++);
                 bytesCopied = 1;
@@ -3568,7 +3655,7 @@
     public long longValue() {
         long result = 0;
 
-        for (int i=1; i>=0; i--)
+        for (int i=1; i >= 0; i--)
             result = (result << 32) + (getInt(i) & LONG_MASK);
         return result;
     }
@@ -3784,7 +3871,7 @@
         int keep;
 
         // Find first nonzero byte
-        for (keep = 0; keep < byteLength && a[keep]==0; keep++)
+        for (keep = 0; keep < byteLength && a[keep] == 0; keep++)
             ;
 
         // Allocate new array and copy relevant part of input array
@@ -3810,16 +3897,16 @@
         int byteLength = a.length;
 
         // Find first non-sign (0xff) byte of input
-        for (keep=0; keep<byteLength && a[keep]==-1; keep++)
+        for (keep=0; keep < byteLength && a[keep] == -1; keep++)
             ;
 
 
         /* Allocate output array.  If all non-sign bytes are 0x00, we must
          * allocate space for one extra output byte. */
-        for (k=keep; k<byteLength && a[k]==0; k++)
+        for (k=keep; k < byteLength && a[k] == 0; k++)
             ;
 
-        int extraByte = (k==byteLength) ? 1 : 0;
+        int extraByte = (k == byteLength) ? 1 : 0;
         int intLength = ((byteLength - keep + extraByte) + 3)/4;
         int result[] = new int[intLength];
 
@@ -3840,7 +3927,7 @@
         }
 
         // Add one to one's complement to generate two's complement
-        for (int i=result.length-1; i>=0; i--) {
+        for (int i=result.length-1; i >= 0; i--) {
             result[i] = (int)((result[i] & LONG_MASK) + 1);
             if (result[i] != 0)
                 break;
@@ -3857,23 +3944,23 @@
         int keep, j;
 
         // Find first non-sign (0xffffffff) int of input
-        for (keep=0; keep<a.length && a[keep]==-1; keep++)
+        for (keep=0; keep < a.length && a[keep] == -1; keep++)
             ;
 
         /* Allocate output array.  If all non-sign ints are 0x00, we must
          * allocate space for one extra output int. */
-        for (j=keep; j<a.length && a[j]==0; j++)
+        for (j=keep; j < a.length && a[j] == 0; j++)
             ;
-        int extraInt = (j==a.length ? 1 : 0);
+        int extraInt = (j == a.length ? 1 : 0);
         int result[] = new int[a.length - keep + extraInt];
 
         /* Copy one's complement of input into output, leaving extra
          * int (if it exists) == 0x00 */
-        for (int i = keep; i<a.length; i++)
+        for (int i = keep; i < a.length; i++)
             result[i - keep + extraInt] = ~a[i];
 
         // Add one to one's complement to generate two's complement
-        for (int i=result.length-1; ++result[i]==0; i--)
+        for (int i=result.length-1; ++result[i] == 0; i--)
             ;
 
         return result;
@@ -4131,7 +4218,7 @@
         byte[] result = new byte[byteLen];
 
         for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0;
-             i>=0; i--) {
+             i >= 0; i--) {
             if (bytesCopied == 4) {
                 nextInt = mag[intIndex--];
                 bytesCopied = 1;
--- a/jdk/src/share/classes/java/math/MutableBigInteger.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/math/MutableBigInteger.java	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -38,14 +38,14 @@
  *
  * @see     BigInteger
  * @author  Michael McCloskey
+ * @author  Timothy Buktu
  * @since   1.3
  */
 
+import static java.math.BigDecimal.INFLATED;
+import static java.math.BigInteger.LONG_MASK;
 import java.util.Arrays;
 
-import static java.math.BigInteger.LONG_MASK;
-import static java.math.BigDecimal.INFLATED;
-
 class MutableBigInteger {
     /**
      * Holds the magnitude of this MutableBigInteger in big endian order.
@@ -75,6 +75,24 @@
      */
     static final MutableBigInteger ONE = new MutableBigInteger(1);
 
+    /**
+     * The minimum {@code intLen} for cancelling powers of two before
+     * dividing.
+     * If the number of ints is less than this threshold,
+     * {@code divideKnuth} does not eliminate common powers of two from
+     * the dividend and divisor.
+     */
+    static final int KNUTH_POW2_THRESH_LEN = 6;
+
+    /**
+     * The minimum number of trailing zero ints for cancelling powers of two
+     * before dividing.
+     * If the dividend and divisor don't share at least this many zero ints
+     * at the end, {@code divideKnuth} does not eliminate common powers
+     * of two from the dividend and divisor.
+     */
+    static final int KNUTH_POW2_THRESH_ZEROS = 3;
+
     // Constructors
 
     /**
@@ -124,6 +142,20 @@
     }
 
     /**
+     * Makes this number an {@code n}-int number all of whose bits are ones.
+     * Used by Burnikel-Ziegler division.
+     * @param n number of ints in the {@code value} array
+     * @return a number equal to {@code ((1<<(32*n)))-1}
+     */
+    private void ones(int n) {
+        if (n > value.length)
+            value = new int[n];
+        Arrays.fill(value, -1);
+        offset = 0;
+        intLen = n;
+    }
+
+    /**
      * Internal helper method to return the magnitude array. The caller is not
      * supposed to modify the returned array.
      */
@@ -155,6 +187,14 @@
     }
 
     /**
+     * Converts this number to a nonnegative {@code BigInteger}.
+     */
+    BigInteger toBigInteger() {
+        normalize();
+        return toBigInteger(isZero() ? 0 : 1);
+    }
+
+    /**
      * Convert this MutableBigInteger to BigDecimal object with the specified sign
      * and scale.
      */
@@ -238,6 +278,32 @@
     }
 
     /**
+     * Returns a value equal to what {@code b.leftShift(32*ints); return compare(b);}
+     * would return, but doesn't change the value of {@code b}.
+     */
+    private int compareShifted(MutableBigInteger b, int ints) {
+        int blen = b.intLen;
+        int alen = intLen - ints;
+        if (alen < blen)
+            return -1;
+        if (alen > blen)
+           return 1;
+
+        // Add Integer.MIN_VALUE to make the comparison act as unsigned integer
+        // comparison.
+        int[] bval = b.value;
+        for (int i = offset, j = b.offset; i < alen + offset; i++, j++) {
+            int b1 = value[i] + 0x80000000;
+            int b2 = bval[j]  + 0x80000000;
+            if (b1 < b2)
+                return -1;
+            if (b1 > b2)
+                return 1;
+        }
+        return 0;
+    }
+
+    /**
      * Compare this against half of a MutableBigInteger object (Needed for
      * remainder tests).
      * Assumes no leading unnecessary zeros, which holds for results
@@ -247,7 +313,7 @@
         int blen = b.intLen;
         int len = intLen;
         if (len <= 0)
-            return blen <=0 ? 0 : -1;
+            return blen <= 0 ? 0 : -1;
         if (len > blen)
             return 1;
         if (len < blen - 1)
@@ -274,7 +340,7 @@
                 return v < hb ? -1 : 1;
             carry = (bv & 1) << 31; // carray will be either 0x80000000 or 0
         }
-        return carry == 0? 0 : -1;
+        return carry == 0 ? 0 : -1;
     }
 
     /**
@@ -285,10 +351,10 @@
         if (intLen == 0)
             return -1;
         int j, b;
-        for (j=intLen-1; (j>0) && (value[j+offset]==0); j--)
+        for (j=intLen-1; (j > 0) && (value[j+offset] == 0); j--)
             ;
         b = value[j+offset];
-        if (b==0)
+        if (b == 0)
             return -1;
         return ((intLen-1-j)<<5) + Integer.numberOfTrailingZeros(b);
     }
@@ -329,11 +395,11 @@
         int indexBound = index+intLen;
         do {
             index++;
-        } while(index < indexBound && value[index]==0);
+        } while(index < indexBound && value[index] == 0);
 
         int numZeros = index - offset;
         intLen -= numZeros;
-        offset = (intLen==0 ?  0 : offset+numZeros);
+        offset = (intLen == 0 ?  0 : offset+numZeros);
     }
 
     /**
@@ -354,7 +420,7 @@
      */
     int[] toIntArray() {
         int[] result = new int[intLen];
-        for(int i=0; i<intLen; i++)
+        for(int i=0; i < intLen; i++)
             result[i] = value[offset+i];
         return result;
     }
@@ -440,7 +506,7 @@
     boolean isNormal() {
         if (intLen + offset > value.length)
             return false;
-        if (intLen ==0)
+        if (intLen == 0)
             return true;
         return (value[offset] != 0);
     }
@@ -454,6 +520,17 @@
     }
 
     /**
+     * Like {@link #rightShift(int)} but {@code n} can be greater than the length of the number.
+     */
+    void safeRightShift(int n) {
+        if (n/32 >= intLen) {
+            reset();
+        } else {
+            rightShift(n);
+        }
+    }
+
+    /**
      * Right shift this MutableBigInteger n bits. The MutableBigInteger is left
      * in normal form.
      */
@@ -475,6 +552,15 @@
     }
 
     /**
+     * Like {@link #leftShift(int)} but {@code n} can be zero.
+     */
+    void safeLeftShift(int n) {
+        if (n > 0) {
+            leftShift(n);
+        }
+    }
+
+    /**
      * Left shift this MutableBigInteger n bits.
      */
     void leftShift(int n) {
@@ -502,18 +588,18 @@
         if (value.length < newLen) {
             // The array must grow
             int[] result = new int[newLen];
-            for (int i=0; i<intLen; i++)
+            for (int i=0; i < intLen; i++)
                 result[i] = value[offset+i];
             setValue(result, newLen);
         } else if (value.length - offset >= newLen) {
             // Use space on right
-            for(int i=0; i<newLen - intLen; i++)
+            for(int i=0; i < newLen - intLen; i++)
                 value[offset+intLen+i] = 0;
         } else {
             // Must use space on left
-            for (int i=0; i<intLen; i++)
+            for (int i=0; i < intLen; i++)
                 value[i] = value[offset+i];
-            for (int i=intLen; i<newLen; i++)
+            for (int i=intLen; i < newLen; i++)
                 value[i] = 0;
             offset = 0;
         }
@@ -590,7 +676,7 @@
     private final void primitiveRightShift(int n) {
         int[] val = value;
         int n2 = 32 - n;
-        for (int i=offset+intLen-1, c=val[i]; i>offset; i--) {
+        for (int i=offset+intLen-1, c=val[i]; i > offset; i--) {
             int b = c;
             c = val[i-1];
             val[i] = (c << n2) | (b >>> n);
@@ -606,7 +692,7 @@
     private final void primitiveLeftShift(int n) {
         int[] val = value;
         int n2 = 32 - n;
-        for (int i=offset, c=val[i], m=i+intLen-1; i<m; i++) {
+        for (int i=offset, c=val[i], m=i+intLen-1; i < m; i++) {
             int b = c;
             c = val[i+1];
             val[i] = (b << n) | (c >>> n2);
@@ -615,6 +701,35 @@
     }
 
     /**
+     * Returns a {@code BigInteger} equal to the {@code n}
+     * low ints of this number.
+     */
+    private BigInteger getLower(int n) {
+        if (isZero()) {
+            return BigInteger.ZERO;
+        } else if (intLen < n) {
+            return toBigInteger(1);
+        } else {
+            // strip zeros
+            int len = n;
+            while (len > 0 && value[offset+intLen-len] == 0)
+                len--;
+            int sign = len > 0 ? 1 : 0;
+            return new BigInteger(Arrays.copyOfRange(value, offset+intLen-len, offset+intLen), sign);
+        }
+    }
+
+    /**
+     * Discards all ints whose index is greater than {@code n}.
+     */
+    private void keepLower(int n) {
+        if (intLen >= n) {
+            offset += intLen - n;
+            intLen = n;
+        }
+    }
+
+    /**
      * Adds the contents of two MutableBigInteger objects.The result
      * is placed within this MutableBigInteger.
      * The contents of the addend are not changed.
@@ -630,7 +745,7 @@
         long carry = 0;
 
         // Add common parts of both numbers
-        while(x>0 && y>0) {
+        while(x > 0 && y > 0) {
             x--; y--;
             sum = (value[x+offset] & LONG_MASK) +
                 (addend.value[y+addend.offset] & LONG_MASK) + carry;
@@ -639,7 +754,7 @@
         }
 
         // Add remainder of the longer number
-        while(x>0) {
+        while(x > 0) {
             x--;
             if (carry == 0 && result == value && rstart == (x + offset))
                 return;
@@ -647,7 +762,7 @@
             result[rstart--] = (int)sum;
             carry = sum >>> 32;
         }
-        while(y>0) {
+        while(y > 0) {
             y--;
             sum = (addend.value[y+addend.offset] & LONG_MASK) + carry;
             result[rstart--] = (int)sum;
@@ -673,6 +788,123 @@
         offset = result.length - resultLen;
     }
 
+    /**
+     * Adds the value of {@code addend} shifted {@code n} ints to the left.
+     * Has the same effect as {@code addend.leftShift(32*ints); add(addend);}
+     * but doesn't change the value of {@code addend}.
+     */
+    void addShifted(MutableBigInteger addend, int n) {
+        if (addend.isZero()) {
+            return;
+        }
+
+        int x = intLen;
+        int y = addend.intLen + n;
+        int resultLen = (intLen > y ? intLen : y);
+        int[] result = (value.length < resultLen ? new int[resultLen] : value);
+
+        int rstart = result.length-1;
+        long sum;
+        long carry = 0;
+
+        // Add common parts of both numbers
+        while (x > 0 && y > 0) {
+            x--; y--;
+            int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0;
+            sum = (value[x+offset] & LONG_MASK) +
+                (bval & LONG_MASK) + carry;
+            result[rstart--] = (int)sum;
+            carry = sum >>> 32;
+        }
+
+        // Add remainder of the longer number
+        while (x > 0) {
+            x--;
+            if (carry == 0 && result == value && rstart == (x + offset)) {
+                return;
+            }
+            sum = (value[x+offset] & LONG_MASK) + carry;
+            result[rstart--] = (int)sum;
+            carry = sum >>> 32;
+        }
+        while (y > 0) {
+            y--;
+            int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0;
+            sum = (bval & LONG_MASK) + carry;
+            result[rstart--] = (int)sum;
+            carry = sum >>> 32;
+        }
+
+        if (carry > 0) { // Result must grow in length
+            resultLen++;
+            if (result.length < resultLen) {
+                int temp[] = new int[resultLen];
+                // Result one word longer from carry-out; copy low-order
+                // bits into new result.
+                System.arraycopy(result, 0, temp, 1, result.length);
+                temp[0] = 1;
+                result = temp;
+            } else {
+                result[rstart--] = 1;
+            }
+        }
+
+        value = result;
+        intLen = resultLen;
+        offset = result.length - resultLen;
+    }
+
+    /**
+     * Like {@link #addShifted(MutableBigInteger, int)} but {@code this.intLen} must
+     * not be greater than {@code n}. In other words, concatenates {@code this}
+     * and {@code addend}.
+     */
+    void addDisjoint(MutableBigInteger addend, int n) {
+        if (addend.isZero())
+            return;
+
+        int x = intLen;
+        int y = addend.intLen + n;
+        int resultLen = (intLen > y ? intLen : y);
+        int[] result;
+        if (value.length < resultLen)
+            result = new int[resultLen];
+        else {
+            result = value;
+            Arrays.fill(value, offset+intLen, value.length, 0);
+        }
+
+        int rstart = result.length-1;
+
+        // copy from this if needed
+        System.arraycopy(value, offset, result, rstart+1-x, x);
+        y -= x;
+        rstart -= x;
+
+        int len = Math.min(y, addend.value.length-addend.offset);
+        System.arraycopy(addend.value, addend.offset, result, rstart+1-y, len);
+
+        // zero the gap
+        for (int i=rstart+1-y+len; i < rstart+1; i++)
+            result[i] = 0;
+
+        value = result;
+        intLen = resultLen;
+        offset = result.length - resultLen;
+    }
+
+    /**
+     * Adds the low {@code n} ints of {@code addend}.
+     */
+    void addLower(MutableBigInteger addend, int n) {
+        MutableBigInteger a = new MutableBigInteger(addend);
+        if (a.offset + a.intLen >= n) {
+            a.offset = a.offset + a.intLen - n;
+            a.intLen = n;
+        }
+        a.normalize();
+        add(a);
+    }
 
     /**
      * Subtracts the smaller of this and b from the larger and places the
@@ -704,7 +936,7 @@
         int rstart = result.length - 1;
 
         // Subtract common parts of both numbers
-        while (y>0) {
+        while (y > 0) {
             x--; y--;
 
             diff = (a.value[x+a.offset] & LONG_MASK) -
@@ -712,7 +944,7 @@
             result[rstart--] = (int)diff;
         }
         // Subtract remainder of longer number
-        while (x>0) {
+        while (x > 0) {
             x--;
             diff = (a.value[x+a.offset] & LONG_MASK) - ((int)-(diff>>32));
             result[rstart--] = (int)diff;
@@ -733,7 +965,7 @@
     private int difference(MutableBigInteger b) {
         MutableBigInteger a = this;
         int sign = a.compare(b);
-        if (sign ==0)
+        if (sign == 0)
             return 0;
         if (sign < 0) {
             MutableBigInteger tmp = a;
@@ -746,14 +978,14 @@
         int y = b.intLen;
 
         // Subtract common parts of both numbers
-        while (y>0) {
+        while (y > 0) {
             x--; y--;
             diff = (a.value[a.offset+ x] & LONG_MASK) -
                 (b.value[b.offset+ y] & LONG_MASK) - ((int)-(diff>>32));
             a.value[a.offset+x] = (int)diff;
         }
         // Subtract remainder of longer number
-        while (x>0) {
+        while (x > 0) {
             x--;
             diff = (a.value[a.offset+ x] & LONG_MASK) - ((int)-(diff>>32));
             a.value[a.offset+x] = (int)diff;
@@ -822,7 +1054,7 @@
 
         // Perform the multiplication word by word
         long ylong = y & LONG_MASK;
-        int[] zval = (z.value.length<intLen+1 ? new int[intLen + 1]
+        int[] zval = (z.value.length < intLen+1 ? new int[intLen + 1]
                                               : z.value);
         long carry = 0;
         for (int i = intLen-1; i >= 0; i--) {
@@ -910,6 +1142,31 @@
      * Calculates the quotient of this div b and places the quotient in the
      * provided MutableBigInteger objects and the remainder object is returned.
      *
+     */
+    MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient) {
+        return divide(b,quotient,true);
+    }
+
+    MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient, boolean needRemainder) {
+        if (intLen < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD ||
+                b.intLen < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD) {
+            return divideKnuth(b, quotient, needRemainder);
+        } else {
+            return divideAndRemainderBurnikelZiegler(b, quotient);
+        }
+    }
+
+    /**
+     * @see #divideKnuth(MutableBigInteger, MutableBigInteger, boolean)
+     */
+    MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient) {
+        return divideKnuth(b,quotient,true);
+    }
+
+    /**
+     * Calculates the quotient of this div b and places the quotient in the
+     * provided MutableBigInteger objects and the remainder object is returned.
+     *
      * Uses Algorithm D in Knuth section 4.3.1.
      * Many optimizations to that algorithm have been adapted from the Colin
      * Plumb C library.
@@ -917,38 +1174,34 @@
      * changed.
      *
      */
-    MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient) {
-        return divide(b,quotient,true);
-    }
-
-    MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient, boolean needReminder) {
+    MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient, boolean needRemainder) {
         if (b.intLen == 0)
             throw new ArithmeticException("BigInteger divide by zero");
 
         // Dividend is zero
         if (intLen == 0) {
-            quotient.intLen = quotient.offset;
-            return needReminder ? new MutableBigInteger() : null;
+            quotient.intLen = quotient.offset = 0;
+            return needRemainder ? new MutableBigInteger() : null;
         }
 
         int cmp = compare(b);
         // Dividend less than divisor
         if (cmp < 0) {
             quotient.intLen = quotient.offset = 0;
-            return needReminder ? new MutableBigInteger(this) : null;
+            return needRemainder ? new MutableBigInteger(this) : null;
         }
         // Dividend equal to divisor
         if (cmp == 0) {
             quotient.value[0] = quotient.intLen = 1;
             quotient.offset = 0;
-            return needReminder ? new MutableBigInteger() : null;
+            return needRemainder ? new MutableBigInteger() : null;
         }
 
         quotient.clear();
         // Special case one word divisor
         if (b.intLen == 1) {
             int r = divideOneWord(b.value[b.offset], quotient);
-            if(needReminder) {
+            if(needRemainder) {
                 if (r == 0)
                     return new MutableBigInteger();
                 return new MutableBigInteger(r);
@@ -956,7 +1209,220 @@
                 return null;
             }
         }
-        return divideMagnitude(b, quotient, needReminder);
+
+        // Cancel common powers of two if we're above the KNUTH_POW2_* thresholds
+        if (intLen >= KNUTH_POW2_THRESH_LEN) {
+            int trailingZeroBits = Math.min(getLowestSetBit(), b.getLowestSetBit());
+            if (trailingZeroBits >= KNUTH_POW2_THRESH_ZEROS*32) {
+                MutableBigInteger a = new MutableBigInteger(this);
+                b = new MutableBigInteger(b);
+                a.rightShift(trailingZeroBits);
+                b.rightShift(trailingZeroBits);
+                MutableBigInteger r = a.divideKnuth(b, quotient);
+                r.leftShift(trailingZeroBits);
+                return r;
+            }
+        }
+
+        return divideMagnitude(b, quotient, needRemainder);
+    }
+
+    /**
+     * Computes {@code this/b} and {@code this%b} using the
+     * <a href="http://cr.yp.to/bib/1998/burnikel.ps"> Burnikel-Ziegler algorithm</a>.
+     * This method implements algorithm 3 from pg. 9 of the Burnikel-Ziegler paper.
+     * The parameter beta was chosen to b 2<sup>32</sup> so almost all shifts are
+     * multiples of 32 bits.<br/>
+     * {@code this} and {@code b} must be nonnegative.
+     * @param b the divisor
+     * @param quotient output parameter for {@code this/b}
+     * @return the remainder
+     */
+    MutableBigInteger divideAndRemainderBurnikelZiegler(MutableBigInteger b, MutableBigInteger quotient) {
+        int r = intLen;
+        int s = b.intLen;
+
+        if (r < s) {
+            return this;
+        } else {
+            // Unlike Knuth division, we don't check for common powers of two here because
+            // BZ already runs faster if both numbers contain powers of two and cancelling them has no
+            // additional benefit.
+
+            // step 1: let m = min{2^k | (2^k)*BURNIKEL_ZIEGLER_THRESHOLD > s}
+            int m = 1 << (32-Integer.numberOfLeadingZeros(s/BigInteger.BURNIKEL_ZIEGLER_THRESHOLD));
+
+            int j = (s+m-1) / m;      // step 2a: j = ceil(s/m)
+            int n = j * m;            // step 2b: block length in 32-bit units
+            int n32 = 32 * n;         // block length in bits
+            int sigma = Math.max(0, n32 - b.bitLength());   // step 3: sigma = max{T | (2^T)*B < beta^n}
+            MutableBigInteger bShifted = new MutableBigInteger(b);
+            bShifted.safeLeftShift(sigma);   // step 4a: shift b so its length is a multiple of n
+            safeLeftShift(sigma);     // step 4b: shift this by the same amount
+
+            // step 5: t is the number of blocks needed to accommodate this plus one additional bit
+            int t = (bitLength()+n32) / n32;
+            if (t < 2) {
+                t = 2;
+            }
+
+            // step 6: conceptually split this into blocks a[t-1], ..., a[0]
+            MutableBigInteger a1 = getBlock(t-1, t, n);   // the most significant block of this
+
+            // step 7: z[t-2] = [a[t-1], a[t-2]]
+            MutableBigInteger z = getBlock(t-2, t, n);    // the second to most significant block
+            z.addDisjoint(a1, n);   // z[t-2]
+
+            // do schoolbook division on blocks, dividing 2-block numbers by 1-block numbers
+            MutableBigInteger qi = new MutableBigInteger();
+            MutableBigInteger ri;
+            quotient.offset = quotient.intLen = 0;
+            for (int i=t-2; i > 0; i--) {
+                // step 8a: compute (qi,ri) such that z=b*qi+ri
+                ri = z.divide2n1n(bShifted, qi);
+
+                // step 8b: z = [ri, a[i-1]]
+                z = getBlock(i-1, t, n);   // a[i-1]
+                z.addDisjoint(ri, n);
+                quotient.addShifted(qi, i*n);   // update q (part of step 9)
+            }
+            // final iteration of step 8: do the loop one more time for i=0 but leave z unchanged
+            ri = z.divide2n1n(bShifted, qi);
+            quotient.add(qi);
+
+            ri.rightShift(sigma);   // step 9: this and b were shifted, so shift back
+            return ri;
+        }
+    }
+
+    /**
+     * This method implements algorithm 1 from pg. 4 of the Burnikel-Ziegler paper.
+     * It divides a 2n-digit number by a n-digit number.<br/>
+     * The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits.
+     * <br/>
+     * {@code this} must be a nonnegative number such that {@code this.bitLength() <= 2*b.bitLength()}
+     * @param b a positive number such that {@code b.bitLength()} is even
+     * @param quotient output parameter for {@code this/b}
+     * @return {@code this%b}
+     */
+    private MutableBigInteger divide2n1n(MutableBigInteger b, MutableBigInteger quotient) {
+        int n = b.intLen;
+
+        // step 1: base case
+        if (n%2 != 0 || n < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD) {
+            return divideKnuth(b, quotient);
+        }
+
+        // step 2: view this as [a1,a2,a3,a4] where each ai is n/2 ints or less
+        MutableBigInteger aUpper = new MutableBigInteger(this);
+        aUpper.safeRightShift(32*(n/2));   // aUpper = [a1,a2,a3]
+        keepLower(n/2);   // this = a4
+
+        // step 3: q1=aUpper/b, r1=aUpper%b
+        MutableBigInteger q1 = new MutableBigInteger();
+        MutableBigInteger r1 = aUpper.divide3n2n(b, q1);
+
+        // step 4: quotient=[r1,this]/b, r2=[r1,this]%b
+        addDisjoint(r1, n/2);   // this = [r1,this]
+        MutableBigInteger r2 = divide3n2n(b, quotient);
+
+        // step 5: let quotient=[q1,quotient] and return r2
+        quotient.addDisjoint(q1, n/2);
+        return r2;
+    }
+
+    /**
+     * This method implements algorithm 2 from pg. 5 of the Burnikel-Ziegler paper.
+     * It divides a 3n-digit number by a 2n-digit number.<br/>
+     * The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits.<br/>
+     * <br/>
+     * {@code this} must be a nonnegative number such that {@code 2*this.bitLength() <= 3*b.bitLength()}
+     * @param quotient output parameter for {@code this/b}
+     * @return {@code this%b}
+     */
+    private MutableBigInteger divide3n2n(MutableBigInteger b, MutableBigInteger quotient) {
+        int n = b.intLen / 2;   // half the length of b in ints
+
+        // step 1: view this as [a1,a2,a3] where each ai is n ints or less; let a12=[a1,a2]
+        MutableBigInteger a12 = new MutableBigInteger(this);
+        a12.safeRightShift(32*n);
+
+        // step 2: view b as [b1,b2] where each bi is n ints or less
+        MutableBigInteger b1 = new MutableBigInteger(b);
+        b1.safeRightShift(n * 32);
+        BigInteger b2 = b.getLower(n);
+
+        MutableBigInteger r;
+        MutableBigInteger d;
+        if (compareShifted(b, n) < 0) {
+            // step 3a: if a1<b1, let quotient=a12/b1 and r=a12%b1
+            r = a12.divide2n1n(b1, quotient);
+
+            // step 4: d=quotient*b2
+            d = new MutableBigInteger(quotient.toBigInteger().multiply(b2));
+        } else {
+            // step 3b: if a1>=b1, let quotient=beta^n-1 and r=a12-b1*2^n+b1
+            quotient.ones(n);
+            a12.add(b1);
+            b1.leftShift(32*n);
+            a12.subtract(b1);
+            r = a12;
+
+            // step 4: d=quotient*b2=(b2 << 32*n) - b2
+            d = new MutableBigInteger(b2);
+            d.leftShift(32 * n);
+            d.subtract(new MutableBigInteger(b2));
+        }
+
+        // step 5: r = r*beta^n + a3 - d (paper says a4)
+        // However, don't subtract d until after the while loop so r doesn't become negative
+        r.leftShift(32 * n);
+        r.addLower(this, n);
+
+        // step 6: add b until r>=d
+        while (r.compare(d) < 0) {
+            r.add(b);
+            quotient.subtract(MutableBigInteger.ONE);
+        }
+        r.subtract(d);
+
+        return r;
+    }
+
+    /**
+     * Returns a {@code MutableBigInteger} containing {@code blockLength} ints from
+     * {@code this} number, starting at {@code index*blockLength}.<br/>
+     * Used by Burnikel-Ziegler division.
+     * @param index the block index
+     * @param numBlocks the total number of blocks in {@code this} number
+     * @param blockLength length of one block in units of 32 bits
+     * @return
+     */
+    private MutableBigInteger getBlock(int index, int numBlocks, int blockLength) {
+        int blockStart = index * blockLength;
+        if (blockStart >= intLen) {
+            return new MutableBigInteger();
+        }
+
+        int blockEnd;
+        if (index == numBlocks-1) {
+            blockEnd = intLen;
+        } else {
+            blockEnd = (index+1) * blockLength;
+        }
+        if (blockEnd > intLen) {
+            return new MutableBigInteger();
+        }
+
+        int[] newVal = Arrays.copyOfRange(value, offset+intLen-blockEnd, offset+intLen-blockStart);
+        return new MutableBigInteger(newVal);
+    }
+
+    /** @see BigInteger#bitLength() */
+    int bitLength() {
+        if (intLen == 0)
+            return 0;
+        return intLen*32 - Integer.numberOfLeadingZeros(value[offset]);
     }
 
     /**
@@ -1006,7 +1472,7 @@
      */
     private MutableBigInteger divideMagnitude(MutableBigInteger div,
                                               MutableBigInteger quotient,
-                                              boolean needReminder ) {
+                                              boolean needRemainder ) {
         // assert div.intLen > 1
         // D1 normalize the divisor
         int shift = Integer.numberOfLeadingZeros(div.value[div.offset]);
@@ -1017,7 +1483,7 @@
         if (shift > 0) {
             divisor = new int[dlen];
             copyAndShift(div.value,div.offset,dlen,divisor,0,shift);
-            if(Integer.numberOfLeadingZeros(value[offset])>=shift) {
+            if (Integer.numberOfLeadingZeros(value[offset]) >= shift) {
                 int[] remarr = new int[intLen + 1];
                 rem = new MutableBigInteger(remarr);
                 rem.intLen = intLen;
@@ -1070,7 +1536,7 @@
         int dl = divisor[1];
 
         // D2 Initialize j
-        for(int j=0; j<limit-1; j++) {
+        for (int j=0; j < limit-1; j++) {
             // D3 Calculate qhat
             // estimate qhat
             int qhat = 0;
@@ -1176,7 +1642,7 @@
             // D4 Multiply and subtract
             int borrow;
             rem.value[limit - 1 + rem.offset] = 0;
-            if(needReminder)
+            if(needRemainder)
                 borrow = mulsub(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset);
             else
                 borrow = mulsubBorrow(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset);
@@ -1184,7 +1650,7 @@
             // D5 Test remainder
             if (borrow + 0x80000000 > nh2) {
                 // D6 Add back
-                if(needReminder)
+                if(needRemainder)
                     divadd(divisor, rem.value, limit - 1 + 1 + rem.offset);
                 qhat--;
             }
@@ -1194,14 +1660,14 @@
         }
 
 
-        if(needReminder) {
+        if (needRemainder) {
             // D8 Unnormalize
             if (shift > 0)
                 rem.rightShift(shift);
             rem.normalize();
         }
         quotient.normalize();
-        return needReminder ? rem : null;
+        return needRemainder ? rem : null;
     }
 
     /**
@@ -1367,7 +1833,7 @@
      * This method divides a long quantity by an int to estimate
      * qhat for two multi precision numbers. It is used when
      * the signed value of n is less than zero.
-     * Returns long value where high 32 bits contain reminder value and
+     * Returns long value where high 32 bits contain remainder value and
      * low 32 bits contain quotient value.
      */
     static long divWord(long n, int d) {
@@ -1436,7 +1902,7 @@
         }
 
         // step B2
-        boolean uOdd = (k==s1);
+        boolean uOdd = (k == s1);
         MutableBigInteger t = uOdd ? v: u;
         int tsign = uOdd ? -1 : 1;
 
@@ -1478,9 +1944,9 @@
      * Calculate GCD of a and b interpreted as unsigned integers.
      */
     static int binaryGcd(int a, int b) {
-        if (b==0)
+        if (b == 0)
             return a;
-        if (a==0)
+        if (a == 0)
             return b;
 
         // Right shift a & b till their last bits equal to 1.
@@ -1582,7 +2048,7 @@
         return result;
     }
 
-    /*
+    /**
      * Returns the multiplicative inverse of val mod 2^32.  Assumes val is odd.
      */
     static int inverseMod32(int val) {
@@ -1595,7 +2061,7 @@
         return t;
     }
 
-    /*
+    /**
      * Calculate the multiplicative inverse of 2^k mod mod, where mod is odd.
      */
     static MutableBigInteger modInverseBP2(MutableBigInteger mod, int k) {
@@ -1631,7 +2097,7 @@
         }
 
         // The Almost Inverse Algorithm
-        while(!f.isOne()) {
+        while (!f.isOne()) {
             // If gcd(f, g) != 1, number is not invertible modulo mod
             if (f.isZero())
                 throw new ArithmeticException("BigInteger not invertible.");
@@ -1665,7 +2131,7 @@
         return fixup(c, p, k);
     }
 
-    /*
+    /**
      * The Fixup Algorithm
      * Calculates X such that X = C * 2^(-k) (mod P)
      * Assumes C<P and P is odd.
@@ -1676,7 +2142,7 @@
         // Set r to the multiplicative inverse of p mod 2^32
         int r = -inverseMod32(p.value[p.offset+p.intLen-1]);
 
-        for(int i=0, numWords = k >> 5; i<numWords; i++) {
+        for (int i=0, numWords = k >> 5; i < numWords; i++) {
             // V = R * c (mod 2^j)
             int  v = r * c.value[c.offset + c.intLen-1];
             // c = c + (v * p)
--- a/jdk/src/share/classes/java/net/Authenticator.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/net/Authenticator.java	Thu Aug 01 17:24:26 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2004, 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
@@ -103,17 +103,17 @@
      * Sets the authenticator that will be used by the networking code
      * when a proxy or an HTTP server asks for authentication.
      * <p>
-     * First, if there is a security manager, its <code>checkPermission</code>
+     * First, if there is a security manager, its {@code checkPermission}
      * method is called with a
-     * <code>NetPermission("setDefaultAuthenticator")</code> permission.
+     * {@code NetPermission("setDefaultAuthenticator")} permission.
      * This may result in a java.lang.SecurityException.
      *
-     * @param   a       The authenticator to be set. If a is <code>null</code> then
+     * @param   a       The authenticator to be set. If a is {@code null} then
      *                  any previously set authenticator is removed.
      *
      * @throws SecurityException
      *        if a security manager exists and its
-     *        <code>checkPermission</code> method doesn't allow
+     *        {@code checkPermission} method doesn't allow
      *        setting the default authenticator.
      *
      * @see SecurityManager#checkPermission
@@ -134,9 +134,9 @@
      * Ask the authenticator that has been registered with the system
      * for a password.
      * <p>
-     * First, if there is a security manager, its <code>checkPermission</code>
+     * First, if there is a security manager, its {@code checkPermission}
      * method is called with a
-     * <code>NetPermission("requestPasswordAuthentication")</code> permission.
+     * {@code NetPermission("requestPasswordAuthentication")} permission.
      * This may result in a java.lang.SecurityException.
      *
      * @param addr The InetAddress of the site requesting authorization,
@@ -151,7 +151,7 @@
      *
      * @throws SecurityException
      *        if a security manager exists and its
-     *        <code>checkPermission</code> method doesn't allow
+     *        {@code checkPermission} method doesn't allow
      *        the password authentication request.
      *
      * @see SecurityManager#checkPermission
@@ -193,9 +193,9 @@
      * because the hostname can be provided in cases where the InetAddress
      * is not available.
      * <p>
-     * First, if there is a security manager, its <code>checkPermission</code>
+     * First, if there is a security manager, its {@code checkPermission}
      * method is called with a
-     * <code>NetPermission("requestPasswordAuthentication")</code> permission.
+     * {@code NetPermission("requestPasswordAuthentication")} permission.
      * This may result in a java.lang.SecurityException.
      *
      * @param host The hostname of the site requesting authentication.
@@ -211,7 +211,7 @@
      *
      * @throws SecurityException
      *        if a security manager exists and its
-     *        <code>checkPermission</code> method doesn't allow
+     *        {@code checkPermission} method doesn't allow
      *        the password authentication request.
      *
      * @see SecurityManager#checkPermission
@@ -254,9 +254,9 @@
      * Ask the authenticator that has been registered with the system
      * for a password.
      * <p>
-     * First, if there is a security manager, its <code>checkPermission</code>
+     * First, if there is a security manager, its {@code checkPermission}
      * method is called with a
-     * <code>NetPermission("requestPasswordAuthentication")</code> permission.
+     * {@code NetPermission("requestPasswordAuthentication")} permission.
      * This may result in a java.lang.SecurityException.
      *
      * @param host The hostname of the site requesting authentication.
@@ -275,7 +275,7 @@
      *
      * @throws SecurityException
      *        if a security manager exists and its
-     *        <code>checkPermission</code> method doesn't allow
+     *        {@code checkPermission} method doesn't allow
      *        the password authentication request.
      *
      * @see SecurityManager#checkPermission
@@ -320,8 +320,8 @@
     }
 
     /**
-     * Gets the <code>hostname</code> of the
-     * site or proxy requesting authentication, or <code>null</code>
+     * Gets the {@code hostname} of the
+     * site or proxy requesting authentication, or {@code null}
      * if not available.
      *
      * @return the hostname of the connection requiring authentication, or null
@@ -333,8 +333,8 @@
     }
 
     /**
-     * Gets the <code>InetAddress</code> of the
-     * site requesting authorization, or <code>null</code>
+     * Gets the {@code InetAddress} of the
+     * site requesting authorization, or {@code null}
      * if not available.
      *
      * @return the InetAddress of the site requesting authorization, or null
@@ -346,7 +346,7 @@
 
     /**
      * Gets the port number for the requested connection.
-     * @return an <code>int</code> indicating the
+     * @return an {@code int} indicating the
      * port for the requested connection.
      */
     protected final int getRequestingPort() {
--- a/jdk/src/share/classes/java/net/ContentHandler.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/net/ContentHandler.java	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -28,21 +28,21 @@
 import java.io.IOException;
 
 /**
- * The abstract class <code>ContentHandler</code> is the superclass
- * of all classes that read an <code>Object</code> from a
- * <code>URLConnection</code>.
+ * The abstract class {@code ContentHandler} is the superclass
+ * of all classes that read an {@code Object} from a
+ * {@code URLConnection}.
  * <p>
  * An application does not generally call the
- * <code>getContent</code> method in this class directly. Instead, an
- * application calls the <code>getContent</code> method in class
- * <code>URL</code> or in <code>URLConnection</code>.
+ * {@code getContent} method in this class directly. Instead, an
+ * application calls the {@code getContent} method in class
+ * {@code URL} or in {@code URLConnection}.
  * The application's content handler factory (an instance of a class that
- * implements the interface <code>ContentHandlerFactory</code> set
- * up by a call to <code>setContentHandler</code>) is
- * called with a <code>String</code> giving the MIME type of the
+ * implements the interface {@code ContentHandlerFactory} set
+ * up by a call to {@code setContentHandler}) is
+ * called with a {@code String} giving the MIME type of the
  * object being received on the socket. The factory returns an
- * instance of a subclass of <code>ContentHandler</code>, and its
- * <code>getContent</code> method is called to create the object.
+ * instance of a subclass of {@code ContentHandler}, and its
+ * {@code getContent} method is called to create the object.
  * <p>
  * If no content handler could be found, URLConnection will
  * look for a content handler in a user-defineable set of places.
@@ -75,7 +75,7 @@
      * creates an object from it.
      *
      * @param      urlc   a URL connection.
-     * @return     the object read by the <code>ContentHandler</code>.
+     * @return     the object read by the {@code ContentHandler}.
      * @exception  IOException  if an I/O error occurs while reading the object.
      */
     abstract public Object getContent(URLConnection urlc) throws IOException;
@@ -90,7 +90,7 @@
      *
      * @param      urlc   a URL connection.
      * @param      classes      an array of types requested
-     * @return     the object read by the <code>ContentHandler</code> that is
+     * @return     the object read by the {@code ContentHandler} that is
      *                 the first match of the suggested types.
      *                 null if none of the requested  are supported.
      * @exception  IOException  if an I/O error occurs while reading the object.
--- a/jdk/src/share/classes/java/net/ContentHandlerFactory.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/net/ContentHandlerFactory.java	Thu Aug 01 17:24:26 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 1997, 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
@@ -28,10 +28,10 @@
 /**
  * This interface defines a factory for content handlers. An
  * implementation of this interface should map a MIME type into an
- * instance of <code>ContentHandler</code>.
+ * instance of {@code ContentHandler}.
  * <p>
- * This interface is used by the <code>URLStreamHandler</code> class
- * to create a <code>ContentHandler</code> for a MIME type.
+ * This interface is used by the {@code URLStreamHandler} class
+ * to create a {@code ContentHandler} for a MIME type.
  *
  * @author  James Gosling
  * @see     java.net.ContentHandler
@@ -40,13 +40,13 @@
  */
 public interface ContentHandlerFactory {
     /**
-     * Creates a new <code>ContentHandler</code> to read an object from
-     * a <code>URLStreamHandler</code>.
+     * Creates a new {@code ContentHandler} to read an object from
+     * a {@code URLStreamHandler}.
      *
      * @param   mimetype   the MIME type for which a content handler is desired.
 
-     * @return  a new <code>ContentHandler</code> to read an object from a
-     *          <code>URLStreamHandler</code>.
+     * @return  a new {@code ContentHandler} to read an object from a
+     *          {@code URLStreamHandler}.
      * @see     java.net.ContentHandler
      * @see     java.net.URLStreamHandler
      */
--- a/jdk/src/share/classes/java/net/CookieHandler.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/net/CookieHandler.java	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -66,7 +66,7 @@
      *        there is no system-wide cookie handler currently set.
      * @throws SecurityException
      *       If a security manager has been installed and it denies
-     * {@link NetPermission}<tt>("getCookieHandler")</tt>
+     * {@link NetPermission}{@code ("getCookieHandler")}
      * @see #setDefault(CookieHandler)
      */
     public synchronized static CookieHandler getDefault() {
@@ -83,10 +83,10 @@
      * Note: non-standard http protocol handlers may ignore this setting.
      *
      * @param cHandler The HTTP cookie handler, or
-     *       <code>null</code> to unset.
+     *       {@code null} to unset.
      * @throws SecurityException
      *       If a security manager has been installed and it denies
-     * {@link NetPermission}<tt>("setCookieHandler")</tt>
+     * {@link NetPermission}{@code ("setCookieHandler")}
      * @see #getDefault()
      */
     public synchronized static void setDefault(CookieHandler cHandler) {
@@ -114,7 +114,7 @@
      * called after all request headers related to choosing cookies
      * are added, and before the request is sent.</P>
      *
-     * @param uri a <code>URI</code> representing the intended use for the
+     * @param uri a {@code URI} representing the intended use for the
      *            cookies
      * @param requestHeaders - a Map from request header
      *            field names to lists of field values representing
@@ -136,7 +136,7 @@
      * fields that are named Set-Cookie2, present in the response
      * headers into a cookie cache.
      *
-     * @param uri a <code>URI</code> where the cookies come from
+     * @param uri a {@code URI} where the cookies come from
      * @param responseHeaders an immutable map from field names to
      *            lists of field values representing the response
      *            header fields returned
--- a/jdk/src/share/classes/java/net/CookieManager.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/net/CookieManager.java	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -131,7 +131,7 @@
      *
      * <p>This constructor will create new cookie manager with default
      * cookie store and accept policy. The effect is same as
-     * <tt>CookieManager(null, null)</tt>.
+     * {@code CookieManager(null, null)}.
      */
     public CookieManager() {
         this(null, null);
@@ -141,12 +141,12 @@
     /**
      * Create a new cookie manager with specified cookie store and cookie policy.
      *
-     * @param store     a <tt>CookieStore</tt> to be used by cookie manager.
-     *                  if <tt>null</tt>, cookie manager will use a default one,
+     * @param store     a {@code CookieStore} to be used by cookie manager.
+     *                  if {@code null}, cookie manager will use a default one,
      *                  which is an in-memory CookieStore implmentation.
-     * @param cookiePolicy      a <tt>CookiePolicy</tt> instance
+     * @param cookiePolicy      a {@code CookiePolicy} instance
      *                          to be used by cookie manager as policy callback.
-     *                          if <tt>null</tt>, ACCEPT_ORIGINAL_SERVER will
+     *                          if {@code null}, ACCEPT_ORIGINAL_SERVER will
      *                          be used.
      */
     public CookieManager(CookieStore store,
@@ -170,11 +170,11 @@
     /**
      * To set the cookie policy of this cookie manager.
      *
-     * <p> A instance of <tt>CookieManager</tt> will have
+     * <p> A instance of {@code CookieManager} will have
      * cookie policy ACCEPT_ORIGINAL_SERVER by default. Users always
      * can call this method to set another cookie policy.
      *
-     * @param cookiePolicy      the cookie policy. Can be <tt>null</tt>, which
+     * @param cookiePolicy      the cookie policy. Can be {@code null}, which
      *                          has no effects on current cookie policy.
      */
     public void setCookiePolicy(CookiePolicy cookiePolicy) {
--- a/jdk/src/share/classes/java/net/CookiePolicy.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/net/CookiePolicy.java	Thu Aug 01 17:24:26 2013 -0700
@@ -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
@@ -71,8 +71,8 @@
      *
      * @param uri       the URI to consult accept policy with
      * @param cookie    the HttpCookie object in question
-     * @return          <tt>true</tt> if this cookie should be accepted;
-     *                  otherwise, <tt>false</tt>
+     * @return          {@code true} if this cookie should be accepted;
+     *                  otherwise, {@code false}
      */
     public boolean shouldAccept(URI uri, HttpCookie cookie);
 }
--- a/jdk/src/share/classes/java/net/CookieStore.java	Fri Jul 19 13:24:09 2013 -0700
+++ b/jdk/src/share/classes/java/net/CookieStore.java	Thu Aug 01 17:24:26 2013 -0700
@@ -32,8 +32,8 @@
  * A CookieStore object represents a storage for cookie. Can store and retrieve
  * cookies.
  *
- * <p>{@link CookieManager} will call <tt>CookieStore.add</tt> to save cookies
- * for every incoming HTTP response, and call <tt>CookieStore.get</tt> to
+ * <p>{@link CookieManager} will call {@code CookieStore.add} to save cookies
+ * for every incoming HTTP response, and call {@code CookieStore.get} to
  * retrieve cookie for every outgoing HTTP request. A CookieStore
  * is responsible for removing HttpCookie instances which have expired.
  *
@@ -55,11 +55,11 @@
      * then it is replaced with the new one.
      *
      * @param uri       the uri this cookie associated with.
-     *                  if <tt>null</tt>, this cookie will not be associated
+     *                  if {@code null}, this cookie will not be associated
      *                  with an