Merge
authorzgu
Tue, 22 Jan 2013 11:54:16 -0800
changeset 15237 9dadd171eeb8
parent 15236 27d5f33652c7 (current diff)
parent 15235 0a73bc0920e5 (diff)
child 15240 4aea0ffdd4ce
child 15430 7c35f12cf1e5
Merge
common/autoconf/closed.version.numbers
common/autoconf/version.numbers
hotspot/src/os/windows/vm/os_windows.cpp
jdk/make/jdk/asm/Makefile
jdk/make/tools/swing-beans/beaninfo/BeanInfoUtils.java
jdk/make/tools/swing-beans/beaninfo/SwingBeanInfoBase.java
jdk/src/share/demo/jfc/CodePointIM/CodePointInputMethod.java
jdk/src/share/demo/jfc/CodePointIM/CodePointInputMethodDescriptor.java
--- a/.hgtags	Tue Jan 22 14:27:41 2013 -0500
+++ b/.hgtags	Tue Jan 22 11:54:16 2013 -0800
@@ -190,3 +190,8 @@
 17820b958ae84f7c1cc6719319c8e2232f7a4f1d jdk8-b66
 76cc9bd3ece407d3a15d3bea537b57927973c5e7 jdk8-b67
 cb33628d4e8f11e879c371959e5948b66a53376f jdk8-b68
+adb5171c554e14cd86f618b5584f6e3d693d5889 jdk8-b69
+0d625373c69e2ad6f546fd88ab50c6c9aad01271 jdk8-b70
+a41ada2ed4ef735449531c6ebe6cec593d890a1c jdk8-b71
+6725b3961f987cf40f446d1c11cd324a3bec545f jdk8-b72
+fe94b40ffd9390f6cffcdf51c0389b0e6dde0c13 jdk8-b73
--- a/.hgtags-top-repo	Tue Jan 22 14:27:41 2013 -0500
+++ b/.hgtags-top-repo	Tue Jan 22 11:54:16 2013 -0800
@@ -190,3 +190,8 @@
 13bb8c326e7b7b0b19d78c8088033e3932e3f7ca jdk8-b66
 9a6ec97ec45c1a62d5233cefa91e8390e380e13a jdk8-b67
 cdb401a60cea6ad5ef3f498725ed1decf8dda1ea jdk8-b68
+6ee8080a6efe0639fcd00627a5e0f839bf010481 jdk8-b69
+105a25ffa4a4f0af70188d4371b4a0385009b7ce jdk8-b70
+51ad2a34342055333eb5f36e2fb514b027895708 jdk8-b71
+c1be681d80a1f1c848dc671d664fccb19e046a12 jdk8-b72
+93b9664f97eeb6f89397a8842318ebacaac9feb9 jdk8-b73
--- a/Makefile	Tue Jan 22 14:27:41 2013 -0500
+++ b/Makefile	Tue Jan 22 11:54:16 2013 -0800
@@ -26,6 +26,11 @@
 # If NEWBUILD is defined, use the new build-infra Makefiles and configure.
 #     See NewMakefile.gmk for more information.
 
+# If not specified, select what the default build is
+ifndef NEWBUILD
+  NEWBUILD=true
+endif
+
 ifeq ($(NEWBUILD),true)
 
   # The new top level Makefile
--- a/NewMakefile.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/NewMakefile.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -23,273 +23,109 @@
 # questions.
 #
 
-# Utilities used in this Makefile
-BASENAME=basename
-CAT=cat
-CD=cd
-CMP=cmp
-CP=cp
-ECHO=echo
-MKDIR=mkdir
-PRINTF=printf
-PWD=pwd
-TAR=tar
-ifeq ($(PLATFORM),windows)
-  ZIP=zip
-else
-  # store symbolic links as the link
-  ZIP=zip -y
-endif
-# Insure we have a path that looks like it came from pwd
-#   (This is mostly for Windows sake and drive letters)
-define UnixPath # path
-$(shell (cd "$1" && $(PWD)))
-endef
-
-# Current root directory
-CURRENT_DIRECTORY := $(shell $(PWD))
-
-# Build directory root
-BUILD_DIR_ROOT = $(CURRENT_DIRECTORY)/build
-
-# All configured Makefiles to run
-ALL_MAKEFILES = $(wildcard $(BUILD_DIR_ROOT)/*-*/Makefile)
-
-# All bundles to create
-ALL_IMAGE_DIRS = $(wildcard $(BUILD_DIR_ROOT)/*-*/images/*-image)
+# This must be the first rule
+default:
 
-# Build all the standard 'all', 'images', and 'clean' targets
-all images clean: checks
-	@if [ "$(ALL_MAKEFILES)" = "" ] ; then \
-	  $(ECHO) "ERROR: No configurations to build"; exit 1; \
-	fi
-	@for bdir in $(dir $(ALL_MAKEFILES)) ; do \
-	  $(ECHO) "$(CD) $${bdir} && $(MAKE) $@" ; \
-	  $(CD) $${bdir} && $(MAKE) $@ ; \
-	done
-
-# TBD: Deploy input
-$(BUILD_DIR_ROOT)/.deploy_input:
-	@if [ "$(ALL_MAKEFILES)" = "" ] ; then \
-	  $(ECHO) "ERROR: No configurations to build"; exit 1; \
-	fi
-	@for bdir in $(dir $(ALL_MAKEFILES)) ; do \
-	  if [ deploy/make/Makefile ] ; then \
-	    echo "Attempting deploy build." ; \
-	    ( \
-	      $(RM) -r $${bdir}/deploy_input ; \
-	      $(MKDIR) -p $${bdir}/deploy_input ; \
-	      ( $(CD) $${bdir}/images && $(TAR) -cf - j2sdk-image j2re-image ) \
-	        | ( $(CD) $${bdir}/deploy_input && $(TAR) -xf - ) ; \
-	    ) ; \
-	  fi; \
-	done
-	touch $@
-
-# TBD: Deploy images
-deploy: $(BUILD_DIR_ROOT)/.deploy_input
-	@if [ "$(ALL_MAKEFILES)" = "" ] ; then \
-	  $(ECHO) "ERROR: No configurations to build"; exit 1; \
-	fi
-	@for bdir in $(dir $(ALL_MAKEFILES)) ; do \
-	  if [ deploy/make/Makefile ] ; then \
-	    echo "Attempting deploy build." ; \
-	    ( \
-	      $(CD) deploy/make && \
-	      $(MAKE) \
-	        ABS_OUTPUTDIR=$${bdir}/deploy_input \
-	        OUTPUTDIR=$${bdir}/deploy_input \
-	    ) ; \
-	  fi; \
-	done
-
-# TBD: Install bundles
-install:
+# Inclusion of this pseudo-target will cause make to execute this file
+# serially, regardless of -j. Recursively called makefiles will not be
+# affected, however. This is required for correct dependency management.
+.NOTPARALLEL:
 
-# Bundle creation
-bundles:
-	@if [ "$(ALL_IMAGE_DIRS)" = "" ] ; then \
-	  $(ECHO) "ERROR: No images to bundle"; exit 1; \
-	fi
-	@for i in $(ALL_IMAGE_DIRS) ; do \
-          $(MKDIR) -p $${i}/../../bundles && \
-          $(RM) $${i}/../../bundles/`$(BASENAME) $${i}`.zip && \
-	  $(ECHO) "$(CD) $${i} && $(ZIP) -q -r ../../bundles/`$(BASENAME) $${i}`.zip ."  && \
-	  $(CD) $${i} && $(ZIP) -q -r ../../bundles/`$(BASENAME) $${i}`.zip . ; \
-	done
-
-# Clobber all the built files
-clobber::
-	$(RM) -r $(BUILD_DIR_ROOT)
-
-# Make various checks to insure the build will be successful
-#   Possibilities:
-#     * Check that if any closed repo is provided, they all must be.
-#     * Check that all open repos exist, at least until we are ready for some
-#       kind of partial build.
-checks:
-	@$(ECHO) "No checks yet"
-
-# Keep track of user targets
-USER_TARGETS += all deploy install images clean clobber checks
-
-###########################################################################
-# To help in adoption of the new configure&&make build process, a bridge
-#   build will use the old settings to run configure and do the build.
-
-# Build with the configure bridge
-bridgeBuild: bridge2configure images
-
-# Bridge from old Makefile ALT settings to configure options
-bridge2configure: $(BUILD_DIR_ROOT)/.bridge2configureOpts
-	bash ./configure $(strip $(shell $(CAT) $<))
-
-# Create a file with configure options created from old Makefile mechanisms.
-$(BUILD_DIR_ROOT)/.bridge2configureOpts: $(BUILD_DIR_ROOT)/.bridge2configureOptsLatest
-	$(RM) $@
-	$(CP) $< $@
+# The shell code below will be executed on /usr/ccs/bin/make on Solaris, but not in GNU make.
+# /usr/ccs/bin/make lacks basically every other flow control mechanism.
+TEST_FOR_NON_GNUMAKE:sh=echo You are not using GNU make/gmake, this is a requirement. Check your path. 1>&2 && exit 1
 
-# Use this file to only change when obvious things have changed
-$(BUILD_DIR_ROOT)/.bridge2configureOptsLatest: FRC
-	$(RM) $@.tmp
-	$(MKDIR) -p $(BUILD_DIR_ROOT)
-	@$(ECHO) " --with-debug-level=$(if $(DEBUG_LEVEL),$(DEBUG_LEVEL),release) " >> $@.tmp
-ifdef ARCH_DATA_MODEL
-	@$(ECHO) " --with-target-bits=$(ARCH_DATA_MODEL) " >> $@.tmp
-endif
-ifdef ALT_PARALLEL_COMPILE_JOBS
-	@$(ECHO) " --with-num-cores=$(ALT_PARALLEL_COMPILE_JOBS) " >> $@.tmp
-endif
-ifdef ALT_BOOTDIR
-	@$(ECHO) " --with-boot-jdk=$(call UnixPath,$(ALT_BOOTDIR)) " >> $@.tmp
-endif
-ifdef ALT_CUPS_HEADERS_PATH
-	@$(ECHO) " --with-cups-include=$(call UnixPath,$(ALT_CUPS_HEADERS_PATH)) " >> $@.tmp
-endif
-ifdef ALT_FREETYPE_HEADERS_PATH
-	@$(ECHO) " --with-freetype=$(call UnixPath,$(ALT_FREETYPE_HEADERS_PATH)/..) " >> $@.tmp
-endif
-	@if [ -f $@ ] ; then \
-          if ! $(CMP) $@ $@.tmp > /dev/null ; then \
-            $(CP) $@.tmp $@ ; \
-          fi ; \
-        else \
-          $(CP) $@.tmp $@ ; \
-        fi
-	$(RM) $@.tmp
-
-# Clobber all the built files
-clobber:: bridge2clobber
-bridge2clobber::
-	$(RM) $(BUILD_DIR_ROOT)/.bridge2*
-	$(RM) $(BUILD_DIR_ROOT)/.deploy_input
-
-# Keep track of phony targets
-PHONY_LIST += bridge2configure bridgeBuild bridge2clobber
-
-###########################################################################
-# Sanity checks (history target)
-#
-
-sanity: checks
-
-# Keep track of user targets
-USER_TARGETS += sanity
-
-###########################################################################
-# Javadocs
-#
-
-javadocs:
-	cd common/makefiles && $(MAKE) -f MakefileJavadoc.gmk
-
-# Keep track of user targets
-USER_TARGETS += javadocs
-
-###########################################################################
-# JPRT targets
-
-ifndef JPRT_ARCHIVE_BUNDLE
-  JPRT_ARCHIVE_BUNDLE=/tmp/jprt_bundles/j2sdk-image.zip
+# Assume we have GNU make, but check version.
+ifeq (,$(findstring 3.81,$(MAKE_VERSION)))
+    ifeq (,$(findstring 3.82,$(MAKE_VERSION)))
+        $(error This version of GNU Make is too low ($(MAKE_VERSION)). Check your path, or upgrade to 3.81 or newer.)
+    endif
 endif
 
-jprt_build_product: DEBUG_LEVEL=release
-jprt_build_product: BUILD_DIRNAME=*-release
-jprt_build_product: jprt_build_generic
+# Locate this Makefile
+ifeq ($(filter /%,$(lastword $(MAKEFILE_LIST))),)
+    makefile_path:=$(CURDIR)/$(lastword $(MAKEFILE_LIST))
+else
+    makefile_path:=$(lastword $(MAKEFILE_LIST))
+endif
+root_dir:=$(dir $(makefile_path))
 
-jprt_build_fastdebug: DEBUG_LEVEL=fastdebug
-jprt_build_fastdebug: BUILD_DIRNAME=*-fastdebug
-jprt_build_fastdebug: jprt_build_generic
+# ... and then we can include our helper functions
+include $(root_dir)/common/makefiles/MakeHelpers.gmk
 
-jprt_build_debug: DEBUG_LEVEL=slowdebug
-jprt_build_debug: BUILD_DIRNAME=*-debug
-jprt_build_debug: jprt_build_generic
-
-jprt_build_generic: $(JPRT_ARCHIVE_BUNDLE)
+$(eval $(call ParseLogLevel))
+$(eval $(call ParseConfAndSpec))
 
-$(JPRT_ARCHIVE_BUNDLE): bridgeBuild bundles
-	$(MKDIR) -p $(@D)
-	$(RM) $@
-	$(CP) $(BUILD_DIR_ROOT)/$(BUILD_DIRNAME)/bundles/j2sdk-image.zip $@
+# Now determine if we have zero, one or several configurations to build.
+ifeq ($(SPEC),)
+    # Since we got past ParseConfAndSpec, we must be building a global target. Do nothing.
+else
+    ifeq ($(words $(SPEC)),1)
+        # We are building a single configuration. This is the normal case. Execute the Main.gmk file.
+        include $(root_dir)/common/makefiles/Main.gmk
+    else
+        # We are building multiple configurations.
+        # First, find out the valid targets
+        # Run the makefile with an arbitraty SPEC using -p -q (quiet dry-run and dump rules) to find
+        # available PHONY targets. Use this list as valid targets to pass on to the repeated calls.
+        all_phony_targets=$(filter-out $(global_targets), $(strip $(shell \
+            $(MAKE) -p -q -f common/makefiles SPEC=$(firstword $(SPEC)) | \
+            grep ^.PHONY: | head -n 1 | cut -d " " -f 2-)))
 
-# Keep track of phony targets
-PHONY_LIST += jprt_build_product jprt_build_fastdebug jprt_build_debug \
-              jprt_build_generic
+$(all_phony_targets):
+	@$(foreach spec,$(SPEC),($(MAKE) -f NewMakefile.gmk SPEC=$(spec) $(VERBOSE) VERBOSE=$(VERBOSE) $@) &&) true
+
+    endif
+endif
 
-###########################################################################
-# Help target
+# Include this after a potential spec file has been included so that the bundles target
+# has access to the spec variables.
+include $(root_dir)/common/makefiles/Jprt.gmk
 
-HELP_FORMAT=%12s%s\n
+# Here are "global" targets, i.e. targets that can be executed without specifying a single configuration.
+# If you addd more global targets, please update the variable global_targets in MakeHelpers.
 
 help:
-	@$(PRINTF) "# JDK Makefile\n"
-	@$(PRINTF) "#\n"
-	@$(PRINTF) "# Usage: make [Target]\n"
-	@$(PRINTF) "#\n"
-	@$(PRINTF) "#   $(HELP_FORMAT)" "Target   " "Description"
-	@$(PRINTF) "#   $(HELP_FORMAT)" "------   " "-----------"
-	@for i in $(USER_TARGETS) ; do \
-	  $(MAKE) help_$${i} ; \
-	done
-	@$(PRINTF) "#\n"
+	$(info )
+	$(info OpenJDK Makefile help)
+	$(info =====================)
+	$(info )
+	$(info Common make targets)
+	$(info .  make [default]         # Compile all product in langtools, hotspot, jaxp, jaxws,)
+	$(info .                         # corba and jdk)
+	$(info .  make all               # Compile everything, all repos and images)
+	$(info .  make images            # Create complete j2sdk and j2re images)
+	$(info .  make overlay-images    # Create limited images for sparc 64 bit platforms)
+	$(info .  make bootcycle-images  # Build images twice, second time with newly build JDK)
+	$(info .  make install           # Install the generated images locally)
+	$(info .  make clean             # Remove all files generated by make, but not those)
+	$(info .                         # generated by configure)
+	$(info .  make dist-clean        # Remove all files, including configuration)
+	$(info .  make help              # Give some help on using make)
+	$(info .  make test              # Run tests, default is all tests (see TEST below))
+	$(info )
+	$(info Targets for specific components)
+	$(info (Component is any of langtools, corba, jaxp, jaxws, hotspot, jdk, images or overlay-images))
+	$(info .  make <component>       # Build <component> and everything it depends on. )
+	$(info .  make <component>-only  # Build <component> only, without dependencies. This)
+	$(info .                         # is faster but can result in incorrect build results!)
+	$(info .  make clean-<component> # Remove files generated by make for <component>)
+	$(info )
+	$(info Useful make variables)
+	$(info .  make CONF=             # Build all configurations (note, assignment is empty))
+	$(info .  make CONF=<substring>  # Build the configuration(s) with a name matching)
+	$(info .                         # <substring>)
+	$(info )
+	$(info .  make LOG=<loglevel>    # Change the log level from warn to <loglevel>)
+	$(info .                         # Available log levels are:)
+	$(info .                         # 'warn' (default), 'info', 'debug' and 'trace')
+	$(info .                         # To see executed command lines, use LOG=debug)
+	$(info )
+	$(info .  make JOBS=<n>          # Run <n> parallel make jobs)
+	$(info .                         # Note that -jN does not work as expected!)
+	$(info )
+	$(info .  make test TEST=<test>  # Only run the given test or tests, e.g.)
+	$(info .                         # make test TEST="jdk_lang jdk_net")
+	$(info )
 
-help_all:
-	@$(PRINTF) "#   $(HELP_FORMAT)" "$(subst help_,,$@) - " \
-	"Build the entire jdk but not the images"
-help_images:
-	@$(PRINTF) "#   $(HELP_FORMAT)" "$(subst help_,,$@) - " \
-	"Create the jdk images for the builds"
-help_deploy:
-	@$(PRINTF) "#   $(HELP_FORMAT)" "$(subst help_,,$@) - " \
-	"Create the jdk deploy images from the jdk images"
-help_install:
-	@$(PRINTF) "#   $(HELP_FORMAT)" "$(subst help_,,$@) - " \
-	"Create the jdk install bundles from the deploy images"
-help_clean:
-	@$(PRINTF) "#   $(HELP_FORMAT)" "$(subst help_,,$@) - " \
-	"Clean and prepare for a fresh build from scratch"
-help_clobber:
-	@$(PRINTF) "#   $(HELP_FORMAT)" "$(subst help_,,$@) - " \
-	"Clean and also purge any hidden derived data"
-help_checks:
-	@$(PRINTF) "#   $(HELP_FORMAT)" "$(subst help_,,$@) - " \
-	"Perform various checks to make sure we can build"
-help_sanity:
-	@$(PRINTF) "#   $(HELP_FORMAT)" "$(subst help_,,$@) - " \
-	"Same as 'make checks'"
-help_javadocs:
-	@$(PRINTF) "#   $(HELP_FORMAT)" "$(subst help_,,$@) - " \
-	"Build the javadocs"
-help_help:
-	@$(PRINTF) "#   $(HELP_FORMAT)" "$(subst help_,,$@) - " \
-	"Print out the help messages"
-
-# Keep track of user targets
-USER_TARGETS += help
-
-###########################################################################
-# Phony targets
-.PHONY: $(PHONY_LIST) $(USER_TARGETS)
-
-# Force target
-FRC:
+.PHONY: help
--- a/common/autoconf/Makefile.in	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/autoconf/Makefile.in	Tue Jan 22 11:54:16 2013 -0800
@@ -24,4 +24,4 @@
 # This Makefile was generated by configure @DATE_WHEN_CONFIGURED@
 # GENERATED FILE, DO NOT EDIT
 SPEC:=@OUTPUT_ROOT@/spec.gmk
-include @SRC_ROOT@/common/makefiles/Makefile
+include @SRC_ROOT@/NewMakefile.gmk
--- a/common/autoconf/autogen.sh	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/autoconf/autogen.sh	Tue Jan 22 11:54:16 2013 -0800
@@ -26,9 +26,11 @@
 
 # Create a timestamp as seconds since epoch
 if test "x`uname -s`" = "xSunOS"; then
-  # date +%s is not available on Solaris, use this workaround
-  # from http://solarisjedi.blogspot.co.uk/2006/06/solaris-date-command-and-epoch-time.html
-  TIMESTAMP=`/usr/bin/truss /usr/bin/date 2>&1 |  nawk -F= '/^time\(\)/ {gsub(/ /,"",$2);print $2}'`
+  TIMESTAMP=`date +%s`
+  if test "x$TIMESTAMP" = "x%s"; then
+    # date +%s not available on this Solaris, use workaround from nawk(1):
+    TIMESTAMP=`nawk 'BEGIN{print srand()}'`
+  fi
 else
   TIMESTAMP=`date +%s`
 fi
--- a/common/autoconf/basics.m4	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/autoconf/basics.m4	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -234,7 +234,9 @@
 BASIC_REQUIRE_PROG(CAT, cat)
 BASIC_REQUIRE_PROG(CHMOD, chmod)
 BASIC_REQUIRE_PROG(CMP, cmp)
+BASIC_REQUIRE_PROG(COMM, comm)
 BASIC_REQUIRE_PROG(CP, cp)
+BASIC_REQUIRE_PROG(CPIO, cpio)
 BASIC_REQUIRE_PROG(CUT, cut)
 BASIC_REQUIRE_PROG(DATE, date)
 BASIC_REQUIRE_PROG(DIFF, [gdiff diff])
@@ -633,6 +635,18 @@
   fi
 ])
 
+# Check that source files have basic read permissions set. This might
+# not be the case in cygwin in certain conditions.
+AC_DEFUN_ONCE([BASIC_CHECK_SRC_PERMS],
+[
+  if test x"$OPENJDK_BUILD_OS" = xwindows; then
+    file_to_test="$SRC_ROOT/LICENSE"
+    if test `$STAT -c '%a' "$file_to_test"` -lt 400; then
+      AC_MSG_ERROR([Bad file permissions on src files. This is usually caused by cloning the repositories with a non cygwin hg in a directory not created in cygwin.])
+    fi
+  fi
+])
+
 AC_DEFUN_ONCE([BASIC_TEST_USABILITY_ISSUES],
 [
 
@@ -642,6 +656,8 @@
   [OUTPUT_DIR_IS_LOCAL="no"])
 AC_MSG_RESULT($OUTPUT_DIR_IS_LOCAL)
 
+BASIC_CHECK_SRC_PERMS
+
 # Check if the user has any old-style ALT_ variables set.
 FOUND_ALT_VARIABLES=`env | grep ^ALT_`
 
--- a/common/autoconf/basics_windows.m4	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/autoconf/basics_windows.m4	Tue Jan 22 11:54:16 2013 -0800
@@ -175,7 +175,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -191,7 +191,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
--- a/common/autoconf/build-aux/autoconf-config.guess	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/autoconf/build-aux/autoconf-config.guess	Tue Jan 22 11:54:16 2013 -0800
@@ -1,4 +1,29 @@
 #! /bin/sh
+#
+# 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.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
 # Attempt to guess a canonical system name.
 #   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
 #   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
--- a/common/autoconf/build-aux/config.sub	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/autoconf/build-aux/config.sub	Tue Jan 22 11:54:16 2013 -0800
@@ -1,4 +1,30 @@
 #! /bin/sh
+
+#
+# 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.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
 # Configuration validation subroutine script.
 #   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
 #   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
--- a/common/autoconf/build-aux/pkg.m4	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/autoconf/build-aux/pkg.m4	Tue Jan 22 11:54:16 2013 -0800
@@ -1,4 +1,30 @@
 # pkg.m4 - Macros to locate and utilise pkg-config.            -*- Autoconf -*-
+
+#
+# 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.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
 # 
 # Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
 #
--- a/common/autoconf/closed.version.numbers	Tue Jan 22 14:27:41 2013 -0500
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,32 +0,0 @@
-#
-# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-LAUNCHER_NAME=java
-PRODUCT_NAME="Java(TM)"
-PRODUCT_SUFFIX="SE Runtime Environment"
-JDK_RC_PLATFORM_NAME="Platform SE"
-COMPANY_NAME="Oracle Corporation"
-
-# Might need better names for these
-MACOSX_BUNDLE_NAME_BASE="Java SE"
-MACOSX_BUNDLE_ID_BASE="com.oracle.java"
--- a/common/autoconf/compare.sh.in	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/autoconf/compare.sh.in	Tue Jan 22 11:54:16 2013 -0800
@@ -1,6 +1,6 @@
 #!/bin/bash
 #
-# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, 2013 Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -48,6 +48,7 @@
 JAVAP="@FIXPATH@ @BOOT_JDK@/bin/javap"
 LDD="@LDD@"
 MKDIR="@MKDIR@"
+NAWK="@NAWK@"
 NM="@NM@"
 OBJDUMP="@OBJDUMP@"
 OTOOL="@OTOOL@"
--- a/common/autoconf/configure.ac	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/autoconf/configure.ac	Tue Jan 22 11:54:16 2013 -0800
@@ -83,6 +83,9 @@
 BASIC_SETUP_PATHS
 BASIC_SETUP_LOGGING
 
+# Check if it's a pure open build or if custom sources are to be used.
+JDKOPT_SETUP_OPEN_OR_CUSTOM
+
 # These are needed to be able to create a configuration name (and thus the output directory)
 JDKOPT_SETUP_JDK_VARIANT
 JDKOPT_SETUP_JVM_VARIANTS
--- a/common/autoconf/generated-configure.sh	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/autoconf/generated-configure.sh	Tue Jan 22 11:54:16 2013 -0800
@@ -752,10 +752,7 @@
 JAVA_CHECK
 JAVAC_CHECK
 COOKED_BUILD_NUMBER
-FULL_VERSION
-RELEASE
 JDK_VERSION
-RUNTIME_NAME
 COPYRIGHT_YEAR
 MACOSX_BUNDLE_ID_BASE
 MACOSX_BUNDLE_NAME_BASE
@@ -770,6 +767,7 @@
 JDK_MICRO_VERSION
 JDK_MINOR_VERSION
 JDK_MAJOR_VERSION
+USER_RELEASE_SUFFIX
 COMPRESS_JARS
 UNLIMITED_CRYPTO
 CACERTS_FILE
@@ -777,14 +775,12 @@
 BUILD_HEADLESS
 SUPPORT_HEADFUL
 SUPPORT_HEADLESS
-SET_OPENJDK
 BDEPS_FTP
 BDEPS_UNZIP
 OS_VERSION_MICRO
 OS_VERSION_MINOR
 OS_VERSION_MAJOR
 PKG_CONFIG
-COMM
 TIME
 STAT
 HG
@@ -812,10 +808,12 @@
 JVM_VARIANT_ZEROSHARK
 JVM_VARIANT_ZERO
 JVM_VARIANT_KERNEL
+JVM_VARIANT_MINIMAL1
 JVM_VARIANT_CLIENT
 JVM_VARIANT_SERVER
 JVM_VARIANTS
 JDK_VARIANT
+SET_OPENJDK
 BUILD_LOG_WRAPPER
 BUILD_LOG_PREVIOUS
 BUILD_LOG
@@ -899,7 +897,9 @@
 DIFF
 DATE
 CUT
+CPIO
 CP
+COMM
 CMP
 CHMOD
 CAT
@@ -954,6 +954,7 @@
 with_sys_root
 with_tools_dir
 with_devkit
+enable_openjdk_only
 with_jdk_variant
 with_jvm_variants
 enable_debug
@@ -963,11 +964,13 @@
 with_builddeps_server
 with_builddeps_dir
 with_builddeps_group
-enable_openjdk_only
 enable_headful
 enable_hotspot_test_in_build
 with_cacerts_file
 enable_unlimited_crypto
+with_milestone
+with_build_number
+with_user_release_suffix
 with_boot_jdk
 with_boot_jdk_jvmargs
 with_add_source_root
@@ -1646,10 +1649,10 @@
   --disable-option-checking  ignore unrecognized --enable/--with options
   --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
   --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
+  --enable-openjdk-only   suppress building custom source even if present
+                          [disabled]
   --enable-debug          set the debug level to fastdebug (shorthand for
                           --with-debug-level=fastdebug) [disabled]
-  --enable-openjdk-only   supress building closed source even if present
-                          [disabled]
   --disable-headful       disable building headful support (graphical UI
                           support) [enabled]
   --enable-hotspot-test-in-build
@@ -1684,7 +1687,7 @@
                           sys-root (for cross-compiling)
   --with-jdk-variant      JDK variant to build (normal) [normal]
   --with-jvm-variants     JVM variants (separated by commas) to build (server,
-                          client, kernel, zero, zeroshark) [server]
+                          client, minimal1, kernel, zero, zeroshark) [server]
   --with-debug-level      set the debug level (release, fastdebug, slowdebug)
                           [release]
   --with-conf-name        use this as the name of the configuration [generated
@@ -1697,6 +1700,11 @@
   --with-builddeps-group  chgrp the downloaded build dependencies to this
                           group
   --with-cacerts-file     specify alternative cacerts file
+  --with-milestone        Set milestone value for build [internal]
+  --with-build-number     Set build number value for build [b00]
+  --with-user-release-suffix
+                          Add a custom string to the version string if build
+                          number isn't set.[username_builddateb00]
   --with-boot-jdk         path to Boot JDK (used to bootstrap build) [probed]
   --with-boot-jdk-jvmargs specify JVM arguments to be passed to all
                           invocations of the Boot JDK, overriding the default
@@ -2919,6 +2927,32 @@
 
 
 # pkg.m4 - Macros to locate and utilise pkg-config.            -*- Autoconf -*-
+
+#
+# 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.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
 #
 # Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
 #
@@ -2982,7 +3016,7 @@
 
 # Include these first...
 #
-# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -3079,6 +3113,10 @@
 # Argument 3: what to do otherwise (remote disk or failure)
 
 
+# Check that source files have basic read permissions set. This might
+# not be the case in cygwin in certain conditions.
+
+
 
 
 #
@@ -3393,7 +3431,7 @@
 
 
 #
-# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -3424,7 +3462,18 @@
 
 
 
-
+###############################################################################
+#
+# Should we build only OpenJDK even if closed sources are present?
+#
+
+
+
+
+###############################################################################
+#
+# Setup version numbers
+#
 
 
 
@@ -3674,7 +3723,7 @@
 #CUSTOM_AUTOCONF_INCLUDE
 
 # Do not change or remove the following line, it is needed for consistency checks:
-DATE_WHEN_GENERATED=1355849613
+DATE_WHEN_GENERATED=1358499442
 
 ###############################################################################
 #
@@ -4001,6 +4050,65 @@
 
 
 
+    for ac_prog in comm
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_path_COMM+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $COMM in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_COMM="$COMM" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_COMM="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  ;;
+esac
+fi
+COMM=$ac_cv_path_COMM
+if test -n "$COMM"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $COMM" >&5
+$as_echo "$COMM" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$COMM" && break
+done
+
+
+    if test "x$COMM" = x; then
+        if test "xcomm" = x; then
+          PROG_NAME=comm
+        else
+          PROG_NAME=comm
+        fi
+        { $as_echo "$as_me:${as_lineno-$LINENO}: Could not find $PROG_NAME!" >&5
+$as_echo "$as_me: Could not find $PROG_NAME!" >&6;}
+        as_fn_error $? "Cannot continue" "$LINENO" 5
+    fi
+
+
+
     for ac_prog in cp
 do
   # Extract the first word of "$ac_prog", so it can be a program name with args.
@@ -4060,6 +4168,65 @@
 
 
 
+    for ac_prog in cpio
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_path_CPIO+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $CPIO in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_CPIO="$CPIO" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_path_CPIO="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  ;;
+esac
+fi
+CPIO=$ac_cv_path_CPIO
+if test -n "$CPIO"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPIO" >&5
+$as_echo "$CPIO" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$CPIO" && break
+done
+
+
+    if test "x$CPIO" = x; then
+        if test "xcpio" = x; then
+          PROG_NAME=cpio
+        else
+          PROG_NAME=cpio
+        fi
+        { $as_echo "$as_me:${as_lineno-$LINENO}: Could not find $PROG_NAME!" >&5
+$as_echo "$as_me: Could not find $PROG_NAME!" >&6;}
+        as_fn_error $? "Cannot continue" "$LINENO" 5
+    fi
+
+
+
     for ac_prog in cut
 do
   # Extract the first word of "$ac_prog", so it can be a program name with args.
@@ -7346,6 +7513,53 @@
 
 
 
+# Check if it's a pure open build or if custom sources are to be used.
+
+  # Check whether --enable-openjdk-only was given.
+if test "${enable_openjdk_only+set}" = set; then :
+  enableval=$enable_openjdk_only;
+else
+  enable_openjdk_only="no"
+fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for presence of closed sources" >&5
+$as_echo_n "checking for presence of closed sources... " >&6; }
+  if test -d "$SRC_ROOT/jdk/src/closed"; then
+    CLOSED_SOURCE_PRESENT=yes
+  else
+    CLOSED_SOURCE_PRESENT=no
+  fi
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CLOSED_SOURCE_PRESENT" >&5
+$as_echo "$CLOSED_SOURCE_PRESENT" >&6; }
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if closed source is suppressed (openjdk-only)" >&5
+$as_echo_n "checking if closed source is suppressed (openjdk-only)... " >&6; }
+  SUPPRESS_CLOSED_SOURCE="$enable_openjdk_only"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $SUPPRESS_CLOSED_SOURCE" >&5
+$as_echo "$SUPPRESS_CLOSED_SOURCE" >&6; }
+
+  if test "x$CLOSED_SOURCE_PRESENT" = xno; then
+    OPENJDK=true
+    if test "x$SUPPRESS_CLOSED_SOURCE" = "xyes"; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: No closed source present, --enable-openjdk-only makes no sense" >&5
+$as_echo "$as_me: WARNING: No closed source present, --enable-openjdk-only makes no sense" >&2;}
+    fi
+  else
+    if test "x$SUPPRESS_CLOSED_SOURCE" = "xyes"; then
+      OPENJDK=true
+    else
+      OPENJDK=false
+    fi
+  fi
+
+  if test "x$OPENJDK" = "xtrue"; then
+    SET_OPENJDK="OPENJDK=true"
+  fi
+
+
+
+
 # These are needed to be able to create a configuration name (and thus the output directory)
 
 ###############################################################################
@@ -7387,6 +7601,7 @@
 # Currently we have:
 #    server: normal interpreter and a tiered C1/C2 compiler
 #    client: normal interpreter and C1 (no C2 compiler) (only 32-bit platforms)
+#    minimal1: reduced form of client with optional VM services and features stripped out
 #    kernel: kernel footprint JVM that passes the TCK without major performance problems,
 #             ie normal interpreter and C1, only the serial GC, kernel jvmti etc
 #    zero: no machine code interpreter, no compiler
@@ -7405,16 +7620,17 @@
 fi
 
 JVM_VARIANTS=",$with_jvm_variants,"
-TEST_VARIANTS=`$ECHO "$JVM_VARIANTS" | $SED -e 's/server,//' -e 's/client,//' -e 's/kernel,//' -e 's/zero,//' -e 's/zeroshark,//'`
+TEST_VARIANTS=`$ECHO "$JVM_VARIANTS" | $SED -e 's/server,//' -e 's/client,//'  -e 's/minimal1,//' -e 's/kernel,//' -e 's/zero,//' -e 's/zeroshark,//'`
 
 if test "x$TEST_VARIANTS" != "x,"; then
-   as_fn_error $? "The available JVM variants are: server, client, kernel, zero, zeroshark" "$LINENO" 5
+   as_fn_error $? "The available JVM variants are: server, client, minimal1, kernel, zero, zeroshark" "$LINENO" 5
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_jvm_variants" >&5
 $as_echo "$with_jvm_variants" >&6; }
 
 JVM_VARIANT_SERVER=`$ECHO "$JVM_VARIANTS" | $SED -e '/,server,/!s/.*/false/g' -e '/,server,/s/.*/true/g'`
 JVM_VARIANT_CLIENT=`$ECHO "$JVM_VARIANTS" | $SED -e '/,client,/!s/.*/false/g' -e '/,client,/s/.*/true/g'`
+JVM_VARIANT_MINIMAL1=`$ECHO "$JVM_VARIANTS" | $SED -e '/,minimal1,/!s/.*/false/g' -e '/,minimal1,/s/.*/true/g'`
 JVM_VARIANT_KERNEL=`$ECHO "$JVM_VARIANTS" | $SED -e '/,kernel,/!s/.*/false/g' -e '/,kernel,/s/.*/true/g'`
 JVM_VARIANT_ZERO=`$ECHO "$JVM_VARIANTS" | $SED -e '/,zero,/!s/.*/false/g' -e '/,zero,/s/.*/true/g'`
 JVM_VARIANT_ZEROSHARK=`$ECHO "$JVM_VARIANTS" | $SED -e '/,zeroshark,/!s/.*/false/g' -e '/,zeroshark,/s/.*/true/g'`
@@ -7429,10 +7645,15 @@
         as_fn_error $? "You cannot build a kernel JVM for a 64-bit machine." "$LINENO" 5
     fi
 fi
+if test "x$JVM_VARIANT_MINIMAL1" = xtrue; then
+    if test "x$OPENJDK_TARGET_CPU_BITS" = x64; then
+        as_fn_error $? "You cannot build a minimal JVM for a 64-bit machine." "$LINENO" 5
+    fi
+fi
 
 # Replace the commas with AND for use in the build directory name.
 ANDED_JVM_VARIANTS=`$ECHO "$JVM_VARIANTS" | $SED -e 's/^,//' -e 's/,$//' -e 's/,/AND/'`
-COUNT_VARIANTS=`$ECHO "$JVM_VARIANTS" | $SED -e 's/server,/1/' -e 's/client,/1/' -e 's/kernel,/1/' -e 's/zero,/1/' -e 's/zeroshark,/1/'`
+COUNT_VARIANTS=`$ECHO "$JVM_VARIANTS" | $SED -e 's/server,/1/' -e 's/client,/1/' -e 's/minimal1,/1/' -e 's/kernel,/1/' -e 's/zero,/1/' -e 's/zeroshark,/1/'`
 if test "x$COUNT_VARIANTS" != "x,1"; then
     BUILDING_MULTIPLE_JVM_VARIANTS=yes
 else
@@ -7446,6 +7667,7 @@
 
 
 
+
 if test "x$OPENJDK_TARGET_OS" = "xmacosx"; then
    MACOSX_UNIVERSAL="true"
 fi
@@ -7531,7 +7753,9 @@
 #####
 # Generate the legacy makefile targets for hotspot.
 # The hotspot api for selecting the build artifacts, really, needs to be improved.
-#
+# JDK-7195896 will fix this on the hotspot side by using the JVM_VARIANT_* variables to
+# determine what needs to be built. All we will need to set here is all_product, all_fastdebug etc
+# But until then ...
 HOTSPOT_TARGET=""
 
 if test "x$JVM_VARIANT_SERVER" = xtrue; then
@@ -7542,6 +7766,10 @@
     HOTSPOT_TARGET="$HOTSPOT_TARGET${HOTSPOT_DEBUG_LEVEL}1 "
 fi
 
+if test "x$JVM_VARIANT_MINIMAL1" = xtrue; then
+    HOTSPOT_TARGET="$HOTSPOT_TARGET${HOTSPOT_DEBUG_LEVEL}minimal1 "
+fi
+
 if test "x$JVM_VARIANT_KERNEL" = xtrue; then
     HOTSPOT_TARGET="$HOTSPOT_TARGET${HOTSPOT_DEBUG_LEVEL}kernel "
 fi
@@ -7561,7 +7789,7 @@
 # from configure, but only server is valid anyway. Fix this
 # when hotspot makefiles are rewritten.
 if test "x$MACOSX_UNIVERSAL" = xtrue; then
-    HOTSPOT_TARGET=universal_product
+    HOTSPOT_TARGET=universal_${HOTSPOT_EXPORT}
 fi
 
 #####
@@ -7962,7 +8190,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -7978,7 +8206,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -8319,7 +8547,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -8335,7 +8563,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -8673,7 +8901,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -8689,7 +8917,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -9032,7 +9260,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -9048,7 +9276,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -9385,7 +9613,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -9401,7 +9629,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -10439,54 +10667,6 @@
 
 ###############################################################################
 #
-# Should we build only OpenJDK even if closed sources are present?
-#
-# Check whether --enable-openjdk-only was given.
-if test "${enable_openjdk_only+set}" = set; then :
-  enableval=$enable_openjdk_only;
-else
-  enable_openjdk_only="no"
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for presence of closed sources" >&5
-$as_echo_n "checking for presence of closed sources... " >&6; }
-if test -d "$SRC_ROOT/jdk/src/closed"; then
-    CLOSED_SOURCE_PRESENT=yes
-else
-    CLOSED_SOURCE_PRESENT=no
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CLOSED_SOURCE_PRESENT" >&5
-$as_echo "$CLOSED_SOURCE_PRESENT" >&6; }
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if closed source is supressed (openjdk-only)" >&5
-$as_echo_n "checking if closed source is supressed (openjdk-only)... " >&6; }
-SUPRESS_CLOSED_SOURCE="$enable_openjdk_only"
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $SUPRESS_CLOSED_SOURCE" >&5
-$as_echo "$SUPRESS_CLOSED_SOURCE" >&6; }
-
-if test "x$CLOSED_SOURCE_PRESENT" = xno; then
-  OPENJDK=true
-  if test "x$SUPRESS_CLOSED_SOURCE" = "xyes"; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: No closed source present, --enable-openjdk-only makes no sense" >&5
-$as_echo "$as_me: WARNING: No closed source present, --enable-openjdk-only makes no sense" >&2;}
-  fi
-else
-  if test "x$SUPRESS_CLOSED_SOURCE" = "xyes"; then
-    OPENJDK=true
-  else
-    OPENJDK=false
-  fi
-fi
-
-if test "x$OPENJDK" = "xtrue"; then
-    SET_OPENJDK="OPENJDK=true"
-fi
-
-
-
-###############################################################################
-#
 # Should we build a JDK/JVM with headful support (ie a graphical ui)?
 # We always build headless support.
 #
@@ -10585,10 +10765,56 @@
 
 
 # Source the version numbers
-. $AUTOCONF_DIR/version.numbers
-if test "x$OPENJDK" = "xfalse"; then
-    . $AUTOCONF_DIR/closed.version.numbers
-fi
+. $AUTOCONF_DIR/version-numbers
+
+# Get the settings from parameters
+
+# Check whether --with-milestone was given.
+if test "${with_milestone+set}" = set; then :
+  withval=$with_milestone;
+fi
+
+if test "x$with_milestone" = xyes; then
+  as_fn_error $? "Milestone must have a value" "$LINENO" 5
+elif test "x$with_milestone" != x; then
+    MILESTONE="$with_milestone"
+else
+  MILESTONE=internal
+fi
+
+
+# Check whether --with-build-number was given.
+if test "${with_build_number+set}" = set; then :
+  withval=$with_build_number;
+fi
+
+if test "x$with_build_number" = xyes; then
+  as_fn_error $? "Build number must have a value" "$LINENO" 5
+elif test "x$with_build_number" != x; then
+  JDK_BUILD_NUMBER="$with_build_number"
+fi
+if test "x$JDK_BUILD_NUMBER" = x; then
+  JDK_BUILD_NUMBER=b00
+fi
+
+
+# Check whether --with-user-release-suffix was given.
+if test "${with_user_release_suffix+set}" = set; then :
+  withval=$with_user_release_suffix;
+fi
+
+if test "x$with_user_release_suffix" = xyes; then
+  as_fn_error $? "Release suffix must have a value" "$LINENO" 5
+elif test "x$with_user_release_suffix" != x; then
+  USER_RELEASE_SUFFIX="$with_user_release_suffix"
+else
+  BUILD_DATE=`date '+%Y_%m_%d_%H_%M'`
+  # Avoid [:alnum:] since it depends on the locale.
+  CLEAN_USERNAME=`echo "$USER" | $TR -d -c 'abcdefghijklmnopqrstuvqxyz0123456789'`
+  USER_RELEASE_SUFFIX=`echo "${CLEAN_USERNAME}_${BUILD_DATE}" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+fi
+
+
 # Now set the JDK version, milestone, build number etc.
 
 
@@ -10607,33 +10833,12 @@
 COPYRIGHT_YEAR=`date +'%Y'`
 
 
-RUNTIME_NAME="$PRODUCT_NAME $PRODUCT_SUFFIX"
-
-
 if test "x$JDK_UPDATE_VERSION" != x; then
-    JDK_VERSION="${JDK_MAJOR_VERSION}.${JDK_MINOR_VERSION}.${JDK_MICRO_VERSION}_${JDK_UPDATE_VERSION}"
-else
-    JDK_VERSION="${JDK_MAJOR_VERSION}.${JDK_MINOR_VERSION}.${JDK_MICRO_VERSION}"
-fi
-
-
-if test "x$MILESTONE" != x; then
-    RELEASE="${JDK_VERSION}-${MILESTONE}${BUILD_VARIANT_RELEASE}"
-else
-    RELEASE="${JDK_VERSION}${BUILD_VARIANT_RELEASE}"
-fi
-
-
-if test "x$JDK_BUILD_NUMBER" != x; then
-    FULL_VERSION="${RELEASE}-${JDK_BUILD_NUMBER}"
-else
-    JDK_BUILD_NUMBER=b00
-    BUILD_DATE=`date '+%Y_%m_%d_%H_%M'`
-    # Avoid [:alnum:] since it depends on the locale.
-    CLEAN_USERNAME=`echo "$USER" | $TR -d -c 'abcdefghijklmnopqrstuvqxyz0123456789'`
-    USER_RELEASE_SUFFIX=`echo "${CLEAN_USERNAME}_${BUILD_DATE}" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
-    FULL_VERSION="${RELEASE}-${USER_RELEASE_SUFFIX}-${JDK_BUILD_NUMBER}"
-fi
+  JDK_VERSION="${JDK_MAJOR_VERSION}.${JDK_MINOR_VERSION}.${JDK_MICRO_VERSION}_${JDK_UPDATE_VERSION}"
+else
+  JDK_VERSION="${JDK_MAJOR_VERSION}.${JDK_MINOR_VERSION}.${JDK_MICRO_VERSION}"
+fi
+
 
 COOKED_BUILD_NUMBER=`$ECHO $JDK_BUILD_NUMBER | $SED -e 's/^b//' -e 's/^0//'`
 
@@ -16225,7 +16430,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -16241,7 +16446,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -16825,7 +17030,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -16841,7 +17046,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -17136,7 +17341,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -17152,7 +17357,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -17442,7 +17647,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -17458,7 +17663,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -18040,7 +18245,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -18056,7 +18261,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -18476,7 +18681,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -18492,7 +18697,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -19609,7 +19814,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -19625,7 +19830,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -20045,7 +20250,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -20061,7 +20266,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -20946,7 +21151,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -20962,7 +21167,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -21327,7 +21532,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -21343,7 +21548,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -21674,7 +21879,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -21690,7 +21895,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -22011,7 +22216,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -22027,7 +22232,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -22332,7 +22537,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -22348,7 +22553,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -22706,7 +22911,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -22722,7 +22927,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -23012,7 +23217,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -23028,7 +23233,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -23423,7 +23628,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -23439,7 +23644,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -23823,7 +24028,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -23839,7 +24044,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -24152,7 +24357,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -24168,7 +24373,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -24469,7 +24674,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -24485,7 +24690,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -24775,7 +24980,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -24791,7 +24996,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -25081,7 +25286,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -25097,7 +25302,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -25440,7 +25645,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -25456,7 +25661,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -25798,7 +26003,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -25814,7 +26019,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -26171,7 +26376,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -26187,7 +26392,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -26542,7 +26747,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -26558,7 +26763,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -26851,7 +27056,7 @@
   # bat and cmd files are not always considered executable in cygwin causing which
   # to not find them
   if test "x$new_path" = x \
-           && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+           && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
            && test "x`$LS \"$path\" 2>/dev/null`" != x; then
     new_path=`$CYGPATH -u "$path"`
   fi
@@ -26867,7 +27072,7 @@
     # bat and cmd files are not always considered executable in cygwin causing which
     # to not find them
     if test "x$new_path" = x \
-             && test "x`$ECHO \"$path\" | $GREP -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
+             && test "x`$ECHO \"$path\" | $GREP -i -e \"\\.bat$\" -e \"\\.cmd$\"`" != x \
              && test "x`$LS \"$path\" 2>/dev/null`" != x; then
       new_path=`$CYGPATH -u "$path"`
     fi
@@ -28105,11 +28310,14 @@
 
     # On some platforms (mac) the linker warns about non existing -L dirs.
     # Add server first if available. Linking aginst client does not always produce the same results.
-    # Only add client dir if client is being built. Default to server for other variants.
+    # Only add client dir if client is being built. Add minimal (note not minimal1) if only building minimal1.
+    # Default to server for other variants.
     if test "x$JVM_VARIANT_SERVER" = xtrue; then
         LDFLAGS_JDKLIB="${LDFLAGS_JDKLIB} -L${JDK_OUTPUTDIR}/lib${OPENJDK_TARGET_CPU_LIBDIR}/server"
     elif test "x$JVM_VARIANT_CLIENT" = xtrue; then
         LDFLAGS_JDKLIB="${LDFLAGS_JDKLIB} -L${JDK_OUTPUTDIR}/lib${OPENJDK_TARGET_CPU_LIBDIR}/client"
+    elif test "x$JVM_VARIANT_MINIMAL1" = xtrue; then
+        LDFLAGS_JDKLIB="${LDFLAGS_JDKLIB} -L${JDK_OUTPUTDIR}/lib${OPENJDK_TARGET_CPU_LIBDIR}/minimal"
     else
         LDFLAGS_JDKLIB="${LDFLAGS_JDKLIB} -L${JDK_OUTPUTDIR}/lib${OPENJDK_TARGET_CPU_LIBDIR}/server"
     fi
@@ -30984,7 +31192,7 @@
 # The name of the Service Agent jar.
 SALIB_NAME="${LIBRARY_PREFIX}saproc${SHARED_LIBRARY_SUFFIX}"
 if test "x$OPENJDK_TARGET_OS" = "xwindows"; then
-    SALIB_NAME="${LIBRARY_PREFIX}sawindbg${SHARED_LIBRARY_SUFFIX}"
+  SALIB_NAME="${LIBRARY_PREFIX}sawindbg${SHARED_LIBRARY_SUFFIX}"
 fi
 
 
@@ -31520,6 +31728,14 @@
 
 # Check for some common pitfalls
 
+  if test x"$OPENJDK_BUILD_OS" = xwindows; then
+    file_to_test="$SRC_ROOT/LICENSE"
+    if test `$STAT -c '%a' "$file_to_test"` -lt 400; then
+      as_fn_error $? "Bad file permissions on src files. This is usually caused by cloning the repositories with a non cygwin hg in a directory not created in cygwin." "$LINENO" 5
+    fi
+  fi
+
+
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking if build directory is on local disk" >&5
 $as_echo_n "checking if build directory is on local disk... " >&6; }
@@ -31550,6 +31766,8 @@
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OUTPUT_DIR_IS_LOCAL" >&5
 $as_echo "$OUTPUT_DIR_IS_LOCAL" >&6; }
 
+
+
 # Check if the user has any old-style ALT_ variables set.
 FOUND_ALT_VARIABLES=`env | grep ^ALT_`
 
--- a/common/autoconf/jdk-options.m4	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/autoconf/jdk-options.m4	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -60,28 +60,30 @@
 # Currently we have:
 #    server: normal interpreter and a tiered C1/C2 compiler
 #    client: normal interpreter and C1 (no C2 compiler) (only 32-bit platforms)
+#    minimal1: reduced form of client with optional VM services and features stripped out
 #    kernel: kernel footprint JVM that passes the TCK without major performance problems,
 #             ie normal interpreter and C1, only the serial GC, kernel jvmti etc
 #    zero: no machine code interpreter, no compiler
 #    zeroshark: zero interpreter and shark/llvm compiler backend
 AC_MSG_CHECKING([which variants of the JVM to build])
 AC_ARG_WITH([jvm-variants], [AS_HELP_STRING([--with-jvm-variants],
-	[JVM variants (separated by commas) to build (server, client, kernel, zero, zeroshark) @<:@server@:>@])])
+	[JVM variants (separated by commas) to build (server, client, minimal1, kernel, zero, zeroshark) @<:@server@:>@])])
 
 if test "x$with_jvm_variants" = x; then
      with_jvm_variants="server"
 fi
 
 JVM_VARIANTS=",$with_jvm_variants,"
-TEST_VARIANTS=`$ECHO "$JVM_VARIANTS" | $SED -e 's/server,//' -e 's/client,//' -e 's/kernel,//' -e 's/zero,//' -e 's/zeroshark,//'`
+TEST_VARIANTS=`$ECHO "$JVM_VARIANTS" | $SED -e 's/server,//' -e 's/client,//'  -e 's/minimal1,//' -e 's/kernel,//' -e 's/zero,//' -e 's/zeroshark,//'`
 
 if test "x$TEST_VARIANTS" != "x,"; then
-   AC_MSG_ERROR([The available JVM variants are: server, client, kernel, zero, zeroshark])
+   AC_MSG_ERROR([The available JVM variants are: server, client, minimal1, kernel, zero, zeroshark])
 fi   
 AC_MSG_RESULT([$with_jvm_variants])
 
 JVM_VARIANT_SERVER=`$ECHO "$JVM_VARIANTS" | $SED -e '/,server,/!s/.*/false/g' -e '/,server,/s/.*/true/g'`
 JVM_VARIANT_CLIENT=`$ECHO "$JVM_VARIANTS" | $SED -e '/,client,/!s/.*/false/g' -e '/,client,/s/.*/true/g'` 
+JVM_VARIANT_MINIMAL1=`$ECHO "$JVM_VARIANTS" | $SED -e '/,minimal1,/!s/.*/false/g' -e '/,minimal1,/s/.*/true/g'`
 JVM_VARIANT_KERNEL=`$ECHO "$JVM_VARIANTS" | $SED -e '/,kernel,/!s/.*/false/g' -e '/,kernel,/s/.*/true/g'`
 JVM_VARIANT_ZERO=`$ECHO "$JVM_VARIANTS" | $SED -e '/,zero,/!s/.*/false/g' -e '/,zero,/s/.*/true/g'`
 JVM_VARIANT_ZEROSHARK=`$ECHO "$JVM_VARIANTS" | $SED -e '/,zeroshark,/!s/.*/false/g' -e '/,zeroshark,/s/.*/true/g'`
@@ -96,10 +98,15 @@
         AC_MSG_ERROR([You cannot build a kernel JVM for a 64-bit machine.])
     fi
 fi
+if test "x$JVM_VARIANT_MINIMAL1" = xtrue; then
+    if test "x$OPENJDK_TARGET_CPU_BITS" = x64; then
+        AC_MSG_ERROR([You cannot build a minimal JVM for a 64-bit machine.])
+    fi
+fi
 
 # Replace the commas with AND for use in the build directory name.
 ANDED_JVM_VARIANTS=`$ECHO "$JVM_VARIANTS" | $SED -e 's/^,//' -e 's/,$//' -e 's/,/AND/'`
-COUNT_VARIANTS=`$ECHO "$JVM_VARIANTS" | $SED -e 's/server,/1/' -e 's/client,/1/' -e 's/kernel,/1/' -e 's/zero,/1/' -e 's/zeroshark,/1/'`
+COUNT_VARIANTS=`$ECHO "$JVM_VARIANTS" | $SED -e 's/server,/1/' -e 's/client,/1/' -e 's/minimal1,/1/' -e 's/kernel,/1/' -e 's/zero,/1/' -e 's/zeroshark,/1/'`
 if test "x$COUNT_VARIANTS" != "x,1"; then
     BUILDING_MULTIPLE_JVM_VARIANTS=yes
 else
@@ -109,6 +116,7 @@
 AC_SUBST(JVM_VARIANTS)
 AC_SUBST(JVM_VARIANT_SERVER)
 AC_SUBST(JVM_VARIANT_CLIENT)
+AC_SUBST(JVM_VARIANT_MINIMAL1)
 AC_SUBST(JVM_VARIANT_KERNEL)
 AC_SUBST(JVM_VARIANT_ZERO)
 AC_SUBST(JVM_VARIANT_ZEROSHARK)
@@ -191,7 +199,9 @@
 #####
 # Generate the legacy makefile targets for hotspot.
 # The hotspot api for selecting the build artifacts, really, needs to be improved.
-#
+# JDK-7195896 will fix this on the hotspot side by using the JVM_VARIANT_* variables to
+# determine what needs to be built. All we will need to set here is all_product, all_fastdebug etc
+# But until then ...
 HOTSPOT_TARGET=""
 
 if test "x$JVM_VARIANT_SERVER" = xtrue; then
@@ -202,6 +212,10 @@
     HOTSPOT_TARGET="$HOTSPOT_TARGET${HOTSPOT_DEBUG_LEVEL}1 "
 fi
 
+if test "x$JVM_VARIANT_MINIMAL1" = xtrue; then
+    HOTSPOT_TARGET="$HOTSPOT_TARGET${HOTSPOT_DEBUG_LEVEL}minimal1 "
+fi
+
 if test "x$JVM_VARIANT_KERNEL" = xtrue; then
     HOTSPOT_TARGET="$HOTSPOT_TARGET${HOTSPOT_DEBUG_LEVEL}kernel "
 fi
@@ -221,7 +235,7 @@
 # from configure, but only server is valid anyway. Fix this
 # when hotspot makefiles are rewritten.
 if test "x$MACOSX_UNIVERSAL" = xtrue; then
-    HOTSPOT_TARGET=universal_product
+    HOTSPOT_TARGET=universal_${HOTSPOT_EXPORT}
 fi
 
 #####
@@ -233,46 +247,50 @@
 AC_SUBST(BUILD_VARIANT_RELEASE)
 ])
 
-AC_DEFUN_ONCE([JDKOPT_SETUP_JDK_OPTIONS],
-[
 
 ###############################################################################
 #
 # Should we build only OpenJDK even if closed sources are present?
 #
-AC_ARG_ENABLE([openjdk-only], [AS_HELP_STRING([--enable-openjdk-only],
-    [supress building closed source even if present @<:@disabled@:>@])],,[enable_openjdk_only="no"])
+AC_DEFUN_ONCE([JDKOPT_SETUP_OPEN_OR_CUSTOM],
+[
+  AC_ARG_ENABLE([openjdk-only], [AS_HELP_STRING([--enable-openjdk-only],
+    [suppress building custom source even if present @<:@disabled@:>@])],,[enable_openjdk_only="no"])
 
-AC_MSG_CHECKING([for presence of closed sources])
-if test -d "$SRC_ROOT/jdk/src/closed"; then
+  AC_MSG_CHECKING([for presence of closed sources])
+  if test -d "$SRC_ROOT/jdk/src/closed"; then
     CLOSED_SOURCE_PRESENT=yes
-else
+  else
     CLOSED_SOURCE_PRESENT=no
-fi
-AC_MSG_RESULT([$CLOSED_SOURCE_PRESENT])
+  fi
+  AC_MSG_RESULT([$CLOSED_SOURCE_PRESENT])
 
-AC_MSG_CHECKING([if closed source is supressed (openjdk-only)])
-SUPRESS_CLOSED_SOURCE="$enable_openjdk_only"
-AC_MSG_RESULT([$SUPRESS_CLOSED_SOURCE])
+  AC_MSG_CHECKING([if closed source is suppressed (openjdk-only)])
+  SUPPRESS_CLOSED_SOURCE="$enable_openjdk_only"
+  AC_MSG_RESULT([$SUPPRESS_CLOSED_SOURCE])
 
-if test "x$CLOSED_SOURCE_PRESENT" = xno; then
-  OPENJDK=true
-  if test "x$SUPRESS_CLOSED_SOURCE" = "xyes"; then
-    AC_MSG_WARN([No closed source present, --enable-openjdk-only makes no sense])
-  fi
-else
-  if test "x$SUPRESS_CLOSED_SOURCE" = "xyes"; then
+  if test "x$CLOSED_SOURCE_PRESENT" = xno; then
     OPENJDK=true
+    if test "x$SUPPRESS_CLOSED_SOURCE" = "xyes"; then
+      AC_MSG_WARN([No closed source present, --enable-openjdk-only makes no sense])
+    fi
   else
-    OPENJDK=false
+    if test "x$SUPPRESS_CLOSED_SOURCE" = "xyes"; then
+      OPENJDK=true
+    else
+      OPENJDK=false
+    fi
   fi
-fi
 
-if test "x$OPENJDK" = "xtrue"; then
+  if test "x$OPENJDK" = "xtrue"; then
     SET_OPENJDK="OPENJDK=true"
-fi
+  fi
 
-AC_SUBST(SET_OPENJDK)
+  AC_SUBST(SET_OPENJDK)
+])
+
+AC_DEFUN_ONCE([JDKOPT_SETUP_JDK_OPTIONS],
+[
 
 ###############################################################################
 #
@@ -355,13 +373,51 @@
 AC_SUBST(COMPRESS_JARS)
 ])
 
+###############################################################################
+#
+# Setup version numbers
+#
 AC_DEFUN_ONCE([JDKOPT_SETUP_JDK_VERSION_NUMBERS],
 [
 # Source the version numbers
-. $AUTOCONF_DIR/version.numbers
-if test "x$OPENJDK" = "xfalse"; then
-    . $AUTOCONF_DIR/closed.version.numbers
+. $AUTOCONF_DIR/version-numbers
+
+# Get the settings from parameters
+AC_ARG_WITH(milestone, [AS_HELP_STRING([--with-milestone], 
+                       [Set milestone value for build @<:@internal@:>@])])
+if test "x$with_milestone" = xyes; then
+  AC_MSG_ERROR([Milestone must have a value])
+elif test "x$with_milestone" != x; then
+    MILESTONE="$with_milestone"
+else
+  MILESTONE=internal
 fi
+
+AC_ARG_WITH(build-number, [AS_HELP_STRING([--with-build-number], 
+                          [Set build number value for build @<:@b00@:>@])])
+if test "x$with_build_number" = xyes; then
+  AC_MSG_ERROR([Build number must have a value])
+elif test "x$with_build_number" != x; then
+  JDK_BUILD_NUMBER="$with_build_number"
+fi
+if test "x$JDK_BUILD_NUMBER" = x; then
+  JDK_BUILD_NUMBER=b00
+fi
+
+AC_ARG_WITH(user-release-suffix, [AS_HELP_STRING([--with-user-release-suffix], 
+        [Add a custom string to the version string if build number isn't set.@<:@username_builddateb00@:>@])])
+if test "x$with_user_release_suffix" = xyes; then
+  AC_MSG_ERROR([Release suffix must have a value])
+elif test "x$with_user_release_suffix" != x; then
+  USER_RELEASE_SUFFIX="$with_user_release_suffix"
+else
+  BUILD_DATE=`date '+%Y_%m_%d_%H_%M'`
+  # Avoid [:alnum:] since it depends on the locale.
+  CLEAN_USERNAME=`echo "$USER" | $TR -d -c 'abcdefghijklmnopqrstuvqxyz0123456789'`
+  USER_RELEASE_SUFFIX=`echo "${CLEAN_USERNAME}_${BUILD_DATE}" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+fi
+AC_SUBST(USER_RELEASE_SUFFIX)
+
 # Now set the JDK version, milestone, build number etc.
 AC_SUBST(JDK_MAJOR_VERSION)
 AC_SUBST(JDK_MINOR_VERSION)
@@ -380,34 +436,13 @@
 COPYRIGHT_YEAR=`date +'%Y'`
 AC_SUBST(COPYRIGHT_YEAR)
 
-RUNTIME_NAME="$PRODUCT_NAME $PRODUCT_SUFFIX"
-AC_SUBST(RUNTIME_NAME)
-
 if test "x$JDK_UPDATE_VERSION" != x; then
-    JDK_VERSION="${JDK_MAJOR_VERSION}.${JDK_MINOR_VERSION}.${JDK_MICRO_VERSION}_${JDK_UPDATE_VERSION}"
+  JDK_VERSION="${JDK_MAJOR_VERSION}.${JDK_MINOR_VERSION}.${JDK_MICRO_VERSION}_${JDK_UPDATE_VERSION}"
 else
-    JDK_VERSION="${JDK_MAJOR_VERSION}.${JDK_MINOR_VERSION}.${JDK_MICRO_VERSION}"
+  JDK_VERSION="${JDK_MAJOR_VERSION}.${JDK_MINOR_VERSION}.${JDK_MICRO_VERSION}"
 fi
 AC_SUBST(JDK_VERSION)
 
-if test "x$MILESTONE" != x; then
-    RELEASE="${JDK_VERSION}-${MILESTONE}${BUILD_VARIANT_RELEASE}"
-else
-    RELEASE="${JDK_VERSION}${BUILD_VARIANT_RELEASE}"
-fi
-AC_SUBST(RELEASE)
-
-if test "x$JDK_BUILD_NUMBER" != x; then
-    FULL_VERSION="${RELEASE}-${JDK_BUILD_NUMBER}"
-else
-    JDK_BUILD_NUMBER=b00
-    BUILD_DATE=`date '+%Y_%m_%d_%H_%M'`
-    # Avoid [:alnum:] since it depends on the locale.
-    CLEAN_USERNAME=`echo "$USER" | $TR -d -c 'abcdefghijklmnopqrstuvqxyz0123456789'`
-    USER_RELEASE_SUFFIX=`echo "${CLEAN_USERNAME}_${BUILD_DATE}" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
-    FULL_VERSION="${RELEASE}-${USER_RELEASE_SUFFIX}-${JDK_BUILD_NUMBER}"
-fi
-AC_SUBST(FULL_VERSION)
 COOKED_BUILD_NUMBER=`$ECHO $JDK_BUILD_NUMBER | $SED -e 's/^b//' -e 's/^0//'`
 AC_SUBST(COOKED_BUILD_NUMBER)
 ])
@@ -420,7 +455,7 @@
 # The name of the Service Agent jar.
 SALIB_NAME="${LIBRARY_PREFIX}saproc${SHARED_LIBRARY_SUFFIX}"
 if test "x$OPENJDK_TARGET_OS" = "xwindows"; then
-    SALIB_NAME="${LIBRARY_PREFIX}sawindbg${SHARED_LIBRARY_SUFFIX}"
+  SALIB_NAME="${LIBRARY_PREFIX}sawindbg${SHARED_LIBRARY_SUFFIX}"
 fi
 AC_SUBST(SALIB_NAME)
 
--- a/common/autoconf/spec.gmk.in	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/autoconf/spec.gmk.in	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -163,11 +163,22 @@
 
 # Different version strings generated from the above information.
 JDK_VERSION:=@JDK_VERSION@
-RUNTIME_NAME:=@RUNTIME_NAME@
-FULL_VERSION:=@FULL_VERSION@
-JRE_RELEASE_VERSION:=@FULL_VERSION@
-RELEASE:=@RELEASE@
+RUNTIME_NAME=$(PRODUCT_NAME) $(PRODUCT_SUFFIX)
 COOKED_BUILD_NUMBER:=@COOKED_BUILD_NUMBER@
+# These variables need to be generated here so that MILESTONE and
+# JDK_BUILD_NUMBER can be overridden on the make command line.
+ifeq ($(MILESTONE),)
+  RELEASE=$(JDK_VERSION)$(BUILD_VARIANT_RELEASE)
+else
+  RELEASE=$(JDK_VERSION)-$(MILESTONE)$(BUILD_VARIANT_RELEASE)
+endif
+ifeq ($(JDK_BUILD_NUMBER),b00)
+  USER_RELEASE_SUFFIX=@USER_RELEASE_SUFFIX@
+  FULL_VERSION=$(RELEASE)-$(USER_RELEASE_SUFFIX)-$(JDK_BUILD_NUMBER)
+else
+  FULL_VERSION=$(RELEASE)-$(JDK_BUILD_NUMBER)
+endif
+JRE_RELEASE_VERSION:=$(FULL_VERSION)
 
 # How to compile the code: release, fastdebug or slowdebug
 DEBUG_LEVEL:=@DEBUG_LEVEL@
@@ -185,11 +196,12 @@
 
 # These are the libjvms that we want to build.
 # The java launcher uses the default.
-# The other can be selected by specifying -client -server -kernel -zero or -zeroshark
+# The others can be selected by specifying -client -server -minimal1 -kernel -zero or -zeroshark
 # on the java launcher command line.
 JVM_VARIANTS:=@JVM_VARIANTS@
 JVM_VARIANT_SERVER:=@JVM_VARIANT_SERVER@
 JVM_VARIANT_CLIENT:=@JVM_VARIANT_CLIENT@
+JVM_VARIANT_MINIMAL1:=@JVM_VARIANT_MINIMAL1@
 JVM_VARIANT_KERNEL:=@JVM_VARIANT_KERNEL@
 JVM_VARIANT_ZERO:=@JVM_VARIANT_ZERO@
 JVM_VARIANT_ZEROSHARK:=@JVM_VARIANT_ZEROSHARK@
@@ -219,6 +231,7 @@
 HOTSPOT_OUTPUTDIR=$(BUILD_OUTPUT)/hotspot
 JDK_OUTPUTDIR=$(BUILD_OUTPUT)/jdk
 IMAGES_OUTPUTDIR=$(BUILD_OUTPUT)/images
+JCE_OUTPUTDIR=$(BUILD_OUTPUT)/jce-release
 
 LANGTOOLS_DIST=$(LANGTOOLS_OUTPUTDIR)/dist
 CORBA_DIST=$(CORBA_OUTPUTDIR)/dist
@@ -419,6 +432,8 @@
 
 NATIVE2ASCII=@FIXPATH@ $(BOOT_JDK)/bin/native2ascii
 
+JARSIGNER=@FIXPATH@ $(BOOT_JDK)/bin/jarsigner
+
 # Base flags for RC
 # Guarding this against resetting value. Legacy make files include spec multiple
 # times.
@@ -439,10 +454,13 @@
 # CD is going away, but remains to cater for legacy makefiles.
 CD:=cd
 CHMOD:=@CHMOD@
+COMM:=@COMM@
 CP:=@CP@
+CPIO:=@CPIO@
 CUT:=@CUT@
 DATE:=@DATE@
 DIFF:=@DIFF@
+DIRNAME:=@DIRNAME@
 FIND:=@FIND@
 FIND_DELETE:=@FIND_DELETE@
 ECHO:=@ECHO@
@@ -467,6 +485,7 @@
 TIME:=@TIME@
 TR:=@TR@
 TOUCH:=@TOUCH@
+UNIQ:=@UNIQ@
 WC:=@WC@
 XARGS:=@XARGS@
 ZIPEXE:=@ZIP@
@@ -599,5 +618,21 @@
 OS_VERSION_MINOR:=@OS_VERSION_MINOR@
 OS_VERSION_MICRO:=@OS_VERSION_MICRO@
 
+# Images directory definitions
+JDK_IMAGE_SUBDIR:=j2sdk-image
+JRE_IMAGE_SUBDIR:=j2re-image
+JDK_OVERLAY_IMAGE_SUBDIR:=j2sdk-overlay-image
+JRE_OVERLAY_IMAGE_SUBDIR:=j2re-overlay-image
+JDK_IMAGE_DIR:=$(IMAGES_OUTPUTDIR)/$(JDK_IMAGE_SUBDIR)
+JRE_IMAGE_DIR:=$(IMAGES_OUTPUTDIR)/$(JRE_IMAGE_SUBDIR)
+JDK_OVERLAY_IMAGE_DIR:=$(IMAGES_OUTPUTDIR)/$(JDK_OVERLAY_IMAGE_SUBDIR)
+JRE_OVERLAY_IMAGE_DIR:=$(IMAGES_OUTPUTDIR)/$(JRE_OVERLAY_IMAGE_SUBDIR)
+
+# Macosx bundles directory definitions
+JDK_BUNDLE_SUBDIR:=j2sdk-bundle/jdk$(JDK_VERSION).jdk/Contents
+JRE_BUNDLE_SUBDIR:=j2re-bundle/jre$(JDK_VERSION).jre/Contents
+JDK_BUNDLE_DIR:=$(IMAGES_OUTPUTDIR)/$(JDK_BUNDLE_SUBDIR)
+JRE_BUNDLE_DIR:=$(IMAGES_OUTPUTDIR)/$(JRE_BUNDLE_SUBDIR)
+
 # Include the custom-spec.gmk file if it exists
 -include $(dir @SPEC@)/custom-spec.gmk
--- a/common/autoconf/toolchain.m4	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/autoconf/toolchain.m4	Tue Jan 22 11:54:16 2013 -0800
@@ -954,11 +954,14 @@
 
     # On some platforms (mac) the linker warns about non existing -L dirs.
     # Add server first if available. Linking aginst client does not always produce the same results.
-    # Only add client dir if client is being built. Default to server for other variants.
+    # Only add client dir if client is being built. Add minimal (note not minimal1) if only building minimal1.
+    # Default to server for other variants.
     if test "x$JVM_VARIANT_SERVER" = xtrue; then
         LDFLAGS_JDKLIB="${LDFLAGS_JDKLIB} -L${JDK_OUTPUTDIR}/lib${OPENJDK_TARGET_CPU_LIBDIR}/server"
     elif test "x$JVM_VARIANT_CLIENT" = xtrue; then
         LDFLAGS_JDKLIB="${LDFLAGS_JDKLIB} -L${JDK_OUTPUTDIR}/lib${OPENJDK_TARGET_CPU_LIBDIR}/client"
+    elif test "x$JVM_VARIANT_MINIMAL1" = xtrue; then
+        LDFLAGS_JDKLIB="${LDFLAGS_JDKLIB} -L${JDK_OUTPUTDIR}/lib${OPENJDK_TARGET_CPU_LIBDIR}/minimal"
     else
         LDFLAGS_JDKLIB="${LDFLAGS_JDKLIB} -L${JDK_OUTPUTDIR}/lib${OPENJDK_TARGET_CPU_LIBDIR}/server"
     fi
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/common/autoconf/version-numbers	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,38 @@
+#
+# 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
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+JDK_MAJOR_VERSION=1
+JDK_MINOR_VERSION=8
+JDK_MICRO_VERSION=0
+JDK_UPDATE_VERSION=
+LAUNCHER_NAME=openjdk
+PRODUCT_NAME=OpenJDK
+PRODUCT_SUFFIX="Runtime Environment"
+JDK_RC_PLATFORM_NAME=Platform
+COMPANY_NAME=N/A
+
+# Might need better names for these
+MACOSX_BUNDLE_NAME_BASE="OpenJDK"
+MACOSX_BUNDLE_ID_BASE="net.java.openjdk"
--- a/common/autoconf/version.numbers	Tue Jan 22 14:27:41 2013 -0500
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,40 +0,0 @@
-#
-# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.  Oracle designates this
-# particular file as subject to the "Classpath" exception as provided
-# by Oracle in the LICENSE file that accompanied this code.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-JDK_MAJOR_VERSION=1
-JDK_MINOR_VERSION=8
-JDK_MICRO_VERSION=0
-JDK_UPDATE_VERSION=
-JDK_BUILD_NUMBER=
-MILESTONE=internal
-LAUNCHER_NAME=openjdk
-PRODUCT_NAME=OpenJDK
-PRODUCT_SUFFIX="Runtime Environment"
-JDK_RC_PLATFORM_NAME=Platform
-COMPANY_NAME=N/A
-
-# Might need better names for these
-MACOSX_BUNDLE_NAME_BASE="OpenJDK"
-MACOSX_BUNDLE_ID_BASE="net.java.openjdk"
--- a/common/bin/compare.sh	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/bin/compare.sh	Tue Jan 22 11:54:16 2013 -0800
@@ -1,6 +1,6 @@
 #!/bin/bash
 #
-# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, 2013 Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -98,24 +98,30 @@
     if test "x$SUFFIX" = "xclass"; then
         # To improve performance when large diffs are found, do a rough filtering of classes
         # elibeble for these exceptions
-        if $GREP -R -e '[0-9]\{4\}_[0-9]\{2\}_[0-9]\{2\}_[0-9]\{2\}_[0-9]\{2\}-b[0-9]\{2\}' -e thePoint -e aPoint -e setItemsPtr ${THIS_FILE} > /dev/null; then
+        if $GREP -R -e '[0-9]\{4\}_[0-9]\{2\}_[0-9]\{2\}_[0-9]\{2\}_[0-9]\{2\}-b[0-9]\{2\}' \
+	        -e '[0-9]\{2\}/[0-9]\{2\}/[0-9]\{4\}' \
+	        -e thePoint -e aPoint -e setItemsPtr ${THIS_FILE} > /dev/null; then
             $JAVAP -c -constants -l -p ${OTHER_FILE} >  ${OTHER_FILE}.javap
             $JAVAP -c -constants -l -p ${THIS_FILE} > ${THIS_FILE}.javap
             TMP=$($DIFF ${OTHER_FILE}.javap ${THIS_FILE}.javap | \
                 $GREP '^[<>]' | \
                 $SED -e '/[<>].*[0-9]\{4\}_[0-9]\{2\}_[0-9]\{2\}_[0-9]\{2\}_[0-9]\{2\}-b[0-9]\{2\}.*/d' \
+		     -e '/[0-9]\{2\}\/[0-9]\{2\}\/[0-9]\{4\}/d' \
  	             -e '/[<>].*Point   Lcom\/apple\/jobjc\/foundation\/NSPoint;/d' \
 	             -e '/[<>].*public com\.apple\.jobjc\.Pointer<com\.apple\.jobjc\..*itemsPtr();/d' \
 	             -e '/[<>].*public void setItemsPtr(com\.apple\.jobjc\.Pointer<com\.apple\.jobjc\..*);/d')
         fi
     fi
     if test "x$SUFFIX" = "xproperties"; then
-        $CAT $OTHER_FILE | $SED -e 's/\([^\\]\):/\1\\:/g' -e  's/\([^\\]\)=/\1\\=/g' -e 's/#.*/#/g' \
-            | $SED -f "$SRC_ROOT/common/makefiles/support/unicode2x.sed" \
-  	    | $SED -e '/^#/d' -e '/^$/d' \
-            -e :a -e '/\\$/N; s/\\\n//; ta' \
-  	    -e 's/^[ \t]*//;s/[ \t]*$//' \
-	    -e 's/\\=/=/' | LANG=C $SORT > $OTHER_FILE.cleaned
+        # Run through nawk to add possibly missing newline at end of file.
+        $CAT $OTHER_FILE | $NAWK '{ print }' > $OTHER_FILE.cleaned
+# Disable this exception since we aren't changing the properties cleaning method yet.
+#        $CAT $OTHER_FILE | $SED -e 's/\([^\\]\):/\1\\:/g' -e  's/\([^\\]\)=/\1\\=/g' -e 's/#.*/#/g' \
+#            | $SED -f "$SRC_ROOT/common/makefiles/support/unicode2x.sed" \
+#  	    | $SED -e '/^#/d' -e '/^$/d' \
+#            -e :a -e '/\\$/N; s/\\\n//; ta' \
+#  	    -e 's/^[ \t]*//;s/[ \t]*$//' \
+#	    -e 's/\\=/=/' | LANG=C $SORT > $OTHER_FILE.cleaned
         TMP=$(LANG=C $DIFF $OTHER_FILE.cleaned $THIS_FILE)
     fi
     if test -n "$TMP"; then
@@ -305,14 +311,17 @@
                 THIS_FILE=$WORK_DIR/$f.this
                 $MKDIR -p $(dirname $OTHER_FILE)
                 $MKDIR -p $(dirname $THIS_FILE)
+                #Note that | doesn't work on mac sed.
                 $CAT $OTHER_DIR/$f | $SED -e 's/\(-- Generated by javadoc \).*\( --\)/\1(removed)\2/' \
                                           -e 's/\(<meta name="date" content="\).*\(">\)/\1(removed)\2/' \
-                                          -e 's/\(Monday\|Tuesday\|Wednesday\|Thursday\|Friday\|Saturday\|Sunday\), [A-Z][a-z]* [0-9][0-9]*, [12][0-9]* [0-9][0-9:]* \(AM\|PM\) [A-Z][A-Z]*/(removed)/' \
+                                          -e 's/[A-Z][a-z]*, [A-Z][a-z]* [0-9][0-9]*, [12][0-9]* [0-9][0-9:]* [AMP]\{2,2\} [A-Z][A-Z]*/(removed)/' \
+                                          -e 's/[A-Z][a-z]* [A-Z][a-z]* [0-9][0-9] [0-9][0-9:]* [A-Z][A-Z]* [12][0-9]*/(removed)/' \
                                           -e 's/^\( from \).*\(\.idl\)$/\1(removed)\2/' \
                     > $OTHER_FILE
                 $CAT $THIS_DIR/$f  | $SED -e 's/\(-- Generated by javadoc \).*\( --\)/\1(removed)\2/' \
                                           -e 's/\(<meta name="date" content="\).*\(">\)/\1(removed)\2/' \
-                                          -e 's/\(Monday\|Tuesday\|Wednesday\|Thursday\|Friday\|Saturday\|Sunday\), [A-Z][a-z]* [0-9][0-9]*, [12][0-9]* [0-9][0-9:]* \(AM\|PM\) [A-Z][A-Z]*/(removed)/' \
+                                          -e 's/[A-Z][a-z]*, [A-Z][a-z]* [0-9][0-9]*, [12][0-9]* [0-9][0-9:]* [AMP]\{2,2\} [A-Z][A-Z]*/(removed)/' \
+                                          -e 's/[A-Z][a-z]* [A-Z][a-z]* [0-9][0-9] [0-9][0-9:]* [A-Z][A-Z]* [12][0-9]*/(removed)/' \
                                           -e 's/^\( from \).*\(\.idl\)$/\1(removed)\2/' \
                     > $THIS_FILE
             else
@@ -370,14 +379,14 @@
     (cd $OTHER_UNZIPDIR && $UNARCHIVE $OTHER_ZIP)
 
     # Find all archives inside and unzip them as well to compare the contents rather than
-    # the archives.
-    EXCEPTIONS=""
-    for pack in $($FIND $THIS_UNZIPDIR -name "*.pack" -o -name "*.pack.gz"); do
+    # the archives. pie.jar.pack.gz i app3.war is corrupt, skip it.
+    EXCEPTIONS="pie.jar.pack.gz"
+    for pack in $($FIND $THIS_UNZIPDIR \( -name "*.pack" -o -name "*.pack.gz" \) -a ! -name pie.jar.pack.gz); do
         ($UNPACK200 $pack $pack.jar)
         # Filter out the unzipped archives from the diff below.
         EXCEPTIONS="$EXCEPTIONS $pack $pack.jar"
     done
-    for pack in $($FIND $OTHER_UNZIPDIR -name "*.pack" -o -name "*.pack.gz"); do
+    for pack in $($FIND $OTHER_UNZIPDIR \( -name "*.pack" -o -name "*.pack.gz" \) -a ! -name pie.jar.pack.gz); do
         ($UNPACK200 $pack $pack.jar)
         EXCEPTIONS="$EXCEPTIONS $pack $pack.jar"
     done
@@ -1073,7 +1082,11 @@
 
 
 # Figure out the layout of the this build. Which kinds of images have been produced
-if [ -d "$THIS/deploy/j2sdk-image" ]; then
+if [ -d "$THIS/install/j2sdk-image" ]; then
+    THIS_J2SDK="$THIS/install/j2sdk-image"
+    THIS_J2RE="$THIS/install/j2re-image"
+    echo "Comparing install images"
+elif [ -d "$THIS/deploy/j2sdk-image" ]; then
     THIS_J2SDK="$THIS/deploy/j2sdk-image"
     THIS_J2RE="$THIS/deploy/j2re-image"
     echo "Comparing deploy images"
@@ -1081,9 +1094,16 @@
     THIS_J2SDK="$THIS/images/j2sdk-image"
     THIS_J2RE="$THIS/images/j2re-image"
 fi
+
 if [ -d "$THIS/images/j2sdk-overlay-image" ]; then
-    THIS_J2SDK_OVERLAY="$THIS/images/j2sdk-overlay-image"
-    THIS_J2RE_OVERLAY="$THIS/images/j2re-overlay-image"
+    if [ -d "$THIS/install/j2sdk-image" ]; then
+        # If there is an install image, prefer that, it's also overlay
+        THIS_J2SDK_OVERLAY="$THIS/install/j2sdk-image"
+        THIS_J2RE_OVERLAY="$THIS/install/j2re-image"
+    else
+        THIS_J2SDK_OVERLAY="$THIS/images/j2sdk-overlay-image"
+        THIS_J2RE_OVERLAY="$THIS/images/j2re-overlay-image"
+    fi
 fi
 
 if [ -d "$THIS/images/j2sdk-bundle" ]; then
@@ -1100,7 +1120,9 @@
         OTHER_J2SDK_OVERLAY="$OTHER/j2sdk-image"
         OTHER_J2RE_OVERLAY="$OTHER/j2re-image"
     fi
-
+elif [ -d "$OTHER/images/j2sdk-image" ]; then
+    OTHER_J2SDK="$OTHER/images/j2sdk-image"
+    OTHER_J2RE="$OTHER/images/j2re-image"
 fi
 
 if [ -d "$OTHER/j2sdk-bundle" ]; then
@@ -1144,6 +1166,26 @@
     echo "WARNING! Other build doesn't contain docs, skipping doc compare."
 fi
 
+if [ -d "$OTHER/images" ]; then
+    OTHER_SEC_DIR="$OTHER/images"
+else
+    OTHER_SEC_DIR="$OTHER/tmp"
+fi
+OTHER_SEC_BIN="$OTHER_SEC_DIR/sec-bin.zip"
+THIS_SEC_DIR="$THIS/images"
+THIS_SEC_BIN="$THIS_SEC_DIR/sec-bin.zip"
+if [ "$OPENJDK_TARGET_OS" = "windows" ]; then
+    if [ "$OPENJDK_TARGET_CPU" = "x86_64" ]; then
+        JGSS_WINDOWS_BIN="jgss-windows-x64-bin.zip"
+    else
+        JGSS_WINDOWS_BIN="jgss-windows-i586-bin.zip"
+    fi
+    OTHER_SEC_WINDOWS_BIN="$OTHER_SEC_DIR/sec-windows-bin.zip"
+    OTHER_JGSS_WINDOWS_BIN="$OTHER_SEC_DIR/$JGSS_WINDOWS_BIN"
+    THIS_SEC_WINDOWS_BIN="$THIS_SEC_DIR/sec-windows-bin.zip"
+    THIS_JGSS_WINDOWS_BIN="$THIS_SEC_DIR/$JGSS_WINDOWS_BIN"
+fi
+
 ##########################################################################################
 # Do the work
 
@@ -1260,6 +1302,24 @@
     if [ -n "$THIS_J2SDK" ] && [ -n "$OTHER_J2SDK" ]; then
         compare_all_zip_files $THIS_J2SDK $OTHER_J2SDK $COMPARE_ROOT/j2sdk
     fi
+    if [ -n "$THIS_SEC_BIN" ] && [ -n "$OTHER_SEC_BIN" ]; then
+        if [ -n "$(echo $THIS_SEC_BIN | $FILTER)" ]; then
+            echo "sec-bin.zip..."
+            compare_zip_file $THIS_SEC_DIR $OTHER_SEC_DIR $COMPARE_ROOT/sec-bin sec-bin.zip
+        fi
+    fi
+    if [ -n "$THIS_SEC_WINDOWS_BIN" ] && [ -n "$OTHER_SEC_WINDOWS_BIN" ]; then
+        if [ -n "$(echo $THIS_SEC_WINDOWS_BIN | $FILTER)" ]; then
+            echo "sec-windows-bin.zip..."
+            compare_zip_file $THIS_SEC_DIR $OTHER_SEC_DIR $COMPARE_ROOT/sec-bin sec-windows-bin.zip
+        fi
+    fi
+    if [ -n "$THIS_JGSS_WINDOWS_BIN" ] && [ -n "$OTHER_JGSS_WINDOWS_BIN" ]; then
+        if [ -n "$(echo $THIS_JGSS_WINDOWS_BIN | $FILTER)" ]; then
+            echo "$JGSS_WINDOWS_BIN..."
+            compare_zip_file $THIS_SEC_DIR $OTHER_SEC_DIR $COMPARE_ROOT/sec-bin $JGSS_WINDOWS_BIN
+        fi
+    fi
 fi
 
 if [ "$CMP_JARS" = "true" ]; then
--- a/common/bin/compare_exceptions.sh.incl	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/bin/compare_exceptions.sh.incl	Tue Jan 22 11:54:16 2013 -0800
@@ -80,6 +80,7 @@
 ./bin/javadoc
 ./bin/javah
 ./bin/javap
+./bin/jdeps
 ./bin/jcmd
 ./bin/jconsole
 ./bin/jdb
@@ -167,6 +168,7 @@
 ./bin/javadoc
 ./bin/javah
 ./bin/javap
+./bin/jdeps
 ./bin/jcmd
 ./bin/jconsole
 ./bin/jdb
@@ -309,6 +311,7 @@
 ./bin/javadoc
 ./bin/javah
 ./bin/javap
+./bin/jdeps
 ./bin/javaws
 ./bin/jcmd
 ./bin/jconsole
@@ -449,6 +452,7 @@
 ./bin/amd64/javadoc
 ./bin/amd64/javah
 ./bin/amd64/javap
+./bin/amd64/jdeps
 ./bin/amd64/jcmd
 ./bin/amd64/jconsole
 ./bin/amd64/jdb
@@ -606,6 +610,7 @@
 ./bin/javadoc
 ./bin/javah
 ./bin/javap
+./bin/jdeps
 ./bin/javaws
 ./bin/jcmd
 ./bin/jconsole
@@ -751,6 +756,7 @@
 ./bin/sparcv9/javadoc
 ./bin/sparcv9/javah
 ./bin/sparcv9/javap
+./bin/sparcv9/jdeps
 ./bin/sparcv9/jcmd
 ./bin/sparcv9/jconsole
 ./bin/sparcv9/jdb
@@ -807,6 +813,10 @@
 
 if [ "$OPENJDK_TARGET_OS" = "windows" ]; then
 
+ACCEPTED_JARZIP_CONTENTS="
+/bin/w2k_lsa_auth.dll
+"
+
 # Probably should add all libs here
 ACCEPTED_SMALL_SIZE_DIFF="
 ./demo/jvmti/gctest/lib/gctest.dll
@@ -815,6 +825,7 @@
 ./jre/bin/attach.dll
 ./jre/bin/java_crw_demo.dll
 ./jre/bin/jsoundds.dll
+./jre/bin/server/jvm.dll
 ./bin/appletviewer.exe
 ./bin/extcheck.exe
 ./bin/idlj.exe
@@ -826,6 +837,7 @@
 ./bin/javadoc.exe
 ./bin/javah.exe
 ./bin/javap.exe
+./bin/jdeps.exe
 ./bin/javaw.exe
 ./bin/jcmd.exe
 ./bin/jconsole.exe
@@ -910,6 +922,7 @@
 ./bin/javadoc
 ./bin/javah
 ./bin/javap
+./bin/jdeps
 ./bin/jcmd
 ./bin/jconsole
 ./bin/jdb
--- a/common/makefiles/IdlCompilation.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/makefiles/IdlCompilation.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -87,7 +87,7 @@
 $1_SRC := $$(abspath $$($1_SRC))
 $1_BIN := $$(abspath $$($1_BIN))
 # Find all existing java files and existing class files.
-$$(shell $(MKDIR) -p $$($1_SRC) $$($1_BIN))
+$$(eval $$(call MakeDir,$$($1_BIN)))
 $1_SRCS     := $$(shell find $$($1_SRC) -name "*.idl")
 $1_BINS     := $$(shell find $$($1_BIN) -name "*.java")
 # Prepend the source/bin path to the filter expressions.
--- a/common/makefiles/JavaCompilation.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/makefiles/JavaCompilation.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -111,9 +111,9 @@
         ifeq ($$(word 20,$$($1_GREP_INCLUDE_PATTERNS)),)
             $1_GREP_INCLUDES:=| $(GREP) $$(patsubst %,$(SPACE)-e$(SPACE)$(DQUOTE)%$(DQUOTE),$$($1_GREP_INCLUDE_PATTERNS))
         else
-            $$(shell $(MKDIR) -p $$($1_BIN) && $(RM) $$($1_BIN)/_the.$$($1_JARNAME)_include)
-            $$(eval $$(call ListPathsSafelyNow,$1_GREP_INCLUDE_PATTERNS,\n, \
-			>> $$($1_BIN)/_the.$$($1_JARNAME)_include))
+            $1_GREP_INCLUDE_OUTPUT:=$(RM) $$($1_BIN)/_the.$$($1_JARNAME)_include && \
+                                    $$(strip $$(call ListPathsSafely,$1_GREP_INCLUDE_PATTERNS,\n, \
+                                        >> $$($1_BIN)/_the.$$($1_JARNAME)_include))
             $1_GREP_INCLUDES:=| $(GREP) -f $$($1_BIN)/_the.$$($1_JARNAME)_include
         endif
     endif
@@ -124,9 +124,9 @@
         ifeq ($$(word 20,$$($1_GREP_EXCLUDE_PATTERNS)),)
             $1_GREP_EXCLUDES:=| $(GREP) -v $$(patsubst %,$(SPACE)-e$(SPACE)$(DQUOTE)%$(DQUOTE),$$($1_GREP_EXCLUDE_PATTERNS))
         else
-            $$(shell $(MKDIR) -p $$($1_BIN) && $(RM) $$($1_BIN)/_the.$$($1_JARNAME)_exclude)
-            $$(eval $$(call ListPathsSafelyNow,$1_GREP_EXCLUDE_PATTERNS,\n, \
-			>> $$($1_BIN)/_the.$$($1_JARNAME)_exclude))
+            $1_GREP_EXCLUDE_OUTPUT=$(RM) $$($1_BIN)/_the.$$($1_JARNAME)_exclude && \
+                                    $$(strip $$(call ListPathsSafely,$1_GREP_EXCLUDE_PATTERNS,\n, \
+                                        >> $$($1_BIN)/_the.$$($1_JARNAME)_exclude))
             $1_GREP_EXCLUDES:=| $(GREP) -v -f $$($1_BIN)/_the.$$($1_JARNAME)_exclude
         endif
     endif
@@ -137,19 +137,25 @@
     else
       $1_JARINDEX = true
     endif
-    # When this macro is run in the same makefile as the java compilation, dependencies are transfered
-    # in make variables. When the macro is run in a different makefile than the java compilation, the 
-    # dependencies need to be found in the filesystem.
+    # When this macro is run in the same makefile as the java compilation, dependencies are 
+    # transfered in make variables. When the macro is run in a different makefile than the 
+    # java compilation, the dependencies need to be found in the filesystem.
     ifneq (,$2)
         $1_DEPS:=$2
     else
+        $1_DEPS:=$$(filter $$(addprefix %,$$($1_FIND_PATTERNS)),\
+                    $$(call CacheFind $$($1_SRCS)))
+        ifneq (,$$($1_GREP_INCLUDE_PATTERNS))
+            $1_DEPS:=$$(filter $$(addsuffix %,$$($1_GREP_INCLUDE_PATTERNS)),$$($1_DEPS))
+        endif
+        ifneq (,$$($1_GREP_EXCLUDE_PATTERNS))
+            $1_DEPS:=$$(filter-out $$(addsuffix %,$$($1_GREP_EXCLUDE_PATTERNS)),$$($1_DEPS))
+        endif
         # The subst of \ is needed because $ has to be escaped with \ in EXTRA_FILES for the command 
         # lines, but not here for use in make dependencies.
-        $1_DEPS:=$$(shell $(FIND) $$($1_SRCS) -type f -a \( $$($1_FIND_PATTERNS) \) \
-			  $$($1_GREP_INCLUDES) $$($1_GREP_EXCLUDES)) \
-		 $$(subst \,,$$(foreach src,$$($1_SRCS),$$(addprefix $$(src)/,$$($1_EXTRA_FILES))))
+        $1_DEPS+=$$(subst \,,$$(foreach src,$$($1_SRCS),$$(addprefix $$(src)/,$$($1_EXTRA_FILES))))
         ifeq (,$$($1_SKIP_METAINF))
-            $1_DEPS+=$$(shell $(FIND) $$(addsuffix /META-INF,$$($1_SRCS)) -type f 2> /dev/null)
+            $1_DEPS+=$$(call CacheFind $$(wildcard $$(addsuffix /META-INF,$$($1_SRCS))))
         endif
     endif
 
@@ -210,6 +216,8 @@
     # Here is the rule that creates/updates the jar file.
     $$($1_JAR) : $$($1_DEPS)
 	$(MKDIR) -p $$($1_BIN)
+	$$($1_GREP_INCLUDE_OUTPUT)
+	$$($1_GREP_EXCLUDE_OUTPUT)
 	$$(if $$($1_MANIFEST),\
 		$(SED) -e "s#@@RELEASE@@#$(RELEASE)#"           \
 		       -e "s#@@COMPANY_NAME@@#$(COMPANY_NAME)#" $$($1_MANIFEST) > $$($1_MANIFEST_FILE) \
@@ -242,14 +250,14 @@
 define SetupZipArchive
     # param 1 is for example ZIP_MYSOURCE
     # param 2,3,4,5,6,7,8,9 are named args.
-    #    SRC,ZIP,INCLUDES,EXCLUDES,EXCLUDE_FILES,SUFFIXES,EXTRA_DEPS
+    #    SRC,ZIP,INCLUDES,INCLUDE_FILES,EXCLUDES,EXCLUDE_FILES,SUFFIXES,EXTRA_DEPS
     $(foreach i,2 3 4 5 6 7 8 9 10 11 12 13 14 15, $(if $($i),$1_$(strip $($i)))$(NEWLINE))
     $(call LogSetupMacroEntry,SetupZipArchive($1),$2,$3,$4,$5,$6,$7,$8,$9,$(10),$(11),$(12),$(13),$(14),$(15))
     $(if $(16),$(error Internal makefile error: Too many arguments to SetupZipArchive, please update JavaCompilation.gmk))
 
     # Find all files in the source tree.
-    $1_SUFFIX_FILTER := $$(patsubst %,-o -name $(DQUOTE)*%$(DQUOTE),$$($1_SUFFIXES))
-    $1_ALL_SRCS := $$(foreach i,$$($1_SRC), $$(shell $(FIND) $$i -type f -a ! -name "_the.*" \( -name FALSE_DUMMY  $$($1_SUFFIX_FILTER) \) ))
+    $1_ALL_SRCS := $$(call not-containing,_the.,\
+            $$(filter $$(addprefix %,$$($1_SUFFIXES)),$$(call CacheFind $$($1_SRC))))
 
     ifneq ($$($1_INCLUDES),)
         $1_SRC_INCLUDES := $$(foreach i,$$($1_SRC),$$(addprefix $$i/,$$(addsuffix /%,$$($1_INCLUDES))))
@@ -259,6 +267,12 @@
         else
             $1_ZIP_INCLUDES := $$(addprefix -i$(SPACE)$(DQUOTE),$$(addsuffix /*$(DQUOTE),$$($1_INCLUDES)))
         endif
+    endif
+    ifneq ($$($1_INCLUDE_FILES),)
+        $1_SRC_INCLUDES += $$(foreach i,$$($1_SRC),$$(addprefix $$i/,$$($1_INCLUDE_FILES)))
+        $1_ZIP_INCLUDES += $$(addprefix -i$(SPACE),$$($1_INCLUDE_FILES))
+    endif
+    ifneq ($$($1_SRC_INCLUDES),)
         $1_ALL_SRCS     := $$(filter $$($1_SRC_INCLUDES),$$($1_ALL_SRCS))
     endif
     ifneq ($$($1_EXCLUDES),)
@@ -376,7 +390,7 @@
     $$(foreach d,$$($1_SRC), $$(if $$(wildcard $$d),,$$(error SRC specified to SetupJavaCompilation $1 contains missing directory $$d)))
     $$(eval $$(call MakeDir,$$($1_BIN)))
     # Find all files in the source trees.
-    $1_ALL_SRCS := $$(filter-out $(OVR_SRCS),$$(shell $(FIND) $$($1_SRC) -type f))
+    $1_ALL_SRCS += $$(filter-out $(OVR_SRCS),$$(call CacheFind,$$($1_SRC)))
     # Extract the java files.
     ifneq ($$($1_EXCLUDE_FILES),)
         $1_EXCLUDE_FILES_PATTERN:=$$(addprefix %,$$($1_EXCLUDE_FILES))
@@ -408,8 +422,6 @@
 
     # Find all files to be copied from source to bin.
     ifneq (,$$($1_COPY))
-        # Rewrite list of patterns into a find statement.
-        $1_COPY_PATTERN:=$(FALSE_FIND_PATTERN) $$(patsubst %,$(SPACE)-o$(SPACE)-name$(SPACE)$(DQUOTE)*%$(DQUOTE),$$($1_COPY))
         # Search for all files to be copied.
         $1_ALL_COPIES := $$(filter $$(addprefix %,$$($1_COPY)),$$($1_ALL_SRCS))
         # Copy these explicitly
@@ -436,8 +448,6 @@
 
     # Find all property files to be copied and cleaned from source to bin.
     ifneq (,$$($1_CLEAN))
-        # Rewrite list of patterns into a find statement.
-        $1_CLEAN_PATTERN:=$(FALSE_FIND_PATTERN) $$(patsubst %,$(SPACE)-o$(SPACE)-name$(SPACE)$(DQUOTE)*%$(DQUOTE),$$($1_CLEAN))
         # Search for all files to be copied.
         $1_ALL_CLEANS := $$(filter $$(addprefix %,$$($1_CLEAN)),$$($1_ALL_SRCS))
         # Copy and clean must also respect filters.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/common/makefiles/Jprt.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,209 @@
+#
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+# This file is included by the root NewerMakefile and contains targets 
+# and utilities needed by JPRT.
+
+# Utilities used in this Makefile. Most of this makefile executes without
+# the context of a spec file from configure.
+CAT=cat
+CMP=cmp
+CP=cp
+ECHO=echo
+MKDIR=mkdir
+PRINTF=printf
+PWD=pwd
+# Insure we have a path that looks like it came from pwd
+#   (This is mostly for Windows sake and drive letters)
+define UnixPath # path
+$(shell (cd "$1" && $(PWD)))
+endef
+
+BUILD_DIR_ROOT:=$(root_dir)/build
+
+ifdef OPENJDK
+  OPEN_BUILD=true
+else
+  OPEN_BUILD := $(if $(or $(wildcard $(root_dir)/jdk/src/closed), \
+                          $(wildcard $(root_dir)/jdk/make/closed), \
+                          $(wildcard $(root_dir)/jdk/test/closed), \
+                          $(wildcard $(root_dir)/hotspot/src/closed), \
+                          $(wildcard $(root_dir)/hotspot/make/closed), \
+                          $(wildcard $(root_dir)/hotspot/test/closed)), \
+                     false,true)
+endif
+
+HOTSPOT_AVAILABLE := $(if $(wildcard $(root_dir)/hotspot),true,false)
+
+###########################################################################
+# To help in adoption of the new configure&&make build process, a bridge
+#   build will use the old settings to run configure and do the build.
+
+# Build with the configure bridge. After running configure, restart make
+# to parse the new spec file.
+BRIDGE_TARGETS := all
+bridgeBuild: bridge2configure
+	@cd $(root_dir) && $(MAKE) -f NewMakefile.gmk $(BRIDGE_TARGETS)
+
+# Bridge from old Makefile ALT settings to configure options
+bridge2configure: $(BUILD_DIR_ROOT)/.bridge2configureOpts
+	bash ./configure $(strip $(shell $(CAT) $<))
+
+# Create a file with configure options created from old Makefile mechanisms.
+$(BUILD_DIR_ROOT)/.bridge2configureOpts: $(BUILD_DIR_ROOT)/.bridge2configureOptsLatest
+	$(RM) $@
+	$(CP) $< $@
+
+# Use this file to only change when obvious things have changed
+$(BUILD_DIR_ROOT)/.bridge2configureOptsLatest: FRC
+	$(RM) $@.tmp
+	$(MKDIR) -p $(BUILD_DIR_ROOT)
+	@$(ECHO) " --with-debug-level=$(if $(DEBUG_LEVEL),$(DEBUG_LEVEL),release) " >> $@.tmp
+ifdef ARCH_DATA_MODEL
+	@$(ECHO) " --with-target-bits=$(ARCH_DATA_MODEL) " >> $@.tmp
+endif
+ifeq ($(ARCH_DATA_MODEL),32)
+	@$(ECHO) " --with-jvm-variants=client,server " >> $@.tmp
+endif
+ifdef ALT_PARALLEL_COMPILE_JOBS
+	@$(ECHO) " --with-num-cores=$(ALT_PARALLEL_COMPILE_JOBS) " >> $@.tmp
+endif
+ifdef ALT_BOOTDIR
+	@$(ECHO) " --with-boot-jdk=$(call UnixPath,$(ALT_BOOTDIR)) " >> $@.tmp
+endif
+ifdef ALT_CUPS_HEADERS_PATH
+	@$(ECHO) " --with-cups-include=$(call UnixPath,$(ALT_CUPS_HEADERS_PATH)) " >> $@.tmp
+endif
+ifdef ALT_FREETYPE_HEADERS_PATH
+	@$(ECHO) " --with-freetype=$(call UnixPath,$(ALT_FREETYPE_HEADERS_PATH)/..) " >> $@.tmp
+endif
+ifeq ($(HOTSPOT_AVAILABLE),false)
+  ifdef ALT_JDK_IMPORT_PATH
+	@$(ECHO) " --with-import-hotspot=$(call UnixPath,$(ALT_JDK_IMPORT_PATH)) " >> $@.tmp
+  endif
+endif
+ifeq ($(OPEN_BUILD),true)
+	@$(ECHO) " --enable-openjdk-only " >> $@.tmp
+else
+  # Todo: move to closed?
+  ifdef ALT_MOZILLA_HEADERS_PATH
+	@$(ECHO) " --with-mozilla-headers=$(call UnixPath,$(ALT_MOZILLA_HEADERS_PATH)) " >> $@.tmp
+  endif
+  ifdef ALT_JUNIT_DIR
+	@$(ECHO) " --with-junit-dir=$(call UnixPath,$(ALT_JUNIT_DIR)) " >> $@.tmp
+  endif
+  ifdef ANT_HOME
+	@$(ECHO) " --with-ant-home=$(call UnixPath,$(ANT_HOME)) " >> $@.tmp
+  endif
+  ifdef ALT_JAVAFX_ZIP_DIR
+	@$(ECHO) " --with-javafx-zip-dir=$(call UnixPath,$(ALT_JAVAFX_ZIP_DIR)) " >> $@.tmp
+  endif
+  ifdef ALT_WIXDIR
+	@$(ECHO) " --with-wix=$(call UnixPath,$(ALT_WIXDIR)) " >> $@.tmp
+  endif
+  ifdef ALT_CCSS_SIGNING_DIR
+	@$(ECHO) " --with-ccss-signing=$(call UnixPath,$(ALT_CCSS_SIGNING_DIR)) " >> $@.tmp
+  endif
+  ifdef ALT_SLASH_JAVA
+	@$(ECHO) " --with-java-devtools=$(call UnixPath,$(ALT_SLASH_JAVA)/devtools) " >> $@.tmp
+  endif
+  ifdef ALT_SPARKLE_FRAMEWORK_DIR
+	@$(ECHO) " --with-sparkle-framework=$(call UnixPath,$(ALT_SPARKLE_FRAMEWORK_DIR)) " >> $@.tmp
+  endif 
+endif
+	@if [ -f $@ ] ; then \
+          if ! $(CMP) $@ $@.tmp > /dev/null ; then \
+            $(CP) $@.tmp $@ ; \
+          fi ; \
+        else \
+          $(CP) $@.tmp $@ ; \
+        fi
+	$(RM) $@.tmp
+
+PHONY_LIST += bridge2configure bridgeBuild
+
+###########################################################################
+# JPRT targets
+
+ifndef JPRT_ARCHIVE_BUNDLE
+  JPRT_ARCHIVE_BUNDLE=/tmp/jprt_bundles/j2sdk-image.zip
+endif
+ifndef JPRT_ARCHIVE_INSTALL_BUNDLE
+    JPRT_ARCHIVE_INSTALL_BUNDLE=/tmp/jprt_bundles/product-install.zip
+endif
+
+# These targets execute in a SPEC free context, before calling bridgeBuild
+# to generate the SPEC.
+jprt_build_product: DEBUG_LEVEL=release
+jprt_build_product: BUILD_DIRNAME=*-release
+jprt_build_product: jprt_build_generic
+
+jprt_build_fastdebug: DEBUG_LEVEL=fastdebug
+jprt_build_fastdebug: BUILD_DIRNAME=*-fastdebug
+jprt_build_fastdebug: jprt_build_generic
+
+jprt_build_debug: DEBUG_LEVEL=slowdebug
+jprt_build_debug: BUILD_DIRNAME=*-debug
+jprt_build_debug: jprt_build_generic
+
+jprt_build_generic: BRIDGE_TARGETS+=jprt_bundle
+jprt_build_generic: bridgeBuild
+
+# This target must be called in the context of a SPEC file
+jprt_bundle: $(JPRT_ARCHIVE_BUNDLE)
+	@$(call CheckIfMakeAtEnd)
+
+# This target must be called in the context of a SPEC file
+$(JPRT_ARCHIVE_BUNDLE): bundles
+	$(MKDIR) -p $(@D)
+	$(RM) $@
+	$(CP) $(BUILD_OUTPUT)/bundles/j2sdk-image.zip $@
+
+# This target must be called in the context of a SPEC file
+bundles: all
+	@$(call TargetEnter)
+	$(MKDIR) -p $(BUILD_OUTPUT)/bundles
+ifeq ($(OPENJDK_TARGET_OS)-$(OPENJDK_TARGET_CPU_BITS),solaris-64)
+	$(CD) $(JDK_OVERLAY_IMAGE_DIR) && $(ZIP) -q -r $(BUILD_OUTPUT)/bundles/j2sdk-image.zip .
+	$(CD) $(JRE_OVERLAY_IMAGE_DIR) && $(ZIP) -q -r $(BUILD_OUTPUT)/bundles/j2re-image.zip .
+else
+	$(CD) $(JDK_IMAGE_DIR) && $(ZIP) -q -r $(BUILD_OUTPUT)/bundles/j2sdk-image.zip .
+	$(CD) $(JRE_IMAGE_DIR) && $(ZIP) -q -r $(BUILD_OUTPUT)/bundles/j2re-image.zip .
+	if [ -d  $(BUILD_OUTPUT)/install/bundles ] ; then \
+           $(CD) $(BUILD_OUTPUT)/install/bundles && $(ZIP) -q -r $(JPRT_ARCHIVE_INSTALL_BUNDLE) . ; \
+        fi
+endif
+	@$(call TargetExit)
+
+# Keep track of phony targets
+PHONY_LIST += jprt_build_product jprt_build_fastdebug jprt_build_debug \
+              jprt_build_generic bundles jprt_bundle
+
+###########################################################################
+# Phony targets
+.PHONY: $(PHONY_LIST)
+
+# Force target
+FRC:
--- a/common/makefiles/Main.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/makefiles/Main.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -65,7 +65,15 @@
 
 ### Main targets
 
-all: jdk
+default: jdk
+	@$(call CheckIfMakeAtEnd)
+
+all: images docs
+	@$(call CheckIfMakeAtEnd)
+
+ifeq ($(OPENJDK_TARGET_OS)-$(OPENJDK_TARGET_CPU_BITS),solaris-64)
+  all: overlay-images
+endif
 
 start-make:
 	@$(call AtMakeStart)
@@ -126,12 +134,6 @@
 	@($(CD) $(JDK_TOPDIR)/makefiles && $(BUILD_LOG_WRAPPER) $(MAKE) $(MAKE_ARGS) -f BuildJdk.gmk overlay-images)
 	@$(call TargetExit)
 
-bundles: images bundles-only
-bundles-only: start-make
-	@$(call TargetEnter)
-	@($(CD) $(JDK_TOPDIR)/makefiles && $(BUILD_LOG_WRAPPER) $(MAKE) $(MAKE_ARGS) -f BuildJdk.gmk bundles)
-	@$(call TargetExit)
-
 install: images install-only
 install-only: start-make
 	@$(call TargetEnter)
@@ -144,6 +146,12 @@
 	@($(CD) $(SRC_ROOT)/common/makefiles/javadoc && $(BUILD_LOG_WRAPPER) $(MAKE) $(MAKE_ARGS) -f Javadoc.gmk docs)
 	@$(call TargetExit)
 
+sign-jars: jdk sign-jars-only
+sign-jars-only: start-make
+	@$(call TargetEnter)
+	@($(CD) $(JDK_TOPDIR)/makefiles && $(BUILD_LOG_WRAPPER) $(MAKE) $(MAKE_ARGS) -f BuildJdk.gmk sign-jars)
+	@$(call TargetExit)
+
 bootcycle-images:
 	@$(ECHO) Boot cycle build step 1: Building the JDK image normally
 	@($(CD) $(SRC_ROOT)/common/makefiles && $(BUILD_LOG_WRAPPER) $(MAKE) SPEC=$(SPEC) images)
--- a/common/makefiles/MakeBase.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/makefiles/MakeBase.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -391,4 +391,46 @@
 endef
 endif
 
+# Convenience functions for working around make's limitations with $(filter ).
+containing = $(foreach v,$2,$(if $(findstring $1,$v),$v))
+not-containing = $(foreach v,$2,$(if $(findstring $1,$v),,$v))
+
+################################################################################
+# In Cygwin, finds are very costly, both because of expensive forks and because
+# of bad file system caching. Find is used extensively in $(shell) commands to
+# find source files. This makes rerunning make with no or few changes rather 
+# expensive. To speed this up, these two macros are used to cache the results
+# of simple find commands for reuse.
+# 
+# Runs a find and stores both the directories where it was run and the results.
+# This macro can be called multiple times to add to the cache. Only finds files
+# with no filters.
+#
+# Needs to be called with $(eval )
+# 
+# Param 1 - Dir to find in
+ifeq ($(OPENJDK_BUILD_OS),windows)
+define FillCacheFind
+    FIND_CACHE_DIR += $1
+    FIND_CACHE := $$(sort $$(FIND_CACHE) $$(shell $(FIND) $1 -type f -o -type l))
+endef
+else
+define FillCacheFind
+endef
+endif
+
+# Mimics find by looking in the cache if all of the directories have been cached.
+# Otherwise reverts to shell find. This is safe to call on all platforms, even if
+# cache is deactivated.
+#
+# The extra - is needed when FIND_CACHE_DIR is empty but should be harmless.
+# Param 1 - Dirs to find in
+define CacheFind
+    $(if $(filter-out $(addsuffix %,- $(FIND_CACHE_DIR)),$1),\
+        $(shell $(FIND) $1 -type f -o -type l),\
+        $(filter $(addsuffix %,$1),$(FIND_CACHE)))
+endef
+
+################################################################################
+
 endif # _MAKEBASE_GMK
--- a/common/makefiles/MakeHelpers.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/makefiles/MakeHelpers.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -50,7 +50,7 @@
 
 # Global targets are possible to run either with or without a SPEC. The prototypical
 # global target is "help". 
-global_targets=help configure
+global_targets=help jprt% bridgeBuild
 
 ##############################
 # Functions
@@ -112,7 +112,7 @@
 
 # Do not indent this function, this will add whitespace at the start which the caller won't handle
 define GetRealTarget
-$(strip $(if $(MAKECMDGOALS),$(MAKECMDGOALS),all))
+$(strip $(if $(MAKECMDGOALS),$(MAKECMDGOALS),default))
 endef
 
 # Do not indent this function, this will add whitespace at the start which the caller won't handle
@@ -126,10 +126,7 @@
     # Check if the current target is the last goal
     $(if $(filter $@,$(call LastGoal)),$(call AtMakeEnd))
     # If the target is 'foo-only', check if our goal was stated as 'foo'
-    $(if $(filter $(patsubst %-only,%,$@),$(call LastGoal)),$(call AtMakeEnd))
-    # If no goal is given, 'all' is default, but the last target executed for all is 'jdk-only'. Check for that, too.
-    # At most one of the tests can be true.
-    $(if $(subst all,,$(call LastGoal)),,$(if $(filter $@,jdk-only),$(call AtMakeEnd)))
+    $(if $(filter $@,$(call LastGoal)-only),$(call AtMakeEnd))
 endef
 
 # Hook to be called when starting to execute a top-level target
--- a/common/makefiles/Makefile	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/makefiles/Makefile	Tue Jan 22 11:54:16 2013 -0800
@@ -23,109 +23,4 @@
 # questions.
 #
 
-# This must be the first rule
-all:
-
-# Inclusion of this pseudo-target will cause make to execute this file
-# serially, regardless of -j. Recursively called makefiles will not be
-# affected, however. This is required for correct dependency management.
-.NOTPARALLEL:
-
-# The shell code below will be executed on /usr/ccs/bin/make on Solaris, but not in GNU make.
-# /usr/ccs/bin/make lacks basically every other flow control mechanism.
-TEST_FOR_NON_GNUMAKE:sh=echo You are not using GNU make/gmake, this is a requirement. Check your path. 1>&2 && exit 1
-
-# Assume we have GNU make, but check version.
-ifeq (,$(findstring 3.81,$(MAKE_VERSION)))
-    ifeq (,$(findstring 3.82,$(MAKE_VERSION)))
-        $(error This version of GNU Make is too low ($(MAKE_VERSION)). Check your path, or upgrade to 3.81 or newer.)
-    endif
-endif
-
-# Locate this Makefile
-ifeq ($(filter /%,$(lastword $(MAKEFILE_LIST))),)
-    makefile_path:=$(CURDIR)/$(lastword $(MAKEFILE_LIST))
-else
-    makefile_path:=$(lastword $(MAKEFILE_LIST))
-endif
-root_dir:=$(patsubst %/common/makefiles/Makefile,%,$(makefile_path))
-
-# ... and then we can include our helper functions
-include $(dir $(makefile_path))/MakeHelpers.gmk
-
-$(eval $(call ParseLogLevel))
-$(eval $(call ParseConfAndSpec))
-
-# Now determine if we have zero, one or several configurations to build.
-ifeq ($(SPEC),)
-    # Since we got past ParseConfAndSpec, we must be building a global target. Do nothing.
-else
-    ifeq ($(words $(SPEC)),1)
-        # We are building a single configuration. This is the normal case. Execute the Main.gmk file.
-        include $(dir $(makefile_path))/Main.gmk
-    else
-        # We are building multiple configurations.
-        # First, find out the valid targets
-        # Run the makefile with an arbitraty SPEC using -p -q (quiet dry-run and dump rules) to find
-        # available PHONY targets. Use this list as valid targets to pass on to the repeated calls.
-        all_phony_targets=$(filter-out $(global_targets), $(strip $(shell \
-            $(MAKE) -p -q -f  $(makefile_path) SPEC=$(firstword $(SPEC)) | \
-            grep ^.PHONY: | head -n 1 | cut -d " " -f 2-)))
-
-$(all_phony_targets):
-	@$(foreach spec,$(SPEC),($(MAKE) -f $(makefile_path) SPEC=$(spec) $(VERBOSE) VERBOSE=$(VERBOSE) $@) &&) true
-
-    endif
-endif
-
-# Here are "global" targets, i.e. targets that can be executed without specifying a single configuration.
-# If you addd more global targets, please update the variable global_targets in MakeHelpers.
-
-help:
-	$(info )
-	$(info OpenJDK Makefile help)
-	$(info =====================)
-	$(info )
-	$(info Common make targets)
-	$(info .  make [all]             # Compile all code but do not create images)
-	$(info .  make images            # Create complete j2sdk and j2re images)
-	$(info .  make overlay-images    # Create limited images for sparc 64 bit platforms)
-	$(info .  make bootcycle-images  # Build images twice, second time with newly build JDK)
-	$(info .  make install           # Install the generated images locally)
-	$(info .  make clean             # Remove all files generated by make, but not those)
-	$(info .                         # generated by configure)
-	$(info .  make dist-clean        # Remove all files, including configuration)
-	$(info .  make help              # Give some help on using make)
-	$(info .  make test              # Run tests, default is all tests (see TEST below))
-	$(info )
-	$(info Targets for specific components)
-	$(info (Component is any of langtools, corba, jaxp, jaxws, hotspot, jdk, images or overlay-images))
-	$(info .  make <component>       # Build <component> and everything it depends on. )
-	$(info .  make <component>-only  # Build <component> only, without dependencies. This)
-	$(info .                         # is faster but can result in incorrect build results!)
-	$(info .  make clean-<component> # Remove files generated by make for <component>)
-	$(info )
-	$(info Useful make variables)
-	$(info .  make CONF=             # Build all configurations (note, assignment is empty))
-	$(info .  make CONF=<substring>  # Build the configuration(s) with a name matching)
-	$(info .                         # <substring>)
-	$(info )
-	$(info .  make LOG=<loglevel>    # Change the log level from warn to <loglevel>)
-	$(info .                         # Available log levels are:)
-	$(info .                         # 'warn' (default), 'info', 'debug' and 'trace')
-	$(info .                         # To see executed command lines, use LOG=debug)
-	$(info )
-	$(info .  make JOBS=<n>          # Run <n> parallel make jobs)
-	$(info .                         # Note that -jN does not work as expected!)
-	$(info )
-	$(info .  make test TEST=<test>  # Only run the given test or tests, e.g.)
-	$(info .                         # make test TEST="jdk_lang jdk_net")
-	$(info )
-
-configure:
-	@$(SHELL) $(root_dir)/configure $(CONFIGURE_ARGS)
-	@echo ====================================================
-	@echo "Note: This is a non-recommended way of running configure."
-	@echo "Instead, run 'sh configure' in the top-level directory"
-
-.PHONY: help configure
+include ../../NewMakefile.gmk
--- a/common/makefiles/NativeCompilation.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/makefiles/NativeCompilation.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -236,7 +236,7 @@
     $$(foreach d,$$($1_SRC), $$(if $$(wildcard $$d),,$$(error SRC specified to SetupNativeCompilation $1 contains missing directory $$d)))
 
     # Find all files in the source trees. Sort to remove duplicates.
-    $1_ALL_SRCS := $$(sort $$(shell $(FIND) $$($1_SRC) -type f))
+    $1_ALL_SRCS := $$(sort $$(call CacheFind,$$($1_SRC)))
     # Extract the C/C++ files.
     $1_EXCLUDE_FILES:=$$(foreach i,$$($1_SRC),$$(addprefix $$i/,$$($1_EXCLUDE_FILES)))
     $1_INCLUDE_FILES:=$$(foreach i,$$($1_SRC),$$(addprefix $$i/,$$($1_INCLUDE_FILES)))
--- a/common/makefiles/RMICompilation.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/makefiles/RMICompilation.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/common/makefiles/javadoc/Javadoc.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/makefiles/javadoc/Javadoc.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -32,8 +32,6 @@
 # Definitions for $(DOCSDIR), $(MKDIR), $(BINDIR), etc.
 #
 
-CLASSPATH_SEPARATOR = :
-
 DOCSDIR=$(OUTPUT_ROOT)/docs
 TEMPDIR=$(OUTPUT_ROOT)/docstemp
 
@@ -137,7 +135,7 @@
 # List of all possible directories for javadoc to look for sources
 #    NOTE: Quotes are required around sourcepath argument only on Windows.
 #          Otherwise, you get "No packages or classes specified." due 
-#          to $(CLASSPATH_SEPARATOR) being interpreted as an end of 
+#          to $(PATH_SEP) being interpreted as an end of 
 #          command (newline or shell ; character)
 ALL_SOURCE_DIRS = $(JDK_SHARE_CLASSES) \
                   $(JDK_IMPSRC) \
@@ -154,7 +152,7 @@
 EMPTY:=
 SPACE:= $(EMPTY) $(EMPTY)
 RELEASEDOCS_SOURCEPATH = \
-    $(subst $(SPACE),$(CLASSPATH_SEPARATOR),$(strip $(ALL_SOURCE_DIRS)))
+    $(subst $(SPACE),$(PATH_SEP),$(strip $(ALL_SOURCE_DIRS)))
 
 define prep-target
 $(MKDIR) -p $(@D)
--- a/common/makefiles/javadoc/NON_CORE_PKGS.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/makefiles/javadoc/NON_CORE_PKGS.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -78,7 +78,8 @@
 
 JCONSOLE_PKGS    = com.sun.tools.jconsole
 
-TREEAPI_PKGS 	 = com.sun.source.tree \
+TREEAPI_PKGS 	 = com.sun.source.doctree \
+		   com.sun.source.tree \
 		   com.sun.source.util
 
 SMARTCARDIO_PKGS = javax.smartcardio
--- a/common/src/fixpath.c	Tue Jan 22 14:27:41 2013 -0500
+++ b/common/src/fixpath.c	Tue Jan 22 11:54:16 2013 -0800
@@ -29,6 +29,29 @@
 #include <string.h>
 #include <malloc.h>
 
+void report_error()
+{
+  LPVOID lpMsgBuf;
+  DWORD dw = GetLastError();
+
+  FormatMessage(
+      FORMAT_MESSAGE_ALLOCATE_BUFFER |
+      FORMAT_MESSAGE_FROM_SYSTEM |
+      FORMAT_MESSAGE_IGNORE_INSERTS,
+      NULL,
+      dw,
+      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+      (LPTSTR) &lpMsgBuf,
+      0,
+      NULL);
+
+  fprintf(stderr,
+          "Could not start process!  Failed with error %d: %s\n",
+          dw, lpMsgBuf);
+
+  LocalFree(lpMsgBuf);
+}
+
 /*
  * Test if pos points to /cygdrive/_/ where _ can
  * be any character.
@@ -256,7 +279,7 @@
     DWORD exitCode;
 
     if (argc<3 || argv[1][0] != '-' || (argv[1][1] != 'c' && argv[1][1] != 'm')) {
-        fprintf(stderr, "Usage: fixpath -c|m<path@path@...> /cygdrive/c/WINDOWS/notepad.exe /cygdrive/c/x/test.txt");
+        fprintf(stderr, "Usage: fixpath -c|m<path@path@...> /cygdrive/c/WINDOWS/notepad.exe /cygdrive/c/x/test.txt\n");
         exit(0);
     }
 
@@ -308,11 +331,10 @@
                        0,
                        &si,
                        &pi);
-    if(!rc)
-    {
-      //Could not start process;
-      fprintf(stderr, "Could not start process!\n");
-      exit(-1);
+    if(!rc) {
+      // Could not start process for some reason.  Try to report why:
+      report_error();
+      exit(rc);
     }
 
     WaitForSingleObject(pi.hProcess,INFINITE);
--- a/corba/.hgtags	Tue Jan 22 14:27:41 2013 -0500
+++ b/corba/.hgtags	Tue Jan 22 11:54:16 2013 -0800
@@ -190,3 +190,8 @@
 65771ad1ca557ca26e4979d4dc633cf685435cb8 jdk8-b66
 394515ad2a55d4d54df990b36065505d3e7a3cbb jdk8-b67
 82000531feaa7baef76b6406099e5cd88943d635 jdk8-b68
+22ddcac208a8dea894a16887d04f3ca4d3c5d267 jdk8-b69
+603cceb495c8133d47b26a7502d51c7d8a67d76b jdk8-b70
+8171d23e914d758836527b80b06debcfdb718f2d jdk8-b71
+cb40427f47145b01b7e53c3e02b38ff7625efbda jdk8-b72
+191afde59e7be0e1a1d76d06f2a32ff17444f0ec jdk8-b73
--- a/hotspot/.hgtags	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/.hgtags	Tue Jan 22 11:54:16 2013 -0800
@@ -303,3 +303,9 @@
 b6c9c0109a608eedbb6b868d260952990e3c91fe hs25-b13
 cb8a4e04bc8c104de8a2f67463c7e31232bf8d68 jdk8-b69
 990bbd393c239d95310ccc38094e57923bbf1d4a hs25-b14
+e94068d4ff52849c8aa0786a53a59b63d1312a39 jdk8-b70
+0847210f85480bf3848dc90bc2ab23c0a4791b55 jdk8-b71
+d5cb5830f570d1304ea4b196dde672a291b55f29 jdk8-b72
+1e129851479e4f5df439109fca2c7be1f1613522 hs25-b15
+11619f33cd683c2f1d6ef72f1c6ff3dacf5a9f1c jdk8-b73
+70c89bd6b895a10d25ca70e08093c09ff2005fda hs25-b16
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciArrayKlass.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciArrayKlass.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciField.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciField.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciInstance.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciInstance.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciKlass.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciKlass.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciMetadata.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciMetadata.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciObjArrayKlass.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciObjArrayKlass.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciObject.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciObject.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciObjectFactory.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciObjectFactory.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciReceiverTypeData.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciReceiverTypeData.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciSymbol.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciSymbol.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciType.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciType.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciTypeArrayKlass.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciTypeArrayKlass.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciVirtualCallData.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/ci/ciVirtualCallData.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/classfile/ClassLoaderData.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/classfile/ClassLoaderData.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/memory/LoaderConstraintTable.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/memory/LoaderConstraintTable.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/BitData.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/BitData.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/InstanceKlass.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/InstanceKlass.java	Tue Jan 22 11:54:16 2013 -0800
@@ -53,6 +53,7 @@
   private static int HIGH_OFFSET;
   private static int FIELD_SLOTS;
   private static short FIELDINFO_TAG_SIZE;
+  private static short FIELDINFO_TAG_MASK;
   private static short FIELDINFO_TAG_OFFSET;
 
   // ClassState constants
@@ -102,6 +103,7 @@
     HIGH_OFFSET                    = db.lookupIntConstant("FieldInfo::high_packed_offset").intValue();
     FIELD_SLOTS                    = db.lookupIntConstant("FieldInfo::field_slots").intValue();
     FIELDINFO_TAG_SIZE             = db.lookupIntConstant("FIELDINFO_TAG_SIZE").shortValue();
+    FIELDINFO_TAG_MASK             = db.lookupIntConstant("FIELDINFO_TAG_MASK").shortValue();
     FIELDINFO_TAG_OFFSET           = db.lookupIntConstant("FIELDINFO_TAG_OFFSET").shortValue();
 
     // read ClassState constants
@@ -321,7 +323,7 @@
     U2Array fields = getFields();
     short lo = fields.at(index * FIELD_SLOTS + LOW_OFFSET);
     short hi = fields.at(index * FIELD_SLOTS + HIGH_OFFSET);
-    if ((lo & FIELDINFO_TAG_SIZE) == FIELDINFO_TAG_OFFSET) {
+    if ((lo & FIELDINFO_TAG_MASK) == FIELDINFO_TAG_OFFSET) {
       return VM.getVM().buildIntFromShorts(lo, hi) >> FIELDINFO_TAG_SIZE;
     }
     throw new RuntimeException("should not reach here");
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/ProfileData.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/ProfileData.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/RetData.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/RetData.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Block.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Block.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Block_Array.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Block_Array.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Block_List.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Block_List.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/CallDynamicJavaNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/CallDynamicJavaNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/CallJavaNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/CallJavaNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/CallNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/CallNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/CallRuntimeNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/CallRuntimeNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/CallStaticJavaNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/CallStaticJavaNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Compile.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Compile.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/HaltNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/HaltNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/InlineTree.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/InlineTree.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/JVMState.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/JVMState.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/LoopNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/LoopNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachCallJavaNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachCallJavaNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachCallNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachCallNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachCallRuntimeNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachCallRuntimeNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachCallStaticJavaNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachCallStaticJavaNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachIfNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachIfNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachReturnNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachReturnNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachSafePointNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MachSafePointNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MultiNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/MultiNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Node.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Node.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Node_Array.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Node_Array.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Node_List.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Node_List.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Phase.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/Phase.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/PhaseCFG.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/PhaseCFG.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/PhaseRegAlloc.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/PhaseRegAlloc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/PhiNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/PhiNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/ProjNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/ProjNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/RegionNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/RegionNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/RootNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/RootNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/SafePointNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/SafePointNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/TypeNode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/opto/TypeNode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/prims/JvmtiExport.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/prims/JvmtiExport.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/utilities/GenericGrowableArray.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/utilities/GenericGrowableArray.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/utilities/GrowableArray.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/utilities/GrowableArray.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  *
  */
 
--- a/hotspot/agent/src/share/native/sadis.c	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/agent/src/share/native/sadis.c	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright 2012, Oracle and/or its affiliates. All Rights Reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/make/bsd/makefiles/mapfile-vers-debug	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-debug	Tue Jan 22 11:54:16 2013 -0800
@@ -3,7 +3,7 @@
 #
 
 #
-# Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -205,7 +205,6 @@
                 JVM_NewMultiArray;
                 JVM_OnExit;
                 JVM_Open;
-                JVM_PrintStackTrace;
                 JVM_RaiseSignal;
                 JVM_RawMonitorCreate;
                 JVM_RawMonitorDestroy;
--- a/hotspot/make/bsd/makefiles/mapfile-vers-product	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/make/bsd/makefiles/mapfile-vers-product	Tue Jan 22 11:54:16 2013 -0800
@@ -3,7 +3,7 @@
 #
 
 #
-# Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -205,7 +205,6 @@
                 JVM_NewMultiArray;
                 JVM_OnExit;
                 JVM_Open;
-                JVM_PrintStackTrace;
                 JVM_RaiseSignal;
                 JVM_RawMonitorCreate;
                 JVM_RawMonitorDestroy;
--- a/hotspot/make/hotspot_version	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/make/hotspot_version	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -31,11 +31,11 @@
 #
 
 # Don't put quotes (fail windows build).
-HOTSPOT_VM_COPYRIGHT=Copyright 2012
+HOTSPOT_VM_COPYRIGHT=Copyright 2013
 
 HS_MAJOR_VER=25
 HS_MINOR_VER=0
-HS_BUILD_NUMBER=15
+HS_BUILD_NUMBER=17
 
 JDK_MAJOR_VER=1
 JDK_MINOR_VER=8
--- a/hotspot/make/linux/makefiles/mapfile-vers-debug	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/make/linux/makefiles/mapfile-vers-debug	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -201,7 +201,6 @@
                 JVM_NewMultiArray;
                 JVM_OnExit;
                 JVM_Open;
-                JVM_PrintStackTrace;
                 JVM_RaiseSignal;
                 JVM_RawMonitorCreate;
                 JVM_RawMonitorDestroy;
--- a/hotspot/make/linux/makefiles/mapfile-vers-product	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/make/linux/makefiles/mapfile-vers-product	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -201,7 +201,6 @@
                 JVM_NewMultiArray;
                 JVM_OnExit;
                 JVM_Open;
-                JVM_PrintStackTrace;
                 JVM_RaiseSignal;
                 JVM_RawMonitorCreate;
                 JVM_RawMonitorDestroy;
--- a/hotspot/make/solaris/makefiles/mapfile-vers	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/make/solaris/makefiles/mapfile-vers	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -201,7 +201,6 @@
                 JVM_NewMultiArray;
                 JVM_OnExit;
                 JVM_Open;
-                JVM_PrintStackTrace;
                 JVM_RaiseSignal;
                 JVM_RawMonitorCreate;
                 JVM_RawMonitorDestroy;
--- a/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -675,8 +675,8 @@
     AbstractAssembler::flush();
   }
 
-  inline void emit_long(int);  // shadows AbstractAssembler::emit_long
-  inline void emit_data(int x) { emit_long(x); }
+  inline void emit_int32(int);  // shadows AbstractAssembler::emit_int32
+  inline void emit_data(int x) { emit_int32(x); }
   inline void emit_data(int, RelocationHolder const&);
   inline void emit_data(int, relocInfo::relocType rtype);
   // helper for above fcns
@@ -691,12 +691,12 @@
   inline void add(Register s1, Register s2, Register d );
   inline void add(Register s1, int simm13a, Register d );
 
-  void addcc(  Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(add_op3  | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
-  void addcc(  Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(add_op3  | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void addc(   Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(addc_op3             ) | rs1(s1) | rs2(s2) ); }
-  void addc(   Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(addc_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void addccc( Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(addc_op3 | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
-  void addccc( Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(addc_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void addcc(  Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(add_op3  | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
+  void addcc(  Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(add_op3  | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void addc(   Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(addc_op3             ) | rs1(s1) | rs2(s2) ); }
+  void addc(   Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(addc_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void addccc( Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(addc_op3 | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
+  void addccc( Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(addc_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
 
   // pp 136
@@ -749,76 +749,76 @@
   // at address s1 is swapped with the data in d. If the values are not equal,
   // the the contents of memory at s1 is loaded into d, without the swap.
 
-  void casa(  Register s1, Register s2, Register d, int ia = -1 ) { v9_only();  emit_long( op(ldst_op) | rd(d) | op3(casa_op3 ) | rs1(s1) | (ia == -1  ? immed(true) : imm_asi(ia)) | rs2(s2)); }
-  void casxa( Register s1, Register s2, Register d, int ia = -1 ) { v9_only();  emit_long( op(ldst_op) | rd(d) | op3(casxa_op3) | rs1(s1) | (ia == -1  ? immed(true) : imm_asi(ia)) | rs2(s2)); }
+  void casa(  Register s1, Register s2, Register d, int ia = -1 ) { v9_only();  emit_int32( op(ldst_op) | rd(d) | op3(casa_op3 ) | rs1(s1) | (ia == -1  ? immed(true) : imm_asi(ia)) | rs2(s2)); }
+  void casxa( Register s1, Register s2, Register d, int ia = -1 ) { v9_only();  emit_int32( op(ldst_op) | rd(d) | op3(casxa_op3) | rs1(s1) | (ia == -1  ? immed(true) : imm_asi(ia)) | rs2(s2)); }
 
   // pp 152
 
-  void udiv(   Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(udiv_op3             ) | rs1(s1) | rs2(s2)); }
-  void udiv(   Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(udiv_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void sdiv(   Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(sdiv_op3             ) | rs1(s1) | rs2(s2)); }
-  void sdiv(   Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(sdiv_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void udivcc( Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(udiv_op3 | cc_bit_op3) | rs1(s1) | rs2(s2)); }
-  void udivcc( Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(udiv_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void sdivcc( Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(sdiv_op3 | cc_bit_op3) | rs1(s1) | rs2(s2)); }
-  void sdivcc( Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(sdiv_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void udiv(   Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(udiv_op3             ) | rs1(s1) | rs2(s2)); }
+  void udiv(   Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(udiv_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void sdiv(   Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(sdiv_op3             ) | rs1(s1) | rs2(s2)); }
+  void sdiv(   Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(sdiv_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void udivcc( Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(udiv_op3 | cc_bit_op3) | rs1(s1) | rs2(s2)); }
+  void udivcc( Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(udiv_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void sdivcc( Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(sdiv_op3 | cc_bit_op3) | rs1(s1) | rs2(s2)); }
+  void sdivcc( Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(sdiv_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 155
 
-  void done()  { v9_only();  cti();  emit_long( op(arith_op) | fcn(0) | op3(done_op3) ); }
-  void retry() { v9_only();  cti();  emit_long( op(arith_op) | fcn(1) | op3(retry_op3) ); }
+  void done()  { v9_only();  cti();  emit_int32( op(arith_op) | fcn(0) | op3(done_op3) ); }
+  void retry() { v9_only();  cti();  emit_int32( op(arith_op) | fcn(1) | op3(retry_op3) ); }
 
   // pp 156
 
-  void fadd( FloatRegisterImpl::Width w, FloatRegister s1, FloatRegister s2, FloatRegister d ) { emit_long( op(arith_op) | fd(d, w) | op3(fpop1_op3) | fs1(s1, w) | opf(0x40 + w) | fs2(s2, w)); }
-  void fsub( FloatRegisterImpl::Width w, FloatRegister s1, FloatRegister s2, FloatRegister d ) { emit_long( op(arith_op) | fd(d, w) | op3(fpop1_op3) | fs1(s1, w) | opf(0x44 + w) | fs2(s2, w)); }
+  void fadd( FloatRegisterImpl::Width w, FloatRegister s1, FloatRegister s2, FloatRegister d ) { emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | fs1(s1, w) | opf(0x40 + w) | fs2(s2, w)); }
+  void fsub( FloatRegisterImpl::Width w, FloatRegister s1, FloatRegister s2, FloatRegister d ) { emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | fs1(s1, w) | opf(0x44 + w) | fs2(s2, w)); }
 
   // pp 157
 
-  void fcmp(  FloatRegisterImpl::Width w, CC cc, FloatRegister s1, FloatRegister s2) { v8_no_cc(cc);  emit_long( op(arith_op) | cmpcc(cc) | op3(fpop2_op3) | fs1(s1, w) | opf(0x50 + w) | fs2(s2, w)); }
-  void fcmpe( FloatRegisterImpl::Width w, CC cc, FloatRegister s1, FloatRegister s2) { v8_no_cc(cc);  emit_long( op(arith_op) | cmpcc(cc) | op3(fpop2_op3) | fs1(s1, w) | opf(0x54 + w) | fs2(s2, w)); }
+  void fcmp(  FloatRegisterImpl::Width w, CC cc, FloatRegister s1, FloatRegister s2) { v8_no_cc(cc);  emit_int32( op(arith_op) | cmpcc(cc) | op3(fpop2_op3) | fs1(s1, w) | opf(0x50 + w) | fs2(s2, w)); }
+  void fcmpe( FloatRegisterImpl::Width w, CC cc, FloatRegister s1, FloatRegister s2) { v8_no_cc(cc);  emit_int32( op(arith_op) | cmpcc(cc) | op3(fpop2_op3) | fs1(s1, w) | opf(0x54 + w) | fs2(s2, w)); }
 
   // pp 159
 
-  void ftox( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { v9_only();  emit_long( op(arith_op) | fd(d, FloatRegisterImpl::D) | op3(fpop1_op3) | opf(0x80 + w) | fs2(s, w)); }
-  void ftoi( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) {             emit_long( op(arith_op) | fd(d, FloatRegisterImpl::S) | op3(fpop1_op3) | opf(0xd0 + w) | fs2(s, w)); }
+  void ftox( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { v9_only();  emit_int32( op(arith_op) | fd(d, FloatRegisterImpl::D) | op3(fpop1_op3) | opf(0x80 + w) | fs2(s, w)); }
+  void ftoi( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) {             emit_int32( op(arith_op) | fd(d, FloatRegisterImpl::S) | op3(fpop1_op3) | opf(0xd0 + w) | fs2(s, w)); }
 
   // pp 160
 
-  void ftof( FloatRegisterImpl::Width sw, FloatRegisterImpl::Width dw, FloatRegister s, FloatRegister d ) { emit_long( op(arith_op) | fd(d, dw) | op3(fpop1_op3) | opf(0xc0 + sw + dw*4) | fs2(s, sw)); }
+  void ftof( FloatRegisterImpl::Width sw, FloatRegisterImpl::Width dw, FloatRegister s, FloatRegister d ) { emit_int32( op(arith_op) | fd(d, dw) | op3(fpop1_op3) | opf(0xc0 + sw + dw*4) | fs2(s, sw)); }
 
   // pp 161
 
-  void fxtof( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { v9_only();  emit_long( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x80 + w*4) | fs2(s, FloatRegisterImpl::D)); }
-  void fitof( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) {             emit_long( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0xc0 + w*4) | fs2(s, FloatRegisterImpl::S)); }
+  void fxtof( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { v9_only();  emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x80 + w*4) | fs2(s, FloatRegisterImpl::D)); }
+  void fitof( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) {             emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0xc0 + w*4) | fs2(s, FloatRegisterImpl::S)); }
 
   // pp 162
 
-  void fmov( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { v8_s_only(w);  emit_long( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x00 + w) | fs2(s, w)); }
+  void fmov( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { v8_s_only(w);  emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x00 + w) | fs2(s, w)); }
 
-  void fneg( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { v8_s_only(w);  emit_long( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x04 + w) | fs2(s, w)); }
+  void fneg( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { v8_s_only(w);  emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x04 + w) | fs2(s, w)); }
 
   // page 144 sparc v8 architecture (double prec works on v8 if the source and destination registers are the same). fnegs is the only instruction available
   // on v8 to do negation of single, double and quad precision floats.
 
-  void fneg( FloatRegisterImpl::Width w, FloatRegister sd ) { if (VM_Version::v9_instructions_work()) emit_long( op(arith_op) | fd(sd, w) | op3(fpop1_op3) | opf(0x04 + w) | fs2(sd, w)); else emit_long( op(arith_op) | fd(sd, w) | op3(fpop1_op3) |  opf(0x05) | fs2(sd, w)); }
+  void fneg( FloatRegisterImpl::Width w, FloatRegister sd ) { if (VM_Version::v9_instructions_work()) emit_int32( op(arith_op) | fd(sd, w) | op3(fpop1_op3) | opf(0x04 + w) | fs2(sd, w)); else emit_int32( op(arith_op) | fd(sd, w) | op3(fpop1_op3) |  opf(0x05) | fs2(sd, w)); }
 
-  void fabs( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { v8_s_only(w);  emit_long( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x08 + w) | fs2(s, w)); }
+  void fabs( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { v8_s_only(w);  emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x08 + w) | fs2(s, w)); }
 
   // page 144 sparc v8 architecture (double prec works on v8 if the source and destination registers are the same). fabss is the only instruction available
   // on v8 to do abs operation on single/double/quad precision floats.
 
-  void fabs( FloatRegisterImpl::Width w, FloatRegister sd ) { if (VM_Version::v9_instructions_work()) emit_long( op(arith_op) | fd(sd, w) | op3(fpop1_op3) | opf(0x08 + w) | fs2(sd, w)); else emit_long( op(arith_op) | fd(sd, w) | op3(fpop1_op3) | opf(0x09) | fs2(sd, w)); }
+  void fabs( FloatRegisterImpl::Width w, FloatRegister sd ) { if (VM_Version::v9_instructions_work()) emit_int32( op(arith_op) | fd(sd, w) | op3(fpop1_op3) | opf(0x08 + w) | fs2(sd, w)); else emit_int32( op(arith_op) | fd(sd, w) | op3(fpop1_op3) | opf(0x09) | fs2(sd, w)); }
 
   // pp 163
 
-  void fmul( FloatRegisterImpl::Width w,                            FloatRegister s1, FloatRegister s2, FloatRegister d ) { emit_long( op(arith_op) | fd(d, w)  | op3(fpop1_op3) | fs1(s1, w)  | opf(0x48 + w)         | fs2(s2, w)); }
-  void fmul( FloatRegisterImpl::Width sw, FloatRegisterImpl::Width dw,  FloatRegister s1, FloatRegister s2, FloatRegister d ) { emit_long( op(arith_op) | fd(d, dw) | op3(fpop1_op3) | fs1(s1, sw) | opf(0x60 + sw + dw*4) | fs2(s2, sw)); }
-  void fdiv( FloatRegisterImpl::Width w,                            FloatRegister s1, FloatRegister s2, FloatRegister d ) { emit_long( op(arith_op) | fd(d, w)  | op3(fpop1_op3) | fs1(s1, w)  | opf(0x4c + w)         | fs2(s2, w)); }
+  void fmul( FloatRegisterImpl::Width w,                            FloatRegister s1, FloatRegister s2, FloatRegister d ) { emit_int32( op(arith_op) | fd(d, w)  | op3(fpop1_op3) | fs1(s1, w)  | opf(0x48 + w)         | fs2(s2, w)); }
+  void fmul( FloatRegisterImpl::Width sw, FloatRegisterImpl::Width dw,  FloatRegister s1, FloatRegister s2, FloatRegister d ) { emit_int32( op(arith_op) | fd(d, dw) | op3(fpop1_op3) | fs1(s1, sw) | opf(0x60 + sw + dw*4) | fs2(s2, sw)); }
+  void fdiv( FloatRegisterImpl::Width w,                            FloatRegister s1, FloatRegister s2, FloatRegister d ) { emit_int32( op(arith_op) | fd(d, w)  | op3(fpop1_op3) | fs1(s1, w)  | opf(0x4c + w)         | fs2(s2, w)); }
 
   // pp 164
 
-  void fsqrt( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { emit_long( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x28 + w) | fs2(s, w)); }
+  void fsqrt( FloatRegisterImpl::Width w, FloatRegister s, FloatRegister d ) { emit_int32( op(arith_op) | fd(d, w) | op3(fpop1_op3) | opf(0x28 + w) | fs2(s, w)); }
 
   // pp 165
 
@@ -827,22 +827,22 @@
 
   // pp 167
 
-  void flushw() { v9_only();  emit_long( op(arith_op) | op3(flushw_op3) ); }
+  void flushw() { v9_only();  emit_int32( op(arith_op) | op3(flushw_op3) ); }
 
   // pp 168
 
-  void illtrap( int const22a) { if (const22a != 0) v9_only();  emit_long( op(branch_op) | u_field(const22a, 21, 0) ); }
+  void illtrap( int const22a) { if (const22a != 0) v9_only();  emit_int32( op(branch_op) | u_field(const22a, 21, 0) ); }
   // v8 unimp == illtrap(0)
 
   // pp 169
 
-  void impdep1( int id1, int const19a ) { v9_only();  emit_long( op(arith_op) | fcn(id1) | op3(impdep1_op3) | u_field(const19a, 18, 0)); }
-  void impdep2( int id1, int const19a ) { v9_only();  emit_long( op(arith_op) | fcn(id1) | op3(impdep2_op3) | u_field(const19a, 18, 0)); }
+  void impdep1( int id1, int const19a ) { v9_only();  emit_int32( op(arith_op) | fcn(id1) | op3(impdep1_op3) | u_field(const19a, 18, 0)); }
+  void impdep2( int id1, int const19a ) { v9_only();  emit_int32( op(arith_op) | fcn(id1) | op3(impdep2_op3) | u_field(const19a, 18, 0)); }
 
   // pp 149 (v8)
 
-  void cpop1( int opc, int cr1, int cr2, int crd ) { v8_only();  emit_long( op(arith_op) | fcn(crd) | op3(impdep1_op3) | u_field(cr1, 18, 14) | opf(opc) | u_field(cr2, 4, 0)); }
-  void cpop2( int opc, int cr1, int cr2, int crd ) { v8_only();  emit_long( op(arith_op) | fcn(crd) | op3(impdep2_op3) | u_field(cr1, 18, 14) | opf(opc) | u_field(cr2, 4, 0)); }
+  void cpop1( int opc, int cr1, int cr2, int crd ) { v8_only();  emit_int32( op(arith_op) | fcn(crd) | op3(impdep1_op3) | u_field(cr1, 18, 14) | opf(opc) | u_field(cr2, 4, 0)); }
+  void cpop2( int opc, int cr1, int cr2, int crd ) { v8_only();  emit_int32( op(arith_op) | fcn(crd) | op3(impdep2_op3) | u_field(cr1, 18, 14) | opf(opc) | u_field(cr2, 4, 0)); }
 
   // pp 170
 
@@ -872,8 +872,8 @@
 
   // 173
 
-  void ldfa(  FloatRegisterImpl::Width w, Register s1, Register s2, int ia, FloatRegister d ) { v9_only();  emit_long( op(ldst_op) | fd(d, w) | alt_op3(ldf_op3 | alt_bit_op3, w) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void ldfa(  FloatRegisterImpl::Width w, Register s1, int simm13a,         FloatRegister d ) { v9_only();  emit_long( op(ldst_op) | fd(d, w) | alt_op3(ldf_op3 | alt_bit_op3, w) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void ldfa(  FloatRegisterImpl::Width w, Register s1, Register s2, int ia, FloatRegister d ) { v9_only();  emit_int32( op(ldst_op) | fd(d, w) | alt_op3(ldf_op3 | alt_bit_op3, w) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void ldfa(  FloatRegisterImpl::Width w, Register s1, int simm13a,         FloatRegister d ) { v9_only();  emit_int32( op(ldst_op) | fd(d, w) | alt_op3(ldf_op3 | alt_bit_op3, w) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 175, lduw is ld on v8
 
@@ -896,22 +896,22 @@
 
   // pp 177
 
-  void ldsba(  Register s1, Register s2, int ia, Register d ) {             emit_long( op(ldst_op) | rd(d) | op3(ldsb_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void ldsba(  Register s1, int simm13a,         Register d ) {             emit_long( op(ldst_op) | rd(d) | op3(ldsb_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void ldsha(  Register s1, Register s2, int ia, Register d ) {             emit_long( op(ldst_op) | rd(d) | op3(ldsh_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void ldsha(  Register s1, int simm13a,         Register d ) {             emit_long( op(ldst_op) | rd(d) | op3(ldsh_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void ldswa(  Register s1, Register s2, int ia, Register d ) { v9_only();  emit_long( op(ldst_op) | rd(d) | op3(ldsw_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void ldswa(  Register s1, int simm13a,         Register d ) { v9_only();  emit_long( op(ldst_op) | rd(d) | op3(ldsw_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void lduba(  Register s1, Register s2, int ia, Register d ) {             emit_long( op(ldst_op) | rd(d) | op3(ldub_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void lduba(  Register s1, int simm13a,         Register d ) {             emit_long( op(ldst_op) | rd(d) | op3(ldub_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void lduha(  Register s1, Register s2, int ia, Register d ) {             emit_long( op(ldst_op) | rd(d) | op3(lduh_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void lduha(  Register s1, int simm13a,         Register d ) {             emit_long( op(ldst_op) | rd(d) | op3(lduh_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void lduwa(  Register s1, Register s2, int ia, Register d ) {             emit_long( op(ldst_op) | rd(d) | op3(lduw_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void lduwa(  Register s1, int simm13a,         Register d ) {             emit_long( op(ldst_op) | rd(d) | op3(lduw_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void ldxa(   Register s1, Register s2, int ia, Register d ) { v9_only();  emit_long( op(ldst_op) | rd(d) | op3(ldx_op3  | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void ldxa(   Register s1, int simm13a,         Register d ) { v9_only();  emit_long( op(ldst_op) | rd(d) | op3(ldx_op3  | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void ldda(   Register s1, Register s2, int ia, Register d ) { v9_dep();   emit_long( op(ldst_op) | rd(d) | op3(ldd_op3  | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void ldda(   Register s1, int simm13a,         Register d ) { v9_dep();   emit_long( op(ldst_op) | rd(d) | op3(ldd_op3  | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void ldsba(  Register s1, Register s2, int ia, Register d ) {             emit_int32( op(ldst_op) | rd(d) | op3(ldsb_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void ldsba(  Register s1, int simm13a,         Register d ) {             emit_int32( op(ldst_op) | rd(d) | op3(ldsb_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void ldsha(  Register s1, Register s2, int ia, Register d ) {             emit_int32( op(ldst_op) | rd(d) | op3(ldsh_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void ldsha(  Register s1, int simm13a,         Register d ) {             emit_int32( op(ldst_op) | rd(d) | op3(ldsh_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void ldswa(  Register s1, Register s2, int ia, Register d ) { v9_only();  emit_int32( op(ldst_op) | rd(d) | op3(ldsw_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void ldswa(  Register s1, int simm13a,         Register d ) { v9_only();  emit_int32( op(ldst_op) | rd(d) | op3(ldsw_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void lduba(  Register s1, Register s2, int ia, Register d ) {             emit_int32( op(ldst_op) | rd(d) | op3(ldub_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void lduba(  Register s1, int simm13a,         Register d ) {             emit_int32( op(ldst_op) | rd(d) | op3(ldub_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void lduha(  Register s1, Register s2, int ia, Register d ) {             emit_int32( op(ldst_op) | rd(d) | op3(lduh_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void lduha(  Register s1, int simm13a,         Register d ) {             emit_int32( op(ldst_op) | rd(d) | op3(lduh_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void lduwa(  Register s1, Register s2, int ia, Register d ) {             emit_int32( op(ldst_op) | rd(d) | op3(lduw_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void lduwa(  Register s1, int simm13a,         Register d ) {             emit_int32( op(ldst_op) | rd(d) | op3(lduw_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void ldxa(   Register s1, Register s2, int ia, Register d ) { v9_only();  emit_int32( op(ldst_op) | rd(d) | op3(ldx_op3  | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void ldxa(   Register s1, int simm13a,         Register d ) { v9_only();  emit_int32( op(ldst_op) | rd(d) | op3(ldx_op3  | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void ldda(   Register s1, Register s2, int ia, Register d ) { v9_dep();   emit_int32( op(ldst_op) | rd(d) | op3(ldd_op3  | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void ldda(   Register s1, int simm13a,         Register d ) { v9_dep();   emit_int32( op(ldst_op) | rd(d) | op3(ldd_op3  | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 179
 
@@ -920,111 +920,111 @@
 
   // pp 180
 
-  void ldstuba( Register s1, Register s2, int ia, Register d ) { emit_long( op(ldst_op) | rd(d) | op3(ldstub_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void ldstuba( Register s1, int simm13a,         Register d ) { emit_long( op(ldst_op) | rd(d) | op3(ldstub_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void ldstuba( Register s1, Register s2, int ia, Register d ) { emit_int32( op(ldst_op) | rd(d) | op3(ldstub_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void ldstuba( Register s1, int simm13a,         Register d ) { emit_int32( op(ldst_op) | rd(d) | op3(ldstub_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 181
 
-  void and3(    Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(and_op3              ) | rs1(s1) | rs2(s2) ); }
-  void and3(    Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(and_op3              ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void andcc(   Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(and_op3  | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
-  void andcc(   Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(and_op3  | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void andn(    Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(andn_op3             ) | rs1(s1) | rs2(s2) ); }
-  void andn(    Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(andn_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void andncc(  Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(andn_op3 | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
-  void andncc(  Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(andn_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void or3(     Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(or_op3               ) | rs1(s1) | rs2(s2) ); }
-  void or3(     Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(or_op3               ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void orcc(    Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(or_op3   | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
-  void orcc(    Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(or_op3   | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void orn(     Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(orn_op3) | rs1(s1) | rs2(s2) ); }
-  void orn(     Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(orn_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void orncc(   Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(orn_op3  | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
-  void orncc(   Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(orn_op3  | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void xor3(    Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(xor_op3              ) | rs1(s1) | rs2(s2) ); }
-  void xor3(    Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(xor_op3              ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void xorcc(   Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(xor_op3  | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
-  void xorcc(   Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(xor_op3  | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void xnor(    Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(xnor_op3             ) | rs1(s1) | rs2(s2) ); }
-  void xnor(    Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(xnor_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void xnorcc(  Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(xnor_op3 | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
-  void xnorcc(  Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(xnor_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void and3(    Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(and_op3              ) | rs1(s1) | rs2(s2) ); }
+  void and3(    Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(and_op3              ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void andcc(   Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(and_op3  | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
+  void andcc(   Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(and_op3  | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void andn(    Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(andn_op3             ) | rs1(s1) | rs2(s2) ); }
+  void andn(    Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(andn_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void andncc(  Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(andn_op3 | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
+  void andncc(  Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(andn_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void or3(     Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(or_op3               ) | rs1(s1) | rs2(s2) ); }
+  void or3(     Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(or_op3               ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void orcc(    Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(or_op3   | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
+  void orcc(    Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(or_op3   | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void orn(     Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(orn_op3) | rs1(s1) | rs2(s2) ); }
+  void orn(     Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(orn_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void orncc(   Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(orn_op3  | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
+  void orncc(   Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(orn_op3  | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void xor3(    Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(xor_op3              ) | rs1(s1) | rs2(s2) ); }
+  void xor3(    Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(xor_op3              ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void xorcc(   Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(xor_op3  | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
+  void xorcc(   Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(xor_op3  | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void xnor(    Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(xnor_op3             ) | rs1(s1) | rs2(s2) ); }
+  void xnor(    Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(xnor_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void xnorcc(  Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(xnor_op3 | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
+  void xnorcc(  Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(xnor_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 183
 
-  void membar( Membar_mask_bits const7a ) { v9_only(); emit_long( op(arith_op) | op3(membar_op3) | rs1(O7) | immed(true) | u_field( int(const7a), 6, 0)); }
+  void membar( Membar_mask_bits const7a ) { v9_only(); emit_int32( op(arith_op) | op3(membar_op3) | rs1(O7) | immed(true) | u_field( int(const7a), 6, 0)); }
 
   // pp 185
 
-  void fmov( FloatRegisterImpl::Width w, Condition c,  bool floatCC, CC cca, FloatRegister s2, FloatRegister d ) { v9_only();  emit_long( op(arith_op) | fd(d, w) | op3(fpop2_op3) | cond_mov(c) | opf_cc(cca, floatCC) | opf_low6(w) | fs2(s2, w)); }
+  void fmov( FloatRegisterImpl::Width w, Condition c,  bool floatCC, CC cca, FloatRegister s2, FloatRegister d ) { v9_only();  emit_int32( op(arith_op) | fd(d, w) | op3(fpop2_op3) | cond_mov(c) | opf_cc(cca, floatCC) | opf_low6(w) | fs2(s2, w)); }
 
   // pp 189
 
-  void fmov( FloatRegisterImpl::Width w, RCondition c, Register s1,  FloatRegister s2, FloatRegister d ) { v9_only();  emit_long( op(arith_op) | fd(d, w) | op3(fpop2_op3) | rs1(s1) | rcond(c) | opf_low5(4 + w) | fs2(s2, w)); }
+  void fmov( FloatRegisterImpl::Width w, RCondition c, Register s1,  FloatRegister s2, FloatRegister d ) { v9_only();  emit_int32( op(arith_op) | fd(d, w) | op3(fpop2_op3) | rs1(s1) | rcond(c) | opf_low5(4 + w) | fs2(s2, w)); }
 
   // pp 191
 
-  void movcc( Condition c, bool floatCC, CC cca, Register s2, Register d ) { v9_only();  emit_long( op(arith_op) | rd(d) | op3(movcc_op3) | mov_cc(cca, floatCC) | cond_mov(c) | rs2(s2) ); }
-  void movcc( Condition c, bool floatCC, CC cca, int simm11a, Register d ) { v9_only();  emit_long( op(arith_op) | rd(d) | op3(movcc_op3) | mov_cc(cca, floatCC) | cond_mov(c) | immed(true) | simm(simm11a, 11) ); }
+  void movcc( Condition c, bool floatCC, CC cca, Register s2, Register d ) { v9_only();  emit_int32( op(arith_op) | rd(d) | op3(movcc_op3) | mov_cc(cca, floatCC) | cond_mov(c) | rs2(s2) ); }
+  void movcc( Condition c, bool floatCC, CC cca, int simm11a, Register d ) { v9_only();  emit_int32( op(arith_op) | rd(d) | op3(movcc_op3) | mov_cc(cca, floatCC) | cond_mov(c) | immed(true) | simm(simm11a, 11) ); }
 
   // pp 195
 
-  void movr( RCondition c, Register s1, Register s2,  Register d ) { v9_only();  emit_long( op(arith_op) | rd(d) | op3(movr_op3) | rs1(s1) | rcond(c) | rs2(s2) ); }
-  void movr( RCondition c, Register s1, int simm10a,  Register d ) { v9_only();  emit_long( op(arith_op) | rd(d) | op3(movr_op3) | rs1(s1) | rcond(c) | immed(true) | simm(simm10a, 10) ); }
+  void movr( RCondition c, Register s1, Register s2,  Register d ) { v9_only();  emit_int32( op(arith_op) | rd(d) | op3(movr_op3) | rs1(s1) | rcond(c) | rs2(s2) ); }
+  void movr( RCondition c, Register s1, int simm10a,  Register d ) { v9_only();  emit_int32( op(arith_op) | rd(d) | op3(movr_op3) | rs1(s1) | rcond(c) | immed(true) | simm(simm10a, 10) ); }
 
   // pp 196
 
-  void mulx(  Register s1, Register s2, Register d ) { v9_only(); emit_long( op(arith_op) | rd(d) | op3(mulx_op3 ) | rs1(s1) | rs2(s2) ); }
-  void mulx(  Register s1, int simm13a, Register d ) { v9_only(); emit_long( op(arith_op) | rd(d) | op3(mulx_op3 ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void sdivx( Register s1, Register s2, Register d ) { v9_only(); emit_long( op(arith_op) | rd(d) | op3(sdivx_op3) | rs1(s1) | rs2(s2) ); }
-  void sdivx( Register s1, int simm13a, Register d ) { v9_only(); emit_long( op(arith_op) | rd(d) | op3(sdivx_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void udivx( Register s1, Register s2, Register d ) { v9_only(); emit_long( op(arith_op) | rd(d) | op3(udivx_op3) | rs1(s1) | rs2(s2) ); }
-  void udivx( Register s1, int simm13a, Register d ) { v9_only(); emit_long( op(arith_op) | rd(d) | op3(udivx_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void mulx(  Register s1, Register s2, Register d ) { v9_only(); emit_int32( op(arith_op) | rd(d) | op3(mulx_op3 ) | rs1(s1) | rs2(s2) ); }
+  void mulx(  Register s1, int simm13a, Register d ) { v9_only(); emit_int32( op(arith_op) | rd(d) | op3(mulx_op3 ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void sdivx( Register s1, Register s2, Register d ) { v9_only(); emit_int32( op(arith_op) | rd(d) | op3(sdivx_op3) | rs1(s1) | rs2(s2) ); }
+  void sdivx( Register s1, int simm13a, Register d ) { v9_only(); emit_int32( op(arith_op) | rd(d) | op3(sdivx_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void udivx( Register s1, Register s2, Register d ) { v9_only(); emit_int32( op(arith_op) | rd(d) | op3(udivx_op3) | rs1(s1) | rs2(s2) ); }
+  void udivx( Register s1, int simm13a, Register d ) { v9_only(); emit_int32( op(arith_op) | rd(d) | op3(udivx_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 197
 
-  void umul(   Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(umul_op3             ) | rs1(s1) | rs2(s2) ); }
-  void umul(   Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(umul_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void smul(   Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(smul_op3             ) | rs1(s1) | rs2(s2) ); }
-  void smul(   Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(smul_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void umulcc( Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(umul_op3 | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
-  void umulcc( Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(umul_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void smulcc( Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(smul_op3 | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
-  void smulcc( Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(smul_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void umul(   Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(umul_op3             ) | rs1(s1) | rs2(s2) ); }
+  void umul(   Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(umul_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void smul(   Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(smul_op3             ) | rs1(s1) | rs2(s2) ); }
+  void smul(   Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(smul_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void umulcc( Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(umul_op3 | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
+  void umulcc( Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(umul_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void smulcc( Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(smul_op3 | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
+  void smulcc( Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(smul_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 199
 
-  void mulscc(   Register s1, Register s2, Register d ) { v9_dep();  emit_long( op(arith_op) | rd(d) | op3(mulscc_op3) | rs1(s1) | rs2(s2) ); }
-  void mulscc(   Register s1, int simm13a, Register d ) { v9_dep();  emit_long( op(arith_op) | rd(d) | op3(mulscc_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void mulscc(   Register s1, Register s2, Register d ) { v9_dep();  emit_int32( op(arith_op) | rd(d) | op3(mulscc_op3) | rs1(s1) | rs2(s2) ); }
+  void mulscc(   Register s1, int simm13a, Register d ) { v9_dep();  emit_int32( op(arith_op) | rd(d) | op3(mulscc_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 201
 
-  void nop() { emit_long( op(branch_op) | op2(sethi_op2) ); }
+  void nop() { emit_int32( op(branch_op) | op2(sethi_op2) ); }
 
 
   // pp 202
 
-  void popc( Register s,  Register d) { v9_only();  emit_long( op(arith_op) | rd(d) | op3(popc_op3) | rs2(s)); }
-  void popc( int simm13a, Register d) { v9_only();  emit_long( op(arith_op) | rd(d) | op3(popc_op3) | immed(true) | simm(simm13a, 13)); }
+  void popc( Register s,  Register d) { v9_only();  emit_int32( op(arith_op) | rd(d) | op3(popc_op3) | rs2(s)); }
+  void popc( int simm13a, Register d) { v9_only();  emit_int32( op(arith_op) | rd(d) | op3(popc_op3) | immed(true) | simm(simm13a, 13)); }
 
   // pp 203
 
-  void prefetch(   Register s1, Register s2, PrefetchFcn f) { v9_only();  emit_long( op(ldst_op) | fcn(f) | op3(prefetch_op3) | rs1(s1) | rs2(s2) ); }
+  void prefetch(   Register s1, Register s2, PrefetchFcn f) { v9_only();  emit_int32( op(ldst_op) | fcn(f) | op3(prefetch_op3) | rs1(s1) | rs2(s2) ); }
   void prefetch(   Register s1, int simm13a, PrefetchFcn f) { v9_only();  emit_data( op(ldst_op) | fcn(f) | op3(prefetch_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
-  void prefetcha(  Register s1, Register s2, int ia, PrefetchFcn f ) { v9_only();  emit_long( op(ldst_op) | fcn(f) | op3(prefetch_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void prefetcha(  Register s1, int simm13a,         PrefetchFcn f ) { v9_only();  emit_long( op(ldst_op) | fcn(f) | op3(prefetch_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void prefetcha(  Register s1, Register s2, int ia, PrefetchFcn f ) { v9_only();  emit_int32( op(ldst_op) | fcn(f) | op3(prefetch_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void prefetcha(  Register s1, int simm13a,         PrefetchFcn f ) { v9_only();  emit_int32( op(ldst_op) | fcn(f) | op3(prefetch_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 208
 
   // not implementing read privileged register
 
-  inline void rdy(    Register d) { v9_dep();  emit_long( op(arith_op) | rd(d) | op3(rdreg_op3) | u_field(0, 18, 14)); }
-  inline void rdccr(  Register d) { v9_only(); emit_long( op(arith_op) | rd(d) | op3(rdreg_op3) | u_field(2, 18, 14)); }
-  inline void rdasi(  Register d) { v9_only(); emit_long( op(arith_op) | rd(d) | op3(rdreg_op3) | u_field(3, 18, 14)); }
-  inline void rdtick( Register d) { v9_only(); emit_long( op(arith_op) | rd(d) | op3(rdreg_op3) | u_field(4, 18, 14)); } // Spoon!
-  inline void rdpc(   Register d) { v9_only(); emit_long( op(arith_op) | rd(d) | op3(rdreg_op3) | u_field(5, 18, 14)); }
-  inline void rdfprs( Register d) { v9_only(); emit_long( op(arith_op) | rd(d) | op3(rdreg_op3) | u_field(6, 18, 14)); }
+  inline void rdy(    Register d) { v9_dep();  emit_int32( op(arith_op) | rd(d) | op3(rdreg_op3) | u_field(0, 18, 14)); }
+  inline void rdccr(  Register d) { v9_only(); emit_int32( op(arith_op) | rd(d) | op3(rdreg_op3) | u_field(2, 18, 14)); }
+  inline void rdasi(  Register d) { v9_only(); emit_int32( op(arith_op) | rd(d) | op3(rdreg_op3) | u_field(3, 18, 14)); }
+  inline void rdtick( Register d) { v9_only(); emit_int32( op(arith_op) | rd(d) | op3(rdreg_op3) | u_field(4, 18, 14)); } // Spoon!
+  inline void rdpc(   Register d) { v9_only(); emit_int32( op(arith_op) | rd(d) | op3(rdreg_op3) | u_field(5, 18, 14)); }
+  inline void rdfprs( Register d) { v9_only(); emit_int32( op(arith_op) | rd(d) | op3(rdreg_op3) | u_field(6, 18, 14)); }
 
   // pp 213
 
@@ -1033,47 +1033,47 @@
 
   // pp 214
 
-  void save(    Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(save_op3) | rs1(s1) | rs2(s2) ); }
+  void save(    Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(save_op3) | rs1(s1) | rs2(s2) ); }
   void save(    Register s1, int simm13a, Register d ) {
     // make sure frame is at least large enough for the register save area
     assert(-simm13a >= 16 * wordSize, "frame too small");
-    emit_long( op(arith_op) | rd(d) | op3(save_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) );
+    emit_int32( op(arith_op) | rd(d) | op3(save_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) );
   }
 
-  void restore( Register s1 = G0,  Register s2 = G0, Register d = G0 ) { emit_long( op(arith_op) | rd(d) | op3(restore_op3) | rs1(s1) | rs2(s2) ); }
-  void restore( Register s1,       int simm13a,      Register d      ) { emit_long( op(arith_op) | rd(d) | op3(restore_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void restore( Register s1 = G0,  Register s2 = G0, Register d = G0 ) { emit_int32( op(arith_op) | rd(d) | op3(restore_op3) | rs1(s1) | rs2(s2) ); }
+  void restore( Register s1,       int simm13a,      Register d      ) { emit_int32( op(arith_op) | rd(d) | op3(restore_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 216
 
-  void saved()    { v9_only();  emit_long( op(arith_op) | fcn(0) | op3(saved_op3)); }
-  void restored() { v9_only();  emit_long( op(arith_op) | fcn(1) | op3(saved_op3)); }
+  void saved()    { v9_only();  emit_int32( op(arith_op) | fcn(0) | op3(saved_op3)); }
+  void restored() { v9_only();  emit_int32( op(arith_op) | fcn(1) | op3(saved_op3)); }
 
   // pp 217
 
   inline void sethi( int imm22a, Register d, RelocationHolder const& rspec = RelocationHolder() );
   // pp 218
 
-  void sll(  Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(sll_op3) | rs1(s1) | sx(0) | rs2(s2) ); }
-  void sll(  Register s1, int imm5a,   Register d ) { emit_long( op(arith_op) | rd(d) | op3(sll_op3) | rs1(s1) | sx(0) | immed(true) | u_field(imm5a, 4, 0) ); }
-  void srl(  Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(srl_op3) | rs1(s1) | sx(0) | rs2(s2) ); }
-  void srl(  Register s1, int imm5a,   Register d ) { emit_long( op(arith_op) | rd(d) | op3(srl_op3) | rs1(s1) | sx(0) | immed(true) | u_field(imm5a, 4, 0) ); }
-  void sra(  Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(sra_op3) | rs1(s1) | sx(0) | rs2(s2) ); }
-  void sra(  Register s1, int imm5a,   Register d ) { emit_long( op(arith_op) | rd(d) | op3(sra_op3) | rs1(s1) | sx(0) | immed(true) | u_field(imm5a, 4, 0) ); }
+  void sll(  Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(sll_op3) | rs1(s1) | sx(0) | rs2(s2) ); }
+  void sll(  Register s1, int imm5a,   Register d ) { emit_int32( op(arith_op) | rd(d) | op3(sll_op3) | rs1(s1) | sx(0) | immed(true) | u_field(imm5a, 4, 0) ); }
+  void srl(  Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(srl_op3) | rs1(s1) | sx(0) | rs2(s2) ); }
+  void srl(  Register s1, int imm5a,   Register d ) { emit_int32( op(arith_op) | rd(d) | op3(srl_op3) | rs1(s1) | sx(0) | immed(true) | u_field(imm5a, 4, 0) ); }
+  void sra(  Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(sra_op3) | rs1(s1) | sx(0) | rs2(s2) ); }
+  void sra(  Register s1, int imm5a,   Register d ) { emit_int32( op(arith_op) | rd(d) | op3(sra_op3) | rs1(s1) | sx(0) | immed(true) | u_field(imm5a, 4, 0) ); }
 
-  void sllx( Register s1, Register s2, Register d ) { v9_only();  emit_long( op(arith_op) | rd(d) | op3(sll_op3) | rs1(s1) | sx(1) | rs2(s2) ); }
-  void sllx( Register s1, int imm6a,   Register d ) { v9_only();  emit_long( op(arith_op) | rd(d) | op3(sll_op3) | rs1(s1) | sx(1) | immed(true) | u_field(imm6a, 5, 0) ); }
-  void srlx( Register s1, Register s2, Register d ) { v9_only();  emit_long( op(arith_op) | rd(d) | op3(srl_op3) | rs1(s1) | sx(1) | rs2(s2) ); }
-  void srlx( Register s1, int imm6a,   Register d ) { v9_only();  emit_long( op(arith_op) | rd(d) | op3(srl_op3) | rs1(s1) | sx(1) | immed(true) | u_field(imm6a, 5, 0) ); }
-  void srax( Register s1, Register s2, Register d ) { v9_only();  emit_long( op(arith_op) | rd(d) | op3(sra_op3) | rs1(s1) | sx(1) | rs2(s2) ); }
-  void srax( Register s1, int imm6a,   Register d ) { v9_only();  emit_long( op(arith_op) | rd(d) | op3(sra_op3) | rs1(s1) | sx(1) | immed(true) | u_field(imm6a, 5, 0) ); }
+  void sllx( Register s1, Register s2, Register d ) { v9_only();  emit_int32( op(arith_op) | rd(d) | op3(sll_op3) | rs1(s1) | sx(1) | rs2(s2) ); }
+  void sllx( Register s1, int imm6a,   Register d ) { v9_only();  emit_int32( op(arith_op) | rd(d) | op3(sll_op3) | rs1(s1) | sx(1) | immed(true) | u_field(imm6a, 5, 0) ); }
+  void srlx( Register s1, Register s2, Register d ) { v9_only();  emit_int32( op(arith_op) | rd(d) | op3(srl_op3) | rs1(s1) | sx(1) | rs2(s2) ); }
+  void srlx( Register s1, int imm6a,   Register d ) { v9_only();  emit_int32( op(arith_op) | rd(d) | op3(srl_op3) | rs1(s1) | sx(1) | immed(true) | u_field(imm6a, 5, 0) ); }
+  void srax( Register s1, Register s2, Register d ) { v9_only();  emit_int32( op(arith_op) | rd(d) | op3(sra_op3) | rs1(s1) | sx(1) | rs2(s2) ); }
+  void srax( Register s1, int imm6a,   Register d ) { v9_only();  emit_int32( op(arith_op) | rd(d) | op3(sra_op3) | rs1(s1) | sx(1) | immed(true) | u_field(imm6a, 5, 0) ); }
 
   // pp 220
 
-  void sir( int simm13a ) { emit_long( op(arith_op) | fcn(15) | op3(sir_op3) | immed(true) | simm(simm13a, 13)); }
+  void sir( int simm13a ) { emit_int32( op(arith_op) | fcn(15) | op3(sir_op3) | immed(true) | simm(simm13a, 13)); }
 
   // pp 221
 
-  void stbar() { emit_long( op(arith_op) | op3(membar_op3) | u_field(15, 18, 14)); }
+  void stbar() { emit_int32( op(arith_op) | op3(membar_op3) | u_field(15, 18, 14)); }
 
   // pp 222
 
@@ -1087,8 +1087,8 @@
 
   //  pp 224
 
-  void stfa(  FloatRegisterImpl::Width w, FloatRegister d, Register s1, Register s2, int ia ) { v9_only();  emit_long( op(ldst_op) | fd(d, w) | alt_op3(stf_op3 | alt_bit_op3, w) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void stfa(  FloatRegisterImpl::Width w, FloatRegister d, Register s1, int simm13a         ) { v9_only();  emit_long( op(ldst_op) | fd(d, w) | alt_op3(stf_op3 | alt_bit_op3, w) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void stfa(  FloatRegisterImpl::Width w, FloatRegister d, Register s1, Register s2, int ia ) { v9_only();  emit_int32( op(ldst_op) | fd(d, w) | alt_op3(stf_op3 | alt_bit_op3, w) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void stfa(  FloatRegisterImpl::Width w, FloatRegister d, Register s1, int simm13a         ) { v9_only();  emit_int32( op(ldst_op) | fd(d, w) | alt_op3(stf_op3 | alt_bit_op3, w) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // p 226
 
@@ -1105,16 +1105,16 @@
 
   // pp 177
 
-  void stba(  Register d, Register s1, Register s2, int ia ) {             emit_long( op(ldst_op) | rd(d) | op3(stb_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void stba(  Register d, Register s1, int simm13a         ) {             emit_long( op(ldst_op) | rd(d) | op3(stb_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void stha(  Register d, Register s1, Register s2, int ia ) {             emit_long( op(ldst_op) | rd(d) | op3(sth_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void stha(  Register d, Register s1, int simm13a         ) {             emit_long( op(ldst_op) | rd(d) | op3(sth_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void stwa(  Register d, Register s1, Register s2, int ia ) {             emit_long( op(ldst_op) | rd(d) | op3(stw_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void stwa(  Register d, Register s1, int simm13a         ) {             emit_long( op(ldst_op) | rd(d) | op3(stw_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void stxa(  Register d, Register s1, Register s2, int ia ) { v9_only();  emit_long( op(ldst_op) | rd(d) | op3(stx_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void stxa(  Register d, Register s1, int simm13a         ) { v9_only();  emit_long( op(ldst_op) | rd(d) | op3(stx_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void stda(  Register d, Register s1, Register s2, int ia ) {             emit_long( op(ldst_op) | rd(d) | op3(std_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void stda(  Register d, Register s1, int simm13a         ) {             emit_long( op(ldst_op) | rd(d) | op3(std_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void stba(  Register d, Register s1, Register s2, int ia ) {             emit_int32( op(ldst_op) | rd(d) | op3(stb_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void stba(  Register d, Register s1, int simm13a         ) {             emit_int32( op(ldst_op) | rd(d) | op3(stb_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void stha(  Register d, Register s1, Register s2, int ia ) {             emit_int32( op(ldst_op) | rd(d) | op3(sth_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void stha(  Register d, Register s1, int simm13a         ) {             emit_int32( op(ldst_op) | rd(d) | op3(sth_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void stwa(  Register d, Register s1, Register s2, int ia ) {             emit_int32( op(ldst_op) | rd(d) | op3(stw_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void stwa(  Register d, Register s1, int simm13a         ) {             emit_int32( op(ldst_op) | rd(d) | op3(stw_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void stxa(  Register d, Register s1, Register s2, int ia ) { v9_only();  emit_int32( op(ldst_op) | rd(d) | op3(stx_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void stxa(  Register d, Register s1, int simm13a         ) { v9_only();  emit_int32( op(ldst_op) | rd(d) | op3(stx_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void stda(  Register d, Register s1, Register s2, int ia ) {             emit_int32( op(ldst_op) | rd(d) | op3(std_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void stda(  Register d, Register s1, int simm13a         ) {             emit_int32( op(ldst_op) | rd(d) | op3(std_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 97 (v8)
 
@@ -1129,15 +1129,15 @@
 
   // pp 230
 
-  void sub(    Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(sub_op3              ) | rs1(s1) | rs2(s2) ); }
-  void sub(    Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(sub_op3              ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void sub(    Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(sub_op3              ) | rs1(s1) | rs2(s2) ); }
+  void sub(    Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(sub_op3              ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
-  void subcc(  Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(sub_op3 | cc_bit_op3 ) | rs1(s1) | rs2(s2) ); }
-  void subcc(  Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(sub_op3 | cc_bit_op3 ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void subc(   Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(subc_op3             ) | rs1(s1) | rs2(s2) ); }
-  void subc(   Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(subc_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void subccc( Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(subc_op3 | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
-  void subccc( Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(subc_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void subcc(  Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(sub_op3 | cc_bit_op3 ) | rs1(s1) | rs2(s2) ); }
+  void subcc(  Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(sub_op3 | cc_bit_op3 ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void subc(   Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(subc_op3             ) | rs1(s1) | rs2(s2) ); }
+  void subc(   Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(subc_op3             ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void subccc( Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(subc_op3 | cc_bit_op3) | rs1(s1) | rs2(s2) ); }
+  void subccc( Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(subc_op3 | cc_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 231
 
@@ -1146,55 +1146,55 @@
 
   // pp 232
 
-  void swapa(   Register s1, Register s2, int ia, Register d ) { v9_dep();  emit_long( op(ldst_op) | rd(d) | op3(swap_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
-  void swapa(   Register s1, int simm13a,         Register d ) { v9_dep();  emit_long( op(ldst_op) | rd(d) | op3(swap_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void swapa(   Register s1, Register s2, int ia, Register d ) { v9_dep();  emit_int32( op(ldst_op) | rd(d) | op3(swap_op3 | alt_bit_op3) | rs1(s1) | imm_asi(ia) | rs2(s2) ); }
+  void swapa(   Register s1, int simm13a,         Register d ) { v9_dep();  emit_int32( op(ldst_op) | rd(d) | op3(swap_op3 | alt_bit_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 234, note op in book is wrong, see pp 268
 
-  void taddcc(    Register s1, Register s2, Register d ) {            emit_long( op(arith_op) | rd(d) | op3(taddcc_op3  ) | rs1(s1) | rs2(s2) ); }
-  void taddcc(    Register s1, int simm13a, Register d ) {            emit_long( op(arith_op) | rd(d) | op3(taddcc_op3  ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void taddcctv(  Register s1, Register s2, Register d ) { v9_dep();  emit_long( op(arith_op) | rd(d) | op3(taddcctv_op3) | rs1(s1) | rs2(s2) ); }
-  void taddcctv(  Register s1, int simm13a, Register d ) { v9_dep();  emit_long( op(arith_op) | rd(d) | op3(taddcctv_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void taddcc(    Register s1, Register s2, Register d ) {            emit_int32( op(arith_op) | rd(d) | op3(taddcc_op3  ) | rs1(s1) | rs2(s2) ); }
+  void taddcc(    Register s1, int simm13a, Register d ) {            emit_int32( op(arith_op) | rd(d) | op3(taddcc_op3  ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void taddcctv(  Register s1, Register s2, Register d ) { v9_dep();  emit_int32( op(arith_op) | rd(d) | op3(taddcctv_op3) | rs1(s1) | rs2(s2) ); }
+  void taddcctv(  Register s1, int simm13a, Register d ) { v9_dep();  emit_int32( op(arith_op) | rd(d) | op3(taddcctv_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 235
 
-  void tsubcc(    Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(tsubcc_op3  ) | rs1(s1) | rs2(s2) ); }
-  void tsubcc(    Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(tsubcc_op3  ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
-  void tsubcctv(  Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(tsubcctv_op3) | rs1(s1) | rs2(s2) ); }
-  void tsubcctv(  Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(tsubcctv_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void tsubcc(    Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(tsubcc_op3  ) | rs1(s1) | rs2(s2) ); }
+  void tsubcc(    Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(tsubcc_op3  ) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+  void tsubcctv(  Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(tsubcctv_op3) | rs1(s1) | rs2(s2) ); }
+  void tsubcctv(  Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(tsubcctv_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
   // pp 237
 
-  void trap( Condition c, CC cc, Register s1, Register s2 ) { v8_no_cc(cc);  emit_long( op(arith_op) | cond(c) | op3(trap_op3) | rs1(s1) | trapcc(cc) | rs2(s2)); }
-  void trap( Condition c, CC cc, Register s1, int trapa   ) { v8_no_cc(cc);  emit_long( op(arith_op) | cond(c) | op3(trap_op3) | rs1(s1) | trapcc(cc) | immed(true) | u_field(trapa, 6, 0)); }
+  void trap( Condition c, CC cc, Register s1, Register s2 ) { v8_no_cc(cc);  emit_int32( op(arith_op) | cond(c) | op3(trap_op3) | rs1(s1) | trapcc(cc) | rs2(s2)); }
+  void trap( Condition c, CC cc, Register s1, int trapa   ) { v8_no_cc(cc);  emit_int32( op(arith_op) | cond(c) | op3(trap_op3) | rs1(s1) | trapcc(cc) | immed(true) | u_field(trapa, 6, 0)); }
   // simple uncond. trap
   void trap( int trapa ) { trap( always, icc, G0, trapa ); }
 
   // pp 239 omit write priv register for now
 
-  inline void wry(    Register d) { v9_dep();  emit_long( op(arith_op) | rs1(d) | op3(wrreg_op3) | u_field(0, 29, 25)); }
-  inline void wrccr(Register s) { v9_only(); emit_long( op(arith_op) | rs1(s) | op3(wrreg_op3) | u_field(2, 29, 25)); }
-  inline void wrccr(Register s, int simm13a) { v9_only(); emit_long( op(arith_op) |
+  inline void wry(    Register d) { v9_dep();  emit_int32( op(arith_op) | rs1(d) | op3(wrreg_op3) | u_field(0, 29, 25)); }
+  inline void wrccr(Register s) { v9_only(); emit_int32( op(arith_op) | rs1(s) | op3(wrreg_op3) | u_field(2, 29, 25)); }
+  inline void wrccr(Register s, int simm13a) { v9_only(); emit_int32( op(arith_op) |
                                                                            rs1(s) |
                                                                            op3(wrreg_op3) |
                                                                            u_field(2, 29, 25) |
                                                                            immed(true) |
                                                                            simm(simm13a, 13)); }
-  inline void wrasi(Register d) { v9_only(); emit_long( op(arith_op) | rs1(d) | op3(wrreg_op3) | u_field(3, 29, 25)); }
+  inline void wrasi(Register d) { v9_only(); emit_int32( op(arith_op) | rs1(d) | op3(wrreg_op3) | u_field(3, 29, 25)); }
   // wrasi(d, imm) stores (d xor imm) to asi
-  inline void wrasi(Register d, int simm13a) { v9_only(); emit_long( op(arith_op) | rs1(d) | op3(wrreg_op3) |
+  inline void wrasi(Register d, int simm13a) { v9_only(); emit_int32( op(arith_op) | rs1(d) | op3(wrreg_op3) |
                                                u_field(3, 29, 25) | immed(true) | simm(simm13a, 13)); }
-  inline void wrfprs( Register d) { v9_only(); emit_long( op(arith_op) | rs1(d) | op3(wrreg_op3) | u_field(6, 29, 25)); }
+  inline void wrfprs( Register d) { v9_only(); emit_int32( op(arith_op) | rs1(d) | op3(wrreg_op3) | u_field(6, 29, 25)); }
 
 
   // VIS3 instructions
 
-  void movstosw( FloatRegister s, Register d ) { vis3_only();  emit_long( op(arith_op) | rd(d) | op3(mftoi_op3) | opf(mstosw_opf) | fs2(s, FloatRegisterImpl::S)); }
-  void movstouw( FloatRegister s, Register d ) { vis3_only();  emit_long( op(arith_op) | rd(d) | op3(mftoi_op3) | opf(mstouw_opf) | fs2(s, FloatRegisterImpl::S)); }
-  void movdtox(  FloatRegister s, Register d ) { vis3_only();  emit_long( op(arith_op) | rd(d) | op3(mftoi_op3) | opf(mdtox_opf) | fs2(s, FloatRegisterImpl::D)); }
+  void movstosw( FloatRegister s, Register d ) { vis3_only();  emit_int32( op(arith_op) | rd(d) | op3(mftoi_op3) | opf(mstosw_opf) | fs2(s, FloatRegisterImpl::S)); }
+  void movstouw( FloatRegister s, Register d ) { vis3_only();  emit_int32( op(arith_op) | rd(d) | op3(mftoi_op3) | opf(mstouw_opf) | fs2(s, FloatRegisterImpl::S)); }
+  void movdtox(  FloatRegister s, Register d ) { vis3_only();  emit_int32( op(arith_op) | rd(d) | op3(mftoi_op3) | opf(mdtox_opf) | fs2(s, FloatRegisterImpl::D)); }
 
-  void movwtos( Register s, FloatRegister d ) { vis3_only();  emit_long( op(arith_op) | fd(d, FloatRegisterImpl::S) | op3(mftoi_op3) | opf(mwtos_opf) | rs2(s)); }
-  void movxtod( Register s, FloatRegister d ) { vis3_only();  emit_long( op(arith_op) | fd(d, FloatRegisterImpl::D) | op3(mftoi_op3) | opf(mxtod_opf) | rs2(s)); }
+  void movwtos( Register s, FloatRegister d ) { vis3_only();  emit_int32( op(arith_op) | fd(d, FloatRegisterImpl::S) | op3(mftoi_op3) | opf(mwtos_opf) | rs2(s)); }
+  void movxtod( Register s, FloatRegister d ) { vis3_only();  emit_int32( op(arith_op) | fd(d, FloatRegisterImpl::D) | op3(mftoi_op3) | opf(mxtod_opf) | rs2(s)); }
 
   // Creation
   Assembler(CodeBuffer* code) : AbstractAssembler(code) {
--- a/hotspot/src/cpu/sparc/vm/assembler_sparc.inline.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/sparc/vm/assembler_sparc.inline.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -35,24 +35,24 @@
 # endif
 }
 
-inline void Assembler::emit_long(int x) {
+inline void Assembler::emit_int32(int x) {
   check_delay();
-  AbstractAssembler::emit_long(x);
+  AbstractAssembler::emit_int32(x);
 }
 
 inline void Assembler::emit_data(int x, relocInfo::relocType rtype) {
   relocate(rtype);
-  emit_long(x);
+  emit_int32(x);
 }
 
 inline void Assembler::emit_data(int x, RelocationHolder const& rspec) {
   relocate(rspec);
-  emit_long(x);
+  emit_int32(x);
 }
 
 
-inline void Assembler::add(Register s1, Register s2, Register d ) { emit_long( op(arith_op) | rd(d) | op3(add_op3) | rs1(s1) | rs2(s2) ); }
-inline void Assembler::add(Register s1, int simm13a, Register d ) { emit_long( op(arith_op) | rd(d) | op3(add_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
+inline void Assembler::add(Register s1, Register s2, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(add_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::add(Register s1, int simm13a, Register d ) { emit_int32( op(arith_op) | rd(d) | op3(add_op3) | rs1(s1) | immed(true) | simm(simm13a, 13) ); }
 
 inline void Assembler::bpr( RCondition c, bool a, Predict p, Register s1, address d, relocInfo::relocType rt ) { v9_only();  cti();  emit_data( op(branch_op) | annul(a) | cond(c) | op2(bpr_op2) | wdisp16(intptr_t(d), intptr_t(pc())) | predict(p) | rs1(s1), rt);  has_delay_slot(); }
 inline void Assembler::bpr( RCondition c, bool a, Predict p, Register s1, Label& L) { bpr( c, a, p, s1, target(L)); }
@@ -79,93 +79,93 @@
 inline void Assembler::call( address d,  relocInfo::relocType rt ) { cti();  emit_data( op(call_op) | wdisp(intptr_t(d), intptr_t(pc()), 30), rt);  has_delay_slot(); assert(rt != relocInfo::virtual_call_type, "must use virtual_call_Relocation::spec"); }
 inline void Assembler::call( Label& L,   relocInfo::relocType rt ) { call( target(L), rt); }
 
-inline void Assembler::flush( Register s1, Register s2) { emit_long( op(arith_op) | op3(flush_op3) | rs1(s1) | rs2(s2)); }
+inline void Assembler::flush( Register s1, Register s2) { emit_int32( op(arith_op) | op3(flush_op3) | rs1(s1) | rs2(s2)); }
 inline void Assembler::flush( Register s1, int simm13a) { emit_data( op(arith_op) | op3(flush_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
-inline void Assembler::jmpl( Register s1, Register s2, Register d ) { cti();  emit_long( op(arith_op) | rd(d) | op3(jmpl_op3) | rs1(s1) | rs2(s2));  has_delay_slot(); }
+inline void Assembler::jmpl( Register s1, Register s2, Register d ) { cti();  emit_int32( op(arith_op) | rd(d) | op3(jmpl_op3) | rs1(s1) | rs2(s2));  has_delay_slot(); }
 inline void Assembler::jmpl( Register s1, int simm13a, Register d, RelocationHolder const& rspec ) { cti();  emit_data( op(arith_op) | rd(d) | op3(jmpl_op3) | rs1(s1) | immed(true) | simm(simm13a, 13), rspec);  has_delay_slot(); }
 
-inline void Assembler::ldf(FloatRegisterImpl::Width w, Register s1, Register s2, FloatRegister d) { emit_long( op(ldst_op) | fd(d, w) | alt_op3(ldf_op3, w) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::ldf(FloatRegisterImpl::Width w, Register s1, Register s2, FloatRegister d) { emit_int32( op(ldst_op) | fd(d, w) | alt_op3(ldf_op3, w) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldf(FloatRegisterImpl::Width w, Register s1, int simm13a, FloatRegister d, RelocationHolder const& rspec) { emit_data( op(ldst_op) | fd(d, w) | alt_op3(ldf_op3, w) | rs1(s1) | immed(true) | simm(simm13a, 13), rspec); }
 
-inline void Assembler::ldfsr(  Register s1, Register s2) { v9_dep();   emit_long( op(ldst_op) |             op3(ldfsr_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::ldfsr(  Register s1, Register s2) { v9_dep();   emit_int32( op(ldst_op) |             op3(ldfsr_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldfsr(  Register s1, int simm13a) { v9_dep();   emit_data( op(ldst_op) |             op3(ldfsr_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::ldxfsr( Register s1, Register s2) { v9_only();  emit_long( op(ldst_op) | rd(G1)    | op3(ldfsr_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::ldxfsr( Register s1, Register s2) { v9_only();  emit_int32( op(ldst_op) | rd(G1)    | op3(ldfsr_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldxfsr( Register s1, int simm13a) { v9_only();  emit_data( op(ldst_op) | rd(G1)    | op3(ldfsr_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
-inline void Assembler::ldc(   Register s1, Register s2, int crd) { v8_only();  emit_long( op(ldst_op) | fcn(crd) | op3(ldc_op3  ) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::ldc(   Register s1, Register s2, int crd) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(ldc_op3  ) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldc(   Register s1, int simm13a, int crd) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(ldc_op3  ) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::lddc(  Register s1, Register s2, int crd) { v8_only();  emit_long( op(ldst_op) | fcn(crd) | op3(lddc_op3 ) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::lddc(  Register s1, Register s2, int crd) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(lddc_op3 ) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::lddc(  Register s1, int simm13a, int crd) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(lddc_op3 ) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::ldcsr( Register s1, Register s2, int crd) { v8_only();  emit_long( op(ldst_op) | fcn(crd) | op3(ldcsr_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::ldcsr( Register s1, Register s2, int crd) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(ldcsr_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldcsr( Register s1, int simm13a, int crd) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(ldcsr_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
-inline void Assembler::ldsb(  Register s1, Register s2, Register d) { emit_long( op(ldst_op) | rd(d) | op3(ldsb_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::ldsb(  Register s1, Register s2, Register d) { emit_int32( op(ldst_op) | rd(d) | op3(ldsb_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldsb(  Register s1, int simm13a, Register d) { emit_data( op(ldst_op) | rd(d) | op3(ldsb_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
-inline void Assembler::ldsh(  Register s1, Register s2, Register d) { emit_long( op(ldst_op) | rd(d) | op3(ldsh_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::ldsh(  Register s1, Register s2, Register d) { emit_int32( op(ldst_op) | rd(d) | op3(ldsh_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldsh(  Register s1, int simm13a, Register d) { emit_data( op(ldst_op) | rd(d) | op3(ldsh_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::ldsw(  Register s1, Register s2, Register d) { emit_long( op(ldst_op) | rd(d) | op3(ldsw_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::ldsw(  Register s1, Register s2, Register d) { emit_int32( op(ldst_op) | rd(d) | op3(ldsw_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldsw(  Register s1, int simm13a, Register d) { emit_data( op(ldst_op) | rd(d) | op3(ldsw_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::ldub(  Register s1, Register s2, Register d) { emit_long( op(ldst_op) | rd(d) | op3(ldub_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::ldub(  Register s1, Register s2, Register d) { emit_int32( op(ldst_op) | rd(d) | op3(ldub_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldub(  Register s1, int simm13a, Register d) { emit_data( op(ldst_op) | rd(d) | op3(ldub_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::lduh(  Register s1, Register s2, Register d) { emit_long( op(ldst_op) | rd(d) | op3(lduh_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::lduh(  Register s1, Register s2, Register d) { emit_int32( op(ldst_op) | rd(d) | op3(lduh_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::lduh(  Register s1, int simm13a, Register d) { emit_data( op(ldst_op) | rd(d) | op3(lduh_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::lduw(  Register s1, Register s2, Register d) { emit_long( op(ldst_op) | rd(d) | op3(lduw_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::lduw(  Register s1, Register s2, Register d) { emit_int32( op(ldst_op) | rd(d) | op3(lduw_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::lduw(  Register s1, int simm13a, Register d) { emit_data( op(ldst_op) | rd(d) | op3(lduw_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
-inline void Assembler::ldx(   Register s1, Register s2, Register d) { v9_only();  emit_long( op(ldst_op) | rd(d) | op3(ldx_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::ldx(   Register s1, Register s2, Register d) { v9_only();  emit_int32( op(ldst_op) | rd(d) | op3(ldx_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldx(   Register s1, int simm13a, Register d) { v9_only();  emit_data( op(ldst_op) | rd(d) | op3(ldx_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::ldd(   Register s1, Register s2, Register d) { v9_dep(); assert(d->is_even(), "not even"); emit_long( op(ldst_op) | rd(d) | op3(ldd_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::ldd(   Register s1, Register s2, Register d) { v9_dep(); assert(d->is_even(), "not even"); emit_int32( op(ldst_op) | rd(d) | op3(ldd_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldd(   Register s1, int simm13a, Register d) { v9_dep(); assert(d->is_even(), "not even"); emit_data( op(ldst_op) | rd(d) | op3(ldd_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
-inline void Assembler::ldstub(  Register s1, Register s2, Register d) { emit_long( op(ldst_op) | rd(d) | op3(ldstub_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::ldstub(  Register s1, Register s2, Register d) { emit_int32( op(ldst_op) | rd(d) | op3(ldstub_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::ldstub(  Register s1, int simm13a, Register d) { emit_data( op(ldst_op) | rd(d) | op3(ldstub_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
-inline void Assembler::rett( Register s1, Register s2                         ) { cti();  emit_long( op(arith_op) | op3(rett_op3) | rs1(s1) | rs2(s2));  has_delay_slot(); }
+inline void Assembler::rett( Register s1, Register s2                         ) { cti();  emit_int32( op(arith_op) | op3(rett_op3) | rs1(s1) | rs2(s2));  has_delay_slot(); }
 inline void Assembler::rett( Register s1, int simm13a, relocInfo::relocType rt) { cti();  emit_data( op(arith_op) | op3(rett_op3) | rs1(s1) | immed(true) | simm(simm13a, 13), rt);  has_delay_slot(); }
 
 inline void Assembler::sethi( int imm22a, Register d, RelocationHolder const& rspec ) { emit_data( op(branch_op) | rd(d) | op2(sethi_op2) | hi22(imm22a), rspec); }
 
   // pp 222
 
-inline void Assembler::stf(    FloatRegisterImpl::Width w, FloatRegister d, Register s1, Register s2) { emit_long( op(ldst_op) | fd(d, w) | alt_op3(stf_op3, w) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::stf(    FloatRegisterImpl::Width w, FloatRegister d, Register s1, Register s2) { emit_int32( op(ldst_op) | fd(d, w) | alt_op3(stf_op3, w) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::stf(    FloatRegisterImpl::Width w, FloatRegister d, Register s1, int simm13a) { emit_data( op(ldst_op) | fd(d, w) | alt_op3(stf_op3, w) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
-inline void Assembler::stfsr(  Register s1, Register s2) { v9_dep();   emit_long( op(ldst_op) |             op3(stfsr_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::stfsr(  Register s1, Register s2) { v9_dep();   emit_int32( op(ldst_op) |             op3(stfsr_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::stfsr(  Register s1, int simm13a) { v9_dep();   emit_data( op(ldst_op) |             op3(stfsr_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::stxfsr( Register s1, Register s2) { v9_only();  emit_long( op(ldst_op) | rd(G1)    | op3(stfsr_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::stxfsr( Register s1, Register s2) { v9_only();  emit_int32( op(ldst_op) | rd(G1)    | op3(stfsr_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::stxfsr( Register s1, int simm13a) { v9_only();  emit_data( op(ldst_op) | rd(G1)    | op3(stfsr_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
   // p 226
 
-inline void Assembler::stb(  Register d, Register s1, Register s2) { emit_long( op(ldst_op) | rd(d) | op3(stb_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::stb(  Register d, Register s1, Register s2) { emit_int32( op(ldst_op) | rd(d) | op3(stb_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::stb(  Register d, Register s1, int simm13a) { emit_data( op(ldst_op) | rd(d) | op3(stb_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::sth(  Register d, Register s1, Register s2) { emit_long( op(ldst_op) | rd(d) | op3(sth_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::sth(  Register d, Register s1, Register s2) { emit_int32( op(ldst_op) | rd(d) | op3(sth_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::sth(  Register d, Register s1, int simm13a) { emit_data( op(ldst_op) | rd(d) | op3(sth_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::stw(  Register d, Register s1, Register s2) { emit_long( op(ldst_op) | rd(d) | op3(stw_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::stw(  Register d, Register s1, Register s2) { emit_int32( op(ldst_op) | rd(d) | op3(stw_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::stw(  Register d, Register s1, int simm13a) { emit_data( op(ldst_op) | rd(d) | op3(stw_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
 
-inline void Assembler::stx(  Register d, Register s1, Register s2) { v9_only();  emit_long( op(ldst_op) | rd(d) | op3(stx_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::stx(  Register d, Register s1, Register s2) { v9_only();  emit_int32( op(ldst_op) | rd(d) | op3(stx_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::stx(  Register d, Register s1, int simm13a) { v9_only();  emit_data( op(ldst_op) | rd(d) | op3(stx_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::std(  Register d, Register s1, Register s2) { v9_dep(); assert(d->is_even(), "not even"); emit_long( op(ldst_op) | rd(d) | op3(std_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::std(  Register d, Register s1, Register s2) { v9_dep(); assert(d->is_even(), "not even"); emit_int32( op(ldst_op) | rd(d) | op3(std_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::std(  Register d, Register s1, int simm13a) { v9_dep(); assert(d->is_even(), "not even"); emit_data( op(ldst_op) | rd(d) | op3(std_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
 // v8 p 99
 
-inline void Assembler::stc(    int crd, Register s1, Register s2) { v8_only();  emit_long( op(ldst_op) | fcn(crd) | op3(stc_op3 ) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::stc(    int crd, Register s1, Register s2) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(stc_op3 ) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::stc(    int crd, Register s1, int simm13a) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(stc_op3 ) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::stdc(   int crd, Register s1, Register s2) { v8_only();  emit_long( op(ldst_op) | fcn(crd) | op3(stdc_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::stdc(   int crd, Register s1, Register s2) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(stdc_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::stdc(   int crd, Register s1, int simm13a) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(stdc_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::stcsr(  int crd, Register s1, Register s2) { v8_only();  emit_long( op(ldst_op) | fcn(crd) | op3(stcsr_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::stcsr(  int crd, Register s1, Register s2) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(stcsr_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::stcsr(  int crd, Register s1, int simm13a) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(stcsr_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
-inline void Assembler::stdcq(  int crd, Register s1, Register s2) { v8_only();  emit_long( op(ldst_op) | fcn(crd) | op3(stdcq_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::stdcq(  int crd, Register s1, Register s2) { v8_only();  emit_int32( op(ldst_op) | fcn(crd) | op3(stdcq_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::stdcq(  int crd, Register s1, int simm13a) { v8_only();  emit_data( op(ldst_op) | fcn(crd) | op3(stdcq_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
 // pp 231
 
-inline void Assembler::swap(    Register s1, Register s2, Register d) { v9_dep();  emit_long( op(ldst_op) | rd(d) | op3(swap_op3) | rs1(s1) | rs2(s2) ); }
+inline void Assembler::swap(    Register s1, Register s2, Register d) { v9_dep();  emit_int32( op(ldst_op) | rd(d) | op3(swap_op3) | rs1(s1) | rs2(s2) ); }
 inline void Assembler::swap(    Register s1, int simm13a, Register d) { v9_dep();  emit_data( op(ldst_op) | rd(d) | op3(swap_op3) | rs1(s1) | immed(true) | simm(simm13a, 13)); }
 
 #endif // CPU_SPARC_VM_ASSEMBLER_SPARC_INLINE_HPP
--- a/hotspot/src/cpu/sparc/vm/cppInterpreter_sparc.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/sparc/vm/cppInterpreter_sparc.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -137,7 +137,7 @@
   }
   __ ret();                           // return from interpreter activation
   __ delayed()->restore(I5_savedSP, G0, SP);  // remove interpreter frame
-  NOT_PRODUCT(__ emit_long(0);)       // marker for disassembly
+  NOT_PRODUCT(__ emit_int32(0);)       // marker for disassembly
   return entry;
 }
 
@@ -232,7 +232,7 @@
   }
   __ retl();                          // return from interpreter activation
   __ delayed()->nop();                // schedule this better
-  NOT_PRODUCT(__ emit_long(0);)       // marker for disassembly
+  NOT_PRODUCT(__ emit_int32(0);)       // marker for disassembly
   return entry;
 }
 
@@ -1473,7 +1473,7 @@
     __ brx(Assembler::equal, false, Assembler::pt, skip);         \
     __ delayed()->nop();                                          \
     __ breakpoint_trap();                                         \
-    __ emit_long(marker);                                         \
+    __ emit_int32(marker);                                         \
     __ bind(skip);                                                \
   }
 #else
--- a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1224,7 +1224,7 @@
   // Relocation with special format (see relocInfo_sparc.hpp).
   relocate(rspec, 1);
   // Assembler::sethi(0x3fffff, d);
-  emit_long( op(branch_op) | rd(d) | op2(sethi_op2) | hi22(0x3fffff) );
+  emit_int32( op(branch_op) | rd(d) | op2(sethi_op2) | hi22(0x3fffff) );
   // Don't add relocation for 'add'. Do patching during 'sethi' processing.
   add(d, 0x3ff, d);
 
@@ -1240,7 +1240,7 @@
   // Relocation with special format (see relocInfo_sparc.hpp).
   relocate(rspec, 1);
   // Assembler::sethi(encoded_k, d);
-  emit_long( op(branch_op) | rd(d) | op2(sethi_op2) | hi22(encoded_k) );
+  emit_int32( op(branch_op) | rd(d) | op2(sethi_op2) | hi22(encoded_k) );
   // Don't add relocation for 'add'. Do patching during 'sethi' processing.
   add(d, low10(encoded_k), d);
 
--- a/hotspot/src/cpu/sparc/vm/templateInterpreter_sparc.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/sparc/vm/templateInterpreter_sparc.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -259,7 +259,7 @@
   }
   __ ret();                           // return from interpreter activation
   __ delayed()->restore(I5_savedSP, G0, SP);  // remove interpreter frame
-  NOT_PRODUCT(__ emit_long(0);)       // marker for disassembly
+  NOT_PRODUCT(__ emit_int32(0);)       // marker for disassembly
   return entry;
 }
 
--- a/hotspot/src/cpu/x86/vm/assembler_x86.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/x86/vm/assembler_x86.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -182,7 +182,7 @@
 // make this go away someday
 void Assembler::emit_data(jint data, relocInfo::relocType rtype, int format) {
   if (rtype == relocInfo::none)
-        emit_long(data);
+        emit_int32(data);
   else  emit_data(data, Relocation::spec_simple(rtype), format);
 }
 
@@ -202,7 +202,7 @@
     else
       code_section()->relocate(inst_mark(), rspec, format);
   }
-  emit_long(data);
+  emit_int32(data);
 }
 
 static int encode(Register r) {
@@ -243,7 +243,7 @@
   } else {
     emit_int8(op1);
     emit_int8(op2 | encode(dst));
-    emit_long(imm32);
+    emit_int32(imm32);
   }
 }
 
@@ -254,7 +254,7 @@
   assert((op1 & 0x02) == 0, "sign-extension bit should not be set");
   emit_int8(op1);
   emit_int8(op2 | encode(dst));
-  emit_long(imm32);
+  emit_int32(imm32);
 }
 
 // immediate-to-memory forms
@@ -268,7 +268,7 @@
   } else {
     emit_int8(op1);
     emit_operand(rm, adr, 4);
-    emit_long(imm32);
+    emit_int32(imm32);
   }
 }
 
@@ -976,7 +976,7 @@
   emit_int8(0x1F);
   emit_int8((unsigned char)0x80);
                    // emit_rm(cbuf, 0x2, EAX_enc, EAX_enc);
-  emit_long(0);    // 32-bits offset (4 bytes)
+  emit_int32(0);   // 32-bits offset (4 bytes)
 }
 
 void Assembler::addr_nop_8() {
@@ -987,7 +987,7 @@
   emit_int8((unsigned char)0x84);
                    // emit_rm(cbuf, 0x2, EAX_enc, 0x4);
   emit_int8(0x00); // emit_rm(cbuf, 0x0, EAX_enc, EAX_enc);
-  emit_long(0);    // 32-bits offset (4 bytes)
+  emit_int32(0);   // 32-bits offset (4 bytes)
 }
 
 void Assembler::addsd(XMMRegister dst, XMMRegister src) {
@@ -1076,7 +1076,7 @@
   prefix(dst);
   emit_int8((unsigned char)0x81);
   emit_operand(rsp, dst, 4);
-  emit_long(imm32);
+  emit_int32(imm32);
 }
 
 void Assembler::andl(Register dst, int32_t imm32) {
@@ -1204,7 +1204,7 @@
   prefix(dst);
   emit_int8((unsigned char)0x81);
   emit_operand(rdi, dst, 4);
-  emit_long(imm32);
+  emit_int32(imm32);
 }
 
 void Assembler::cmpl(Register dst, int32_t imm32) {
@@ -1408,7 +1408,7 @@
   } else {
     emit_int8(0x69);
     emit_int8((unsigned char)(0xC0 | encode));
-    emit_long(value);
+    emit_int32(value);
   }
 }
 
@@ -1440,7 +1440,7 @@
              "must be 32bit offset (call4)");
       emit_int8(0x0F);
       emit_int8((unsigned char)(0x80 | cc));
-      emit_long(offs - long_size);
+      emit_int32(offs - long_size);
     }
   } else {
     // Note: could eliminate cond. jumps to this jump if condition
@@ -1450,7 +1450,7 @@
     L.add_patch_at(code(), locator());
     emit_int8(0x0F);
     emit_int8((unsigned char)(0x80 | cc));
-    emit_long(0);
+    emit_int32(0);
   }
 }
 
@@ -1498,7 +1498,7 @@
       emit_int8((offs - short_size) & 0xFF);
     } else {
       emit_int8((unsigned char)0xE9);
-      emit_long(offs - long_size);
+      emit_int32(offs - long_size);
     }
   } else {
     // By default, forward jumps are always 32-bit displacements, since
@@ -1508,7 +1508,7 @@
     InstructionMark im(this);
     L.add_patch_at(code(), locator());
     emit_int8((unsigned char)0xE9);
-    emit_long(0);
+    emit_int32(0);
   }
 }
 
@@ -1732,7 +1732,7 @@
 void Assembler::movl(Register dst, int32_t imm32) {
   int encode = prefix_and_encode(dst->encoding());
   emit_int8((unsigned char)(0xB8 | encode));
-  emit_long(imm32);
+  emit_int32(imm32);
 }
 
 void Assembler::movl(Register dst, Register src) {
@@ -1753,7 +1753,7 @@
   prefix(dst);
   emit_int8((unsigned char)0xC7);
   emit_operand(rax, dst, 4);
-  emit_long(imm32);
+  emit_int32(imm32);
 }
 
 void Assembler::movl(Address dst, Register src) {
@@ -2468,6 +2468,26 @@
   emit_int8((unsigned char)(0xC0 | encode));
 }
 
+void Assembler::vptest(XMMRegister dst, Address src) {
+  assert(VM_Version::supports_avx(), "");
+  InstructionMark im(this);
+  bool vector256 = true;
+  assert(dst != xnoreg, "sanity");
+  int dst_enc = dst->encoding();
+  // swap src<->dst for encoding
+  vex_prefix(src, dst_enc, dst_enc, VEX_SIMD_66, VEX_OPCODE_0F_38, false, vector256);
+  emit_int8(0x17);
+  emit_operand(dst, src);
+}
+
+void Assembler::vptest(XMMRegister dst, XMMRegister src) {
+  assert(VM_Version::supports_avx(), "");
+  bool vector256 = true;
+  int encode = vex_prefix_and_encode(dst, xnoreg, src, VEX_SIMD_66, vector256, VEX_OPCODE_0F_38);
+  emit_int8(0x17);
+  emit_int8((unsigned char)(0xC0 | encode));
+}
+
 void Assembler::punpcklbw(XMMRegister dst, Address src) {
   NOT_LP64(assert(VM_Version::supports_sse2(), ""));
   assert((UseAVX > 0), "SSE mode requires address alignment 16 bytes");
@@ -2499,7 +2519,7 @@
   // in 64bits we push 64bits onto the stack but only
   // take a 32bit immediate
   emit_int8(0x68);
-  emit_long(imm32);
+  emit_int32(imm32);
 }
 
 void Assembler::push(Register src) {
@@ -2544,12 +2564,18 @@
   emit_int8((unsigned char)0xA5);
 }
 
+// sets rcx bytes with rax, value at [edi]
+void Assembler::rep_stosb() {
+  emit_int8((unsigned char)0xF3); // REP
+  LP64_ONLY(prefix(REX_W));
+  emit_int8((unsigned char)0xAA); // STOSB
+}
+
 // sets rcx pointer sized words with rax, value at [edi]
 // generic
-void Assembler::rep_set() { // rep_set
-  emit_int8((unsigned char)0xF3);
-  // STOSQ
-  LP64_ONLY(prefix(REX_W));
+void Assembler::rep_stos() {
+  emit_int8((unsigned char)0xF3); // REP
+  LP64_ONLY(prefix(REX_W));       // LP64:STOSQ, LP32:STOSD
   emit_int8((unsigned char)0xAB);
 }
 
@@ -2785,7 +2811,7 @@
     emit_int8((unsigned char)0xF7);
     emit_int8((unsigned char)(0xC0 | encode));
   }
-  emit_long(imm32);
+  emit_int32(imm32);
 }
 
 void Assembler::testl(Register dst, Register src) {
@@ -3650,6 +3676,15 @@
   emit_int8(0x01);
 }
 
+// duplicate 4-bytes integer data from src into 8 locations in dest
+void Assembler::vpbroadcastd(XMMRegister dst, XMMRegister src) {
+  assert(VM_Version::supports_avx2(), "");
+  bool vector256 = true;
+  int encode = vex_prefix_and_encode(dst, xnoreg, src, VEX_SIMD_66, vector256, VEX_OPCODE_0F_38);
+  emit_int8(0x58);
+  emit_int8((unsigned char)(0xC0 | encode));
+}
+
 void Assembler::vzeroupper() {
   assert(VM_Version::supports_avx(), "");
   (void)vex_prefix_and_encode(xmm0, xmm0, xmm0, VEX_SIMD_NONE);
@@ -4720,7 +4755,7 @@
   prefixq(dst);
   emit_int8((unsigned char)0x81);
   emit_operand(rsp, dst, 4);
-  emit_long(imm32);
+  emit_int32(imm32);
 }
 
 void Assembler::andq(Register dst, int32_t imm32) {
@@ -4793,7 +4828,7 @@
   prefixq(dst);
   emit_int8((unsigned char)0x81);
   emit_operand(rdi, dst, 4);
-  emit_long(imm32);
+  emit_int32(imm32);
 }
 
 void Assembler::cmpq(Register dst, int32_t imm32) {
@@ -4932,7 +4967,7 @@
   } else {
     emit_int8(0x69);
     emit_int8((unsigned char)(0xC0 | encode));
-    emit_long(value);
+    emit_int32(value);
   }
 }
 
@@ -5085,7 +5120,7 @@
   InstructionMark im(this);
   int encode = prefixq_and_encode(dst->encoding());
   emit_int8((unsigned char)(0xC7 | encode));
-  emit_long(imm32);
+  emit_int32(imm32);
 }
 
 void Assembler::movslq(Address dst, int32_t imm32) {
@@ -5094,7 +5129,7 @@
   prefixq(dst);
   emit_int8((unsigned char)0xC7);
   emit_operand(rax, dst, 4);
-  emit_long(imm32);
+  emit_int32(imm32);
 }
 
 void Assembler::movslq(Register dst, Address src) {
@@ -5172,7 +5207,7 @@
   prefixq(dst);
   emit_int8((unsigned char)0x81);
   emit_operand(rcx, dst, 4);
-  emit_long(imm32);
+  emit_int32(imm32);
 }
 
 void Assembler::orq(Register dst, int32_t imm32) {
@@ -5407,7 +5442,7 @@
     emit_int8((unsigned char)0xF7);
     emit_int8((unsigned char)(0xC0 | encode));
   }
-  emit_long(imm32);
+  emit_int32(imm32);
 }
 
 void Assembler::testq(Register dst, Register src) {
--- a/hotspot/src/cpu/x86/vm/assembler_x86.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/x86/vm/assembler_x86.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -832,7 +832,8 @@
 
   // These do register sized moves/scans
   void rep_mov();
-  void rep_set();
+  void rep_stos();
+  void rep_stosb();
   void repne_scan();
 #ifdef _LP64
   void repne_scanl();
@@ -1443,9 +1444,12 @@
   // Shift Right by bytes Logical DoubleQuadword Immediate
   void psrldq(XMMRegister dst, int shift);
 
-  // Logical Compare Double Quadword
+  // Logical Compare 128bit
   void ptest(XMMRegister dst, XMMRegister src);
   void ptest(XMMRegister dst, Address src);
+  // Logical Compare 256bit
+  void vptest(XMMRegister dst, XMMRegister src);
+  void vptest(XMMRegister dst, Address src);
 
   // Interleave Low Bytes
   void punpcklbw(XMMRegister dst, XMMRegister src);
@@ -1753,6 +1757,9 @@
   void vextractf128h(Address dst, XMMRegister src);
   void vextracti128h(Address dst, XMMRegister src);
 
+  // duplicate 4-bytes integer data from src into 8 locations in dest
+  void vpbroadcastd(XMMRegister dst, XMMRegister src);
+
   // AVX instruction which is used to clear upper 128 bits of YMM registers and
   // to avoid transaction penalty between AVX and SSE states. There is no
   // penalty if legacy SSE instructions are encoded using VEX prefix because
--- a/hotspot/src/cpu/x86/vm/globals_x86.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/x86/vm/globals_x86.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -120,6 +120,9 @@
   product(bool, UseUnalignedLoadStores, false,                              \
           "Use SSE2 MOVDQU instruction for Arraycopy")                      \
                                                                             \
+  product(bool, UseFastStosb, false,                                        \
+          "Use fast-string operation for zeroing: rep stosb")               \
+                                                                            \
   /* assembler */                                                           \
   product(bool, Use486InstrsOnly, false,                                    \
           "Use 80486 Compliant instruction subset")                         \
--- a/hotspot/src/cpu/x86/vm/jni_x86.h	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/x86/vm/jni_x86.h	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,14 +38,9 @@
 
   #define JNICALL
   typedef int jint;
-#if defined(_LP64) && !defined(__APPLE__)
+#if defined(_LP64)
   typedef long jlong;
 #else
-  /*
-   * On _LP64 __APPLE__ "long" and "long long" are both 64 bits,
-   * but we use the "long long" typedef to avoid complaints from
-   * the __APPLE__ compiler about fprintf formats.
-   */
   typedef long long jlong;
 #endif
 
--- a/hotspot/src/cpu/x86/vm/macroAssembler_x86.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/x86/vm/macroAssembler_x86.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -2540,7 +2540,7 @@
       // 0000 1111 1000 tttn #32-bit disp
       emit_int8(0x0F);
       emit_int8((unsigned char)(0x80 | cc));
-      emit_long(offs - long_size);
+      emit_int32(offs - long_size);
     }
   } else {
 #ifdef ASSERT
@@ -5224,6 +5224,22 @@
 
 }
 
+void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp) {
+  // cnt - number of qwords (8-byte words).
+  // base - start address, qword aligned.
+  assert(base==rdi, "base register must be edi for rep stos");
+  assert(tmp==rax,   "tmp register must be eax for rep stos");
+  assert(cnt==rcx,   "cnt register must be ecx for rep stos");
+
+  xorptr(tmp, tmp);
+  if (UseFastStosb) {
+    shlptr(cnt,3); // convert to number of bytes
+    rep_stosb();
+  } else {
+    NOT_LP64(shlptr(cnt,1);) // convert to number of dwords for 32-bit VM
+    rep_stos();
+  }
+}
 
 // IndexOf for constant substrings with size >= 8 chars
 // which don't need to be loaded through stack.
@@ -5659,42 +5675,114 @@
   testl(cnt2, cnt2);
   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
 
-  // Load first characters
+  // Compare first characters
   load_unsigned_short(result, Address(str1, 0));
   load_unsigned_short(cnt1, Address(str2, 0));
-
-  // Compare first characters
   subl(result, cnt1);
   jcc(Assembler::notZero,  POP_LABEL);
-  decrementl(cnt2);
-  jcc(Assembler::zero, LENGTH_DIFF_LABEL);
-
-  {
-    // Check after comparing first character to see if strings are equivalent
-    Label LSkip2;
-    // Check if the strings start at same location
-    cmpptr(str1, str2);
-    jccb(Assembler::notEqual, LSkip2);
-
-    // Check if the length difference is zero (from stack)
-    cmpl(Address(rsp, 0), 0x0);
-    jcc(Assembler::equal,  LENGTH_DIFF_LABEL);
-
-    // Strings might not be equivalent
-    bind(LSkip2);
-  }
+  cmpl(cnt2, 1);
+  jcc(Assembler::equal, LENGTH_DIFF_LABEL);
+
+  // Check if the strings start at the same location.
+  cmpptr(str1, str2);
+  jcc(Assembler::equal, LENGTH_DIFF_LABEL);
 
   Address::ScaleFactor scale = Address::times_2;
   int stride = 8;
 
-  // Advance to next element
-  addptr(str1, 16/stride);
-  addptr(str2, 16/stride);
-
-  if (UseSSE42Intrinsics) {
+  if (UseAVX >= 2) {
+    Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
+    Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
+    Label COMPARE_TAIL_LONG;
+    int pcmpmask = 0x19;
+
+    // Setup to compare 16-chars (32-bytes) vectors,
+    // start from first character again because it has aligned address.
+    int stride2 = 16;
+    int adr_stride  = stride  << scale;
+    int adr_stride2 = stride2 << scale;
+
+    assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
+    // rax and rdx are used by pcmpestri as elements counters
+    movl(result, cnt2);
+    andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
+    jcc(Assembler::zero, COMPARE_TAIL_LONG);
+
+    // fast path : compare first 2 8-char vectors.
+    bind(COMPARE_16_CHARS);
+    movdqu(vec1, Address(str1, 0));
+    pcmpestri(vec1, Address(str2, 0), pcmpmask);
+    jccb(Assembler::below, COMPARE_INDEX_CHAR);
+
+    movdqu(vec1, Address(str1, adr_stride));
+    pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
+    jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
+    addl(cnt1, stride);
+
+    // Compare the characters at index in cnt1
+    bind(COMPARE_INDEX_CHAR); //cnt1 has the offset of the mismatching character
+    load_unsigned_short(result, Address(str1, cnt1, scale));
+    load_unsigned_short(cnt2, Address(str2, cnt1, scale));
+    subl(result, cnt2);
+    jmp(POP_LABEL);
+
+    // Setup the registers to start vector comparison loop
+    bind(COMPARE_WIDE_VECTORS);
+    lea(str1, Address(str1, result, scale));
+    lea(str2, Address(str2, result, scale));
+    subl(result, stride2);
+    subl(cnt2, stride2);
+    jccb(Assembler::zero, COMPARE_WIDE_TAIL);
+    negptr(result);
+
+    //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
+    bind(COMPARE_WIDE_VECTORS_LOOP);
+    vmovdqu(vec1, Address(str1, result, scale));
+    vpxor(vec1, Address(str2, result, scale));
+    vptest(vec1, vec1);
+    jccb(Assembler::notZero, VECTOR_NOT_EQUAL);
+    addptr(result, stride2);
+    subl(cnt2, stride2);
+    jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
+
+    // compare wide vectors tail
+    bind(COMPARE_WIDE_TAIL);
+    testptr(result, result);
+    jccb(Assembler::zero, LENGTH_DIFF_LABEL);
+
+    movl(result, stride2);
+    movl(cnt2, result);
+    negptr(result);
+    jmpb(COMPARE_WIDE_VECTORS_LOOP);
+
+    // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
+    bind(VECTOR_NOT_EQUAL);
+    lea(str1, Address(str1, result, scale));
+    lea(str2, Address(str2, result, scale));
+    jmp(COMPARE_16_CHARS);
+
+    // Compare tail chars, length between 1 to 15 chars
+    bind(COMPARE_TAIL_LONG);
+    movl(cnt2, result);
+    cmpl(cnt2, stride);
+    jccb(Assembler::less, COMPARE_SMALL_STR);
+
+    movdqu(vec1, Address(str1, 0));
+    pcmpestri(vec1, Address(str2, 0), pcmpmask);
+    jcc(Assembler::below, COMPARE_INDEX_CHAR);
+    subptr(cnt2, stride);
+    jccb(Assembler::zero, LENGTH_DIFF_LABEL);
+    lea(str1, Address(str1, result, scale));
+    lea(str2, Address(str2, result, scale));
+    negptr(cnt2);
+    jmpb(WHILE_HEAD_LABEL);
+
+    bind(COMPARE_SMALL_STR);
+  } else if (UseSSE42Intrinsics) {
     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
     int pcmpmask = 0x19;
-    // Setup to compare 16-byte vectors
+    // Setup to compare 8-char (16-byte) vectors,
+    // start from first character again because it has aligned address.
     movl(result, cnt2);
     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
     jccb(Assembler::zero, COMPARE_TAIL);
@@ -5726,7 +5814,7 @@
     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
 
     // compare wide vectors tail
-    testl(result, result);
+    testptr(result, result);
     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
 
     movl(cnt2, stride);
@@ -5738,21 +5826,20 @@
 
     // Mismatched characters in the vectors
     bind(VECTOR_NOT_EQUAL);
-    addptr(result, cnt1);
-    movptr(cnt2, result);
-    load_unsigned_short(result, Address(str1, cnt2, scale));
-    load_unsigned_short(cnt1, Address(str2, cnt2, scale));
-    subl(result, cnt1);
+    addptr(cnt1, result);
+    load_unsigned_short(result, Address(str1, cnt1, scale));
+    load_unsigned_short(cnt2, Address(str2, cnt1, scale));
+    subl(result, cnt2);
     jmpb(POP_LABEL);
 
     bind(COMPARE_TAIL); // limit is zero
     movl(cnt2, result);
     // Fallthru to tail compare
   }
-
   // Shift str2 and str1 to the end of the arrays, negate min
-  lea(str1, Address(str1, cnt2, scale, 0));
-  lea(str2, Address(str2, cnt2, scale, 0));
+  lea(str1, Address(str1, cnt2, scale));
+  lea(str2, Address(str2, cnt2, scale));
+  decrementl(cnt2);  // first character was compared already
   negptr(cnt2);
 
   // Compare the rest of the elements
@@ -5817,7 +5904,44 @@
   shll(limit, 1);      // byte count != 0
   movl(result, limit); // copy
 
-  if (UseSSE42Intrinsics) {
+  if (UseAVX >= 2) {
+    // With AVX2, use 32-byte vector compare
+    Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
+
+    // Compare 32-byte vectors
+    andl(result, 0x0000001e);  //   tail count (in bytes)
+    andl(limit, 0xffffffe0);   // vector count (in bytes)
+    jccb(Assembler::zero, COMPARE_TAIL);
+
+    lea(ary1, Address(ary1, limit, Address::times_1));
+    lea(ary2, Address(ary2, limit, Address::times_1));
+    negptr(limit);
+
+    bind(COMPARE_WIDE_VECTORS);
+    vmovdqu(vec1, Address(ary1, limit, Address::times_1));
+    vmovdqu(vec2, Address(ary2, limit, Address::times_1));
+    vpxor(vec1, vec2);
+
+    vptest(vec1, vec1);
+    jccb(Assembler::notZero, FALSE_LABEL);
+    addptr(limit, 32);
+    jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
+
+    testl(result, result);
+    jccb(Assembler::zero, TRUE_LABEL);
+
+    vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
+    vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
+    vpxor(vec1, vec2);
+
+    vptest(vec1, vec1);
+    jccb(Assembler::notZero, FALSE_LABEL);
+    jmpb(TRUE_LABEL);
+
+    bind(COMPARE_TAIL); // limit is zero
+    movl(limit, result);
+    // Fallthru to tail compare
+  } else if (UseSSE42Intrinsics) {
     // With SSE4.2, use double quad vector compare
     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
 
@@ -5995,29 +6119,53 @@
     {
       assert( UseSSE >= 2, "supported cpu only" );
       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
-      // Fill 32-byte chunks
       movdl(xtmp, value);
-      pshufd(xtmp, xtmp, 0);
-
-      subl(count, 8 << shift);
-      jcc(Assembler::less, L_check_fill_8_bytes);
-      align(16);
-
-      BIND(L_fill_32_bytes_loop);
-
-      if (UseUnalignedLoadStores) {
-        movdqu(Address(to, 0), xtmp);
-        movdqu(Address(to, 16), xtmp);
+      if (UseAVX >= 2 && UseUnalignedLoadStores) {
+        // Fill 64-byte chunks
+        Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
+        vpbroadcastd(xtmp, xtmp);
+
+        subl(count, 16 << shift);
+        jcc(Assembler::less, L_check_fill_32_bytes);
+        align(16);
+
+        BIND(L_fill_64_bytes_loop);
+        vmovdqu(Address(to, 0), xtmp);
+        vmovdqu(Address(to, 32), xtmp);
+        addptr(to, 64);
+        subl(count, 16 << shift);
+        jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
+
+        BIND(L_check_fill_32_bytes);
+        addl(count, 8 << shift);
+        jccb(Assembler::less, L_check_fill_8_bytes);
+        vmovdqu(Address(to, 0), xtmp);
+        addptr(to, 32);
+        subl(count, 8 << shift);
       } else {
-        movq(Address(to, 0), xtmp);
-        movq(Address(to, 8), xtmp);
-        movq(Address(to, 16), xtmp);
-        movq(Address(to, 24), xtmp);
+        // Fill 32-byte chunks
+        pshufd(xtmp, xtmp, 0);
+
+        subl(count, 8 << shift);
+        jcc(Assembler::less, L_check_fill_8_bytes);
+        align(16);
+
+        BIND(L_fill_32_bytes_loop);
+
+        if (UseUnalignedLoadStores) {
+          movdqu(Address(to, 0), xtmp);
+          movdqu(Address(to, 16), xtmp);
+        } else {
+          movq(Address(to, 0), xtmp);
+          movq(Address(to, 8), xtmp);
+          movq(Address(to, 16), xtmp);
+          movq(Address(to, 24), xtmp);
+        }
+
+        addptr(to, 32);
+        subl(count, 8 << shift);
+        jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
       }
-
-      addptr(to, 32);
-      subl(count, 8 << shift);
-      jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
       BIND(L_check_fill_8_bytes);
       addl(count, 8 << shift);
       jccb(Assembler::zero, L_exit);
--- a/hotspot/src/cpu/x86/vm/macroAssembler_x86.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/x86/vm/macroAssembler_x86.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1011,6 +1011,10 @@
       Assembler::vxorpd(dst, nds, src, vector256);
   }
 
+  // Simple version for AVX2 256bit vectors
+  void vpxor(XMMRegister dst, XMMRegister src) { Assembler::vpxor(dst, dst, src, true); }
+  void vpxor(XMMRegister dst, Address src) { Assembler::vpxor(dst, dst, src, true); }
+
   // Move packed integer values from low 128 bit to hign 128 bit in 256 bit vector.
   void vinserti128h(XMMRegister dst, XMMRegister nds, XMMRegister src) {
     if (UseAVX > 1) // vinserti128h is available only in AVX2
@@ -1096,6 +1100,9 @@
   // C2 compiled method's prolog code.
   void verified_entry(int framesize, bool stack_bang, bool fp_mode_24b);
 
+  // clear memory of size 'cnt' qwords, starting at 'base'.
+  void clear_mem(Register base, Register cnt, Register rtmp);
+
   // IndexOf strings.
   // Small strings are loaded through stack if they cross page boundary.
   void string_indexof(Register str1, Register str2,
--- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -796,16 +796,22 @@
     __ align(OptoLoopAlignment);
   __ BIND(L_copy_64_bytes_loop);
 
-    if(UseUnalignedLoadStores) {
-      __ movdqu(xmm0, Address(from, 0));
-      __ movdqu(Address(from, to_from, Address::times_1, 0), xmm0);
-      __ movdqu(xmm1, Address(from, 16));
-      __ movdqu(Address(from, to_from, Address::times_1, 16), xmm1);
-      __ movdqu(xmm2, Address(from, 32));
-      __ movdqu(Address(from, to_from, Address::times_1, 32), xmm2);
-      __ movdqu(xmm3, Address(from, 48));
-      __ movdqu(Address(from, to_from, Address::times_1, 48), xmm3);
-
+    if (UseUnalignedLoadStores) {
+      if (UseAVX >= 2) {
+        __ vmovdqu(xmm0, Address(from,  0));
+        __ vmovdqu(Address(from, to_from, Address::times_1,  0), xmm0);
+        __ vmovdqu(xmm1, Address(from, 32));
+        __ vmovdqu(Address(from, to_from, Address::times_1, 32), xmm1);
+      } else {
+        __ movdqu(xmm0, Address(from, 0));
+        __ movdqu(Address(from, to_from, Address::times_1, 0), xmm0);
+        __ movdqu(xmm1, Address(from, 16));
+        __ movdqu(Address(from, to_from, Address::times_1, 16), xmm1);
+        __ movdqu(xmm2, Address(from, 32));
+        __ movdqu(Address(from, to_from, Address::times_1, 32), xmm2);
+        __ movdqu(xmm3, Address(from, 48));
+        __ movdqu(Address(from, to_from, Address::times_1, 48), xmm3);
+      }
     } else {
       __ movq(xmm0, Address(from, 0));
       __ movq(Address(from, to_from, Address::times_1, 0), xmm0);
--- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1286,23 +1286,54 @@
   //   end_to       - destination array end address
   //   qword_count  - 64-bits element count, negative
   //   to           - scratch
-  //   L_copy_32_bytes - entry label
+  //   L_copy_bytes - entry label
   //   L_copy_8_bytes  - exit  label
   //
-  void copy_32_bytes_forward(Register end_from, Register end_to,
+  void copy_bytes_forward(Register end_from, Register end_to,
                              Register qword_count, Register to,
-                             Label& L_copy_32_bytes, Label& L_copy_8_bytes) {
+                             Label& L_copy_bytes, Label& L_copy_8_bytes) {
     DEBUG_ONLY(__ stop("enter at entry label, not here"));
     Label L_loop;
     __ align(OptoLoopAlignment);
-  __ BIND(L_loop);
-    if(UseUnalignedLoadStores) {
-      __ movdqu(xmm0, Address(end_from, qword_count, Address::times_8, -24));
-      __ movdqu(Address(end_to, qword_count, Address::times_8, -24), xmm0);
-      __ movdqu(xmm1, Address(end_from, qword_count, Address::times_8, - 8));
-      __ movdqu(Address(end_to, qword_count, Address::times_8, - 8), xmm1);
-
+    if (UseUnalignedLoadStores) {
+      Label L_end;
+      // Copy 64-bytes per iteration
+      __ BIND(L_loop);
+      if (UseAVX >= 2) {
+        __ vmovdqu(xmm0, Address(end_from, qword_count, Address::times_8, -56));
+        __ vmovdqu(Address(end_to, qword_count, Address::times_8, -56), xmm0);
+        __ vmovdqu(xmm1, Address(end_from, qword_count, Address::times_8, -24));
+        __ vmovdqu(Address(end_to, qword_count, Address::times_8, -24), xmm1);
+      } else {
+        __ movdqu(xmm0, Address(end_from, qword_count, Address::times_8, -56));
+        __ movdqu(Address(end_to, qword_count, Address::times_8, -56), xmm0);
+        __ movdqu(xmm1, Address(end_from, qword_count, Address::times_8, -40));
+        __ movdqu(Address(end_to, qword_count, Address::times_8, -40), xmm1);
+        __ movdqu(xmm2, Address(end_from, qword_count, Address::times_8, -24));
+        __ movdqu(Address(end_to, qword_count, Address::times_8, -24), xmm2);
+        __ movdqu(xmm3, Address(end_from, qword_count, Address::times_8, - 8));
+        __ movdqu(Address(end_to, qword_count, Address::times_8, - 8), xmm3);
+      }
+      __ BIND(L_copy_bytes);
+      __ addptr(qword_count, 8);
+      __ jcc(Assembler::lessEqual, L_loop);
+      __ subptr(qword_count, 4);  // sub(8) and add(4)
+      __ jccb(Assembler::greater, L_end);
+      // Copy trailing 32 bytes
+      if (UseAVX >= 2) {
+        __ vmovdqu(xmm0, Address(end_from, qword_count, Address::times_8, -24));
+        __ vmovdqu(Address(end_to, qword_count, Address::times_8, -24), xmm0);
+      } else {
+        __ movdqu(xmm0, Address(end_from, qword_count, Address::times_8, -24));
+        __ movdqu(Address(end_to, qword_count, Address::times_8, -24), xmm0);
+        __ movdqu(xmm1, Address(end_from, qword_count, Address::times_8, - 8));
+        __ movdqu(Address(end_to, qword_count, Address::times_8, - 8), xmm1);
+      }
+      __ addptr(qword_count, 4);
+      __ BIND(L_end);
     } else {
+      // Copy 32-bytes per iteration
+      __ BIND(L_loop);
       __ movq(to, Address(end_from, qword_count, Address::times_8, -24));
       __ movq(Address(end_to, qword_count, Address::times_8, -24), to);
       __ movq(to, Address(end_from, qword_count, Address::times_8, -16));
@@ -1311,15 +1342,15 @@
       __ movq(Address(end_to, qword_count, Address::times_8, - 8), to);
       __ movq(to, Address(end_from, qword_count, Address::times_8, - 0));
       __ movq(Address(end_to, qword_count, Address::times_8, - 0), to);
+
+      __ BIND(L_copy_bytes);
+      __ addptr(qword_count, 4);
+      __ jcc(Assembler::lessEqual, L_loop);
     }
-  __ BIND(L_copy_32_bytes);
-    __ addptr(qword_count, 4);
-    __ jcc(Assembler::lessEqual, L_loop);
     __ subptr(qword_count, 4);
     __ jcc(Assembler::less, L_copy_8_bytes); // Copy trailing qwords
   }
 
-
   // Copy big chunks backward
   //
   // Inputs:
@@ -1327,23 +1358,55 @@
   //   dest         - destination array address
   //   qword_count  - 64-bits element count
   //   to           - scratch
-  //   L_copy_32_bytes - entry label
+  //   L_copy_bytes - entry label
   //   L_copy_8_bytes  - exit  label
   //
-  void copy_32_bytes_backward(Register from, Register dest,
+  void copy_bytes_backward(Register from, Register dest,
                               Register qword_count, Register to,
-                              Label& L_copy_32_bytes, Label& L_copy_8_bytes) {
+                              Label& L_copy_bytes, Label& L_copy_8_bytes) {
     DEBUG_ONLY(__ stop("enter at entry label, not here"));
     Label L_loop;
     __ align(OptoLoopAlignment);
-  __ BIND(L_loop);
-    if(UseUnalignedLoadStores) {
-      __ movdqu(xmm0, Address(from, qword_count, Address::times_8, 16));
-      __ movdqu(Address(dest, qword_count, Address::times_8, 16), xmm0);
-      __ movdqu(xmm1, Address(from, qword_count, Address::times_8,  0));
-      __ movdqu(Address(dest, qword_count, Address::times_8,  0), xmm1);
-
+    if (UseUnalignedLoadStores) {
+      Label L_end;
+      // Copy 64-bytes per iteration
+      __ BIND(L_loop);
+      if (UseAVX >= 2) {
+        __ vmovdqu(xmm0, Address(from, qword_count, Address::times_8, 32));
+        __ vmovdqu(Address(dest, qword_count, Address::times_8, 32), xmm0);
+        __ vmovdqu(xmm1, Address(from, qword_count, Address::times_8,  0));
+        __ vmovdqu(Address(dest, qword_count, Address::times_8,  0), xmm1);
+      } else {
+        __ movdqu(xmm0, Address(from, qword_count, Address::times_8, 48));
+        __ movdqu(Address(dest, qword_count, Address::times_8, 48), xmm0);
+        __ movdqu(xmm1, Address(from, qword_count, Address::times_8, 32));
+        __ movdqu(Address(dest, qword_count, Address::times_8, 32), xmm1);
+        __ movdqu(xmm2, Address(from, qword_count, Address::times_8, 16));
+        __ movdqu(Address(dest, qword_count, Address::times_8, 16), xmm2);
+        __ movdqu(xmm3, Address(from, qword_count, Address::times_8,  0));
+        __ movdqu(Address(dest, qword_count, Address::times_8,  0), xmm3);
+      }
+      __ BIND(L_copy_bytes);
+      __ subptr(qword_count, 8);
+      __ jcc(Assembler::greaterEqual, L_loop);
+
+      __ addptr(qword_count, 4);  // add(8) and sub(4)
+      __ jccb(Assembler::less, L_end);
+      // Copy trailing 32 bytes
+      if (UseAVX >= 2) {
+        __ vmovdqu(xmm0, Address(from, qword_count, Address::times_8, 0));
+        __ vmovdqu(Address(dest, qword_count, Address::times_8, 0), xmm0);
+      } else {
+        __ movdqu(xmm0, Address(from, qword_count, Address::times_8, 16));
+        __ movdqu(Address(dest, qword_count, Address::times_8, 16), xmm0);
+        __ movdqu(xmm1, Address(from, qword_count, Address::times_8,  0));
+        __ movdqu(Address(dest, qword_count, Address::times_8,  0), xmm1);
+      }
+      __ subptr(qword_count, 4);
+      __ BIND(L_end);
     } else {
+      // Copy 32-bytes per iteration
+      __ BIND(L_loop);
       __ movq(to, Address(from, qword_count, Address::times_8, 24));
       __ movq(Address(dest, qword_count, Address::times_8, 24), to);
       __ movq(to, Address(from, qword_count, Address::times_8, 16));
@@ -1352,10 +1415,11 @@
       __ movq(Address(dest, qword_count, Address::times_8,  8), to);
       __ movq(to, Address(from, qword_count, Address::times_8,  0));
       __ movq(Address(dest, qword_count, Address::times_8,  0), to);
+
+      __ BIND(L_copy_bytes);
+      __ subptr(qword_count, 4);
+      __ jcc(Assembler::greaterEqual, L_loop);
     }
-  __ BIND(L_copy_32_bytes);
-    __ subptr(qword_count, 4);
-    __ jcc(Assembler::greaterEqual, L_loop);
     __ addptr(qword_count, 4);
     __ jcc(Assembler::greater, L_copy_8_bytes); // Copy trailing qwords
   }
@@ -1385,7 +1449,7 @@
     StubCodeMark mark(this, "StubRoutines", name);
     address start = __ pc();
 
-    Label L_copy_32_bytes, L_copy_8_bytes, L_copy_4_bytes, L_copy_2_bytes;
+    Label L_copy_bytes, L_copy_8_bytes, L_copy_4_bytes, L_copy_2_bytes;
     Label L_copy_byte, L_exit;
     const Register from        = rdi;  // source array address
     const Register to          = rsi;  // destination array address
@@ -1417,7 +1481,7 @@
     __ lea(end_from, Address(from, qword_count, Address::times_8, -8));
     __ lea(end_to,   Address(to,   qword_count, Address::times_8, -8));
     __ negptr(qword_count); // make the count negative
-    __ jmp(L_copy_32_bytes);
+    __ jmp(L_copy_bytes);
 
     // Copy trailing qwords
   __ BIND(L_copy_8_bytes);
@@ -1460,8 +1524,8 @@
     __ leave(); // required for proper stackwalking of RuntimeStub frame
     __ ret(0);
 
-    // Copy in 32-bytes chunks
-    copy_32_bytes_forward(end_from, end_to, qword_count, rax, L_copy_32_bytes, L_copy_8_bytes);
+    // Copy in multi-bytes chunks
+    copy_bytes_forward(end_from, end_to, qword_count, rax, L_copy_bytes, L_copy_8_bytes);
     __ jmp(L_copy_4_bytes);
 
     return start;
@@ -1488,7 +1552,7 @@
     StubCodeMark mark(this, "StubRoutines", name);
     address start = __ pc();
 
-    Label L_copy_32_bytes, L_copy_8_bytes, L_copy_4_bytes, L_copy_2_bytes;
+    Label L_copy_bytes, L_copy_8_bytes, L_copy_4_bytes, L_copy_2_bytes;
     const Register from        = rdi;  // source array address
     const Register to          = rsi;  // destination array address
     const Register count       = rdx;  // elements count
@@ -1531,10 +1595,10 @@
     // Check for and copy trailing dword
   __ BIND(L_copy_4_bytes);
     __ testl(byte_count, 4);
-    __ jcc(Assembler::zero, L_copy_32_bytes);
+    __ jcc(Assembler::zero, L_copy_bytes);
     __ movl(rax, Address(from, qword_count, Address::times_8));
     __ movl(Address(to, qword_count, Address::times_8), rax);
-    __ jmp(L_copy_32_bytes);
+    __ jmp(L_copy_bytes);
 
     // Copy trailing qwords
   __ BIND(L_copy_8_bytes);
@@ -1549,8 +1613,8 @@
     __ leave(); // required for proper stackwalking of RuntimeStub frame
     __ ret(0);
 
-    // Copy in 32-bytes chunks
-    copy_32_bytes_backward(from, to, qword_count, rax, L_copy_32_bytes, L_copy_8_bytes);
+    // Copy in multi-bytes chunks
+    copy_bytes_backward(from, to, qword_count, rax, L_copy_bytes, L_copy_8_bytes);
 
     restore_arg_regs();
     inc_counter_np(SharedRuntime::_jbyte_array_copy_ctr); // Update counter after rscratch1 is free
@@ -1585,7 +1649,7 @@
     StubCodeMark mark(this, "StubRoutines", name);
     address start = __ pc();
 
-    Label L_copy_32_bytes, L_copy_8_bytes, L_copy_4_bytes,L_copy_2_bytes,L_exit;
+    Label L_copy_bytes, L_copy_8_bytes, L_copy_4_bytes,L_copy_2_bytes,L_exit;
     const Register from        = rdi;  // source array address
     const Register to          = rsi;  // destination array address
     const Register count       = rdx;  // elements count
@@ -1616,7 +1680,7 @@
     __ lea(end_from, Address(from, qword_count, Address::times_8, -8));
     __ lea(end_to,   Address(to,   qword_count, Address::times_8, -8));
     __ negptr(qword_count);
-    __ jmp(L_copy_32_bytes);
+    __ jmp(L_copy_bytes);
 
     // Copy trailing qwords
   __ BIND(L_copy_8_bytes);
@@ -1652,8 +1716,8 @@
     __ leave(); // required for proper stackwalking of RuntimeStub frame
     __ ret(0);
 
-    // Copy in 32-bytes chunks
-    copy_32_bytes_forward(end_from, end_to, qword_count, rax, L_copy_32_bytes, L_copy_8_bytes);
+    // Copy in multi-bytes chunks
+    copy_bytes_forward(end_from, end_to, qword_count, rax, L_copy_bytes, L_copy_8_bytes);
     __ jmp(L_copy_4_bytes);
 
     return start;
@@ -1700,7 +1764,7 @@
     StubCodeMark mark(this, "StubRoutines", name);
     address start = __ pc();
 
-    Label L_copy_32_bytes, L_copy_8_bytes, L_copy_4_bytes;
+    Label L_copy_bytes, L_copy_8_bytes, L_copy_4_bytes;
     const Register from        = rdi;  // source array address
     const Register to          = rsi;  // destination array address
     const Register count       = rdx;  // elements count
@@ -1735,10 +1799,10 @@
     // Check for and copy trailing dword
   __ BIND(L_copy_4_bytes);
     __ testl(word_count, 2);
-    __ jcc(Assembler::zero, L_copy_32_bytes);
+    __ jcc(Assembler::zero, L_copy_bytes);
     __ movl(rax, Address(from, qword_count, Address::times_8));
     __ movl(Address(to, qword_count, Address::times_8), rax);
-    __ jmp(L_copy_32_bytes);
+    __ jmp(L_copy_bytes);
 
     // Copy trailing qwords
   __ BIND(L_copy_8_bytes);
@@ -1753,8 +1817,8 @@
     __ leave(); // required for proper stackwalking of RuntimeStub frame
     __ ret(0);
 
-    // Copy in 32-bytes chunks
-    copy_32_bytes_backward(from, to, qword_count, rax, L_copy_32_bytes, L_copy_8_bytes);
+    // Copy in multi-bytes chunks
+    copy_bytes_backward(from, to, qword_count, rax, L_copy_bytes, L_copy_8_bytes);
 
     restore_arg_regs();
     inc_counter_np(SharedRuntime::_jshort_array_copy_ctr); // Update counter after rscratch1 is free
@@ -1790,7 +1854,7 @@
     StubCodeMark mark(this, "StubRoutines", name);
     address start = __ pc();
 
-    Label L_copy_32_bytes, L_copy_8_bytes, L_copy_4_bytes, L_exit;
+    Label L_copy_bytes, L_copy_8_bytes, L_copy_4_bytes, L_exit;
     const Register from        = rdi;  // source array address
     const Register to          = rsi;  // destination array address
     const Register count       = rdx;  // elements count
@@ -1826,7 +1890,7 @@
     __ lea(end_from, Address(from, qword_count, Address::times_8, -8));
     __ lea(end_to,   Address(to,   qword_count, Address::times_8, -8));
     __ negptr(qword_count);
-    __ jmp(L_copy_32_bytes);
+    __ jmp(L_copy_bytes);
 
     // Copy trailing qwords
   __ BIND(L_copy_8_bytes);
@@ -1853,8 +1917,8 @@
     __ leave(); // required for proper stackwalking of RuntimeStub frame
     __ ret(0);
 
-    // Copy 32-bytes chunks
-    copy_32_bytes_forward(end_from, end_to, qword_count, rax, L_copy_32_bytes, L_copy_8_bytes);
+    // Copy in multi-bytes chunks
+    copy_bytes_forward(end_from, end_to, qword_count, rax, L_copy_bytes, L_copy_8_bytes);
     __ jmp(L_copy_4_bytes);
 
     return start;
@@ -1882,7 +1946,7 @@
     StubCodeMark mark(this, "StubRoutines", name);
     address start = __ pc();
 
-    Label L_copy_32_bytes, L_copy_8_bytes, L_copy_2_bytes, L_exit;
+    Label L_copy_bytes, L_copy_8_bytes, L_copy_2_bytes, L_exit;
     const Register from        = rdi;  // source array address
     const Register to          = rsi;  // destination array address
     const Register count       = rdx;  // elements count
@@ -1916,10 +1980,10 @@
 
     // Check for and copy trailing dword
     __ testl(dword_count, 1);
-    __ jcc(Assembler::zero, L_copy_32_bytes);
+    __ jcc(Assembler::zero, L_copy_bytes);
     __ movl(rax, Address(from, dword_count, Address::times_4, -4));
     __ movl(Address(to, dword_count, Address::times_4, -4), rax);
-    __ jmp(L_copy_32_bytes);
+    __ jmp(L_copy_bytes);
 
     // Copy trailing qwords
   __ BIND(L_copy_8_bytes);
@@ -1937,8 +2001,8 @@
     __ leave(); // required for proper stackwalking of RuntimeStub frame
     __ ret(0);
 
-    // Copy in 32-bytes chunks
-    copy_32_bytes_backward(from, to, qword_count, rax, L_copy_32_bytes, L_copy_8_bytes);
+    // Copy in multi-bytes chunks
+    copy_bytes_backward(from, to, qword_count, rax, L_copy_bytes, L_copy_8_bytes);
 
    __ bind(L_exit);
      if (is_oop) {
@@ -1976,7 +2040,7 @@
     StubCodeMark mark(this, "StubRoutines", name);
     address start = __ pc();
 
-    Label L_copy_32_bytes, L_copy_8_bytes, L_exit;
+    Label L_copy_bytes, L_copy_8_bytes, L_exit;
     const Register from        = rdi;  // source array address
     const Register to          = rsi;  // destination array address
     const Register qword_count = rdx;  // elements count
@@ -2008,7 +2072,7 @@
     __ lea(end_from, Address(from, qword_count, Address::times_8, -8));
     __ lea(end_to,   Address(to,   qword_count, Address::times_8, -8));
     __ negptr(qword_count);
-    __ jmp(L_copy_32_bytes);
+    __ jmp(L_copy_bytes);
 
     // Copy trailing qwords
   __ BIND(L_copy_8_bytes);
@@ -2027,8 +2091,8 @@
       __ ret(0);
     }
 
-    // Copy 64-byte chunks
-    copy_32_bytes_forward(end_from, end_to, qword_count, rax, L_copy_32_bytes, L_copy_8_bytes);
+    // Copy in multi-bytes chunks
+    copy_bytes_forward(end_from, end_to, qword_count, rax, L_copy_bytes, L_copy_8_bytes);
 
     if (is_oop) {
     __ BIND(L_exit);
@@ -2065,7 +2129,7 @@
     StubCodeMark mark(this, "StubRoutines", name);
     address start = __ pc();
 
-    Label L_copy_32_bytes, L_copy_8_bytes, L_exit;
+    Label L_copy_bytes, L_copy_8_bytes, L_exit;
     const Register from        = rdi;  // source array address
     const Register to          = rsi;  // destination array address
     const Register qword_count = rdx;  // elements count
@@ -2091,7 +2155,7 @@
       gen_write_ref_array_pre_barrier(to, saved_count, dest_uninitialized);
     }
 
-    __ jmp(L_copy_32_bytes);
+    __ jmp(L_copy_bytes);
 
     // Copy trailing qwords
   __ BIND(L_copy_8_bytes);
@@ -2110,8 +2174,8 @@
       __ ret(0);
     }
 
-    // Copy in 32-bytes chunks
-    copy_32_bytes_backward(from, to, qword_count, rax, L_copy_32_bytes, L_copy_8_bytes);
+    // Copy in multi-bytes chunks
+    copy_bytes_backward(from, to, qword_count, rax, L_copy_bytes, L_copy_8_bytes);
 
     if (is_oop) {
     __ BIND(L_exit);
--- a/hotspot/src/cpu/x86/vm/vm_version_x86.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/x86/vm/vm_version_x86.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -429,7 +429,7 @@
   }
 
   char buf[256];
-  jio_snprintf(buf, sizeof(buf), "(%u cores per cpu, %u threads per core) family %d model %d stepping %d%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
+  jio_snprintf(buf, sizeof(buf), "(%u cores per cpu, %u threads per core) family %d model %d stepping %d%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
                cores_per_cpu(), threads_per_core(),
                cpu_family(), _model, _stepping,
                (supports_cmov() ? ", cmov" : ""),
@@ -446,6 +446,7 @@
                (supports_avx()    ? ", avx" : ""),
                (supports_avx2()   ? ", avx2" : ""),
                (supports_aes()    ? ", aes" : ""),
+               (supports_erms()   ? ", erms" : ""),
                (supports_mmx_ext() ? ", mmxext" : ""),
                (supports_3dnow_prefetch() ? ", 3dnowpref" : ""),
                (supports_lzcnt()   ? ", lzcnt": ""),
@@ -671,6 +672,16 @@
     FLAG_SET_DEFAULT(UsePopCountInstruction, false);
   }
 
+  // Use fast-string operations if available.
+  if (supports_erms()) {
+    if (FLAG_IS_DEFAULT(UseFastStosb)) {
+      UseFastStosb = true;
+    }
+  } else if (UseFastStosb) {
+    warning("fast-string operations are not available on this CPU");
+    FLAG_SET_DEFAULT(UseFastStosb, false);
+  }
+
 #ifdef COMPILER2
   if (FLAG_IS_DEFAULT(AlignVector)) {
     // Modern processors allow misaligned memory operations for vectors.
--- a/hotspot/src/cpu/x86/vm/vm_version_x86.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/x86/vm/vm_version_x86.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -204,7 +204,8 @@
                    avx2 : 1,
                         : 2,
                    bmi2 : 1,
-                        : 23;
+                   erms : 1,
+                        : 22;
     } bits;
   };
 
@@ -247,7 +248,8 @@
     CPU_TSCINV = (1 << 16),
     CPU_AVX    = (1 << 17),
     CPU_AVX2   = (1 << 18),
-    CPU_AES    = (1 << 19)
+    CPU_AES    = (1 << 19),
+    CPU_ERMS   = (1 << 20) // enhanced 'rep movsb/stosb' instructions
   } cpuFeatureFlags;
 
   enum {
@@ -425,6 +427,8 @@
       result |= CPU_TSCINV;
     if (_cpuid_info.std_cpuid1_ecx.bits.aes != 0)
       result |= CPU_AES;
+    if (_cpuid_info.sef_cpuid7_ebx.bits.erms != 0)
+      result |= CPU_ERMS;
 
     // AMD features.
     if (is_amd()) {
@@ -489,7 +493,7 @@
     return (_cpuid_info.std_max_function >= 0xB) &&
            // eax[4:0] | ebx[0:15] == 0 indicates invalid topology level.
            // Some cpus have max cpuid >= 0xB but do not support processor topology.
-           ((_cpuid_info.tpl_cpuidB0_eax & 0x1f | _cpuid_info.tpl_cpuidB0_ebx.bits.logical_cpus) != 0);
+           (((_cpuid_info.tpl_cpuidB0_eax & 0x1f) | _cpuid_info.tpl_cpuidB0_ebx.bits.logical_cpus) != 0);
   }
 
   static uint cores_per_cpu()  {
@@ -550,6 +554,7 @@
   static bool supports_avx2()     { return (_cpuFeatures & CPU_AVX2) != 0; }
   static bool supports_tsc()      { return (_cpuFeatures & CPU_TSC)    != 0; }
   static bool supports_aes()      { return (_cpuFeatures & CPU_AES) != 0; }
+  static bool supports_erms()     { return (_cpuFeatures & CPU_ERMS) != 0; }
 
   // Intel features
   static bool is_intel_family_core() { return is_intel() &&
--- a/hotspot/src/cpu/x86/vm/x86_32.ad	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/x86/vm/x86_32.ad	Tue Jan 22 11:54:16 2013 -0800
@@ -11572,15 +11572,28 @@
 // =======================================================================
 // fast clearing of an array
 instruct rep_stos(eCXRegI cnt, eDIRegP base, eAXRegI zero, Universe dummy, eFlagsReg cr) %{
+  predicate(!UseFastStosb);
   match(Set dummy (ClearArray cnt base));
   effect(USE_KILL cnt, USE_KILL base, KILL zero, KILL cr);
-  format %{ "SHL    ECX,1\t# Convert doublewords to words\n\t"
-            "XOR    EAX,EAX\n\t"
+  format %{ "XOR    EAX,EAX\t# ClearArray:\n\t"
+            "SHL    ECX,1\t# Convert doublewords to words\n\t"
             "REP STOS\t# store EAX into [EDI++] while ECX--" %}
-  opcode(0,0x4);
-  ins_encode( Opcode(0xD1), RegOpc(ECX),
-              OpcRegReg(0x33,EAX,EAX),
-              Opcode(0xF3), Opcode(0xAB) );
+  ins_encode %{ 
+    __ clear_mem($base$$Register, $cnt$$Register, $zero$$Register);
+  %}
+  ins_pipe( pipe_slow );
+%}
+
+instruct rep_fast_stosb(eCXRegI cnt, eDIRegP base, eAXRegI zero, Universe dummy, eFlagsReg cr) %{
+  predicate(UseFastStosb);
+  match(Set dummy (ClearArray cnt base));
+  effect(USE_KILL cnt, USE_KILL base, KILL zero, KILL cr);
+  format %{ "XOR    EAX,EAX\t# ClearArray:\n\t"
+            "SHL    ECX,3\t# Convert doublewords to bytes\n\t"
+            "REP STOSB\t# store EAX into [EDI++] while ECX--" %}
+  ins_encode %{ 
+    __ clear_mem($base$$Register, $cnt$$Register, $zero$$Register);
+  %}
   ins_pipe( pipe_slow );
 %}
 
--- a/hotspot/src/cpu/x86/vm/x86_64.ad	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/x86/vm/x86_64.ad	Tue Jan 22 11:54:16 2013 -0800
@@ -10374,16 +10374,33 @@
 instruct rep_stos(rcx_RegL cnt, rdi_RegP base, rax_RegI zero, Universe dummy,
                   rFlagsReg cr)
 %{
+  predicate(!UseFastStosb);
   match(Set dummy (ClearArray cnt base));
   effect(USE_KILL cnt, USE_KILL base, KILL zero, KILL cr);
 
-  format %{ "xorl    rax, rax\t# ClearArray:\n\t"
-            "rep stosq\t# Store rax to *rdi++ while rcx--" %}
-  ins_encode(opc_reg_reg(0x33, RAX, RAX), // xorl %eax, %eax
-             Opcode(0xF3), Opcode(0x48), Opcode(0xAB)); // rep REX_W stos
+  format %{ "xorq    rax, rax\t# ClearArray:\n\t"
+            "rep     stosq\t# Store rax to *rdi++ while rcx--" %}
+  ins_encode %{ 
+    __ clear_mem($base$$Register, $cnt$$Register, $zero$$Register);
+  %}
   ins_pipe(pipe_slow);
 %}
 
+instruct rep_fast_stosb(rcx_RegL cnt, rdi_RegP base, rax_RegI zero, Universe dummy,
+                        rFlagsReg cr)
+%{
+  predicate(UseFastStosb);
+  match(Set dummy (ClearArray cnt base));
+  effect(USE_KILL cnt, USE_KILL base, KILL zero, KILL cr);
+  format %{ "xorq    rax, rax\t# ClearArray:\n\t"
+            "shlq    rcx,3\t# Convert doublewords to bytes\n\t"
+            "rep     stosb\t# Store rax to *rdi++ while rcx--" %}
+  ins_encode %{ 
+    __ clear_mem($base$$Register, $cnt$$Register, $zero$$Register);
+  %}
+  ins_pipe( pipe_slow );
+%}
+
 instruct string_compare(rdi_RegP str1, rcx_RegI cnt1, rsi_RegP str2, rdx_RegI cnt2,
                         rax_RegI result, regD tmp1, rFlagsReg cr)
 %{
--- a/hotspot/src/cpu/zero/vm/frame_zero.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/zero/vm/frame_zero.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -98,10 +98,20 @@
 #endif // CC_INTERP
 
 void frame::patch_pc(Thread* thread, address pc) {
-  // We borrow this call to set the thread pointer in the interpreter
-  // state; the hook to set up deoptimized frames isn't supplied it.
-  assert(pc == NULL, "should be");
-  get_interpreterState()->set_thread((JavaThread *) thread);
+
+  if (pc != NULL) {
+    _cb = CodeCache::find_blob(pc);
+    SharkFrame* sharkframe = zeroframe()->as_shark_frame();
+    sharkframe->set_pc(pc);
+    _pc = pc;
+    _deopt_state = is_deoptimized;
+
+  } else {
+    // We borrow this call to set the thread pointer in the interpreter
+    // state; the hook to set up deoptimized frames isn't supplied it.
+    assert(pc == NULL, "should be");
+    get_interpreterState()->set_thread((JavaThread *) thread);
+  }
 }
 
 bool frame::safe_for_sender(JavaThread *thread) {
--- a/hotspot/src/cpu/zero/vm/frame_zero.inline.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/zero/vm/frame_zero.inline.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -45,27 +45,36 @@
   case ZeroFrame::ENTRY_FRAME:
     _pc = StubRoutines::call_stub_return_pc();
     _cb = NULL;
+    _deopt_state = not_deoptimized;
     break;
 
   case ZeroFrame::INTERPRETER_FRAME:
     _pc = NULL;
     _cb = NULL;
+    _deopt_state = not_deoptimized;
     break;
 
-  case ZeroFrame::SHARK_FRAME:
+  case ZeroFrame::SHARK_FRAME: {
     _pc = zero_sharkframe()->pc();
     _cb = CodeCache::find_blob_unsafe(pc());
+    address original_pc = nmethod::get_deopt_original_pc(this);
+    if (original_pc != NULL) {
+      _pc = original_pc;
+      _deopt_state = is_deoptimized;
+    } else {
+      _deopt_state = not_deoptimized;
+    }
     break;
-
+  }
   case ZeroFrame::FAKE_STUB_FRAME:
     _pc = NULL;
     _cb = NULL;
+    _deopt_state = not_deoptimized;
     break;
 
   default:
     ShouldNotReachHere();
   }
-  _deopt_state = not_deoptimized;
 }
 
 // Accessors
--- a/hotspot/src/cpu/zero/vm/sharkFrame_zero.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/cpu/zero/vm/sharkFrame_zero.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -68,6 +68,10 @@
     return (address) value_of_word(pc_off);
   }
 
+  void set_pc(address pc) const {
+    *((address*) addr_of_word(pc_off)) = pc;
+  }
+
   intptr_t* unextended_sp() const {
     return (intptr_t *) value_of_word(unextended_sp_off);
   }
--- a/hotspot/src/os/bsd/vm/os_bsd.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/os/bsd/vm/os_bsd.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, 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
@@ -243,29 +243,32 @@
   int mib[2];
   size_t len;
   int cpu_val;
-  u_long mem_val;
+  julong mem_val;
 
   /* get processors count via hw.ncpus sysctl */
   mib[0] = CTL_HW;
   mib[1] = HW_NCPU;
   len = sizeof(cpu_val);
   if (sysctl(mib, 2, &cpu_val, &len, NULL, 0) != -1 && cpu_val >= 1) {
+       assert(len == sizeof(cpu_val), "unexpected data size");
        set_processor_count(cpu_val);
   }
   else {
        set_processor_count(1);   // fallback
   }
 
-  /* get physical memory via hw.usermem sysctl (hw.usermem is used
-   * instead of hw.physmem because we need size of allocatable memory
+  /* get physical memory via hw.memsize sysctl (hw.memsize is used
+   * since it returns a 64 bit value)
    */
   mib[0] = CTL_HW;
-  mib[1] = HW_USERMEM;
+  mib[1] = HW_MEMSIZE;
   len = sizeof(mem_val);
-  if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1)
+  if (sysctl(mib, 2, &mem_val, &len, NULL, 0) != -1) {
+       assert(len == sizeof(mem_val), "unexpected data size");
        _physical_memory = mem_val;
-  else
+  } else {
        _physical_memory = 256*1024*1024;       // fallback (XXXBSD?)
+  }
 
 #ifdef __OpenBSD__
   {
@@ -4091,11 +4094,12 @@
      }
      -- _nParked ;
 
-    // In theory we could move the ST of 0 into _Event past the unlock(),
-    // but then we'd need a MEMBAR after the ST.
     _Event = 0 ;
      status = pthread_mutex_unlock(_mutex);
      assert_status(status == 0, status, "mutex_unlock");
+    // Paranoia to ensure our locked and lock-free paths interact
+    // correctly with each other.
+    OrderAccess::fence();
   }
   guarantee (_Event >= 0, "invariant") ;
 }
@@ -4158,40 +4162,44 @@
   status = pthread_mutex_unlock(_mutex);
   assert_status(status == 0, status, "mutex_unlock");
   assert (_nParked == 0, "invariant") ;
+  // Paranoia to ensure our locked and lock-free paths interact
+  // correctly with each other.
+  OrderAccess::fence();
   return ret;
 }
 
 void os::PlatformEvent::unpark() {
-  int v, AnyWaiters ;
-  for (;;) {
-      v = _Event ;
-      if (v > 0) {
-         // The LD of _Event could have reordered or be satisfied
-         // by a read-aside from this processor's write buffer.
-         // To avoid problems execute a barrier and then
-         // ratify the value.
-         OrderAccess::fence() ;
-         if (_Event == v) return ;
-         continue ;
-      }
-      if (Atomic::cmpxchg (v+1, &_Event, v) == v) break ;
+  // Transitions for _Event:
+  //    0 :=> 1
+  //    1 :=> 1
+  //   -1 :=> either 0 or 1; must signal target thread
+  //          That is, we can safely transition _Event from -1 to either
+  //          0 or 1. Forcing 1 is slightly more efficient for back-to-back
+  //          unpark() calls.
+  // See also: "Semaphores in Plan 9" by Mullender & Cox
+  //
+  // Note: Forcing a transition from "-1" to "1" on an unpark() means
+  // that it will take two back-to-back park() calls for the owning
+  // thread to block. This has the benefit of forcing a spurious return
+  // from the first park() call after an unpark() call which will help
+  // shake out uses of park() and unpark() without condition variables.
+
+  if (Atomic::xchg(1, &_Event) >= 0) return;
+
+  // Wait for the thread associated with the event to vacate
+  int status = pthread_mutex_lock(_mutex);
+  assert_status(status == 0, status, "mutex_lock");
+  int AnyWaiters = _nParked;
+  assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
+  if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
+    AnyWaiters = 0;
+    pthread_cond_signal(_cond);
   }
-  if (v < 0) {
-     // Wait for the thread associated with the event to vacate
-     int status = pthread_mutex_lock(_mutex);
-     assert_status(status == 0, status, "mutex_lock");
-     AnyWaiters = _nParked ;
-     assert (AnyWaiters == 0 || AnyWaiters == 1, "invariant") ;
-     if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
-        AnyWaiters = 0 ;
-        pthread_cond_signal (_cond);
-     }
-     status = pthread_mutex_unlock(_mutex);
-     assert_status(status == 0, status, "mutex_unlock");
-     if (AnyWaiters != 0) {
-        status = pthread_cond_signal(_cond);
-        assert_status(status == 0, status, "cond_signal");
-     }
+  status = pthread_mutex_unlock(_mutex);
+  assert_status(status == 0, status, "mutex_unlock");
+  if (AnyWaiters != 0) {
+    status = pthread_cond_signal(_cond);
+    assert_status(status == 0, status, "cond_signal");
   }
 
   // Note that we signal() _after dropping the lock for "immortal" Events.
@@ -4277,13 +4285,14 @@
 }
 
 void Parker::park(bool isAbsolute, jlong time) {
+  // Ideally we'd do something useful while spinning, such
+  // as calling unpackTime().
+
   // Optional fast-path check:
   // Return immediately if a permit is available.
-  if (_counter > 0) {
-      _counter = 0 ;
-      OrderAccess::fence();
-      return ;
-  }
+  // We depend on Atomic::xchg() having full barrier semantics
+  // since we are doing a lock-free update to _counter.
+  if (Atomic::xchg(0, &_counter) > 0) return;
 
   Thread* thread = Thread::current();
   assert(thread->is_Java_thread(), "Must be JavaThread");
@@ -4324,6 +4333,8 @@
     _counter = 0;
     status = pthread_mutex_unlock(_mutex);
     assert (status == 0, "invariant") ;
+    // Paranoia to ensure our locked and lock-free paths interact
+    // correctly with each other and Java-level accesses.
     OrderAccess::fence();
     return;
   }
@@ -4360,12 +4371,14 @@
   _counter = 0 ;
   status = pthread_mutex_unlock(_mutex) ;
   assert_status(status == 0, status, "invariant") ;
+  // Paranoia to ensure our locked and lock-free paths interact
+  // correctly with each other and Java-level accesses.
+  OrderAccess::fence();
+
   // If externally suspended while waiting, re-suspend
   if (jt->handle_special_suspend_equivalent_condition()) {
     jt->java_suspend_self();
   }
-
-  OrderAccess::fence();
 }
 
 void Parker::unpark() {
--- a/hotspot/src/os/bsd/vm/os_bsd.inline.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/os/bsd/vm/os_bsd.inline.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, 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
@@ -59,14 +59,6 @@
   return ":";
 }
 
-inline const char* os::jlong_format_specifier() {
-  return "%lld";
-}
-
-inline const char* os::julong_format_specifier() {
-  return "%llu";
-}
-
 // File names are case-sensitive on windows only
 inline int os::file_name_strcmp(const char* s1, const char* s2) {
   return strcmp(s1, s2);
--- a/hotspot/src/os/linux/vm/os_linux.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/os/linux/vm/os_linux.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, 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
@@ -5001,11 +5001,12 @@
      }
      -- _nParked ;
 
-    // In theory we could move the ST of 0 into _Event past the unlock(),
-    // but then we'd need a MEMBAR after the ST.
     _Event = 0 ;
      status = pthread_mutex_unlock(_mutex);
      assert_status(status == 0, status, "mutex_unlock");
+    // Paranoia to ensure our locked and lock-free paths interact
+    // correctly with each other.
+    OrderAccess::fence();
   }
   guarantee (_Event >= 0, "invariant") ;
 }
@@ -5068,40 +5069,44 @@
   status = pthread_mutex_unlock(_mutex);
   assert_status(status == 0, status, "mutex_unlock");
   assert (_nParked == 0, "invariant") ;
+  // Paranoia to ensure our locked and lock-free paths interact
+  // correctly with each other.
+  OrderAccess::fence();
   return ret;
 }
 
 void os::PlatformEvent::unpark() {
-  int v, AnyWaiters ;
-  for (;;) {
-      v = _Event ;
-      if (v > 0) {
-         // The LD of _Event could have reordered or be satisfied
-         // by a read-aside from this processor's write buffer.
-         // To avoid problems execute a barrier and then
-         // ratify the value.
-         OrderAccess::fence() ;
-         if (_Event == v) return ;
-         continue ;
-      }
-      if (Atomic::cmpxchg (v+1, &_Event, v) == v) break ;
-  }
-  if (v < 0) {
-     // Wait for the thread associated with the event to vacate
-     int status = pthread_mutex_lock(_mutex);
-     assert_status(status == 0, status, "mutex_lock");
-     AnyWaiters = _nParked ;
-     assert (AnyWaiters == 0 || AnyWaiters == 1, "invariant") ;
-     if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
-        AnyWaiters = 0 ;
-        pthread_cond_signal (_cond);
-     }
-     status = pthread_mutex_unlock(_mutex);
-     assert_status(status == 0, status, "mutex_unlock");
-     if (AnyWaiters != 0) {
-        status = pthread_cond_signal(_cond);
-        assert_status(status == 0, status, "cond_signal");
-     }
+  // Transitions for _Event:
+  //    0 :=> 1
+  //    1 :=> 1
+  //   -1 :=> either 0 or 1; must signal target thread
+  //          That is, we can safely transition _Event from -1 to either
+  //          0 or 1. Forcing 1 is slightly more efficient for back-to-back
+  //          unpark() calls.
+  // See also: "Semaphores in Plan 9" by Mullender & Cox
+  //
+  // Note: Forcing a transition from "-1" to "1" on an unpark() means
+  // that it will take two back-to-back park() calls for the owning
+  // thread to block. This has the benefit of forcing a spurious return
+  // from the first park() call after an unpark() call which will help
+  // shake out uses of park() and unpark() without condition variables.
+
+  if (Atomic::xchg(1, &_Event) >= 0) return;
+
+  // Wait for the thread associated with the event to vacate
+  int status = pthread_mutex_lock(_mutex);
+  assert_status(status == 0, status, "mutex_lock");
+  int AnyWaiters = _nParked;
+  assert(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
+  if (AnyWaiters != 0 && WorkAroundNPTLTimedWaitHang) {
+    AnyWaiters = 0;
+    pthread_cond_signal(_cond);
+  }
+  status = pthread_mutex_unlock(_mutex);
+  assert_status(status == 0, status, "mutex_unlock");
+  if (AnyWaiters != 0) {
+    status = pthread_cond_signal(_cond);
+    assert_status(status == 0, status, "cond_signal");
   }
 
   // Note that we signal() _after dropping the lock for "immortal" Events.
@@ -5187,13 +5192,14 @@
 }
 
 void Parker::park(bool isAbsolute, jlong time) {
+  // Ideally we'd do something useful while spinning, such
+  // as calling unpackTime().
+
   // Optional fast-path check:
   // Return immediately if a permit is available.
-  if (_counter > 0) {
-      _counter = 0 ;
-      OrderAccess::fence();
-      return ;
-  }
+  // We depend on Atomic::xchg() having full barrier semantics
+  // since we are doing a lock-free update to _counter.
+  if (Atomic::xchg(0, &_counter) > 0) return;
 
   Thread* thread = Thread::current();
   assert(thread->is_Java_thread(), "Must be JavaThread");
@@ -5234,6 +5240,8 @@
     _counter = 0;
     status = pthread_mutex_unlock(_mutex);
     assert (status == 0, "invariant") ;
+    // Paranoia to ensure our locked and lock-free paths interact
+    // correctly with each other and Java-level accesses.
     OrderAccess::fence();
     return;
   }
@@ -5270,12 +5278,14 @@
   _counter = 0 ;
   status = pthread_mutex_unlock(_mutex) ;
   assert_status(status == 0, status, "invariant") ;
+  // Paranoia to ensure our locked and lock-free paths interact
+  // correctly with each other and Java-level accesses.
+  OrderAccess::fence();
+
   // If externally suspended while waiting, re-suspend
   if (jt->handle_special_suspend_equivalent_condition()) {
     jt->java_suspend_self();
   }
-
-  OrderAccess::fence();
 }
 
 void Parker::unpark() {
--- a/hotspot/src/os/linux/vm/os_linux.inline.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/os/linux/vm/os_linux.inline.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, 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
@@ -68,14 +68,6 @@
   return ":";
 }
 
-inline const char* os::jlong_format_specifier() {
-  return "%lld";
-}
-
-inline const char* os::julong_format_specifier() {
-  return "%llu";
-}
-
 // File names are case-sensitive on windows only
 inline int os::file_name_strcmp(const char* s1, const char* s2) {
   return strcmp(s1, s2);
--- a/hotspot/src/os/posix/launcher/java_md.c	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/os/posix/launcher/java_md.c	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, 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
@@ -1876,11 +1876,6 @@
     }
 }
 
-const char *
-jlong_format_specifier() {
-    return "%lld";
-}
-
 /*
  * Block current thread and continue execution in a new thread
  */
--- a/hotspot/src/os/posix/launcher/java_md.h	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/os/posix/launcher/java_md.h	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -64,6 +64,12 @@
 #define Counter2Micros(counts)    (1)
 #endif /* HAVE_GETHRTIME */
 
+#ifdef _LP64
+#define JLONG_FORMAT "%ld"
+#else
+#define JLONG_FORMAT "%lld"
+#endif
+
 /*
  * Function prototypes.
  */
--- a/hotspot/src/os/solaris/vm/os_solaris.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/os/solaris/vm/os_solaris.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -6014,6 +6014,9 @@
      _Event = 0 ;
      status = os::Solaris::mutex_unlock(_mutex);
      assert_status(status == 0, status, "mutex_unlock");
+    // Paranoia to ensure our locked and lock-free paths interact
+    // correctly with each other.
+    OrderAccess::fence();
   }
 }
 
@@ -6055,51 +6058,43 @@
   _Event = 0 ;
   status = os::Solaris::mutex_unlock(_mutex);
   assert_status(status == 0, status, "mutex_unlock");
+  // Paranoia to ensure our locked and lock-free paths interact
+  // correctly with each other.
+  OrderAccess::fence();
   return ret;
 }
 
 void os::PlatformEvent::unpark() {
-  int v, AnyWaiters;
-
-  // Increment _Event.
-  // Another acceptable implementation would be to simply swap 1
-  // into _Event:
-  //   if (Swap (&_Event, 1) < 0) {
-  //      mutex_lock (_mutex) ; AnyWaiters = nParked; mutex_unlock (_mutex) ;
-  //      if (AnyWaiters) cond_signal (_cond) ;
-  //   }
-
-  for (;;) {
-    v = _Event ;
-    if (v > 0) {
-       // The LD of _Event could have reordered or be satisfied
-       // by a read-aside from this processor's write buffer.
-       // To avoid problems execute a barrier and then
-       // ratify the value.  A degenerate CAS() would also work.
-       // Viz., CAS (v+0, &_Event, v) == v).
-       OrderAccess::fence() ;
-       if (_Event == v) return ;
-       continue ;
-    }
-    if (Atomic::cmpxchg (v+1, &_Event, v) == v) break ;
-  }
+  // Transitions for _Event:
+  //    0 :=> 1
+  //    1 :=> 1
+  //   -1 :=> either 0 or 1; must signal target thread
+  //          That is, we can safely transition _Event from -1 to either
+  //          0 or 1. Forcing 1 is slightly more efficient for back-to-back
+  //          unpark() calls.
+  // See also: "Semaphores in Plan 9" by Mullender & Cox
+  //
+  // Note: Forcing a transition from "-1" to "1" on an unpark() means
+  // that it will take two back-to-back park() calls for the owning
+  // thread to block. This has the benefit of forcing a spurious return
+  // from the first park() call after an unpark() call which will help
+  // shake out uses of park() and unpark() without condition variables.
+
+  if (Atomic::xchg(1, &_Event) >= 0) return;
 
   // If the thread associated with the event was parked, wake it.
-  if (v < 0) {
-     int status ;
-     // Wait for the thread assoc with the PlatformEvent to vacate.
-     status = os::Solaris::mutex_lock(_mutex);
-     assert_status(status == 0, status, "mutex_lock");
-     AnyWaiters = _nParked ;
-     status = os::Solaris::mutex_unlock(_mutex);
-     assert_status(status == 0, status, "mutex_unlock");
-     guarantee (AnyWaiters == 0 || AnyWaiters == 1, "invariant") ;
-     if (AnyWaiters != 0) {
-       // We intentional signal *after* dropping the lock
-       // to avoid a common class of futile wakeups.
-       status = os::Solaris::cond_signal(_cond);
-       assert_status(status == 0, status, "cond_signal");
-     }
+  // Wait for the thread assoc with the PlatformEvent to vacate.
+  int status = os::Solaris::mutex_lock(_mutex);
+  assert_status(status == 0, status, "mutex_lock");
+  int AnyWaiters = _nParked;
+  status = os::Solaris::mutex_unlock(_mutex);
+  assert_status(status == 0, status, "mutex_unlock");
+  guarantee(AnyWaiters == 0 || AnyWaiters == 1, "invariant");
+  if (AnyWaiters != 0) {
+    // We intentional signal *after* dropping the lock
+    // to avoid a common class of futile wakeups.
+    status = os::Solaris::cond_signal(_cond);
+    assert_status(status == 0, status, "cond_signal");
   }
 }
 
@@ -6177,14 +6172,14 @@
 }
 
 void Parker::park(bool isAbsolute, jlong time) {
+  // Ideally we'd do something useful while spinning, such
+  // as calling unpackTime().
 
   // Optional fast-path check:
   // Return immediately if a permit is available.
-  if (_counter > 0) {
-      _counter = 0 ;
-      OrderAccess::fence();
-      return ;
-  }
+  // We depend on Atomic::xchg() having full barrier semantics
+  // since we are doing a lock-free update to _counter.
+  if (Atomic::xchg(0, &_counter) > 0) return;
 
   // Optional fast-exit: Check interrupt before trying to wait
   Thread* thread = Thread::current();
@@ -6226,6 +6221,8 @@
     _counter = 0;
     status = os::Solaris::mutex_unlock(_mutex);
     assert (status == 0, "invariant") ;
+    // Paranoia to ensure our locked and lock-free paths interact
+    // correctly with each other and Java-level accesses.
     OrderAccess::fence();
     return;
   }
@@ -6267,12 +6264,14 @@
   _counter = 0 ;
   status = os::Solaris::mutex_unlock(_mutex);
   assert_status(status == 0, status, "mutex_unlock") ;
+  // Paranoia to ensure our locked and lock-free paths interact
+  // correctly with each other and Java-level accesses.
+  OrderAccess::fence();
 
   // If externally suspended while waiting, re-suspend
   if (jt->handle_special_suspend_equivalent_condition()) {
     jt->java_suspend_self();
   }
-  OrderAccess::fence();
 }
 
 void Parker::unpark() {
--- a/hotspot/src/os/solaris/vm/os_solaris.inline.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/os/solaris/vm/os_solaris.inline.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -50,9 +50,6 @@
 inline const char* os::line_separator() { return "\n"; }
 inline const char* os::path_separator() { return ":"; }
 
-inline const char* os::jlong_format_specifier()   { return "%lld"; }
-inline const char* os::julong_format_specifier()  { return "%llu"; }
-
 // File names are case-sensitive on windows only
 inline int os::file_name_strcmp(const char* s1, const char* s2) {
   return strcmp(s1, s2);
--- a/hotspot/src/os/windows/launcher/java_md.c	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/os/windows/launcher/java_md.c	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1323,11 +1323,6 @@
     }
 }
 
-const char *
-jlong_format_specifier() {
-    return "%I64d";
-}
-
 /*
  * Block current thread and continue execution in a new thread
  */
--- a/hotspot/src/os/windows/launcher/java_md.h	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/os/windows/launcher/java_md.h	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -69,6 +69,8 @@
 extern int _main(int argc, char **argv);
 #endif
 
+#define JLONG_FORMAT "%I64d"
+
 /*
  * Function prototypes.
  */
--- a/hotspot/src/os/windows/vm/os_windows.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/os/windows/vm/os_windows.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -2960,7 +2960,7 @@
     }
     if( Verbose && PrintMiscellaneous ) {
       reserveTimer.stop();
-      tty->print_cr("reserve_memory of %Ix bytes took %ld ms (%ld ticks)", bytes,
+      tty->print_cr("reserve_memory of %Ix bytes took " JLONG_FORMAT " ms (" JLONG_FORMAT " ticks)", bytes,
                     reserveTimer.milliseconds(), reserveTimer.ticks());
     }
   }
@@ -4319,7 +4319,7 @@
   if (hFile == NULL) {
     if (PrintMiscellaneous && Verbose) {
       DWORD err = GetLastError();
-      tty->print_cr("CreateFile() failed: GetLastError->%ld.");
+      tty->print_cr("CreateFile() failed: GetLastError->%ld.", err);
     }
     return NULL;
   }
@@ -4369,7 +4369,7 @@
     if (hMap == NULL) {
       if (PrintMiscellaneous && Verbose) {
         DWORD err = GetLastError();
-        tty->print_cr("CreateFileMapping() failed: GetLastError->%ld.");
+        tty->print_cr("CreateFileMapping() failed: GetLastError->%ld.", err);
       }
       CloseHandle(hFile);
       return NULL;
@@ -4579,6 +4579,7 @@
     }
     v = _Event ;
     _Event = 0 ;
+    // see comment at end of os::PlatformEvent::park() below:
     OrderAccess::fence() ;
     // If we encounter a nearly simultanous timeout expiry and unpark()
     // we return OS_OK indicating we awoke via unpark().
@@ -4616,25 +4617,25 @@
 
 void os::PlatformEvent::unpark() {
   guarantee (_ParkHandle != NULL, "Invariant") ;
-  int v ;
-  for (;;) {
-      v = _Event ;      // Increment _Event if it's < 1.
-      if (v > 0) {
-         // If it's already signaled just return.
-         // The LD of _Event could have reordered or be satisfied
-         // by a read-aside from this processor's write buffer.
-         // To avoid problems execute a barrier and then
-         // ratify the value.  A degenerate CAS() would also work.
-         // Viz., CAS (v+0, &_Event, v) == v).
-         OrderAccess::fence() ;
-         if (_Event == v) return ;
-         continue ;
-      }
-      if (Atomic::cmpxchg (v+1, &_Event, v) == v) break ;
-  }
-  if (v < 0) {
-     ::SetEvent (_ParkHandle) ;
-  }
+
+  // Transitions for _Event:
+  //    0 :=> 1
+  //    1 :=> 1
+  //   -1 :=> either 0 or 1; must signal target thread
+  //          That is, we can safely transition _Event from -1 to either
+  //          0 or 1. Forcing 1 is slightly more efficient for back-to-back
+  //          unpark() calls.
+  // See also: "Semaphores in Plan 9" by Mullender & Cox
+  //
+  // Note: Forcing a transition from "-1" to "1" on an unpark() means
+  // that it will take two back-to-back park() calls for the owning
+  // thread to block. This has the benefit of forcing a spurious return
+  // from the first park() call after an unpark() call which will help
+  // shake out uses of park() and unpark() without condition variables.
+
+  if (Atomic::xchg(1, &_Event) >= 0) return;
+
+  ::SetEvent(_ParkHandle);
 }
 
 
--- a/hotspot/src/os/windows/vm/os_windows.inline.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/os/windows/vm/os_windows.inline.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,9 +38,6 @@
 inline const char* os::path_separator()                { return ";"; }
 inline const char* os::dll_file_extension()            { return ".dll"; }
 
-inline const char* os::jlong_format_specifier()        { return "%I64d"; }
-inline const char* os::julong_format_specifier()       { return "%I64u"; }
-
 inline const int os::default_file_open_flags() { return O_BINARY | O_NOINHERIT;}
 
 // File names are case-insensitive on windows only
--- a/hotspot/src/share/tools/launcher/java.c	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/tools/launcher/java.c	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -808,7 +808,7 @@
 static int
 parse_stack_size(const char *s, jlong *result) {
   jlong n = 0;
-  int args_read = sscanf(s, jlong_format_specifier(), &n);
+  int args_read = sscanf(s, JLONG_FORMAT, &n);
   if (args_read != 1) {
     return 0;
   }
--- a/hotspot/src/share/tools/launcher/java.h	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/tools/launcher/java.h	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -86,7 +86,6 @@
 jboolean RemovableMachineDependentOption(char * option);
 void PrintMachineDependentOptions();
 
-const char *jlong_format_specifier();
 /*
  * Block current thread and continue execution in new thread
  */
--- a/hotspot/src/share/vm/asm/assembler.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/asm/assembler.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -216,8 +216,6 @@
   bool isByte(int x) const             { return 0 <= x && x < 0x100; }
   bool isShiftCount(int x) const       { return 0 <= x && x < 32; }
 
-  void emit_long(jint x) { emit_int32(x); }  // deprecated
-
   // Instruction boundaries (required when emitting relocatable values).
   class InstructionMark: public StackObj {
    private:
--- a/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -3223,7 +3223,12 @@
   }
   if (try_inline_full(callee, holder_known, bc, receiver))
     return true;
-  print_inlining(callee, _inline_bailout_msg, /*success*/ false);
+
+  // Entire compilation could fail during try_inline_full call.
+  // In that case printing inlining decision info is useless.
+  if (!bailed_out())
+    print_inlining(callee, _inline_bailout_msg, /*success*/ false);
+
   return false;
 }
 
@@ -3753,7 +3758,8 @@
   push_scope(callee, cont);
 
   // the BlockListBuilder for the callee could have bailed out
-  CHECK_BAILOUT_(false);
+  if (bailed_out())
+      return false;
 
   // Temporarily set up bytecode stream so we can append instructions
   // (only using the bci of this stream)
@@ -3819,7 +3825,8 @@
   iterate_all_blocks(callee_start_block == NULL);
 
   // If we bailed out during parsing, return immediately (this is bad news)
-  if (bailed_out()) return false;
+  if (bailed_out())
+      return false;
 
   // iterate_all_blocks theoretically traverses in random order; in
   // practice, we have only traversed the continuation if we are
@@ -3828,9 +3835,6 @@
          !continuation()->is_set(BlockBegin::was_visited_flag),
          "continuation should not have been parsed yet if we created it");
 
-  // If we bailed out during parsing, return immediately (this is bad news)
-  CHECK_BAILOUT_(false);
-
   // At this point we are almost ready to return and resume parsing of
   // the caller back in the GraphBuilder. The only thing we want to do
   // first is an optimization: during parsing of the callee we
@@ -4171,7 +4175,10 @@
       else
         log->inline_success("receiver is statically known");
     } else {
-      log->inline_fail(msg);
+      if (msg != NULL)
+        log->inline_fail(msg);
+      else
+        log->inline_fail("reason unknown");
     }
   }
 
--- a/hotspot/src/share/vm/c1/c1_InstructionPrinter.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/c1/c1_InstructionPrinter.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, 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
@@ -360,7 +360,7 @@
   ValueType* t = x->type();
   switch (t->tag()) {
     case intTag    : output()->print("%d"  , t->as_IntConstant   ()->value());    break;
-    case longTag   : output()->print(os::jlong_format_specifier(), t->as_LongConstant()->value()); output()->print("L"); break;
+    case longTag   : output()->print(JLONG_FORMAT, t->as_LongConstant()->value()); output()->print("L"); break;
     case floatTag  : output()->print("%g"  , t->as_FloatConstant ()->value());    break;
     case doubleTag : output()->print("%gD" , t->as_DoubleConstant()->value());    break;
     case objectTag : print_object(x);                                        break;
--- a/hotspot/src/share/vm/c1/c1_LIR.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/c1/c1_LIR.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1563,7 +1563,7 @@
   switch (type()) {
     case T_ADDRESS:out->print("address:%d",as_jint());          break;
     case T_INT:    out->print("int:%d",   as_jint());           break;
-    case T_LONG:   out->print("lng:%lld", as_jlong());          break;
+    case T_LONG:   out->print("lng:" JLONG_FORMAT, as_jlong()); break;
     case T_FLOAT:  out->print("flt:%f",   as_jfloat());         break;
     case T_DOUBLE: out->print("dbl:%f",   as_jdouble());        break;
     case T_OBJECT: out->print("obj:0x%x", as_jobject());        break;
--- a/hotspot/src/share/vm/c1/c1_LIR.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/c1/c1_LIR.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -2259,7 +2259,7 @@
   typedef enum { inputMode, firstMode = inputMode, tempMode, outputMode, numModes, invalidMode = -1 } OprMode;
 
   enum {
-    maxNumberOfOperands = 16,
+    maxNumberOfOperands = 20,
     maxNumberOfInfos = 4
   };
 
--- a/hotspot/src/share/vm/c1/c1_globals.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/c1/c1_globals.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -147,7 +147,7 @@
           "Inline methods containing exception handlers "                   \
           "(NOTE: does not work with current backend)")                     \
                                                                             \
-  develop(bool, InlineSynchronizedMethods, true,                            \
+  product(bool, InlineSynchronizedMethods, true,                            \
           "Inline synchronized methods")                                    \
                                                                             \
   develop(bool, InlineNIOCheckIndex, true,                                  \
--- a/hotspot/src/share/vm/ci/ciReplay.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/ci/ciReplay.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,4 +1,4 @@
-/* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -645,7 +645,7 @@
         java_mirror->bool_field_put(fd.offset(), value);
       } else if (strcmp(field_signature, "J") == 0) {
         jlong value;
-        if (sscanf(string_value, INT64_FORMAT, &value) != 1) {
+        if (sscanf(string_value, JLONG_FORMAT, &value) != 1) {
           fprintf(stderr, "Error parsing long: %s\n", string_value);
           return;
         }
--- a/hotspot/src/share/vm/ci/ciType.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/ci/ciType.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -60,6 +60,19 @@
 }
 
 // ------------------------------------------------------------------
+// ciType::name
+//
+// Return the name of this type
+const char* ciType::name() {
+  if (is_primitive_type()) {
+    return type2name(basic_type());
+  } else {
+    assert(is_klass(), "must be");
+    return as_klass()->name()->as_utf8();
+  }
+}
+
+// ------------------------------------------------------------------
 // ciType::print_impl
 //
 // Implementation of the print method.
@@ -73,7 +86,8 @@
 //
 // Print the name of this type
 void ciType::print_name_on(outputStream* st) {
-  st->print(type2name(basic_type()));
+  ResourceMark rm;
+  st->print(name());
 }
 
 
--- a/hotspot/src/share/vm/ci/ciType.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/ci/ciType.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -77,6 +77,7 @@
   bool is_type() const                      { return true; }
   bool is_classless() const                 { return is_primitive_type(); }
 
+  const char* name();
   virtual void print_name_on(outputStream* st);
   void print_name() {
     print_name_on(tty);
--- a/hotspot/src/share/vm/classfile/classFileParser.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/classfile/classFileParser.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -59,6 +59,7 @@
 #include "services/classLoadingService.hpp"
 #include "services/threadService.hpp"
 #include "utilities/array.hpp"
+#include "utilities/globalDefinitions.hpp"
 
 // We generally try to create the oops directly when parsing, rather than
 // allocating temporary data structures and copying the bytes twice. A
@@ -2159,9 +2160,21 @@
                                      cp, CHECK_(nullHandle));
     } else if (method_attribute_name == vmSymbols::tag_method_parameters()) {
       method_parameters_length = cfs->get_u1_fast();
+      // Track the actual size (note: this is written for clarity; a
+      // decent compiler will CSE and constant-fold this into a single
+      // expression)
+      u2 actual_size = 1;
       method_parameters_data = cfs->get_u1_buffer();
+      actual_size += 2 * method_parameters_length;
       cfs->skip_u2_fast(method_parameters_length);
+      actual_size += 4 * method_parameters_length;
       cfs->skip_u4_fast(method_parameters_length);
+      // Enforce attribute length
+      if (method_attribute_length != actual_size) {
+        classfile_parse_error(
+          "Invalid MethodParameters method attribute length %u in class file %s",
+          method_attribute_length, CHECK_(nullHandle));
+      }
       // ignore this attribute if it cannot be reflected
       if (!SystemDictionary::Parameter_klass_loaded())
         method_parameters_length = 0;
@@ -2309,7 +2322,10 @@
       elem[i].name_cp_index =
         Bytes::get_Java_u2(method_parameters_data);
       method_parameters_data += 2;
-      elem[i].flags = Bytes::get_Java_u4(method_parameters_data);
+      u4 flags = Bytes::get_Java_u4(method_parameters_data);
+      // This caused an alignment fault on Sparc, if flags was a u4
+      elem[i].flags_lo = extract_low_short_from_int(flags);
+      elem[i].flags_hi = extract_high_short_from_int(flags);
       method_parameters_data += 4;
     }
   }
@@ -2487,26 +2503,38 @@
         *has_default_methods = true;
       }
       methods->at_put(index, method());
-      if (*methods_annotations == NULL) {
-        *methods_annotations =
-             MetadataFactory::new_array<AnnotationArray*>(loader_data, length, NULL, CHECK_NULL);
+
+      if (method_annotations != NULL) {
+        if (*methods_annotations == NULL) {
+          *methods_annotations =
+              MetadataFactory::new_array<AnnotationArray*>(loader_data, length, NULL, CHECK_NULL);
+        }
+        (*methods_annotations)->at_put(index, method_annotations);
       }
-      (*methods_annotations)->at_put(index, method_annotations);
-      if (*methods_parameter_annotations == NULL) {
-        *methods_parameter_annotations =
-            MetadataFactory::new_array<AnnotationArray*>(loader_data, length, NULL, CHECK_NULL);
+
+      if (method_parameter_annotations != NULL) {
+        if (*methods_parameter_annotations == NULL) {
+          *methods_parameter_annotations =
+              MetadataFactory::new_array<AnnotationArray*>(loader_data, length, NULL, CHECK_NULL);
+        }
+        (*methods_parameter_annotations)->at_put(index, method_parameter_annotations);
       }
-      (*methods_parameter_annotations)->at_put(index, method_parameter_annotations);
-      if (*methods_default_annotations == NULL) {
-        *methods_default_annotations =
-            MetadataFactory::new_array<AnnotationArray*>(loader_data, length, NULL, CHECK_NULL);
+
+      if (method_default_annotations != NULL) {
+        if (*methods_default_annotations == NULL) {
+          *methods_default_annotations =
+              MetadataFactory::new_array<AnnotationArray*>(loader_data, length, NULL, CHECK_NULL);
+        }
+        (*methods_default_annotations)->at_put(index, method_default_annotations);
       }
-      (*methods_default_annotations)->at_put(index, method_default_annotations);
-      if (*methods_type_annotations == NULL) {
-        *methods_type_annotations =
-             MetadataFactory::new_array<AnnotationArray*>(loader_data, length, NULL, CHECK_NULL);
+
+      if (method_type_annotations != NULL) {
+        if (*methods_type_annotations == NULL) {
+          *methods_type_annotations =
+              MetadataFactory::new_array<AnnotationArray*>(loader_data, length, NULL, CHECK_NULL);
+        }
+        (*methods_type_annotations)->at_put(index, method_type_annotations);
       }
-      (*methods_type_annotations)->at_put(index, method_type_annotations);
     }
 
     if (_need_verify && length > 1) {
@@ -3322,8 +3350,7 @@
     bool has_final_method = false;
     AccessFlags promoted_flags;
     promoted_flags.set_flags(0);
-    // These need to be oop pointers because they are allocated lazily
-    // inside parse_methods inside a nested HandleMark
+
     Array<AnnotationArray*>* methods_annotations = NULL;
     Array<AnnotationArray*>* methods_parameter_annotations = NULL;
     Array<AnnotationArray*>* methods_default_annotations = NULL;
--- a/hotspot/src/share/vm/classfile/classLoaderData.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/classfile/classLoaderData.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -318,6 +318,7 @@
 }
 
 Metaspace* ClassLoaderData::metaspace_non_null() {
+  assert(!DumpSharedSpaces, "wrong metaspace!");
   // If the metaspace has not been allocated, create a new one.  Might want
   // to create smaller arena for Reflection class loaders also.
   // The reason for the delayed allocation is because some class loaders are
@@ -330,10 +331,19 @@
     }
     if (this == the_null_class_loader_data()) {
       assert (class_loader() == NULL, "Must be");
-      size_t word_size = Metaspace::first_chunk_word_size();
-      set_metaspace(new Metaspace(_metaspace_lock, word_size));
+      set_metaspace(new Metaspace(_metaspace_lock, Metaspace::BootMetaspaceType));
+    } else if (is_anonymous()) {
+      if (TraceClassLoaderData && Verbose && class_loader() != NULL) {
+        tty->print_cr("is_anonymous: %s", class_loader()->klass()->internal_name());
+      }
+      set_metaspace(new Metaspace(_metaspace_lock, Metaspace::AnonymousMetaspaceType));
+    } else if (class_loader()->is_a(SystemDictionary::reflect_DelegatingClassLoader_klass())) {
+      if (TraceClassLoaderData && Verbose && class_loader() != NULL) {
+        tty->print_cr("is_reflection: %s", class_loader()->klass()->internal_name());
+      }
+      set_metaspace(new Metaspace(_metaspace_lock, Metaspace::ReflectionMetaspaceType));
     } else {
-      set_metaspace(new Metaspace(_metaspace_lock));  // default size for now.
+      set_metaspace(new Metaspace(_metaspace_lock, Metaspace::StandardMetaspaceType));
     }
   }
   return _metaspace;
@@ -672,8 +682,8 @@
          "only supported for null loader data for now");
   assert (!_shared_metaspaces_initialized, "only initialize once");
   MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
-  _ro_metaspace = new Metaspace(_metaspace_lock, SharedReadOnlySize/wordSize);
-  _rw_metaspace = new Metaspace(_metaspace_lock, SharedReadWriteSize/wordSize);
+  _ro_metaspace = new Metaspace(_metaspace_lock, Metaspace::ROMetaspaceType);
+  _rw_metaspace = new Metaspace(_metaspace_lock, Metaspace::ReadWriteMetaspaceType);
   _shared_metaspaces_initialized = true;
 }
 
--- a/hotspot/src/share/vm/classfile/classLoaderData.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/classfile/classLoaderData.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -8,7 +8,7 @@
  *
  * 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
+ * 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).
  *
--- a/hotspot/src/share/vm/classfile/defaultMethods.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/classfile/defaultMethods.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1285,13 +1285,15 @@
 
   enum { ANNOTATIONS, PARAMETERS, DEFAULTS, NUM_ARRAYS };
 
-  Array<AnnotationArray*>* original_annots[NUM_ARRAYS];
+  Array<AnnotationArray*>* original_annots[NUM_ARRAYS] = { NULL };
 
   Array<Method*>* original_methods = klass->methods();
   Annotations* annots = klass->annotations();
-  original_annots[ANNOTATIONS] = annots->methods_annotations();
-  original_annots[PARAMETERS]  = annots->methods_parameter_annotations();
-  original_annots[DEFAULTS]    = annots->methods_default_annotations();
+  if (annots != NULL) {
+    original_annots[ANNOTATIONS] = annots->methods_annotations();
+    original_annots[PARAMETERS]  = annots->methods_parameter_annotations();
+    original_annots[DEFAULTS]    = annots->methods_default_annotations();
+  }
 
   Array<int>* original_ordering = klass->method_ordering();
   Array<int>* merged_ordering = Universe::the_empty_int_array();
@@ -1370,9 +1372,15 @@
 
   // Replace klass methods with new merged lists
   klass->set_methods(merged_methods);
-  annots->set_methods_annotations(merged_annots[ANNOTATIONS]);
-  annots->set_methods_parameter_annotations(merged_annots[PARAMETERS]);
-  annots->set_methods_default_annotations(merged_annots[DEFAULTS]);
+  if (annots != NULL) {
+    annots->set_methods_annotations(merged_annots[ANNOTATIONS]);
+    annots->set_methods_parameter_annotations(merged_annots[PARAMETERS]);
+    annots->set_methods_default_annotations(merged_annots[DEFAULTS]);
+  } else {
+    assert(merged_annots[ANNOTATIONS] == NULL, "Must be");
+    assert(merged_annots[PARAMETERS] == NULL, "Must be");
+    assert(merged_annots[DEFAULTS] == NULL, "Must be");
+  }
 
   ClassLoaderData* cld = klass->class_loader_data();
   MetadataFactory::free_array(cld, original_methods);
--- a/hotspot/src/share/vm/classfile/javaClasses.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/classfile/javaClasses.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -687,19 +687,6 @@
 }
 
 
-Method* java_lang_Class::resolved_constructor(oop java_class) {
-  Metadata* constructor = java_class->metadata_field(_resolved_constructor_offset);
-  assert(constructor == NULL || constructor->is_method(), "should be method");
-  return ((Method*)constructor);
-}
-
-
-void java_lang_Class::set_resolved_constructor(oop java_class, Method* constructor) {
-  assert(constructor->is_method(), "should be method");
-  java_class->metadata_field_put(_resolved_constructor_offset, constructor);
-}
-
-
 bool java_lang_Class::is_primitive(oop java_class) {
   // should assert:
   //assert(java_lang_Class::is_instance(java_class), "must be a Class object");
@@ -924,7 +911,6 @@
 // Write the thread status value to threadStatus field in java.lang.Thread java class.
 void java_lang_Thread::set_thread_status(oop java_thread,
                                          java_lang_Thread::ThreadStatus status) {
-  assert(JavaThread::current()->thread_state() == _thread_in_vm, "Java Thread is not running in vm");
   // The threadStatus is only present starting in 1.5
   if (_thread_status_offset > 0) {
     java_thread->int_field_put(_thread_status_offset, status);
@@ -1158,179 +1144,43 @@
   }
 }
 
-// Print stack trace element to resource allocated buffer
-char* java_lang_Throwable::print_stack_element_to_buffer(Method* method, int bci) {
-  // Get strings and string lengths
-  InstanceKlass* klass = method->method_holder();
-  const char* klass_name  = klass->external_name();
-  int buf_len = (int)strlen(klass_name);
-  char* source_file_name;
-  if (klass->source_file_name() == NULL) {
-    source_file_name = NULL;
+// After this many redefines, the stack trace is unreliable.
+const int MAX_VERSION = USHRT_MAX;
+
+// Helper backtrace functions to store bci|version together.
+static inline int merge_bci_and_version(int bci, int version) {
+  // only store u2 for version, checking for overflow.
+  if (version > USHRT_MAX || version < 0) version = MAX_VERSION;
+  assert((jushort)bci == bci, "bci should be short");
+  return build_int_from_shorts(version, bci);
+}
+
+static inline int bci_at(unsigned int merged) {
+  return extract_high_short_from_int(merged);
+}
+static inline int version_at(unsigned int merged) {
+  return extract_low_short_from_int(merged);
+}
+
+static inline bool version_matches(Method* method, int version) {
+  return (method->constants()->version() == version && version < MAX_VERSION);
+}
+
+static inline int get_line_number(Method* method, int bci) {
+  int line_number = 0;
+  if (method->is_native()) {
+    // Negative value different from -1 below, enabling Java code in
+    // class java.lang.StackTraceElement to distinguish "native" from
+    // "no LineNumberTable".  JDK tests for -2.
+    line_number = -2;
   } else {
-    source_file_name = klass->source_file_name()->as_C_string();
-    buf_len += (int)strlen(source_file_name);
-  }
-  char* method_name = method->name()->as_C_string();
-  buf_len += (int)strlen(method_name);
-
-  // Allocate temporary buffer with extra space for formatting and line number
-  char* buf = NEW_RESOURCE_ARRAY(char, buf_len + 64);
-
-  // Print stack trace line in buffer
-  sprintf(buf, "\tat %s.%s", klass_name, method_name);
-  if (method->is_native()) {
-    strcat(buf, "(Native Method)");
-  } else {
-    int line_number = method->line_number_from_bci(bci);
-    if (source_file_name != NULL && (line_number != -1)) {
-      // Sourcename and linenumber
-      sprintf(buf + (int)strlen(buf), "(%s:%d)", source_file_name, line_number);
-    } else if (source_file_name != NULL) {
-      // Just sourcename
-      sprintf(buf + (int)strlen(buf), "(%s)", source_file_name);
-    } else {
-      // Neither soucename and linenumber
-      sprintf(buf + (int)strlen(buf), "(Unknown Source)");
-    }
-    nmethod* nm = method->code();
-    if (WizardMode && nm != NULL) {
-      sprintf(buf + (int)strlen(buf), "(nmethod " INTPTR_FORMAT ")", (intptr_t)nm);
+    // Returns -1 if no LineNumberTable, and otherwise actual line number
+    line_number = method->line_number_from_bci(bci);
+    if (line_number == -1 && ShowHiddenFrames) {
+      line_number = bci + 1000000;
     }
   }
-
-  return buf;
-}
-
-
-void java_lang_Throwable::print_stack_element(Handle stream, Method* method, int bci) {
-  ResourceMark rm;
-  char* buf = print_stack_element_to_buffer(method, bci);
-  print_to_stream(stream, buf);
-}
-
-void java_lang_Throwable::print_stack_element(outputStream *st, Method* method, int bci) {
-  ResourceMark rm;
-  char* buf = print_stack_element_to_buffer(method, bci);
-  st->print_cr("%s", buf);
-}
-
-void java_lang_Throwable::print_to_stream(Handle stream, const char* str) {
-  if (stream.is_null()) {
-    tty->print_cr("%s", str);
-  } else {
-    EXCEPTION_MARK;
-    JavaValue result(T_VOID);
-    Handle arg (THREAD, oopFactory::new_charArray(str, THREAD));
-    if (!HAS_PENDING_EXCEPTION) {
-      JavaCalls::call_virtual(&result,
-                              stream,
-                              KlassHandle(THREAD, stream->klass()),
-                              vmSymbols::println_name(),
-                              vmSymbols::char_array_void_signature(),
-                              arg,
-                              THREAD);
-    }
-    // Ignore any exceptions. we are in the middle of exception handling. Same as classic VM.
-    if (HAS_PENDING_EXCEPTION) CLEAR_PENDING_EXCEPTION;
-  }
-
-}
-
-
-const char* java_lang_Throwable::no_stack_trace_message() {
-  return "\t<<no stack trace available>>";
-}
-
-
-// Currently used only for exceptions occurring during startup
-void java_lang_Throwable::print_stack_trace(oop throwable, outputStream* st) {
-  Thread *THREAD = Thread::current();
-  Handle h_throwable(THREAD, throwable);
-  while (h_throwable.not_null()) {
-    objArrayHandle result (THREAD, objArrayOop(backtrace(h_throwable())));
-    if (result.is_null()) {
-      st->print_cr(no_stack_trace_message());
-      return;
-    }
-
-    while (result.not_null()) {
-      typeArrayHandle methods (THREAD,
-                               typeArrayOop(result->obj_at(trace_methods_offset)));
-      typeArrayHandle bcis (THREAD,
-                            typeArrayOop(result->obj_at(trace_bcis_offset)));
-
-      if (methods.is_null() || bcis.is_null()) {
-        st->print_cr(no_stack_trace_message());
-        return;
-      }
-
-      int length = methods()->length();
-      for (int index = 0; index < length; index++) {
-        Method* method = ((Method*)methods()->metadata_at(index));
-        if (method == NULL) goto handle_cause;
-        int bci = bcis->ushort_at(index);
-        print_stack_element(st, method, bci);
-      }
-      result = objArrayHandle(THREAD, objArrayOop(result->obj_at(trace_next_offset)));
-    }
-  handle_cause:
-    {
-      EXCEPTION_MARK;
-      JavaValue result(T_OBJECT);
-      JavaCalls::call_virtual(&result,
-                              h_throwable,
-                              KlassHandle(THREAD, h_throwable->klass()),
-                              vmSymbols::getCause_name(),
-                              vmSymbols::void_throwable_signature(),
-                              THREAD);
-      // Ignore any exceptions. we are in the middle of exception handling. Same as classic VM.
-      if (HAS_PENDING_EXCEPTION) {
-        CLEAR_PENDING_EXCEPTION;
-        h_throwable = Handle();
-      } else {
-        h_throwable = Handle(THREAD, (oop) result.get_jobject());
-        if (h_throwable.not_null()) {
-          st->print("Caused by: ");
-          print(h_throwable, st);
-          st->cr();
-        }
-      }
-    }
-  }
-}
-
-
-void java_lang_Throwable::print_stack_trace(oop throwable, oop print_stream) {
-  // Note: this is no longer used in Merlin, but we support it for compatibility.
-  Thread *thread = Thread::current();
-  Handle stream(thread, print_stream);
-  objArrayHandle result (thread, objArrayOop(backtrace(throwable)));
-  if (result.is_null()) {
-    print_to_stream(stream, no_stack_trace_message());
-    return;
-  }
-
-  while (result.not_null()) {
-    typeArrayHandle methods(thread,
-                            typeArrayOop(result->obj_at(trace_methods_offset)));
-    typeArrayHandle bcis (thread,
-                          typeArrayOop(result->obj_at(trace_bcis_offset)));
-
-    if (methods.is_null() || bcis.is_null()) {
-      print_to_stream(stream, no_stack_trace_message());
-      return;
-    }
-
-    int length = methods()->length();
-    for (int index = 0; index < length; index++) {
-      Method* method = ((Method*)methods()->metadata_at(index));
-      if (method == NULL) return;
-      int bci = bcis->ushort_at(index);
-      print_stack_element(stream, method, bci);
-    }
-    result = objArrayHandle(thread, objArrayOop(result->obj_at(trace_next_offset)));
-  }
+  return line_number;
 }
 
 // This class provides a simple wrapper over the internal structure of
@@ -1350,13 +1200,30 @@
 
   enum {
     trace_methods_offset = java_lang_Throwable::trace_methods_offset,
-    trace_bcis_offset    = java_lang_Throwable::trace_bcis_offset,
+    trace_bcis_offset = java_lang_Throwable::trace_bcis_offset,
     trace_mirrors_offset = java_lang_Throwable::trace_mirrors_offset,
     trace_next_offset    = java_lang_Throwable::trace_next_offset,
     trace_size           = java_lang_Throwable::trace_size,
     trace_chunk_size     = java_lang_Throwable::trace_chunk_size
   };
 
+  // get info out of chunks
+  static typeArrayOop get_methods(objArrayHandle chunk) {
+    typeArrayOop methods = typeArrayOop(chunk->obj_at(trace_methods_offset));
+    assert(methods != NULL, "method array should be initialized in backtrace");
+    return methods;
+  }
+  static typeArrayOop get_bcis(objArrayHandle chunk) {
+    typeArrayOop bcis = typeArrayOop(chunk->obj_at(trace_bcis_offset));
+    assert(bcis != NULL, "bci array should be initialized in backtrace");
+    return bcis;
+  }
+  static objArrayOop get_mirrors(objArrayHandle chunk) {
+    objArrayOop mirrors = objArrayOop(chunk->obj_at(trace_mirrors_offset));
+    assert(mirrors != NULL, "mirror array should be initialized in backtrace");
+    return mirrors;
+  }
+
   // constructor for new backtrace
   BacktraceBuilder(TRAPS): _methods(NULL), _bcis(NULL), _head(NULL), _mirrors(NULL) {
     expand(CHECK);
@@ -1364,6 +1231,19 @@
     _index = 0;
   }
 
+  BacktraceBuilder(objArrayHandle backtrace) {
+    _methods = get_methods(backtrace);
+    _bcis = get_bcis(backtrace);
+    _mirrors = get_mirrors(backtrace);
+    assert(_methods->length() == _bcis->length() &&
+           _methods->length() == _mirrors->length(),
+           "method and source information arrays should match");
+
+    // head is the preallocated backtrace
+    _backtrace = _head = backtrace();
+    _index = 0;
+  }
+
   void expand(TRAPS) {
     objArrayHandle old_head(THREAD, _head);
     Pause_No_Safepoint_Verifier pnsv(&_nsv);
@@ -1371,10 +1251,10 @@
     objArrayOop head = oopFactory::new_objectArray(trace_size, CHECK);
     objArrayHandle new_head(THREAD, head);
 
-    typeArrayOop methods = oopFactory::new_metaDataArray(trace_chunk_size, CHECK);
+    typeArrayOop methods = oopFactory::new_shortArray(trace_chunk_size, CHECK);
     typeArrayHandle new_methods(THREAD, methods);
 
-    typeArrayOop bcis = oopFactory::new_shortArray(trace_chunk_size, CHECK);
+    typeArrayOop bcis = oopFactory::new_intArray(trace_chunk_size, CHECK);
     typeArrayHandle new_bcis(THREAD, bcis);
 
     objArrayOop mirrors = oopFactory::new_objectArray(trace_chunk_size, CHECK);
@@ -1389,7 +1269,7 @@
 
     _head    = new_head();
     _methods = new_methods();
-    _bcis    = new_bcis();
+    _bcis = new_bcis();
     _mirrors = new_mirrors();
     _index = 0;
   }
@@ -1403,7 +1283,6 @@
     // shorts.  The later line number lookup would just smear the -1
     // to a 0 even if it could be recorded.
     if (bci == SynchronizationEntryBCI) bci = 0;
-    assert(bci == (jushort)bci, "doesn't fit");
 
     if (_index >= trace_chunk_size) {
       methodHandle mhandle(THREAD, method);
@@ -1411,26 +1290,148 @@
       method = mhandle();
     }
 
-    _methods->metadata_at_put(_index, method);
-    _bcis->ushort_at_put(_index, bci);
-    // we need to save the mirrors in the backtrace to keep the methods from
-    // being unloaded if their class loader is unloaded while we still have
-    // this stack trace.
+    _methods->short_at_put(_index, method->method_idnum());
+    _bcis->int_at_put(_index, merge_bci_and_version(bci, method->constants()->version()));
+
+    // We need to save the mirrors in the backtrace to keep the class
+    // from being unloaded while we still have this stack trace.
+    assert(method->method_holder()->java_mirror() != NULL, "never push null for mirror");
     _mirrors->obj_at_put(_index, method->method_holder()->java_mirror());
     _index++;
   }
 
-  Method* current_method() {
-    assert(_index >= 0 && _index < trace_chunk_size, "out of range");
-    return ((Method*)_methods->metadata_at(_index));
+};
+
+// Print stack trace element to resource allocated buffer
+char* java_lang_Throwable::print_stack_element_to_buffer(Handle mirror,
+                                  int method_id, int version, int bci) {
+
+  // Get strings and string lengths
+  InstanceKlass* holder = InstanceKlass::cast(java_lang_Class::as_Klass(mirror()));
+  const char* klass_name  = holder->external_name();
+  int buf_len = (int)strlen(klass_name);
+
+  // pushing to the stack trace added one.
+  Method* method = holder->method_with_idnum(method_id);
+  char* method_name = method->name()->as_C_string();
+  buf_len += (int)strlen(method_name);
+
+  char* source_file_name = NULL;
+  if (version_matches(method, version)) {
+    Symbol* source = holder->source_file_name();
+    if (source != NULL) {
+      source_file_name = source->as_C_string();
+      buf_len += (int)strlen(source_file_name);
+    }
+  }
+
+  // Allocate temporary buffer with extra space for formatting and line number
+  char* buf = NEW_RESOURCE_ARRAY(char, buf_len + 64);
+
+  // Print stack trace line in buffer
+  sprintf(buf, "\tat %s.%s", klass_name, method_name);
+
+  if (!version_matches(method, version)) {
+    strcat(buf, "(Redefined)");
+  } else {
+    int line_number = get_line_number(method, bci);
+    if (line_number == -2) {
+      strcat(buf, "(Native Method)");
+    } else {
+      if (source_file_name != NULL && (line_number != -1)) {
+        // Sourcename and linenumber
+        sprintf(buf + (int)strlen(buf), "(%s:%d)", source_file_name, line_number);
+      } else if (source_file_name != NULL) {
+        // Just sourcename
+        sprintf(buf + (int)strlen(buf), "(%s)", source_file_name);
+      } else {
+        // Neither sourcename nor linenumber
+        sprintf(buf + (int)strlen(buf), "(Unknown Source)");
+      }
+      nmethod* nm = method->code();
+      if (WizardMode && nm != NULL) {
+        sprintf(buf + (int)strlen(buf), "(nmethod " INTPTR_FORMAT ")", (intptr_t)nm);
+      }
+    }
   }
 
-  jushort current_bci() {
-    assert(_index >= 0 && _index < trace_chunk_size, "out of range");
-    return _bcis->ushort_at(_index);
+  return buf;
+}
+
+void java_lang_Throwable::print_stack_element(outputStream *st, Handle mirror,
+                                              int method_id, int version, int bci) {
+  ResourceMark rm;
+  char* buf = print_stack_element_to_buffer(mirror, method_id, version, bci);
+  st->print_cr("%s", buf);
+}
+
+void java_lang_Throwable::print_stack_element(outputStream *st, methodHandle method, int bci) {
+  Handle mirror = method->method_holder()->java_mirror();
+  int method_id = method->method_idnum();
+  int version = method->constants()->version();
+  print_stack_element(st, mirror, method_id, version, bci);
+}
+
+const char* java_lang_Throwable::no_stack_trace_message() {
+  return "\t<<no stack trace available>>";
+}
+
+
+// Currently used only for exceptions occurring during startup
+void java_lang_Throwable::print_stack_trace(oop throwable, outputStream* st) {
+  Thread *THREAD = Thread::current();
+  Handle h_throwable(THREAD, throwable);
+  while (h_throwable.not_null()) {
+    objArrayHandle result (THREAD, objArrayOop(backtrace(h_throwable())));
+    if (result.is_null()) {
+      st->print_cr(no_stack_trace_message());
+      return;
+    }
+
+    while (result.not_null()) {
+
+      // Get method id, bci, version and mirror from chunk
+      typeArrayHandle methods (THREAD, BacktraceBuilder::get_methods(result));
+      typeArrayHandle bcis (THREAD, BacktraceBuilder::get_bcis(result));
+      objArrayHandle mirrors (THREAD, BacktraceBuilder::get_mirrors(result));
+
+      int length = methods()->length();
+      for (int index = 0; index < length; index++) {
+        Handle mirror(THREAD, mirrors->obj_at(index));
+        // NULL mirror means end of stack trace
+        if (mirror.is_null()) goto handle_cause;
+        int method = methods->short_at(index);
+        int version = version_at(bcis->int_at(index));
+        int bci = bci_at(bcis->int_at(index));
+        print_stack_element(st, mirror, method, version, bci);
+      }
+      result = objArrayHandle(THREAD, objArrayOop(result->obj_at(trace_next_offset)));
+    }
+  handle_cause:
+    {
+      EXCEPTION_MARK;
+      JavaValue cause(T_OBJECT);
+      JavaCalls::call_virtual(&cause,
+                              h_throwable,
+                              KlassHandle(THREAD, h_throwable->klass()),
+                              vmSymbols::getCause_name(),
+                              vmSymbols::void_throwable_signature(),
+                              THREAD);
+      // Ignore any exceptions. we are in the middle of exception handling. Same as classic VM.
+      if (HAS_PENDING_EXCEPTION) {
+        CLEAR_PENDING_EXCEPTION;
+        h_throwable = Handle();
+      } else {
+        h_throwable = Handle(THREAD, (oop) cause.get_jobject());
+        if (h_throwable.not_null()) {
+          st->print("Caused by: ");
+          print(h_throwable, st);
+          st->cr();
+        }
+      }
+    }
   }
-};
-
+}
 
 void java_lang_Throwable::fill_in_stack_trace(Handle throwable, methodHandle method, TRAPS) {
   if (!StackTraceInThrowable) return;
@@ -1591,21 +1592,8 @@
 
   // No-op if stack trace is disabled
   if (!StackTraceInThrowable) return;
-
-  objArrayOop h_oop = oopFactory::new_objectArray(trace_size, CHECK);
-  objArrayHandle backtrace  (THREAD, h_oop);
-  typeArrayOop m_oop = oopFactory::new_metaDataArray(trace_chunk_size, CHECK);
-  typeArrayHandle methods (THREAD, m_oop);
-  typeArrayOop b = oopFactory::new_shortArray(trace_chunk_size, CHECK);
-  typeArrayHandle bcis(THREAD, b);
-  objArrayOop mirror_oop = oopFactory::new_objectArray(trace_chunk_size, CHECK);
-  objArrayHandle mirrors (THREAD, mirror_oop);
-
-  // backtrace has space for one chunk (next is NULL)
-  backtrace->obj_at_put(trace_methods_offset, methods());
-  backtrace->obj_at_put(trace_bcis_offset, bcis());
-  backtrace->obj_at_put(trace_mirrors_offset, mirrors());
-  set_backtrace(throwable(), backtrace());
+  BacktraceBuilder bt(CHECK);   // creates a backtrace
+  set_backtrace(throwable(), bt.backtrace());
 }
 
 
@@ -1617,48 +1605,26 @@
 
   assert(throwable->is_a(SystemDictionary::Throwable_klass()), "sanity check");
 
-  objArrayOop backtrace = (objArrayOop)java_lang_Throwable::backtrace(throwable());
-  assert(backtrace != NULL, "backtrace not preallocated");
-
-  oop m = backtrace->obj_at(trace_methods_offset);
-  typeArrayOop methods = typeArrayOop(m);
-  assert(methods != NULL && methods->length() > 0, "method array not preallocated");
-
-  oop b = backtrace->obj_at(trace_bcis_offset);
-  typeArrayOop bcis = typeArrayOop(b);
-  assert(bcis != NULL, "bci array not preallocated");
-
-  oop mr = backtrace->obj_at(trace_mirrors_offset);
-  objArrayOop mirrors = objArrayOop(mr);
-  assert(mirrors != NULL, "bci array not preallocated");
-
-  assert(methods->length() == bcis->length() &&
-         methods->length() == mirrors->length(),
-         "method and bci arrays should match");
-
-  JavaThread* thread = JavaThread::current();
-  ResourceMark rm(thread);
-  vframeStream st(thread);
+  JavaThread* THREAD = JavaThread::current();
+
+  objArrayHandle backtrace (THREAD, (objArrayOop)java_lang_Throwable::backtrace(throwable()));
+  assert(backtrace.not_null(), "backtrace should have been preallocated");
+
+  ResourceMark rm(THREAD);
+  vframeStream st(THREAD);
+
+  BacktraceBuilder bt(backtrace);
 
   // Unlike fill_in_stack_trace we do not skip fillInStackTrace or throwable init
   // methods as preallocated errors aren't created by "java" code.
 
   // fill in as much stack trace as possible
+  typeArrayOop methods = BacktraceBuilder::get_methods(backtrace);
   int max_chunks = MIN2(methods->length(), (int)MaxJavaStackTraceDepth);
   int chunk_count = 0;
 
   for (;!st.at_end(); st.next()) {
-    // Add entry and smear the -1 bci to 0 since the array only holds
-    // unsigned shorts.  The later line number lookup would just smear
-    // the -1 to a 0 even if it could be recorded.
-    int bci = st.bci();
-    if (bci == SynchronizationEntryBCI) bci = 0;
-    assert(bci == (jushort)bci, "doesn't fit");
-    bcis->ushort_at_put(chunk_count, bci);
-    methods->metadata_at_put(chunk_count, st.method());
-    mirrors->obj_at_put(chunk_count,
-                   st.method()->method_holder()->java_mirror());
-
+    bt.push(st.method(), st.bci(), CHECK);
     chunk_count++;
 
     // Bail-out for deep stacks
@@ -1672,7 +1638,6 @@
       java_lang_Throwable::set_stacktrace(throwable(), java_lang_Throwable::unassigned_stacktrace());
       assert(java_lang_Throwable::unassigned_stacktrace() != NULL, "not initialized");
   }
-
 }
 
 
@@ -1691,12 +1656,12 @@
       chunk = next;
     }
     assert(chunk != NULL && chunk->obj_at(trace_next_offset) == NULL, "sanity check");
-    // Count element in remaining partial chunk
-    typeArrayOop methods = typeArrayOop(chunk->obj_at(trace_methods_offset));
-    typeArrayOop bcis = typeArrayOop(chunk->obj_at(trace_bcis_offset));
-    assert(methods != NULL && bcis != NULL, "sanity check");
-    for (int i = 0; i < methods->length(); i++) {
-      if (methods->metadata_at(i) == NULL) break;
+    // Count element in remaining partial chunk.  NULL value for mirror
+    // marks the end of the stack trace elements that are saved.
+    objArrayOop mirrors = BacktraceBuilder::get_mirrors(chunk);
+    assert(mirrors != NULL, "sanity check");
+    for (int i = 0; i < mirrors->length(); i++) {
+      if (mirrors->obj_at(i) == NULL) break;
       depth++;
     }
   }
@@ -1722,25 +1687,28 @@
   if (chunk == NULL) {
     THROW_(vmSymbols::java_lang_IndexOutOfBoundsException(), NULL);
   }
-  // Get method,bci from chunk
-  typeArrayOop methods = typeArrayOop(chunk->obj_at(trace_methods_offset));
-  typeArrayOop bcis = typeArrayOop(chunk->obj_at(trace_bcis_offset));
-  assert(methods != NULL && bcis != NULL, "sanity check");
-  methodHandle method(THREAD, ((Method*)methods->metadata_at(chunk_index)));
-  int bci = bcis->ushort_at(chunk_index);
+  // Get method id, bci, version and mirror from chunk
+  typeArrayOop methods = BacktraceBuilder::get_methods(chunk);
+  typeArrayOop bcis = BacktraceBuilder::get_bcis(chunk);
+  objArrayOop mirrors = BacktraceBuilder::get_mirrors(chunk);
+
+  assert(methods != NULL && bcis != NULL && mirrors != NULL, "sanity check");
+
+  int method = methods->short_at(chunk_index);
+  int version = version_at(bcis->int_at(chunk_index));
+  int bci = bci_at(bcis->int_at(chunk_index));
+  Handle mirror(THREAD, mirrors->obj_at(chunk_index));
+
   // Chunk can be partial full
-  if (method.is_null()) {
+  if (mirror.is_null()) {
     THROW_(vmSymbols::java_lang_IndexOutOfBoundsException(), NULL);
   }
 
-  oop element = java_lang_StackTraceElement::create(method, bci, CHECK_0);
+  oop element = java_lang_StackTraceElement::create(mirror, method, version, bci, CHECK_0);
   return element;
 }
 
-oop java_lang_StackTraceElement::create(methodHandle method, int bci, TRAPS) {
-  // SystemDictionary::stackTraceElement_klass() will be null for pre-1.4 JDKs
-  assert(JDK_Version::is_gte_jdk14x_version(), "should only be called in >= 1.4");
-
+oop java_lang_StackTraceElement::create(Handle mirror, int method_id, int version, int bci, TRAPS) {
   // Allocate java.lang.StackTraceElement instance
   Klass* k = SystemDictionary::StackTraceElement_klass();
   assert(k != NULL, "must be loaded in 1.4+");
@@ -1752,37 +1720,39 @@
   Handle element = ik->allocate_instance_handle(CHECK_0);
   // Fill in class name
   ResourceMark rm(THREAD);
-  const char* str = method->method_holder()->external_name();
+  InstanceKlass* holder = InstanceKlass::cast(java_lang_Class::as_Klass(mirror()));
+  const char* str = holder->external_name();
   oop classname = StringTable::intern((char*) str, CHECK_0);
   java_lang_StackTraceElement::set_declaringClass(element(), classname);
+
   // Fill in method name
+  Method* method = holder->method_with_idnum(method_id);
   oop methodname = StringTable::intern(method->name(), CHECK_0);
   java_lang_StackTraceElement::set_methodName(element(), methodname);
-  // Fill in source file name
-  Symbol* source = method->method_holder()->source_file_name();
-  if (ShowHiddenFrames && source == NULL)
-    source = vmSymbols::unknown_class_name();
-  oop filename = StringTable::intern(source, CHECK_0);
-  java_lang_StackTraceElement::set_fileName(element(), filename);
-  // File in source line number
-  int line_number;
-  if (method->is_native()) {
-    // Negative value different from -1 below, enabling Java code in
-    // class java.lang.StackTraceElement to distinguish "native" from
-    // "no LineNumberTable".
-    line_number = -2;
+
+  if (!version_matches(method, version)) {
+    // The method was redefined, accurate line number information isn't available
+    java_lang_StackTraceElement::set_fileName(element(), NULL);
+    java_lang_StackTraceElement::set_lineNumber(element(), -1);
   } else {
-    // Returns -1 if no LineNumberTable, and otherwise actual line number
-    line_number = method->line_number_from_bci(bci);
-    if (line_number == -1 && ShowHiddenFrames) {
-      line_number = bci + 1000000;
-    }
+    // Fill in source file name and line number.
+    Symbol* source = holder->source_file_name();
+    if (ShowHiddenFrames && source == NULL)
+      source = vmSymbols::unknown_class_name();
+    oop filename = StringTable::intern(source, CHECK_0);
+    java_lang_StackTraceElement::set_fileName(element(), filename);
+
+    int line_number = get_line_number(method, bci);
+    java_lang_StackTraceElement::set_lineNumber(element(), line_number);
   }
-  java_lang_StackTraceElement::set_lineNumber(element(), line_number);
-
   return element();
 }
 
+oop java_lang_StackTraceElement::create(methodHandle method, int bci, TRAPS) {
+  Handle mirror (THREAD, method->method_holder()->java_mirror());
+  int method_id = method->method_idnum();
+  return create(mirror, method_id, method->constants()->version(), bci, THREAD);
+}
 
 void java_lang_reflect_AccessibleObject::compute_offsets() {
   Klass* k = SystemDictionary::reflect_AccessibleObject_klass();
@@ -2949,7 +2919,6 @@
 
 int java_lang_Class::_klass_offset;
 int java_lang_Class::_array_klass_offset;
-int java_lang_Class::_resolved_constructor_offset;
 int java_lang_Class::_oop_size_offset;
 int java_lang_Class::_static_oop_field_count_offset;
 GrowableArray<Klass*>* java_lang_Class::_fixup_mirror_list = NULL;
@@ -3303,7 +3272,6 @@
   // Fake fields
   // CHECK_OFFSET("java/lang/Class", java_lang_Class, klass); // %%% this needs to be checked
   // CHECK_OFFSET("java/lang/Class", java_lang_Class, array_klass); // %%% this needs to be checked
-  // CHECK_OFFSET("java/lang/Class", java_lang_Class, resolved_constructor); // %%% this needs to be checked
 
   // java.lang.Throwable
 
--- a/hotspot/src/share/vm/classfile/javaClasses.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/classfile/javaClasses.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -206,7 +206,6 @@
 
 #define CLASS_INJECTED_FIELDS(macro)                                       \
   macro(java_lang_Class, klass,                  intptr_signature,  false) \
-  macro(java_lang_Class, resolved_constructor,   intptr_signature,  false) \
   macro(java_lang_Class, array_klass,            intptr_signature,  false) \
   macro(java_lang_Class, oop_size,               int_signature,     false) \
   macro(java_lang_Class, static_oop_field_count, int_signature,     false)
@@ -218,7 +217,6 @@
   // The fake offsets are added by the class loader when java.lang.Class is loaded
 
   static int _klass_offset;
-  static int _resolved_constructor_offset;
   static int _array_klass_offset;
 
   static int _oop_size_offset;
@@ -254,15 +252,11 @@
   static bool is_primitive(oop java_class);
   static BasicType primitive_type(oop java_class);
   static oop primitive_mirror(BasicType t);
-  // JVM_NewInstance support
-  static Method* resolved_constructor(oop java_class);
-  static void set_resolved_constructor(oop java_class, Method* constructor);
   // JVM_NewArray support
   static Klass* array_klass(oop java_class);
   static void set_array_klass(oop java_class, Klass* klass);
   // compiler support for class operations
   static int klass_offset_in_bytes()                { return _klass_offset; }
-  static int resolved_constructor_offset_in_bytes() { return _resolved_constructor_offset; }
   static int array_klass_offset_in_bytes()          { return _array_klass_offset; }
   // Support for classRedefinedCount field
   static int classRedefinedCount(oop the_class_mirror);
@@ -469,8 +463,7 @@
   static int static_unassigned_stacktrace_offset;
 
   // Printing
-  static char* print_stack_element_to_buffer(Method* method, int bci);
-  static void print_to_stream(Handle stream, const char* str);
+  static char* print_stack_element_to_buffer(Handle mirror, int method, int version, int bci);
   // StackTrace (programmatic access, new since 1.4)
   static void clear_stacktrace(oop throwable);
   // No stack trace available
@@ -490,12 +483,9 @@
   static oop message(oop throwable);
   static oop message(Handle throwable);
   static void set_message(oop throwable, oop value);
-  // Print stack trace stored in exception by call-back to Java
-  // Note: this is no longer used in Merlin, but we still suppport
-  // it for compatibility.
-  static void print_stack_trace(oop throwable, oop print_stream);
-  static void print_stack_element(Handle stream, Method* method, int bci);
-  static void print_stack_element(outputStream *st, Method* method, int bci);
+  static void print_stack_element(outputStream *st, Handle mirror, int method,
+                                  int version, int bci);
+  static void print_stack_element(outputStream *st, methodHandle method, int bci);
   static void print_stack_usage(Handle stream);
 
   // Allocate space for backtrace (created but stack trace not filled in)
@@ -1263,7 +1253,8 @@
   static void set_lineNumber(oop element, int value);
 
   // Create an instance of StackTraceElement
-  static oop create(methodHandle m, int bci, TRAPS);
+  static oop create(Handle mirror, int method, int version, int bci, TRAPS);
+  static oop create(methodHandle method, int bci, TRAPS);
 
   // Debugging
   friend class JavaClasses;
--- a/hotspot/src/share/vm/classfile/vmSymbols.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -386,7 +386,6 @@
   template(basicType_name,                            "basicType")                                \
   template(append_name,                               "append")                                   \
   template(klass_name,                                "klass")                                    \
-  template(resolved_constructor_name,                 "resolved_constructor")                     \
   template(array_klass_name,                          "array_klass")                              \
   template(oop_size_name,                             "oop_size")                                 \
   template(static_oop_field_count_name,               "static_oop_field_count")                   \
--- a/hotspot/src/share/vm/code/codeCache.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/code/codeCache.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -30,6 +30,7 @@
 #include "code/icBuffer.hpp"
 #include "code/nmethod.hpp"
 #include "code/pcDesc.hpp"
+#include "compiler/compileBroker.hpp"
 #include "gc_implementation/shared/markSweep.hpp"
 #include "memory/allocation.inline.hpp"
 #include "memory/gcLocker.hpp"
@@ -39,6 +40,7 @@
 #include "oops/objArrayOop.hpp"
 #include "oops/oop.inline.hpp"
 #include "runtime/handles.inline.hpp"
+#include "runtime/arguments.hpp"
 #include "runtime/icache.hpp"
 #include "runtime/java.hpp"
 #include "runtime/mutexLocker.hpp"
@@ -168,6 +170,8 @@
   return (nmethod*)cb;
 }
 
+static size_t maxCodeCacheUsed = 0;
+
 CodeBlob* CodeCache::allocate(int size) {
   // Do not seize the CodeCache lock here--if the caller has not
   // already done so, we are going to lose bigtime, since the code
@@ -192,6 +196,8 @@
                     (address)_heap->end() - (address)_heap->begin());
     }
   }
+  maxCodeCacheUsed = MAX2(maxCodeCacheUsed, ((address)_heap->high_boundary() -
+                          (address)_heap->low_boundary()) - unallocated_capacity());
   verify_if_often();
   print_trace("allocation", cb, size);
   return cb;
@@ -928,7 +934,14 @@
   FREE_C_HEAP_ARRAY(int, buckets, mtCode);
 }
 
+#endif // !PRODUCT
+
 void CodeCache::print() {
+  print_summary(tty);
+
+#ifndef PRODUCT
+  if (!Verbose) return;
+
   CodeBlob_sizes live;
   CodeBlob_sizes dead;
 
@@ -953,7 +966,7 @@
   }
 
 
-  if (Verbose) {
+  if (WizardMode) {
      // print the oop_map usage
     int code_size = 0;
     int number_of_blobs = 0;
@@ -977,20 +990,30 @@
     tty->print_cr("  map size  = %d", map_size);
   }
 
+#endif // !PRODUCT
 }
 
-#endif // PRODUCT
+void CodeCache::print_summary(outputStream* st, bool detailed) {
+  size_t total = (_heap->high_boundary() - _heap->low_boundary());
+  st->print_cr("CodeCache: size=" SIZE_FORMAT "Kb used=" SIZE_FORMAT
+               "Kb max_used=" SIZE_FORMAT "Kb free=" SIZE_FORMAT
+               "Kb max_free_chunk=" SIZE_FORMAT "Kb",
+               total/K, (total - unallocated_capacity())/K,
+               maxCodeCacheUsed/K, unallocated_capacity()/K, largest_free_block()/K);
 
-void CodeCache::print_bounds(outputStream* st) {
-  st->print_cr("Code Cache  [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT ")",
-               _heap->low_boundary(),
-               _heap->high(),
-               _heap->high_boundary());
-  st->print_cr(" total_blobs=" UINT32_FORMAT " nmethods=" UINT32_FORMAT
-               " adapters=" UINT32_FORMAT " free_code_cache=" SIZE_FORMAT "Kb"
-               " largest_free_block=" SIZE_FORMAT,
-               nof_blobs(), nof_nmethods(), nof_adapters(),
-               unallocated_capacity()/K, largest_free_block());
+  if (detailed) {
+    st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]",
+                 _heap->low_boundary(),
+                 _heap->high(),
+                 _heap->high_boundary());
+    st->print_cr(" total_blobs=" UINT32_FORMAT " nmethods=" UINT32_FORMAT
+                 " adapters=" UINT32_FORMAT,
+                 nof_blobs(), nof_nmethods(), nof_adapters());
+    st->print_cr(" compilation: %s", CompileBroker::should_compile_new_jobs() ?
+                 "enabled" : Arguments::mode() == Arguments::_int ?
+                 "disabled (interpreter mode)" :
+                 "disabled (not enough contiguous free space left)");
+  }
 }
 
 void CodeCache::log_state(outputStream* st) {
--- a/hotspot/src/share/vm/code/codeCache.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/code/codeCache.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -145,11 +145,11 @@
   static void prune_scavenge_root_nmethods();
 
   // Printing/debugging
-  static void print()   PRODUCT_RETURN;          // prints summary
+  static void print();                           // prints summary
   static void print_internals();
   static void verify();                          // verifies the code cache
   static void print_trace(const char* event, CodeBlob* cb, int size = 0) PRODUCT_RETURN;
-  static void print_bounds(outputStream* st);    // Prints a summary of the bounds of the code cache
+  static void print_summary(outputStream* st, bool detailed = true); // Prints a summary of the code cache usage
   static void log_state(outputStream* st);
 
   // The full limits of the codeCache
--- a/hotspot/src/share/vm/compiler/abstractCompiler.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/compiler/abstractCompiler.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -50,6 +50,7 @@
   // Missing feature tests
   virtual bool supports_native()                 { return true; }
   virtual bool supports_osr   ()                 { return true; }
+  virtual bool can_compile_method(methodHandle method)  { return true; }
 #if defined(TIERED) || ( !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK))
   virtual bool is_c1   ()                        { return false; }
   virtual bool is_c2   ()                        { return false; }
--- a/hotspot/src/share/vm/compiler/compileBroker.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/compiler/compileBroker.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1218,7 +1218,7 @@
   // lock, make sure that the compilation
   // isn't prohibited in a straightforward way.
 
-  if (compiler(comp_level) == NULL || compilation_is_prohibited(method, osr_bci, comp_level)) {
+  if (compiler(comp_level) == NULL || !compiler(comp_level)->can_compile_method(method) || compilation_is_prohibited(method, osr_bci, comp_level)) {
     return NULL;
   }
 
@@ -1714,6 +1714,20 @@
   }
 }
 
+// wrapper for CodeCache::print_summary()
+static void codecache_print(bool detailed)
+{
+  ResourceMark rm;
+  stringStream s;
+  // Dump code cache  into a buffer before locking the tty,
+  {
+    MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
+    CodeCache::print_summary(&s, detailed);
+  }
+  ttyLocker ttyl;
+  tty->print_cr(s.as_string());
+}
+
 // ------------------------------------------------------------------
 // CompileBroker::invoke_compiler_on_method
 //
@@ -1841,6 +1855,9 @@
     tty->print_cr("size: %d time: %d inlined: %d bytes", code_size, (int)time.milliseconds(), task->num_inlined_bytecodes());
   }
 
+  if (PrintCodeCacheOnCompilation)
+    codecache_print(/* detailed= */ false);
+
   // Disable compilation, if required.
   switch (compilable) {
   case ciEnv::MethodCompilable_never:
@@ -1885,6 +1902,7 @@
   UseInterpreter = true;
   if (UseCompiler || AlwaysCompileLoopMethods ) {
     if (xtty != NULL) {
+      ResourceMark rm;
       stringStream s;
       // Dump code cache state into a buffer before locking the tty,
       // because log_state() will use locks causing lock conflicts.
@@ -1898,9 +1916,9 @@
     }
     warning("CodeCache is full. Compiler has been disabled.");
     warning("Try increasing the code cache size using -XX:ReservedCodeCacheSize=");
-    CodeCache::print_bounds(tty);
 #ifndef PRODUCT
     if (CompileTheWorld || ExitOnFullCodeCache) {
+      codecache_print(/* detailed= */ true);
       before_exit(JavaThread::current());
       exit_globals(); // will delete tty
       vm_direct_exit(CompileTheWorld ? 0 : 1);
@@ -1913,6 +1931,7 @@
       AlwaysCompileLoopMethods  = false;
     }
   }
+  codecache_print(/* detailed= */ true);
 }
 
 // ------------------------------------------------------------------
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsCollectorPolicy.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsCollectorPolicy.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -56,7 +56,7 @@
   if (_generations == NULL)
     vm_exit_during_initialization("Unable to allocate gen spec");
 
-  if (ParNewGeneration::in_use()) {
+  if (UseParNewGC) {
     if (UseAdaptiveSizePolicy) {
       _generations[0] = new GenerationSpec(Generation::ASParNew,
                                            _initial_gen0_size, _max_gen0_size);
@@ -96,7 +96,7 @@
 
 void ConcurrentMarkSweepPolicy::initialize_gc_policy_counters() {
   // initialize the policy counters - 2 collectors, 3 generations
-  if (ParNewGeneration::in_use()) {
+  if (UseParNewGC) {
     _gc_policy_counters = new GCPolicyCounters("ParNew:CMS", 2, 3);
   }
   else {
@@ -119,7 +119,7 @@
 
   assert(size_policy() != NULL, "A size policy is required");
   // initialize the policy counters - 2 collectors, 3 generations
-  if (ParNewGeneration::in_use()) {
+  if (UseParNewGC) {
     _gc_policy_counters = new CMSGCAdaptivePolicyCounters("ParNew:CMS", 2, 3,
       size_policy());
   }
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -214,7 +214,6 @@
     assert(q->forwardee() == NULL, "should be forwarded to NULL");
   }
 
-  VALIDATE_MARK_SWEEP_ONLY(MarkSweep::register_live_oop(q, adjusted_size));
   compact_top += adjusted_size;
 
   // we need to update the offset table so that the beginnings of objects can be
@@ -555,7 +554,7 @@
     reportIndexedFreeListStatistics();
     size_t total_size = totalSizeInIndexedFreeLists() +
                        _dictionary->total_chunk_size(DEBUG_ONLY(freelistLock()));
-    gclog_or_tty->print(" free=%ld frag=%1.4f\n", total_size, flsFrag());
+    gclog_or_tty->print(" free=" SIZE_FORMAT " frag=%1.4f\n", total_size, flsFrag());
   }
 }
 
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -827,10 +827,10 @@
   GenCollectedHeap* gch = GenCollectedHeap::heap();
   if (PrintGCDetails) {
     if (Verbose) {
-      gclog_or_tty->print(" [%d %s-%s: "SIZE_FORMAT"("SIZE_FORMAT")]",
+      gclog_or_tty->print("[%d %s-%s: "SIZE_FORMAT"("SIZE_FORMAT")]",
         level(), short_name(), s, used(), capacity());
     } else {
-      gclog_or_tty->print(" [%d %s-%s: "SIZE_FORMAT"K("SIZE_FORMAT"K)]",
+      gclog_or_tty->print("[%d %s-%s: "SIZE_FORMAT"K("SIZE_FORMAT"K)]",
         level(), short_name(), s, used() / K, capacity() / K);
     }
   }
@@ -3338,7 +3338,7 @@
     if (Verbose && PrintGC) {
       size_t new_mem_size = _virtual_space.committed_size();
       size_t old_mem_size = new_mem_size - bytes;
-      gclog_or_tty->print_cr("Expanding %s from %ldK by %ldK to %ldK",
+      gclog_or_tty->print_cr("Expanding %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K",
                     name(), old_mem_size/K, bytes/K, new_mem_size/K);
     }
   }
@@ -9203,7 +9203,7 @@
       if (Verbose && PrintGCDetails) {
         size_t new_mem_size = _virtual_space.committed_size();
         size_t old_mem_size = new_mem_size + bytes;
-        gclog_or_tty->print_cr("Shrinking %s from %ldK by %ldK to %ldK",
+        gclog_or_tty->print_cr("Shrinking %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K",
                       name(), old_mem_size/K, bytes/K, new_mem_size/K);
       }
     }
--- a/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -85,7 +85,7 @@
     _curr_index(0), _length(0), _first_par_unreserved_idx(0),
     _region_live_threshold_bytes(0), _remaining_reclaimable_bytes(0) {
   _region_live_threshold_bytes =
-    HeapRegion::GrainBytes * (size_t) G1OldCSetRegionLiveThresholdPercent / 100;
+    HeapRegion::GrainBytes * (size_t) G1MixedGCLiveThresholdPercent / 100;
 }
 
 #ifndef PRODUCT
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -192,6 +192,7 @@
   setEmpty();
   _capacity = (jint) capacity;
   _saved_index = -1;
+  _should_expand = false;
   NOT_PRODUCT(_max_depth = 0);
   return true;
 }
@@ -747,8 +748,8 @@
   assert(_heap_end != NULL, "heap bounds should look ok");
   assert(_heap_start < _heap_end, "heap bounds should look ok");
 
-  // reset all the marking data structures and any necessary flags
-  clear_marking_state();
+  // Reset all the marking data structures and any necessary flags
+  reset_marking_state();
 
   if (verbose_low()) {
     gclog_or_tty->print_cr("[global] resetting");
@@ -766,6 +767,23 @@
   set_concurrent_marking_in_progress();
 }
 
+
+void ConcurrentMark::reset_marking_state(bool clear_overflow) {
+  _markStack.set_should_expand();
+  _markStack.setEmpty();        // Also clears the _markStack overflow flag
+  if (clear_overflow) {
+    clear_has_overflown();
+  } else {
+    assert(has_overflown(), "pre-condition");
+  }
+  _finger = _heap_start;
+
+  for (uint i = 0; i < _max_worker_id; ++i) {
+    CMTaskQueue* queue = _task_queues->queue(i);
+    queue->set_empty();
+  }
+}
+
 void ConcurrentMark::set_phase(uint active_tasks, bool concurrent) {
   assert(active_tasks <= _max_worker_id, "we should not have more");
 
@@ -796,7 +814,7 @@
 void ConcurrentMark::set_non_marking_state() {
   // We set the global marking state to some default values when we're
   // not doing marking.
-  clear_marking_state();
+  reset_marking_state();
   _active_tasks = 0;
   clear_concurrent_marking_in_progress();
 }
@@ -963,7 +981,7 @@
     // not clear the overflow flag since we rely on it being true when
     // we exit this method to abort the pause and restart concurent
     // marking.
-    clear_marking_state(concurrent() /* clear_overflow */);
+    reset_marking_state(concurrent() /* clear_overflow */);
     force_overflow()->update();
 
     if (G1Log::fine()) {
@@ -1257,8 +1275,9 @@
   if (has_overflown()) {
     // Oops.  We overflowed.  Restart concurrent marking.
     _restart_for_overflow = true;
-    // Clear the flag. We do not need it any more.
-    clear_has_overflown();
+    // Clear the marking state because we will be restarting
+    // marking due to overflowing the global mark stack.
+    reset_marking_state();
     if (G1TraceMarkStackOverflow) {
       gclog_or_tty->print_cr("\nRemark led to restart for overflow.");
     }
@@ -1282,6 +1301,8 @@
                        /* option */ VerifyOption_G1UseNextMarking);
     }
     assert(!restart_for_overflow(), "sanity");
+    // Completely reset the marking state since marking completed
+    set_non_marking_state();
   }
 
   // Expand the marking stack, if we have to and if we can.
@@ -1289,11 +1310,6 @@
     _markStack.expand();
   }
 
-  // Reset the marking state if marking completed
-  if (!restart_for_overflow()) {
-    set_non_marking_state();
-  }
-
 #if VERIFY_OBJS_PROCESSED
   _scan_obj_cl.objs_processed = 0;
   ThreadLocalObjQueue::objs_enqueued = 0;
@@ -2963,22 +2979,6 @@
 }
 #endif // PRODUCT
 
-void ConcurrentMark::clear_marking_state(bool clear_overflow) {
-  _markStack.set_should_expand();
-  _markStack.setEmpty();        // Also clears the _markStack overflow flag
-  if (clear_overflow) {
-    clear_has_overflown();
-  } else {
-    assert(has_overflown(), "pre-condition");
-  }
-  _finger = _heap_start;
-
-  for (uint i = 0; i < _max_worker_id; ++i) {
-    CMTaskQueue* queue = _task_queues->queue(i);
-    queue->set_empty();
-  }
-}
-
 // Aggregate the counting data that was constructed concurrently
 // with marking.
 class AggregateCountDataHRClosure: public HeapRegionClosure {
@@ -3185,7 +3185,7 @@
   // Clear the liveness counting data
   clear_all_count_data();
   // Empty mark stack
-  clear_marking_state();
+  reset_marking_state();
   for (uint i = 0; i < _max_worker_id; ++i) {
     _tasks[i]->clear_region_fields();
   }
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -478,15 +478,18 @@
   // It resets the global marking data structures, as well as the
   // task local ones; should be called during initial mark.
   void reset();
-  // It resets all the marking data structures.
-  void clear_marking_state(bool clear_overflow = true);
+
+  // Resets all the marking data structures. Called when we have to restart
+  // marking or when marking completes (via set_non_marking_state below).
+  void reset_marking_state(bool clear_overflow = true);
+
+  // We do this after we're done with marking so that the marking data
+  // structures are initialised to a sensible and predictable state.
+  void set_non_marking_state();
 
   // It should be called to indicate which phase we're in (concurrent
   // mark or remark) and how many threads are currently active.
   void set_phase(uint active_tasks, bool concurrent);
-  // We do this after we're done with marking so that the marking data
-  // structures are initialised to a sensible and predictable state.
-  void set_non_marking_state();
 
   // prints all gathered CM-related statistics
   void print_stats();
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -159,13 +159,11 @@
           VM_CGC_Operation op(&final_cl, verbose_str, true /* needs_pll */);
           VMThread::execute(&op);
         }
-        if (cm()->restart_for_overflow() &&
-            G1TraceMarkStackOverflow) {
-          gclog_or_tty->print_cr("Restarting conc marking because of MS overflow "
-                                 "in remark (restart #%d).", iter);
-        }
-
         if (cm()->restart_for_overflow()) {
+          if (G1TraceMarkStackOverflow) {
+            gclog_or_tty->print_cr("Restarting conc marking because of MS overflow "
+                                   "in remark (restart #%d).", iter);
+          }
           if (G1Log::fine()) {
             gclog_or_tty->date_stamp(PrintGCDateStamps);
             gclog_or_tty->stamp(PrintGCTimeStamps);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -3668,7 +3668,7 @@
   gclog_or_tty->stamp(PrintGCTimeStamps);
 
   GCCauseString gc_cause_str = GCCauseString("GC pause", gc_cause())
-    .append(g1_policy()->gcs_are_young() ? " (young)" : " (mixed)")
+    .append(g1_policy()->gcs_are_young() ? "(young)" : "(mixed)")
     .append(g1_policy()->during_initial_mark_pause() ? " (initial-mark)" : "");
 
   gclog_or_tty->print("[%s", (const char*)gc_cause_str);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -309,9 +309,9 @@
 }
 
 G1YoungGenSizer::G1YoungGenSizer() : _sizer_kind(SizerDefaults), _adaptive_size(true) {
-  assert(G1DefaultMinNewGenPercent <= G1DefaultMaxNewGenPercent, "Min larger than max");
-  assert(G1DefaultMinNewGenPercent > 0 && G1DefaultMinNewGenPercent < 100, "Min out of bounds");
-  assert(G1DefaultMaxNewGenPercent > 0 && G1DefaultMaxNewGenPercent < 100, "Max out of bounds");
+  assert(G1NewSizePercent <= G1MaxNewSizePercent, "Min larger than max");
+  assert(G1NewSizePercent > 0 && G1NewSizePercent < 100, "Min out of bounds");
+  assert(G1MaxNewSizePercent > 0 && G1MaxNewSizePercent < 100, "Max out of bounds");
 
   if (FLAG_IS_CMDLINE(NewRatio)) {
     if (FLAG_IS_CMDLINE(NewSize) || FLAG_IS_CMDLINE(MaxNewSize)) {
@@ -344,12 +344,12 @@
 }
 
 uint G1YoungGenSizer::calculate_default_min_length(uint new_number_of_heap_regions) {
-  uint default_value = (new_number_of_heap_regions * G1DefaultMinNewGenPercent) / 100;
+  uint default_value = (new_number_of_heap_regions * G1NewSizePercent) / 100;
   return MAX2(1U, default_value);
 }
 
 uint G1YoungGenSizer::calculate_default_max_length(uint new_number_of_heap_regions) {
-  uint default_value = (new_number_of_heap_regions * G1DefaultMaxNewGenPercent) / 100;
+  uint default_value = (new_number_of_heap_regions * G1MaxNewSizePercent) / 100;
   return MAX2(1U, default_value);
 }
 
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -94,18 +94,18 @@
 // will occur.
 //
 // If nothing related to the the young gen size is set on the command
-// line we should allow the young gen to be between
-// G1DefaultMinNewGenPercent and G1DefaultMaxNewGenPercent of the
-// heap size. This means that every time the heap size changes the
-// limits for the young gen size will be updated.
+// line we should allow the young gen to be between G1NewSizePercent
+// and G1MaxNewSizePercent of the heap size. This means that every time
+// the heap size changes, the limits for the young gen size will be
+// recalculated.
 //
 // If only -XX:NewSize is set we should use the specified value as the
-// minimum size for young gen. Still using G1DefaultMaxNewGenPercent
-// of the heap as maximum.
+// minimum size for young gen. Still using G1MaxNewSizePercent of the
+// heap as maximum.
 //
 // If only -XX:MaxNewSize is set we should use the specified value as the
-// maximum size for young gen. Still using G1DefaultMinNewGenPercent
-// of the heap as minimum.
+// maximum size for young gen. Still using G1NewSizePercent of the heap
+// as minimum.
 //
 // If -XX:NewSize and -XX:MaxNewSize are both specified we use these values.
 // No updates when the heap size changes. There is a special case when
--- a/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -282,10 +282,8 @@
       if (r->startsHumongous()) {
         // We must adjust the pointers on the single H object.
         oop obj = oop(r->bottom());
-        debug_only(GenMarkSweep::track_interior_pointers(obj));
         // point all the oops to the new location
         obj->adjust_pointers();
-        debug_only(GenMarkSweep::check_interior_pointers());
       }
     } else {
       // This really ought to be "as_CompactibleSpace"...
--- a/hotspot/src/share/vm/gc_implementation/g1/g1_globals.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1_globals.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -287,23 +287,24 @@
           "The number of times we'll force an overflow during "             \
           "concurrent marking")                                             \
                                                                             \
-  experimental(uintx, G1DefaultMinNewGenPercent, 20,                        \
-          "Percentage (0-100) of the heap size to use as minimum "          \
-          "young gen size.")                                                \
+  experimental(uintx, G1NewSizePercent, 5,                                  \
+          "Percentage (0-100) of the heap size to use as default "          \
+          "minimum young gen size.")                                        \
                                                                             \
-  experimental(uintx, G1DefaultMaxNewGenPercent, 80,                        \
-          "Percentage (0-100) of the heap size to use as maximum "          \
-          "young gen size.")                                                \
+  experimental(uintx, G1MaxNewSizePercent, 60,                              \
+          "Percentage (0-100) of the heap size to use as default "          \
+          " maximum young gen size.")                                       \
                                                                             \
-  experimental(uintx, G1OldCSetRegionLiveThresholdPercent, 90,              \
-          "Threshold for regions to be added to the collection set. "       \
-          "Regions with more live bytes than this will not be collected.")  \
+  experimental(uintx, G1MixedGCLiveThresholdPercent, 65,                    \
+          "Threshold for regions to be considered for inclusion in the "    \
+          "collection set of mixed GCs. "                                   \
+          "Regions with live bytes exceeding this will not be collected.")  \
                                                                             \
-  product(uintx, G1HeapWastePercent, 5,                                     \
+  product(uintx, G1HeapWastePercent, 10,                                    \
           "Amount of space, expressed as a percentage of the heap size, "   \
           "that G1 is willing not to collect to avoid expensive GCs.")      \
                                                                             \
-  product(uintx, G1MixedGCCountTarget, 4,                                   \
+  product(uintx, G1MixedGCCountTarget, 8,                                   \
           "The target number of mixed GCs after a marking cycle.")          \
                                                                             \
   experimental(uintx, G1OldCSetRegionThresholdPercent, 10,                  \
--- a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -878,12 +878,6 @@
 
 bool ParNewGeneration::_avoid_promotion_undo = false;
 
-void ParNewGeneration::adjust_desired_tenuring_threshold() {
-  // Set the desired survivor size to half the real survivor space
-  _tenuring_threshold =
-    age_table()->compute_tenuring_threshold(to()->capacity()/HeapWordSize);
-}
-
 // A Generation that does parallel young-gen collection.
 
 void ParNewGeneration::collect(bool   full,
@@ -1013,6 +1007,8 @@
     size_policy->reset_gc_overhead_limit_count();
 
     assert(to()->is_empty(), "to space should be empty now");
+
+    adjust_desired_tenuring_threshold();
   } else {
     assert(_promo_failure_scan_stack.is_empty(), "post condition");
     _promo_failure_scan_stack.clear(true); // Clear cached segments.
@@ -1035,7 +1031,6 @@
   from()->set_concurrent_iteration_safe_limit(from()->top());
   to()->set_concurrent_iteration_safe_limit(to()->top());
 
-  adjust_desired_tenuring_threshold();
   if (ResizePLAB) {
     plab_stats()->adjust_desired_plab_sz(n_workers);
   }
@@ -1623,7 +1618,3 @@
 const char* ParNewGeneration::name() const {
   return "par new generation";
 }
-
-bool ParNewGeneration::in_use() {
-  return UseParNewGC && ParallelGCThreads > 0;
-}
--- a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -347,10 +347,6 @@
   bool survivor_overflow() { return _survivor_overflow; }
   void set_survivor_overflow(bool v) { _survivor_overflow = v; }
 
-  // Adjust the tenuring threshold.  See the implementation for
-  // the details of the policy.
-  virtual void adjust_desired_tenuring_threshold();
-
  public:
   ParNewGeneration(ReservedSpace rs, size_t initial_byte_size, int level);
 
@@ -361,8 +357,6 @@
     delete _task_queues;
   }
 
-  static bool in_use();
-
   virtual void ref_processor_init();
   virtual Generation::Name kind()        { return Generation::ParNew; }
   virtual const char* name() const;
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweepDecorator.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweepDecorator.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -164,7 +164,6 @@
         start_array->allocate_block(compact_top);
       }
 
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::register_live_oop(oop(q), size));
       compact_top += size;
       assert(compact_top <= dest->space()->end(),
         "Exceeding space in destination");
@@ -225,7 +224,6 @@
             start_array->allocate_block(compact_top);
           }
 
-          VALIDATE_MARK_SWEEP_ONLY(MarkSweep::register_live_oop(oop(q), sz));
           compact_top += sz;
           assert(compact_top <= dest->space()->end(),
             "Exceeding space in destination");
@@ -304,11 +302,8 @@
     HeapWord* end = _first_dead;
 
     while (q < end) {
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::track_interior_pointers(oop(q)));
       // point all the oops to the new location
       size_t size = oop(q)->adjust_pointers();
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::check_interior_pointers());
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::validate_live_oop(oop(q), size));
       q += size;
     }
 
@@ -328,11 +323,8 @@
     Prefetch::write(q, interval);
     if (oop(q)->is_gc_marked()) {
       // q is alive
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::track_interior_pointers(oop(q)));
       // point all the oops to the new location
       size_t size = oop(q)->adjust_pointers();
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::check_interior_pointers());
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::validate_live_oop(oop(q), size));
       debug_only(prev_q = q);
       q += size;
     } else {
@@ -366,7 +358,6 @@
     while (q < end) {
       size_t size = oop(q)->size();
       assert(!oop(q)->is_gc_marked(), "should be unmarked (special dense prefix handling)");
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::live_oop_moved_to(q, size, q));
       debug_only(prev_q = q);
       q += size;
     }
@@ -401,7 +392,6 @@
       Prefetch::write(compaction_top, copy_interval);
 
       // copy object and reinit its mark
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::live_oop_moved_to(q, size, compaction_top));
       assert(q != compaction_top, "everything in this pass should be moving");
       Copy::aligned_conjoint_words(q, compaction_top, size);
       oop(compaction_top)->init_mark();
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -99,25 +99,6 @@
 bool   PSParallelCompact::_dwl_initialized = false;
 #endif  // #ifdef ASSERT
 
-#ifdef VALIDATE_MARK_SWEEP
-GrowableArray<void*>*   PSParallelCompact::_root_refs_stack = NULL;
-GrowableArray<oop> *    PSParallelCompact::_live_oops = NULL;
-GrowableArray<oop> *    PSParallelCompact::_live_oops_moved_to = NULL;
-GrowableArray<size_t>*  PSParallelCompact::_live_oops_size = NULL;
-size_t                  PSParallelCompact::_live_oops_index = 0;
-GrowableArray<void*>*   PSParallelCompact::_other_refs_stack = NULL;
-GrowableArray<void*>*   PSParallelCompact::_adjusted_pointers = NULL;
-bool                    PSParallelCompact::_pointer_tracking = false;
-bool                    PSParallelCompact::_root_tracking = true;
-
-GrowableArray<HeapWord*>* PSParallelCompact::_cur_gc_live_oops = NULL;
-GrowableArray<HeapWord*>* PSParallelCompact::_cur_gc_live_oops_moved_to = NULL;
-GrowableArray<size_t>   * PSParallelCompact::_cur_gc_live_oops_size = NULL;
-GrowableArray<HeapWord*>* PSParallelCompact::_last_gc_live_oops = NULL;
-GrowableArray<HeapWord*>* PSParallelCompact::_last_gc_live_oops_moved_to = NULL;
-GrowableArray<size_t>   * PSParallelCompact::_last_gc_live_oops_size = NULL;
-#endif
-
 void SplitInfo::record(size_t src_region_idx, size_t partial_obj_size,
                        HeapWord* destination)
 {
@@ -2715,151 +2696,6 @@
 }
 #endif  // #ifdef ASSERT
 
-
-#ifdef VALIDATE_MARK_SWEEP
-
-void PSParallelCompact::track_adjusted_pointer(void* p, bool isroot) {
-  if (!ValidateMarkSweep)
-    return;
-
-  if (!isroot) {
-    if (_pointer_tracking) {
-      guarantee(_adjusted_pointers->contains(p), "should have seen this pointer");
-      _adjusted_pointers->remove(p);
-    }
-  } else {
-    ptrdiff_t index = _root_refs_stack->find(p);
-    if (index != -1) {
-      int l = _root_refs_stack->length();
-      if (l > 0 && l - 1 != index) {
-        void* last = _root_refs_stack->pop();
-        assert(last != p, "should be different");
-        _root_refs_stack->at_put(index, last);
-      } else {
-        _root_refs_stack->remove(p);
-      }
-    }
-  }
-}
-
-
-void PSParallelCompact::check_adjust_pointer(void* p) {
-  _adjusted_pointers->push(p);
-}
-
-
-class AdjusterTracker: public OopClosure {
- public:
-  AdjusterTracker() {};
-  void do_oop(oop* o)         { PSParallelCompact::check_adjust_pointer(o); }
-  void do_oop(narrowOop* o)   { PSParallelCompact::check_adjust_pointer(o); }
-};
-
-
-void PSParallelCompact::track_interior_pointers(oop obj) {
-  if (ValidateMarkSweep) {
-    _adjusted_pointers->clear();
-    _pointer_tracking = true;
-
-    AdjusterTracker checker;
-    obj->oop_iterate_no_header(&checker);
-  }
-}
-
-
-void PSParallelCompact::check_interior_pointers() {
-  if (ValidateMarkSweep) {
-    _pointer_tracking = false;
-    guarantee(_adjusted_pointers->length() == 0, "should have processed the same pointers");
-  }
-}
-
-
-void PSParallelCompact::reset_live_oop_tracking() {
-  if (ValidateMarkSweep) {
-    guarantee((size_t)_live_oops->length() == _live_oops_index, "should be at end of live oops");
-    _live_oops_index = 0;
-  }
-}
-
-
-void PSParallelCompact::register_live_oop(oop p, size_t size) {
-  if (ValidateMarkSweep) {
-    _live_oops->push(p);
-    _live_oops_size->push(size);
-    _live_oops_index++;
-  }
-}
-
-void PSParallelCompact::validate_live_oop(oop p, size_t size) {
-  if (ValidateMarkSweep) {
-    oop obj = _live_oops->at((int)_live_oops_index);
-    guarantee(obj == p, "should be the same object");
-    guarantee(_live_oops_size->at((int)_live_oops_index) == size, "should be the same size");
-    _live_oops_index++;
-  }
-}
-
-void PSParallelCompact::live_oop_moved_to(HeapWord* q, size_t size,
-                                  HeapWord* compaction_top) {
-  assert(oop(q)->forwardee() == NULL || oop(q)->forwardee() == oop(compaction_top),
-         "should be moved to forwarded location");
-  if (ValidateMarkSweep) {
-    PSParallelCompact::validate_live_oop(oop(q), size);
-    _live_oops_moved_to->push(oop(compaction_top));
-  }
-  if (RecordMarkSweepCompaction) {
-    _cur_gc_live_oops->push(q);
-    _cur_gc_live_oops_moved_to->push(compaction_top);
-    _cur_gc_live_oops_size->push(size);
-  }
-}
-
-
-void PSParallelCompact::compaction_complete() {
-  if (RecordMarkSweepCompaction) {
-    GrowableArray<HeapWord*>* _tmp_live_oops          = _cur_gc_live_oops;
-    GrowableArray<HeapWord*>* _tmp_live_oops_moved_to = _cur_gc_live_oops_moved_to;
-    GrowableArray<size_t>   * _tmp_live_oops_size     = _cur_gc_live_oops_size;
-
-    _cur_gc_live_oops           = _last_gc_live_oops;
-    _cur_gc_live_oops_moved_to  = _last_gc_live_oops_moved_to;
-    _cur_gc_live_oops_size      = _last_gc_live_oops_size;
-    _last_gc_live_oops          = _tmp_live_oops;
-    _last_gc_live_oops_moved_to = _tmp_live_oops_moved_to;
-    _last_gc_live_oops_size     = _tmp_live_oops_size;
-  }
-}
-
-
-void PSParallelCompact::print_new_location_of_heap_address(HeapWord* q) {
-  if (!RecordMarkSweepCompaction) {
-    tty->print_cr("Requires RecordMarkSweepCompaction to be enabled");
-    return;
-  }
-
-  if (_last_gc_live_oops == NULL) {
-    tty->print_cr("No compaction information gathered yet");
-    return;
-  }
-
-  for (int i = 0; i < _last_gc_live_oops->length(); i++) {
-    HeapWord* old_oop = _last_gc_live_oops->at(i);
-    size_t    sz      = _last_gc_live_oops_size->at(i);
-    if (old_oop <= q && q < (old_oop + sz)) {
-      HeapWord* new_oop = _last_gc_live_oops_moved_to->at(i);
-      size_t offset = (q - old_oop);
-      tty->print_cr("Address " PTR_FORMAT, q);
-      tty->print_cr(" Was in oop " PTR_FORMAT ", size %d, at offset %d", old_oop, sz, offset);
-      tty->print_cr(" Now in oop " PTR_FORMAT ", actual address " PTR_FORMAT, new_oop, new_oop + offset);
-      return;
-    }
-  }
-
-  tty->print_cr("Address " PTR_FORMAT " not found in live oop information from last GC", q);
-}
-#endif //VALIDATE_MARK_SWEEP
-
 // Update interior oops in the ranges of regions [beg_region, end_region).
 void
 PSParallelCompact::update_and_deadwood_in_dense_prefix(ParCompactionManager* cm,
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1006,34 +1006,6 @@
   // Reset time since last full gc
   static void reset_millis_since_last_gc();
 
- protected:
-#ifdef VALIDATE_MARK_SWEEP
-  static GrowableArray<void*>*           _root_refs_stack;
-  static GrowableArray<oop> *            _live_oops;
-  static GrowableArray<oop> *            _live_oops_moved_to;
-  static GrowableArray<size_t>*          _live_oops_size;
-  static size_t                          _live_oops_index;
-  static size_t                          _live_oops_index_at_perm;
-  static GrowableArray<void*>*           _other_refs_stack;
-  static GrowableArray<void*>*           _adjusted_pointers;
-  static bool                            _pointer_tracking;
-  static bool                            _root_tracking;
-
-  // The following arrays are saved since the time of the last GC and
-  // assist in tracking down problems where someone has done an errant
-  // store into the heap, usually to an oop that wasn't properly
-  // handleized across a GC. If we crash or otherwise fail before the
-  // next GC, we can query these arrays to find out the object we had
-  // intended to do the store to (assuming it is still alive) and the
-  // offset within that object. Covered under RecordMarkSweepCompaction.
-  static GrowableArray<HeapWord*> *      _cur_gc_live_oops;
-  static GrowableArray<HeapWord*> *      _cur_gc_live_oops_moved_to;
-  static GrowableArray<size_t>*          _cur_gc_live_oops_size;
-  static GrowableArray<HeapWord*> *      _last_gc_live_oops;
-  static GrowableArray<HeapWord*> *      _last_gc_live_oops_moved_to;
-  static GrowableArray<size_t>*          _last_gc_live_oops_size;
-#endif
-
  public:
   class MarkAndPushClosure: public OopClosure {
    private:
@@ -1191,25 +1163,6 @@
   // Time since last full gc (in milliseconds).
   static jlong millis_since_last_gc();
 
-#ifdef VALIDATE_MARK_SWEEP
-  static void track_adjusted_pointer(void* p, bool isroot);
-  static void check_adjust_pointer(void* p);
-  static void track_interior_pointers(oop obj);
-  static void check_interior_pointers();
-
-  static void reset_live_oop_tracking();
-  static void register_live_oop(oop p, size_t size);
-  static void validate_live_oop(oop p, size_t size);
-  static void live_oop_moved_to(HeapWord* q, size_t size, HeapWord* compaction_top);
-  static void compaction_complete();
-
-  // Querying operation of RecordMarkSweepCompaction results.
-  // Finds and prints the current base oop and offset for a word
-  // within an oop that was live during the last GC. Helpful for
-  // tracking down heap stomps.
-  static void print_new_location_of_heap_address(HeapWord* q);
-#endif  // #ifdef VALIDATE_MARK_SWEEP
-
 #ifndef PRODUCT
   // Debugging support.
   static const char* space_names[last_space_id];
@@ -1250,12 +1203,7 @@
 inline void PSParallelCompact::follow_root(ParCompactionManager* cm, T* p) {
   assert(!Universe::heap()->is_in_reserved(p),
          "roots shouldn't be things within the heap");
-#ifdef VALIDATE_MARK_SWEEP
-  if (ValidateMarkSweep) {
-    guarantee(!_root_refs_stack->contains(p), "should only be in here once");
-    _root_refs_stack->push(p);
-  }
-#endif
+
   T heap_oop = oopDesc::load_heap_oop(p);
   if (!oopDesc::is_null(heap_oop)) {
     oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
@@ -1294,20 +1242,10 @@
       oopDesc::encode_store_heap_oop_not_null(p, new_obj);
     }
   }
-  VALIDATE_MARK_SWEEP_ONLY(track_adjusted_pointer(p, isroot));
 }
 
 template <class T>
 inline void PSParallelCompact::KeepAliveClosure::do_oop_work(T* p) {
-#ifdef VALIDATE_MARK_SWEEP
-  if (ValidateMarkSweep) {
-    if (!Universe::heap()->is_in_reserved(p)) {
-      _root_refs_stack->push(p);
-    } else {
-      _other_refs_stack->push(p);
-    }
-  }
-#endif
   mark_and_push(_compaction_manager, p);
 }
 
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -529,7 +529,7 @@
 
        if (PrintTenuringDistribution) {
          gclog_or_tty->cr();
-         gclog_or_tty->print_cr("Desired survivor size %ld bytes, new threshold %u (max %u)",
+         gclog_or_tty->print_cr("Desired survivor size " SIZE_FORMAT " bytes, new threshold %u (max %u)",
                                 size_policy->calculated_survivor_size_in_bytes(),
                                 _tenuring_threshold, MaxTenuringThreshold);
        }
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -808,8 +808,9 @@
   st->print("  to  "); to_space()->print_on(st);
 }
 
+// Note that a space is not printed before the [NAME:
 void PSYoungGen::print_used_change(size_t prev_used) const {
-  gclog_or_tty->print(" [%s:", name());
+  gclog_or_tty->print("[%s:", name());
   gclog_or_tty->print(" "  SIZE_FORMAT "K"
                       "->" SIZE_FORMAT "K"
                       "("  SIZE_FORMAT "K)",
--- a/hotspot/src/share/vm/gc_implementation/shared/ageTable.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/shared/ageTable.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -96,7 +96,7 @@
 
     if (PrintTenuringDistribution) {
       gclog_or_tty->cr();
-      gclog_or_tty->print_cr("Desired survivor size %ld bytes, new threshold %u (max %u)",
+      gclog_or_tty->print_cr("Desired survivor size " SIZE_FORMAT " bytes, new threshold %u (max %u)",
         desired_survivor_size*oopSize, result, MaxTenuringThreshold);
     }
 
--- a/hotspot/src/share/vm/gc_implementation/shared/markSweep.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/shared/markSweep.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -42,26 +42,6 @@
 PreservedMark*          MarkSweep::_preserved_marks = NULL;
 ReferenceProcessor*     MarkSweep::_ref_processor   = NULL;
 
-#ifdef VALIDATE_MARK_SWEEP
-GrowableArray<void*>*   MarkSweep::_root_refs_stack = NULL;
-GrowableArray<oop> *    MarkSweep::_live_oops = NULL;
-GrowableArray<oop> *    MarkSweep::_live_oops_moved_to = NULL;
-GrowableArray<size_t>*  MarkSweep::_live_oops_size = NULL;
-size_t                  MarkSweep::_live_oops_index = 0;
-size_t                  MarkSweep::_live_oops_index_at_perm = 0;
-GrowableArray<void*>*   MarkSweep::_other_refs_stack = NULL;
-GrowableArray<void*>*   MarkSweep::_adjusted_pointers = NULL;
-bool                         MarkSweep::_pointer_tracking = false;
-bool                         MarkSweep::_root_tracking = true;
-
-GrowableArray<HeapWord*>* MarkSweep::_cur_gc_live_oops = NULL;
-GrowableArray<HeapWord*>* MarkSweep::_cur_gc_live_oops_moved_to = NULL;
-GrowableArray<size_t>   * MarkSweep::_cur_gc_live_oops_size = NULL;
-GrowableArray<HeapWord*>* MarkSweep::_last_gc_live_oops = NULL;
-GrowableArray<HeapWord*>* MarkSweep::_last_gc_live_oops_moved_to = NULL;
-GrowableArray<size_t>   * MarkSweep::_last_gc_live_oops_size = NULL;
-#endif
-
 MarkSweep::FollowRootClosure  MarkSweep::follow_root_closure;
 CodeBlobToOopClosure MarkSweep::follow_code_root_closure(&MarkSweep::follow_root_closure, /*do_marking=*/ true);
 
@@ -185,142 +165,6 @@
   }
 }
 
-#ifdef VALIDATE_MARK_SWEEP
-
-void MarkSweep::track_adjusted_pointer(void* p, bool isroot) {
-  if (!ValidateMarkSweep)
-    return;
-
-  if (!isroot) {
-    if (_pointer_tracking) {
-      guarantee(_adjusted_pointers->contains(p), "should have seen this pointer");
-      _adjusted_pointers->remove(p);
-    }
-  } else {
-    ptrdiff_t index = _root_refs_stack->find(p);
-    if (index != -1) {
-      int l = _root_refs_stack->length();
-      if (l > 0 && l - 1 != index) {
-        void* last = _root_refs_stack->pop();
-        assert(last != p, "should be different");
-        _root_refs_stack->at_put(index, last);
-      } else {
-        _root_refs_stack->remove(p);
-      }
-    }
-  }
-}
-
-void MarkSweep::check_adjust_pointer(void* p) {
-  _adjusted_pointers->push(p);
-}
-
-class AdjusterTracker: public OopClosure {
- public:
-  AdjusterTracker() {}
-  void do_oop(oop* o)       { MarkSweep::check_adjust_pointer(o); }
-  void do_oop(narrowOop* o) { MarkSweep::check_adjust_pointer(o); }
-};
-
-void MarkSweep::track_interior_pointers(oop obj) {
-  if (ValidateMarkSweep) {
-    _adjusted_pointers->clear();
-    _pointer_tracking = true;
-
-    AdjusterTracker checker;
-    obj->oop_iterate_no_header(&checker);
-  }
-}
-
-void MarkSweep::check_interior_pointers() {
-  if (ValidateMarkSweep) {
-    _pointer_tracking = false;
-    guarantee(_adjusted_pointers->length() == 0, "should have processed the same pointers");
-  }
-}
-
-void MarkSweep::reset_live_oop_tracking() {
-  if (ValidateMarkSweep) {
-    guarantee((size_t)_live_oops->length() == _live_oops_index, "should be at end of live oops");
-    _live_oops_index = 0;
-  }
-}
-
-void MarkSweep::register_live_oop(oop p, size_t size) {
-  if (ValidateMarkSweep) {
-    _live_oops->push(p);
-    _live_oops_size->push(size);
-    _live_oops_index++;
-  }
-}
-
-void MarkSweep::validate_live_oop(oop p, size_t size) {
-  if (ValidateMarkSweep) {
-    oop obj = _live_oops->at((int)_live_oops_index);
-    guarantee(obj == p, "should be the same object");
-    guarantee(_live_oops_size->at((int)_live_oops_index) == size, "should be the same size");
-    _live_oops_index++;
-  }
-}
-
-void MarkSweep::live_oop_moved_to(HeapWord* q, size_t size,
-                                  HeapWord* compaction_top) {
-  assert(oop(q)->forwardee() == NULL || oop(q)->forwardee() == oop(compaction_top),
-         "should be moved to forwarded location");
-  if (ValidateMarkSweep) {
-    MarkSweep::validate_live_oop(oop(q), size);
-    _live_oops_moved_to->push(oop(compaction_top));
-  }
-  if (RecordMarkSweepCompaction) {
-    _cur_gc_live_oops->push(q);
-    _cur_gc_live_oops_moved_to->push(compaction_top);
-    _cur_gc_live_oops_size->push(size);
-  }
-}
-
-void MarkSweep::compaction_complete() {
-  if (RecordMarkSweepCompaction) {
-    GrowableArray<HeapWord*>* _tmp_live_oops          = _cur_gc_live_oops;
-    GrowableArray<HeapWord*>* _tmp_live_oops_moved_to = _cur_gc_live_oops_moved_to;
-    GrowableArray<size_t>   * _tmp_live_oops_size     = _cur_gc_live_oops_size;
-
-    _cur_gc_live_oops           = _last_gc_live_oops;
-    _cur_gc_live_oops_moved_to  = _last_gc_live_oops_moved_to;
-    _cur_gc_live_oops_size      = _last_gc_live_oops_size;
-    _last_gc_live_oops          = _tmp_live_oops;
-    _last_gc_live_oops_moved_to = _tmp_live_oops_moved_to;
-    _last_gc_live_oops_size     = _tmp_live_oops_size;
-  }
-}
-
-void MarkSweep::print_new_location_of_heap_address(HeapWord* q) {
-  if (!RecordMarkSweepCompaction) {
-    tty->print_cr("Requires RecordMarkSweepCompaction to be enabled");
-    return;
-  }
-
-  if (_last_gc_live_oops == NULL) {
-    tty->print_cr("No compaction information gathered yet");
-    return;
-  }
-
-  for (int i = 0; i < _last_gc_live_oops->length(); i++) {
-    HeapWord* old_oop = _last_gc_live_oops->at(i);
-    size_t    sz      = _last_gc_live_oops_size->at(i);
-    if (old_oop <= q && q < (old_oop + sz)) {
-      HeapWord* new_oop = _last_gc_live_oops_moved_to->at(i);
-      size_t offset = (q - old_oop);
-      tty->print_cr("Address " PTR_FORMAT, q);
-      tty->print_cr(" Was in oop " PTR_FORMAT ", size " SIZE_FORMAT ", at offset " SIZE_FORMAT, old_oop, sz, offset);
-      tty->print_cr(" Now in oop " PTR_FORMAT ", actual address " PTR_FORMAT, new_oop, new_oop + offset);
-      return;
-    }
-  }
-
-  tty->print_cr("Address " PTR_FORMAT " not found in live oop information from last GC", q);
-}
-#endif //VALIDATE_MARK_SWEEP
-
 MarkSweep::IsAliveClosure   MarkSweep::is_alive;
 
 void MarkSweep::IsAliveClosure::do_object(oop p)   { ShouldNotReachHere(); }
--- a/hotspot/src/share/vm/gc_implementation/shared/markSweep.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/shared/markSweep.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -44,21 +44,6 @@
 //
 // Class unloading will only occur when a full gc is invoked.
 
-// If VALIDATE_MARK_SWEEP is defined, the -XX:+ValidateMarkSweep flag will
-// be operational, and will provide slow but comprehensive self-checks within
-// the GC.  This is not enabled by default in product or release builds,
-// since the extra call to track_adjusted_pointer() in _adjust_pointer()
-// would be too much overhead, and would disturb performance measurement.
-// However, debug builds are sometimes way too slow to run GC tests!
-#ifdef ASSERT
-#define VALIDATE_MARK_SWEEP 1
-#endif
-#ifdef VALIDATE_MARK_SWEEP
-#define VALIDATE_MARK_SWEEP_ONLY(code) code
-#else
-#define VALIDATE_MARK_SWEEP_ONLY(code)
-#endif
-
 // declared at end
 class PreservedMark;
 
@@ -147,33 +132,6 @@
   // Reference processing (used in ...follow_contents)
   static ReferenceProcessor*             _ref_processor;
 
-#ifdef VALIDATE_MARK_SWEEP
-  static GrowableArray<void*>*           _root_refs_stack;
-  static GrowableArray<oop> *            _live_oops;
-  static GrowableArray<oop> *            _live_oops_moved_to;
-  static GrowableArray<size_t>*          _live_oops_size;
-  static size_t                          _live_oops_index;
-  static size_t                          _live_oops_index_at_perm;
-  static GrowableArray<void*>*           _other_refs_stack;
-  static GrowableArray<void*>*           _adjusted_pointers;
-  static bool                            _pointer_tracking;
-  static bool                            _root_tracking;
-
-  // The following arrays are saved since the time of the last GC and
-  // assist in tracking down problems where someone has done an errant
-  // store into the heap, usually to an oop that wasn't properly
-  // handleized across a GC. If we crash or otherwise fail before the
-  // next GC, we can query these arrays to find out the object we had
-  // intended to do the store to (assuming it is still alive) and the
-  // offset within that object. Covered under RecordMarkSweepCompaction.
-  static GrowableArray<HeapWord*> *      _cur_gc_live_oops;
-  static GrowableArray<HeapWord*> *      _cur_gc_live_oops_moved_to;
-  static GrowableArray<size_t>*          _cur_gc_live_oops_size;
-  static GrowableArray<HeapWord*> *      _last_gc_live_oops;
-  static GrowableArray<HeapWord*> *      _last_gc_live_oops_moved_to;
-  static GrowableArray<size_t>*          _last_gc_live_oops_size;
-#endif
-
   // Non public closures
   static KeepAliveClosure keep_alive;
 
@@ -227,24 +185,6 @@
   static void adjust_pointer(oop* p)       { adjust_pointer(p, false); }
   static void adjust_pointer(narrowOop* p) { adjust_pointer(p, false); }
 
-#ifdef VALIDATE_MARK_SWEEP
-  static void track_adjusted_pointer(void* p, bool isroot);
-  static void check_adjust_pointer(void* p);
-  static void track_interior_pointers(oop obj);
-  static void check_interior_pointers();
-
-  static void reset_live_oop_tracking();
-  static void register_live_oop(oop p, size_t size);
-  static void validate_live_oop(oop p, size_t size);
-  static void live_oop_moved_to(HeapWord* q, size_t size, HeapWord* compaction_top);
-  static void compaction_complete();
-
-  // Querying operation of RecordMarkSweepCompaction results.
-  // Finds and prints the current base oop and offset for a word
-  // within an oop that was live during the last GC. Helpful for
-  // tracking down heap stomps.
-  static void print_new_location_of_heap_address(HeapWord* q);
-#endif
 };
 
 class PreservedMark VALUE_OBJ_CLASS_SPEC {
--- a/hotspot/src/share/vm/gc_implementation/shared/markSweep.inline.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_implementation/shared/markSweep.inline.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -46,12 +46,6 @@
 template <class T> inline void MarkSweep::follow_root(T* p) {
   assert(!Universe::heap()->is_in_reserved(p),
          "roots shouldn't be things within the heap");
-#ifdef VALIDATE_MARK_SWEEP
-  if (ValidateMarkSweep) {
-    guarantee(!_root_refs_stack->contains(p), "should only be in here once");
-    _root_refs_stack->push(p);
-  }
-#endif
   T heap_oop = oopDesc::load_heap_oop(p);
   if (!oopDesc::is_null(heap_oop)) {
     oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
@@ -97,19 +91,9 @@
       oopDesc::encode_store_heap_oop_not_null(p, new_obj);
     }
   }
-  VALIDATE_MARK_SWEEP_ONLY(track_adjusted_pointer(p, isroot));
 }
 
 template <class T> inline void MarkSweep::KeepAliveClosure::do_oop_work(T* p) {
-#ifdef VALIDATE_MARK_SWEEP
-  if (ValidateMarkSweep) {
-    if (!Universe::heap()->is_in_reserved(p)) {
-      _root_refs_stack->push(p);
-    } else {
-      _other_refs_stack->push(p);
-    }
-  }
-#endif
   mark_and_push(p);
 }
 
--- a/hotspot/src/share/vm/gc_interface/gcCause.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/gc_interface/gcCause.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -99,9 +99,9 @@
  public:
    GCCauseString(const char* prefix, GCCause::Cause cause) {
      if (PrintGCCause) {
-      _position = jio_snprintf(_buffer, _length, "%s (%s)", prefix, GCCause::to_string(cause));
+      _position = jio_snprintf(_buffer, _length, "%s (%s) ", prefix, GCCause::to_string(cause));
      } else {
-      _position = jio_snprintf(_buffer, _length, "%s", prefix);
+      _position = jio_snprintf(_buffer, _length, "%s ", prefix);
      }
      assert(_position >= 0 && _position <= _length,
        err_msg("Need to increase the buffer size in GCCauseString? %d", _position));
--- a/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/interpreter/interpreterRuntime.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -417,7 +417,7 @@
 
     // exception handler lookup
     KlassHandle h_klass(THREAD, h_exception->klass());
-    handler_bci = h_method->fast_exception_handler_bci_for(h_klass, current_bci, THREAD);
+    handler_bci = Method::fast_exception_handler_bci_for(h_method, h_klass, current_bci, THREAD);
     if (HAS_PENDING_EXCEPTION) {
       // We threw an exception while trying to find the exception handler.
       // Transfer the new exception to the exception handle which will
--- a/hotspot/src/share/vm/memory/binaryTreeDictionary.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/binaryTreeDictionary.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -67,7 +67,8 @@
 }
 
 template <class Chunk_t, template <class> class FreeList_t>
-TreeList<Chunk_t, FreeList_t>::TreeList() {}
+TreeList<Chunk_t, FreeList_t>::TreeList() : _parent(NULL),
+  _left(NULL), _right(NULL) {}
 
 template <class Chunk_t, template <class> class FreeList_t>
 TreeList<Chunk_t, FreeList_t>*
@@ -82,7 +83,7 @@
   tl->link_head(tc);
   tl->link_tail(tc);
   tl->set_count(1);
-
+  assert(tl->parent() == NULL, "Should be clear");
   return tl;
 }
 
--- a/hotspot/src/share/vm/memory/collectorPolicy.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/collectorPolicy.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -777,6 +777,15 @@
                                        full_gc_count,
                                        GCCause::_metadata_GC_threshold);
     VMThread::execute(&op);
+
+    // If GC was locked out, try again.  Check
+    // before checking success because the prologue
+    // could have succeeded and the GC still have
+    // been locked out.
+    if (op.gc_locked()) {
+      continue;
+    }
+
     if (op.prologue_succeeded()) {
       return op.result();
     }
@@ -818,7 +827,7 @@
   if (_generations == NULL)
     vm_exit_during_initialization("Unable to allocate gen spec");
 
-  if (UseParNewGC && ParallelGCThreads > 0) {
+  if (UseParNewGC) {
     _generations[0] = new GenerationSpec(Generation::ParNew, _initial_gen0_size, _max_gen0_size);
   } else {
     _generations[0] = new GenerationSpec(Generation::DefNew, _initial_gen0_size, _max_gen0_size);
@@ -831,10 +840,9 @@
 
 void MarkSweepPolicy::initialize_gc_policy_counters() {
   // initialize the policy counters - 2 collectors, 3 generations
-  if (UseParNewGC && ParallelGCThreads > 0) {
+  if (UseParNewGC) {
     _gc_policy_counters = new GCPolicyCounters("ParNew:MSC", 2, 3);
-  }
-  else {
+  } else {
     _gc_policy_counters = new GCPolicyCounters("Copy:MSC", 2, 3);
   }
 }
--- a/hotspot/src/share/vm/memory/defNewGeneration.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/defNewGeneration.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -550,6 +550,11 @@
   return allocate(size, is_tlab);
 }
 
+void DefNewGeneration::adjust_desired_tenuring_threshold() {
+  // Set the desired survivor size to half the real survivor space
+  _tenuring_threshold =
+    age_table()->compute_tenuring_threshold(to()->capacity()/HeapWordSize);
+}
 
 void DefNewGeneration::collect(bool   full,
                                bool   clear_all_soft_refs,
@@ -649,9 +654,7 @@
 
     assert(to()->is_empty(), "to space should be empty now");
 
-    // Set the desired survivor size to half the real survivor space
-    _tenuring_threshold =
-      age_table()->compute_tenuring_threshold(to()->capacity()/HeapWordSize);
+    adjust_desired_tenuring_threshold();
 
     // A successful scavenge should restart the GC time limit count which is
     // for full GC's.
--- a/hotspot/src/share/vm/memory/defNewGeneration.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/defNewGeneration.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -124,7 +124,9 @@
     _should_allocate_from_space = true;
   }
 
- protected:
+  // Tenuring
+  void adjust_desired_tenuring_threshold();
+
   // Spaces
   EdenSpace*       _eden_space;
   ContiguousSpace* _from_space;
--- a/hotspot/src/share/vm/memory/genMarkSweep.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/genMarkSweep.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -100,21 +100,8 @@
 
   mark_sweep_phase3(level);
 
-  VALIDATE_MARK_SWEEP_ONLY(
-    if (ValidateMarkSweep) {
-      guarantee(_root_refs_stack->length() == 0, "should be empty by now");
-    }
-  )
-
   mark_sweep_phase4();
 
-  VALIDATE_MARK_SWEEP_ONLY(
-    if (ValidateMarkSweep) {
-      guarantee(_live_oops->length() == _live_oops_moved_to->length(),
-                "should be the same size");
-    }
-  )
-
   restore_marks();
 
   // Set saved marks for allocation profiler (and other things? -- dld)
@@ -187,31 +174,6 @@
 
   _preserved_marks = (PreservedMark*)scratch;
   _preserved_count = 0;
-
-#ifdef VALIDATE_MARK_SWEEP
-  if (ValidateMarkSweep) {
-    _root_refs_stack    = new (ResourceObj::C_HEAP, mtGC) GrowableArray<void*>(100, true);
-    _other_refs_stack   = new (ResourceObj::C_HEAP, mtGC) GrowableArray<void*>(100, true);
-    _adjusted_pointers  = new (ResourceObj::C_HEAP, mtGC) GrowableArray<void*>(100, true);
-    _live_oops          = new (ResourceObj::C_HEAP, mtGC) GrowableArray<oop>(100, true);
-    _live_oops_moved_to = new (ResourceObj::C_HEAP, mtGC) GrowableArray<oop>(100, true);
-    _live_oops_size     = new (ResourceObj::C_HEAP, mtGC) GrowableArray<size_t>(100, true);
-  }
-  if (RecordMarkSweepCompaction) {
-    if (_cur_gc_live_oops == NULL) {
-      _cur_gc_live_oops           = new(ResourceObj::C_HEAP, mtGC) GrowableArray<HeapWord*>(100, true);
-      _cur_gc_live_oops_moved_to  = new(ResourceObj::C_HEAP, mtGC) GrowableArray<HeapWord*>(100, true);
-      _cur_gc_live_oops_size      = new(ResourceObj::C_HEAP, mtGC) GrowableArray<size_t>(100, true);
-      _last_gc_live_oops          = new(ResourceObj::C_HEAP, mtGC) GrowableArray<HeapWord*>(100, true);
-      _last_gc_live_oops_moved_to = new(ResourceObj::C_HEAP, mtGC) GrowableArray<HeapWord*>(100, true);
-      _last_gc_live_oops_size     = new(ResourceObj::C_HEAP, mtGC) GrowableArray<size_t>(100, true);
-    } else {
-      _cur_gc_live_oops->clear();
-      _cur_gc_live_oops_moved_to->clear();
-      _cur_gc_live_oops_size->clear();
-    }
-  }
-#endif
 }
 
 
@@ -225,19 +187,6 @@
   _preserved_oop_stack.clear(true);
   _marking_stack.clear();
   _objarray_stack.clear(true);
-
-#ifdef VALIDATE_MARK_SWEEP
-  if (ValidateMarkSweep) {
-    delete _root_refs_stack;
-    delete _other_refs_stack;
-    delete _adjusted_pointers;
-    delete _live_oops;
-    delete _live_oops_size;
-    delete _live_oops_moved_to;
-    _live_oops_index = 0;
-    _live_oops_index_at_perm = 0;
-  }
-#endif
 }
 
 void GenMarkSweep::mark_sweep_phase1(int level,
@@ -246,8 +195,6 @@
   TraceTime tm("phase 1", PrintGC && Verbose, true, gclog_or_tty);
   trace(" 1");
 
-  VALIDATE_MARK_SWEEP_ONLY(reset_live_oop_tracking());
-
   GenCollectedHeap* gch = GenCollectedHeap::heap();
 
   // Because follow_root_closure is created statically, cannot
@@ -315,8 +262,6 @@
   TraceTime tm("phase 2", PrintGC && Verbose, true, gclog_or_tty);
   trace("2");
 
-  VALIDATE_MARK_SWEEP_ONLY(reset_live_oop_tracking());
-
   gch->prepare_for_compaction();
 }
 
@@ -337,8 +282,6 @@
   // Need new claim bits for the pointer adjustment tracing.
   ClassLoaderDataGraph::clear_claimed_marks();
 
-  VALIDATE_MARK_SWEEP_ONLY(reset_live_oop_tracking());
-
   // Because the two closures below are created statically, cannot
   // use OopsInGenClosure constructor which takes a generation,
   // as the Universe has not been created when the static constructors
@@ -393,10 +336,6 @@
   TraceTime tm("phase 4", PrintGC && Verbose, true, gclog_or_tty);
   trace("4");
 
-  VALIDATE_MARK_SWEEP_ONLY(reset_live_oop_tracking());
-
   GenCompactClosure blk;
   gch->generation_iterate(&blk, true);
-
-  VALIDATE_MARK_SWEEP_ONLY(compaction_complete());
 }
--- a/hotspot/src/share/vm/memory/metachunk.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/metachunk.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -56,6 +56,7 @@
   assert(chunk_end > chunk_bottom, "Chunk must be too small");
   chunk->set_end(chunk_end);
   chunk->set_next(NULL);
+  chunk->set_prev(NULL);
   chunk->set_word_size(word_size);
 #ifdef ASSERT
   size_t data_word_size = pointer_delta(chunk_end, chunk_bottom, sizeof(MetaWord));
@@ -76,15 +77,15 @@
 }
 
 // _bottom points to the start of the chunk including the overhead.
-size_t Metachunk::used_word_size() {
+size_t Metachunk::used_word_size() const {
   return pointer_delta(_top, _bottom, sizeof(MetaWord));
 }
 
-size_t Metachunk::free_word_size() {
+size_t Metachunk::free_word_size() const {
   return pointer_delta(_end, _top, sizeof(MetaWord));
 }
 
-size_t Metachunk::capacity_word_size() {
+size_t Metachunk::capacity_word_size() const {
   return pointer_delta(_end, _bottom, sizeof(MetaWord));
 }
 
@@ -93,6 +94,10 @@
                " bottom " PTR_FORMAT " top " PTR_FORMAT
                " end " PTR_FORMAT " size " SIZE_FORMAT,
                bottom(), top(), end(), word_size());
+  if (Verbose) {
+    st->print_cr("    used " SIZE_FORMAT " free " SIZE_FORMAT,
+                 used_word_size(), free_word_size());
+  }
 }
 
 #ifndef PRODUCT
--- a/hotspot/src/share/vm/memory/metachunk.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/metachunk.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -67,9 +67,11 @@
   void set_word_size(size_t v) { _word_size = v; }
  public:
 #ifdef ASSERT
-  Metachunk() : _bottom(NULL), _end(NULL), _top(NULL), _is_free(false) {}
+  Metachunk() : _bottom(NULL), _end(NULL), _top(NULL), _is_free(false),
+    _next(NULL), _prev(NULL) {}
 #else
-  Metachunk() : _bottom(NULL), _end(NULL), _top(NULL) {}
+  Metachunk() : _bottom(NULL), _end(NULL), _top(NULL),
+    _next(NULL), _prev(NULL) {}
 #endif
 
   // Used to add a Metachunk to a list of Metachunks
@@ -102,15 +104,15 @@
   }
 
   // Reset top to bottom so chunk can be reused.
-  void reset_empty() { _top = (_bottom + _overhead); }
+  void reset_empty() { _top = (_bottom + _overhead); _next = NULL; _prev = NULL; }
   bool is_empty() { return _top == (_bottom + _overhead); }
 
   // used (has been allocated)
   // free (available for future allocations)
   // capacity (total size of chunk)
-  size_t used_word_size();
-  size_t free_word_size();
-  size_t capacity_word_size();
+  size_t used_word_size() const;
+  size_t free_word_size() const;
+  size_t capacity_word_size()const;
 
   // Debug support
 #ifdef ASSERT
--- a/hotspot/src/share/vm/memory/metadataFactory.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/metadataFactory.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -66,7 +66,11 @@
     if (data != NULL) {
       assert(loader_data != NULL, "shouldn't pass null");
       int size = data->size();
-      loader_data->metaspace_non_null()->deallocate((MetaWord*)data, size, false);
+      if (DumpSharedSpaces) {
+        loader_data->ro_metaspace()->deallocate((MetaWord*)data, size, false);
+      } else {
+        loader_data->metaspace_non_null()->deallocate((MetaWord*)data, size, false);
+      }
     }
   }
 
@@ -77,6 +81,7 @@
       assert(loader_data != NULL, "shouldn't pass null");
       int size = md->size();
       // Call metadata's deallocate function which will call deallocate fields
+      assert(!DumpSharedSpaces, "cannot deallocate metadata when dumping CDS archive");
       assert(!md->on_stack(), "can't deallocate things on stack");
       md->deallocate_contents(loader_data);
       loader_data->metaspace_non_null()->deallocate((MetaWord*)md, size, md->is_klass());
--- a/hotspot/src/share/vm/memory/metaspace.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/metaspace.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -58,11 +58,23 @@
 
 // Used in declarations in SpaceManager and ChunkManager
 enum ChunkIndex {
-  SmallIndex = 0,
-  MediumIndex = 1,
-  HumongousIndex = 2,
-  NumberOfFreeLists = 2,
-  NumberOfInUseLists = 3
+  ZeroIndex = 0,
+  SpecializedIndex = ZeroIndex,
+  SmallIndex = SpecializedIndex + 1,
+  MediumIndex = SmallIndex + 1,
+  HumongousIndex = MediumIndex + 1,
+  NumberOfFreeLists = 3,
+  NumberOfInUseLists = 4
+};
+
+enum ChunkSizes {    // in words.
+  ClassSpecializedChunk = 128,
+  SpecializedChunk = 128,
+  ClassSmallChunk = 256,
+  SmallChunk = 512,
+  ClassMediumChunk = 1 * K,
+  MediumChunk = 8 * K,
+  HumongousChunkGranularity = 8
 };
 
 static ChunkIndex next_chunk_index(ChunkIndex i) {
@@ -126,6 +138,7 @@
   //   HumongousChunk
   ChunkList _free_chunks[NumberOfFreeLists];
 
+
   //   HumongousChunk
   ChunkTreeDictionary _humongous_dictionary;
 
@@ -169,6 +182,10 @@
   Metachunk* chunk_freelist_allocate(size_t word_size);
   void chunk_freelist_deallocate(Metachunk* chunk);
 
+  // Map a size to a list index assuming that there are lists
+  // for special, small, medium, and humongous chunks.
+  static ChunkIndex list_index(size_t size);
+
   // Total of the space in the free chunks list
   size_t free_chunks_total();
   size_t free_chunks_total_in_bytes();
@@ -180,8 +197,6 @@
     Atomic::add_ptr(count, &_free_chunks_count);
     Atomic::add_ptr(v, &_free_chunks_total);
   }
-  ChunkList* free_medium_chunks() { return &_free_chunks[1]; }
-  ChunkList* free_small_chunks() { return &_free_chunks[0]; }
   ChunkTreeDictionary* humongous_dictionary() {
     return &_humongous_dictionary;
   }
@@ -400,7 +415,14 @@
   VirtualSpaceList(size_t word_size);
   VirtualSpaceList(ReservedSpace rs);
 
-  Metachunk* get_new_chunk(size_t word_size, size_t grow_chunks_by_words);
+  Metachunk* get_new_chunk(size_t word_size,
+                           size_t grow_chunks_by_words,
+                           size_t medium_chunk_bunch);
+
+  // Get the first chunk for a Metaspace.  Used for
+  // special cases such as the boot class loader, reflection
+  // class loader and anonymous class loader.
+  Metachunk* get_initialization_chunk(size_t word_size, size_t chunk_bunch);
 
   VirtualSpaceNode* current_virtual_space() {
     return _current_virtual_space;
@@ -501,9 +523,13 @@
   friend class Metadebug;
 
  private:
+
   // protects allocations and contains.
   Mutex* const _lock;
 
+  // Chunk related size
+  size_t _medium_chunk_bunch;
+
   // List of chunks in use by this SpaceManager.  Allocations
   // are done from the current chunk.  The list is used for deallocating
   // chunks when the SpaceManager is freed.
@@ -532,6 +558,7 @@
   static const int    _expand_lock_rank;
   static Mutex* const _expand_lock;
 
+ private:
   // Accessors
   Metachunk* chunks_in_use(ChunkIndex index) const { return _chunks_in_use[index]; }
   void set_chunks_in_use(ChunkIndex index, Metachunk* v) { _chunks_in_use[index] = v; }
@@ -554,23 +581,37 @@
 
   Mutex* lock() const { return _lock; }
 
+  const char* chunk_size_name(ChunkIndex index) const;
+
+ protected:
+  void initialize();
+
  public:
-  SpaceManager(Mutex* lock, VirtualSpaceList* vs_list);
+  SpaceManager(Mutex* lock,
+               VirtualSpaceList* vs_list);
   ~SpaceManager();
 
-  enum ChunkSizes {    // in words.
-    SmallChunk = 512,
-    MediumChunk = 8 * K,
-    MediumChunkBunch = 4 * MediumChunk
+  enum ChunkMultiples {
+    MediumChunkMultiple = 4
   };
 
   // Accessors
+  size_t specialized_chunk_size() { return SpecializedChunk; }
+  size_t small_chunk_size() { return (size_t) vs_list()->is_class() ? ClassSmallChunk : SmallChunk; }
+  size_t medium_chunk_size() { return (size_t) vs_list()->is_class() ? ClassMediumChunk : MediumChunk; }
+  size_t medium_chunk_bunch() { return medium_chunk_size() * MediumChunkMultiple; }
+
   size_t allocation_total() const { return _allocation_total; }
   void inc_allocation_total(size_t v) { Atomic::add_ptr(v, &_allocation_total); }
-  static bool is_humongous(size_t word_size) { return word_size > MediumChunk; }
+  bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); }
 
   static Mutex* expand_lock() { return _expand_lock; }
 
+  // Set the sizes for the initial chunks.
+  void get_initial_chunk_sizes(Metaspace::MetaspaceType type,
+                               size_t* chunk_word_size,
+                               size_t* class_chunk_word_size);
+
   size_t sum_capacity_in_chunks_in_use() const;
   size_t sum_used_in_chunks_in_use() const;
   size_t sum_free_in_chunks_in_use() const;
@@ -580,6 +621,8 @@
   size_t sum_count_in_chunks_in_use();
   size_t sum_count_in_chunks_in_use(ChunkIndex i);
 
+  Metachunk* get_new_chunk(size_t word_size, size_t grow_chunks_by_words);
+
   // Block allocation and deallocation.
   // Allocates a block from the current chunk
   MetaWord* allocate(size_t word_size);
@@ -772,8 +815,10 @@
     return false;
   }
 
-  // Commit only 1 page instead of the whole reserved space _rs.size()
-  size_t committed_byte_size = os::vm_page_size();
+  // An allocation out of this Virtualspace that is larger
+  // than an initial commit size can waste that initial committed
+  // space.
+  size_t committed_byte_size = 0;
   bool result = virtual_space()->initialize(_rs, committed_byte_size);
   if (result) {
     set_top((MetaWord*)virtual_space()->low());
@@ -799,7 +844,8 @@
   st->print_cr("   space @ " PTR_FORMAT " " SIZE_FORMAT "K, %3d%% used "
            "[" PTR_FORMAT ", " PTR_FORMAT ", "
            PTR_FORMAT ", " PTR_FORMAT ")",
-           vs, capacity / K, used * 100 / capacity,
+           vs, capacity / K,
+           capacity == 0 ? 0 : used * 100 / capacity,
            bottom(), top(), end(),
            vs->high_boundary());
 }
@@ -922,7 +968,8 @@
 }
 
 Metachunk* VirtualSpaceList::get_new_chunk(size_t word_size,
-                                           size_t grow_chunks_by_words) {
+                                           size_t grow_chunks_by_words,
+                                           size_t medium_chunk_bunch) {
 
   // Get a chunk from the chunk freelist
   Metachunk* next = chunk_manager()->chunk_freelist_allocate(grow_chunks_by_words);
@@ -935,8 +982,8 @@
   if (next == NULL) {
     // Not enough room in current virtual space.  Try to commit
     // more space.
-    size_t expand_vs_by_words = MAX2((size_t)SpaceManager::MediumChunkBunch,
-                                       grow_chunks_by_words);
+    size_t expand_vs_by_words = MAX2(medium_chunk_bunch,
+                                     grow_chunks_by_words);
     size_t page_size_words = os::vm_page_size() / BytesPerWord;
     size_t aligned_expand_vs_by_words = align_size_up(expand_vs_by_words,
                                                         page_size_words);
@@ -954,12 +1001,6 @@
           // Got it.  It's on the list now.  Get a chunk from it.
           next = current_virtual_space()->get_chunk_vs_with_expand(grow_chunks_by_words);
         }
-        if (TraceMetadataHumongousAllocation && SpaceManager::is_humongous(word_size)) {
-          gclog_or_tty->print_cr("  aligned_expand_vs_by_words " PTR_FORMAT,
-                                 aligned_expand_vs_by_words);
-          gclog_or_tty->print_cr("  grow_vs_words " PTR_FORMAT,
-                                 grow_vs_words);
-        }
       } else {
         // Allocation will fail and induce a GC
         if (TraceMetadataChunkAllocation && Verbose) {
@@ -974,9 +1015,20 @@
     }
   }
 
+  assert(next == NULL || (next->next() == NULL && next->prev() == NULL),
+         "New chunk is still on some list");
   return next;
 }
 
+Metachunk* VirtualSpaceList::get_initialization_chunk(size_t chunk_word_size,
+                                                      size_t chunk_bunch) {
+  // Get a chunk from the chunk freelist
+  Metachunk* new_chunk = get_new_chunk(chunk_word_size,
+                                       chunk_word_size,
+                                       chunk_bunch);
+  return new_chunk;
+}
+
 void VirtualSpaceList::print_on(outputStream* st) const {
   if (TraceMetadataChunkAllocation && Verbose) {
     VirtualSpaceListIterator iter(virtual_space_list());
@@ -1373,16 +1425,17 @@
 
 void ChunkList::add_at_head(Metachunk* head, Metachunk* tail) {
   assert_lock_strong(SpaceManager::expand_lock());
-  assert(tail->next() == NULL, "Not the tail");
+  assert(head == tail || tail->next() == NULL,
+         "Not the tail or the head has already been added to a list");
 
   if (TraceMetadataChunkAllocation && Verbose) {
-    tty->print("ChunkList::add_at_head: ");
+    gclog_or_tty->print("ChunkList::add_at_head(head, tail): ");
     Metachunk* cur = head;
     while (cur != NULL) {
-    tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ", cur, cur->word_size());
+      gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ", cur, cur->word_size());
       cur = cur->next();
     }
-    tty->print_cr("");
+    gclog_or_tty->print_cr("");
   }
 
   if (tail != NULL) {
@@ -1486,13 +1539,13 @@
 
 void ChunkManager::locked_print_free_chunks(outputStream* st) {
   assert_lock_strong(SpaceManager::expand_lock());
-  st->print_cr("Free chunk total 0x%x  count 0x%x",
+  st->print_cr("Free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
                 _free_chunks_total, _free_chunks_count);
 }
 
 void ChunkManager::locked_print_sum_free_chunks(outputStream* st) {
   assert_lock_strong(SpaceManager::expand_lock());
-  st->print_cr("Sum free chunk total 0x%x  count 0x%x",
+  st->print_cr("Sum free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
                 sum_free_chunks(), sum_free_chunks_count());
 }
 ChunkList* ChunkManager::free_chunks(ChunkIndex index) {
@@ -1504,7 +1557,7 @@
 size_t ChunkManager::sum_free_chunks() {
   assert_lock_strong(SpaceManager::expand_lock());
   size_t result = 0;
-  for (ChunkIndex i = SmallIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
+  for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
     ChunkList* list = free_chunks(i);
 
     if (list == NULL) {
@@ -1520,7 +1573,7 @@
 size_t ChunkManager::sum_free_chunks_count() {
   assert_lock_strong(SpaceManager::expand_lock());
   size_t count = 0;
-  for (ChunkIndex i = SmallIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
+  for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
     ChunkList* list = free_chunks(i);
     if (list == NULL) {
       continue;
@@ -1532,15 +1585,9 @@
 }
 
 ChunkList* ChunkManager::find_free_chunks_list(size_t word_size) {
-  switch (word_size) {
-  case SpaceManager::SmallChunk :
-      return &_free_chunks[0];
-  case SpaceManager::MediumChunk :
-      return &_free_chunks[1];
-  default:
-    assert(word_size > SpaceManager::MediumChunk, "List inconsistency");
-    return &_free_chunks[2];
-  }
+  ChunkIndex index = list_index(word_size);
+  assert(index < HumongousIndex, "No humongous list");
+  return free_chunks(index);
 }
 
 void ChunkManager::free_chunks_put(Metachunk* chunk) {
@@ -1574,7 +1621,7 @@
   slow_locked_verify();
 
   Metachunk* chunk = NULL;
-  if (!SpaceManager::is_humongous(word_size)) {
+  if (list_index(word_size) != HumongousIndex) {
     ChunkList* free_list = find_free_chunks_list(word_size);
     assert(free_list != NULL, "Sanity check");
 
@@ -1587,8 +1634,8 @@
 
     // Remove the chunk as the head of the list.
     free_list->set_head(chunk->next());
-    chunk->set_next(NULL);
-    // Chunk has been removed from the chunks free list.
+
+    // Chunk is being removed from the chunks free list.
     dec_free_chunks_total(chunk->capacity_word_size());
 
     if (TraceMetadataChunkAllocation && Verbose) {
@@ -1614,8 +1661,14 @@
 #ifdef ASSERT
       chunk->set_is_free(false);
 #endif
+    } else {
+      return NULL;
     }
   }
+
+  // Remove it from the links to this freelist
+  chunk->set_next(NULL);
+  chunk->set_prev(NULL);
   slow_locked_verify();
   return chunk;
 }
@@ -1630,13 +1683,20 @@
     return NULL;
   }
 
-  assert(word_size <= chunk->word_size() ||
-           SpaceManager::is_humongous(chunk->word_size()),
-           "Non-humongous variable sized chunk");
+  assert((word_size <= chunk->word_size()) ||
+         list_index(chunk->word_size() == HumongousIndex),
+         "Non-humongous variable sized chunk");
   if (TraceMetadataChunkAllocation) {
-    tty->print("ChunkManager::chunk_freelist_allocate: chunk "
-               PTR_FORMAT "  size " SIZE_FORMAT " ",
-               chunk, chunk->word_size());
+    size_t list_count;
+    if (list_index(word_size) < HumongousIndex) {
+      ChunkList* list = find_free_chunks_list(word_size);
+      list_count = list->sum_list_count();
+    } else {
+      list_count = humongous_dictionary()->total_count();
+    }
+    tty->print("ChunkManager::chunk_freelist_allocate: " PTR_FORMAT " chunk "
+               PTR_FORMAT "  size " SIZE_FORMAT " count " SIZE_FORMAT " ",
+               this, chunk, chunk->word_size(), list_count);
     locked_print_free_chunks(tty);
   }
 
@@ -1651,10 +1711,42 @@
 
 // SpaceManager methods
 
+void SpaceManager::get_initial_chunk_sizes(Metaspace::MetaspaceType type,
+                                           size_t* chunk_word_size,
+                                           size_t* class_chunk_word_size) {
+  switch (type) {
+  case Metaspace::BootMetaspaceType:
+    *chunk_word_size = Metaspace::first_chunk_word_size();
+    *class_chunk_word_size = Metaspace::first_class_chunk_word_size();
+    break;
+  case Metaspace::ROMetaspaceType:
+    *chunk_word_size = SharedReadOnlySize / wordSize;
+    *class_chunk_word_size = ClassSpecializedChunk;
+    break;
+  case Metaspace::ReadWriteMetaspaceType:
+    *chunk_word_size = SharedReadWriteSize / wordSize;
+    *class_chunk_word_size = ClassSpecializedChunk;
+    break;
+  case Metaspace::AnonymousMetaspaceType:
+  case Metaspace::ReflectionMetaspaceType:
+    *chunk_word_size = SpecializedChunk;
+    *class_chunk_word_size = ClassSpecializedChunk;
+    break;
+  default:
+    *chunk_word_size = SmallChunk;
+    *class_chunk_word_size = ClassSmallChunk;
+    break;
+  }
+  assert(chunk_word_size != 0 && class_chunk_word_size != 0,
+    err_msg("Initial chunks sizes bad: data  " SIZE_FORMAT
+            " class " SIZE_FORMAT,
+            chunk_word_size, class_chunk_word_size));
+}
+
 size_t SpaceManager::sum_free_in_chunks_in_use() const {
   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
   size_t free = 0;
-  for (ChunkIndex i = SmallIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
+  for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
     Metachunk* chunk = chunks_in_use(i);
     while (chunk != NULL) {
       free += chunk->free_word_size();
@@ -1667,9 +1759,7 @@
 size_t SpaceManager::sum_waste_in_chunks_in_use() const {
   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
   size_t result = 0;
-  for (ChunkIndex i = SmallIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
-
-
+  for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
    result += sum_waste_in_chunks_in_use(i);
   }
 
@@ -1678,7 +1768,6 @@
 
 size_t SpaceManager::sum_waste_in_chunks_in_use(ChunkIndex index) const {
   size_t result = 0;
-  size_t count = 0;
   Metachunk* chunk = chunks_in_use(index);
   // Count the free space in all the chunk but not the
   // current chunk from which allocations are still being done.
@@ -1688,7 +1777,6 @@
       result += chunk->free_word_size();
       prev = chunk;
       chunk = chunk->next();
-      count++;
     }
   }
   return result;
@@ -1697,7 +1785,7 @@
 size_t SpaceManager::sum_capacity_in_chunks_in_use() const {
   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
   size_t sum = 0;
-  for (ChunkIndex i = SmallIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
+  for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
     Metachunk* chunk = chunks_in_use(i);
     while (chunk != NULL) {
       // Just changed this sum += chunk->capacity_word_size();
@@ -1711,7 +1799,7 @@
 
 size_t SpaceManager::sum_count_in_chunks_in_use() {
   size_t count = 0;
-  for (ChunkIndex i = SmallIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
+  for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
     count = count + sum_count_in_chunks_in_use(i);
   }
 
@@ -1732,7 +1820,7 @@
 size_t SpaceManager::sum_used_in_chunks_in_use() const {
   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
   size_t used = 0;
-  for (ChunkIndex i = SmallIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
+  for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
     Metachunk* chunk = chunks_in_use(i);
     while (chunk != NULL) {
       used += chunk->used_word_size();
@@ -1744,19 +1832,17 @@
 
 void SpaceManager::locked_print_chunks_in_use_on(outputStream* st) const {
 
-  Metachunk* small_chunk = chunks_in_use(SmallIndex);
-  st->print_cr("SpaceManager: small chunk " PTR_FORMAT
-               " free " SIZE_FORMAT,
-               small_chunk,
-               small_chunk->free_word_size());
-
-  Metachunk* medium_chunk = chunks_in_use(MediumIndex);
-  st->print("medium chunk " PTR_FORMAT, medium_chunk);
-  Metachunk* tail = current_chunk();
-  st->print_cr(" current chunk " PTR_FORMAT, tail);
-
-  Metachunk* head = chunks_in_use(HumongousIndex);
-  st->print_cr("humongous chunk " PTR_FORMAT, head);
+  for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
+    Metachunk* chunk = chunks_in_use(i);
+    st->print("SpaceManager: %s " PTR_FORMAT,
+                 chunk_size_name(i), chunk);
+    if (chunk != NULL) {
+      st->print_cr(" free " SIZE_FORMAT,
+                   chunk->free_word_size());
+    } else {
+      st->print_cr("");
+    }
+  }
 
   vs_list()->chunk_manager()->locked_print_free_chunks(st);
   vs_list()->chunk_manager()->locked_print_sum_free_chunks(st);
@@ -1772,18 +1858,28 @@
   if (chunks_in_use(MediumIndex) == NULL &&
       (!has_small_chunk_limit() ||
        sum_count_in_chunks_in_use(SmallIndex) < _small_chunk_limit)) {
-    chunk_word_size = (size_t) SpaceManager::SmallChunk;
-    if (word_size + Metachunk::overhead() > SpaceManager::SmallChunk) {
-      chunk_word_size = MediumChunk;
+    chunk_word_size = (size_t) small_chunk_size();
+    if (word_size + Metachunk::overhead() > small_chunk_size()) {
+      chunk_word_size = medium_chunk_size();
     }
   } else {
-    chunk_word_size = MediumChunk;
+    chunk_word_size = medium_chunk_size();
   }
 
-  // Might still need a humongous chunk
+  // Might still need a humongous chunk.  Enforce an
+  // eight word granularity to facilitate reuse (some
+  // wastage but better chance of reuse).
+  size_t if_humongous_sized_chunk =
+    align_size_up(word_size + Metachunk::overhead(),
+                  HumongousChunkGranularity);
   chunk_word_size =
-    MAX2((size_t) chunk_word_size, word_size + Metachunk::overhead());
-
+    MAX2((size_t) chunk_word_size, if_humongous_sized_chunk);
+
+  assert(!SpaceManager::is_humongous(word_size) ||
+         chunk_word_size == if_humongous_sized_chunk,
+         err_msg("Size calculation is wrong, word_size " SIZE_FORMAT
+                 " chunk_word_size " SIZE_FORMAT,
+                 word_size, chunk_word_size));
   if (TraceMetadataHumongousAllocation &&
       SpaceManager::is_humongous(word_size)) {
     gclog_or_tty->print_cr("Metadata humongous allocation:");
@@ -1805,15 +1901,21 @@
   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
 
   if (TraceMetadataChunkAllocation && Verbose) {
+    size_t words_left = 0;
+    size_t words_used = 0;
+    if (current_chunk() != NULL) {
+      words_left = current_chunk()->free_word_size();
+      words_used = current_chunk()->used_word_size();
+    }
     gclog_or_tty->print_cr("SpaceManager::grow_and_allocate for " SIZE_FORMAT
-                           " words " SIZE_FORMAT " space left",
-                            word_size, current_chunk() != NULL ?
-                              current_chunk()->free_word_size() : 0);
+                           " words " SIZE_FORMAT " words used " SIZE_FORMAT
+                           " words left",
+                            word_size, words_used, words_left);
   }
 
   // Get another chunk out of the virtual space
   size_t grow_chunks_by_words = calc_chunk_size(word_size);
-  Metachunk* next = vs_list()->get_new_chunk(word_size, grow_chunks_by_words);
+  Metachunk* next = get_new_chunk(word_size, grow_chunks_by_words);
 
   // If a chunk was available, add it to the in-use chunk list
   // and do an allocation from it.
@@ -1828,7 +1930,7 @@
 
 void SpaceManager::print_on(outputStream* st) const {
 
-  for (ChunkIndex i = SmallIndex;
+  for (ChunkIndex i = ZeroIndex;
        i < NumberOfInUseLists ;
        i = next_chunk_index(i) ) {
     st->print_cr("  chunks_in_use " PTR_FORMAT " chunk size " PTR_FORMAT,
@@ -1847,12 +1949,18 @@
   }
 }
 
-SpaceManager::SpaceManager(Mutex* lock, VirtualSpaceList* vs_list) :
+SpaceManager::SpaceManager(Mutex* lock,
+                           VirtualSpaceList* vs_list) :
   _vs_list(vs_list),
   _allocation_total(0),
-  _lock(lock) {
+  _lock(lock)
+{
+  initialize();
+}
+
+void SpaceManager::initialize() {
   Metadebug::init_allocation_fail_alot_count();
-  for (ChunkIndex i = SmallIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
+  for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
     _chunks_in_use[i] = NULL;
   }
   _current_chunk = NULL;
@@ -1885,30 +1993,37 @@
   // Add all the chunks in use by this space manager
   // to the global list of free chunks.
 
-  // Small chunks.  There is one _current_chunk for each
-  // Metaspace.  It could point to a small or medium chunk.
-  // Rather than determine which it is, follow the list of
-  // small chunks to add them to the free list
-  Metachunk* small_chunk = chunks_in_use(SmallIndex);
-  chunk_manager->free_small_chunks()->add_at_head(small_chunk);
-  set_chunks_in_use(SmallIndex, NULL);
-
-  // After the small chunk are the medium chunks
-  Metachunk* medium_chunk = chunks_in_use(MediumIndex);
-  assert(medium_chunk == NULL ||
-         medium_chunk->word_size() == MediumChunk,
-         "Chunk is on the wrong list");
-
-  if (medium_chunk != NULL) {
-    Metachunk* head = medium_chunk;
-    // If there is a medium chunk then the _current_chunk can only
-    // point to the last medium chunk.
-    Metachunk* tail = current_chunk();
-    chunk_manager->free_medium_chunks()->add_at_head(head, tail);
-    set_chunks_in_use(MediumIndex, NULL);
+  // Follow each list of chunks-in-use and add them to the
+  // free lists.  Each list is NULL terminated.
+
+  for (ChunkIndex i = ZeroIndex; i < HumongousIndex; i = next_chunk_index(i)) {
+    if (TraceMetadataChunkAllocation && Verbose) {
+      gclog_or_tty->print_cr("returned %d %s chunks to freelist",
+                             sum_count_in_chunks_in_use(i),
+                             chunk_size_name(i));
+    }
+    Metachunk* chunks = chunks_in_use(i);
+    chunk_manager->free_chunks(i)->add_at_head(chunks);
+    set_chunks_in_use(i, NULL);
+    if (TraceMetadataChunkAllocation && Verbose) {
+      gclog_or_tty->print_cr("updated freelist count %d %s",
+                             chunk_manager->free_chunks(i)->sum_list_count(),
+                             chunk_size_name(i));
+    }
+    assert(i != HumongousIndex, "Humongous chunks are handled explicitly later");
   }
 
+  // The medium chunk case may be optimized by passing the head and
+  // tail of the medium chunk list to add_at_head().  The tail is often
+  // the current chunk but there are probably exceptions.
+
   // Humongous chunks
+  if (TraceMetadataChunkAllocation && Verbose) {
+    gclog_or_tty->print_cr("returned %d %s humongous chunks to dictionary",
+                            sum_count_in_chunks_in_use(HumongousIndex),
+                            chunk_size_name(HumongousIndex));
+    gclog_or_tty->print("Humongous chunk dictionary: ");
+  }
   // Humongous chunks are never the current chunk.
   Metachunk* humongous_chunks = chunks_in_use(HumongousIndex);
 
@@ -1916,14 +2031,65 @@
 #ifdef ASSERT
     humongous_chunks->set_is_free(true);
 #endif
+    if (TraceMetadataChunkAllocation && Verbose) {
+      gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ",
+                          humongous_chunks,
+                          humongous_chunks->word_size());
+    }
+    assert(humongous_chunks->word_size() == (size_t)
+           align_size_up(humongous_chunks->word_size(),
+                             HumongousChunkGranularity),
+           err_msg("Humongous chunk size is wrong: word size " SIZE_FORMAT
+                   " granularity " SIZE_FORMAT,
+                   humongous_chunks->word_size(), HumongousChunkGranularity));
     Metachunk* next_humongous_chunks = humongous_chunks->next();
     chunk_manager->humongous_dictionary()->return_chunk(humongous_chunks);
     humongous_chunks = next_humongous_chunks;
   }
+  if (TraceMetadataChunkAllocation && Verbose) {
+    gclog_or_tty->print_cr("");
+    gclog_or_tty->print_cr("updated dictionary count %d %s",
+                     chunk_manager->humongous_dictionary()->total_count(),
+                     chunk_size_name(HumongousIndex));
+  }
   set_chunks_in_use(HumongousIndex, NULL);
   chunk_manager->slow_locked_verify();
 }
 
+const char* SpaceManager::chunk_size_name(ChunkIndex index) const {
+  switch (index) {
+    case SpecializedIndex:
+      return "Specialized";
+    case SmallIndex:
+      return "Small";
+    case MediumIndex:
+      return "Medium";
+    case HumongousIndex:
+      return "Humongous";
+    default:
+      return NULL;
+  }
+}
+
+ChunkIndex ChunkManager::list_index(size_t size) {
+  switch (size) {
+    case SpecializedChunk:
+      assert(SpecializedChunk == ClassSpecializedChunk,
+             "Need branch for ClassSpecializedChunk");
+      return SpecializedIndex;
+    case SmallChunk:
+    case ClassSmallChunk:
+      return SmallIndex;
+    case MediumChunk:
+    case ClassMediumChunk:
+      return MediumIndex;
+    default:
+      assert(size > MediumChunk || size > ClassMediumChunk,
+             "Not a humongous chunk");
+      return HumongousIndex;
+  }
+}
+
 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
   assert_lock_strong(_lock);
   size_t min_size = TreeChunk<Metablock, FreeList>::min_size();
@@ -1942,52 +2108,13 @@
 
   // Find the correct list and and set the current
   // chunk for that list.
-  switch (new_chunk->word_size()) {
-  case SpaceManager::SmallChunk :
-    if (chunks_in_use(SmallIndex) == NULL) {
-      // First chunk to add to the list
-      set_chunks_in_use(SmallIndex, new_chunk);
-    } else {
-      assert(current_chunk()->word_size() == SpaceManager::SmallChunk,
-        err_msg( "Incorrect mix of sizes in chunk list "
-        SIZE_FORMAT " new chunk " SIZE_FORMAT,
-        current_chunk()->word_size(), new_chunk->word_size()));
-      current_chunk()->set_next(new_chunk);
-    }
-    // Make current chunk
+  ChunkIndex index = ChunkManager::list_index(new_chunk->word_size());
+
+  if (index != HumongousIndex) {
     set_current_chunk(new_chunk);
-    break;
-  case SpaceManager::MediumChunk :
-    if (chunks_in_use(MediumIndex) == NULL) {
-      // About to add the first medium chunk so teminate the
-      // small chunk list.  In general once medium chunks are
-      // being added, we're past the need for small chunks.
-      if (current_chunk() != NULL) {
-        // Only a small chunk or the initial chunk could be
-        // the current chunk if this is the first medium chunk.
-        assert(current_chunk()->word_size() == SpaceManager::SmallChunk ||
-          chunks_in_use(SmallIndex) == NULL,
-          err_msg("Should be a small chunk or initial chunk, current chunk "
-          SIZE_FORMAT " new chunk " SIZE_FORMAT,
-          current_chunk()->word_size(), new_chunk->word_size()));
-        current_chunk()->set_next(NULL);
-      }
-      // First chunk to add to the list
-      set_chunks_in_use(MediumIndex, new_chunk);
-
-    } else {
-      // As a minimum the first medium chunk added would
-      // have become the _current_chunk
-      // so the _current_chunk has to be non-NULL here
-      // (although not necessarily still the first medium chunk).
-      assert(current_chunk()->word_size() == SpaceManager::MediumChunk,
-             "A medium chunk should the current chunk");
-      current_chunk()->set_next(new_chunk);
-    }
-    // Make current chunk
-    set_current_chunk(new_chunk);
-    break;
-  default: {
+    new_chunk->set_next(chunks_in_use(index));
+    set_chunks_in_use(index, new_chunk);
+  } else {
     // For null class loader data and DumpSharedSpaces, the first chunk isn't
     // small, so small will be null.  Link this first chunk as the current
     // chunk.
@@ -2002,8 +2129,7 @@
     new_chunk->set_next(chunks_in_use(HumongousIndex));
     set_chunks_in_use(HumongousIndex, new_chunk);
 
-    assert(new_chunk->word_size() > MediumChunk, "List inconsistency");
-  }
+    assert(new_chunk->word_size() > medium_chunk_size(), "List inconsistency");
   }
 
   assert(new_chunk->is_empty(), "Not ready for reuse");
@@ -2015,6 +2141,22 @@
   }
 }
 
+Metachunk* SpaceManager::get_new_chunk(size_t word_size,
+                                       size_t grow_chunks_by_words) {
+
+  Metachunk* next = vs_list()->get_new_chunk(word_size,
+                                             grow_chunks_by_words,
+                                             medium_chunk_bunch());
+
+  if (TraceMetadataHumongousAllocation &&
+      SpaceManager::is_humongous(next->word_size())) {
+    gclog_or_tty->print_cr("  new humongous chunk word size " PTR_FORMAT,
+                           next->word_size());
+  }
+
+  return next;
+}
+
 MetaWord* SpaceManager::allocate(size_t word_size) {
   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
 
@@ -2090,12 +2232,7 @@
   // verfication of chunks does not work since
   // being in the dictionary alters a chunk.
   if (block_freelists()->total_size() == 0) {
-    // Skip the small chunks because their next link points to
-    // medium chunks.  This is because the small chunk is the
-    // current chunk (for allocations) until it is full and the
-    // the addition of the next chunk does not NULL the next
-    // like of the small chunk.
-    for (ChunkIndex i = MediumIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
+    for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
       Metachunk* curr = chunks_in_use(i);
       while (curr != NULL) {
         curr->verify();
@@ -2108,15 +2245,15 @@
 
 void SpaceManager::verify_chunk_size(Metachunk* chunk) {
   assert(is_humongous(chunk->word_size()) ||
-         chunk->word_size() == MediumChunk ||
-         chunk->word_size() == SmallChunk,
+         chunk->word_size() == medium_chunk_size() ||
+         chunk->word_size() == small_chunk_size() ||
+         chunk->word_size() == specialized_chunk_size(),
          "Chunk size is wrong");
   return;
 }
 
 #ifdef ASSERT
 void SpaceManager::verify_allocation_total() {
-#if 0
   // Verification is only guaranteed at a safepoint.
   if (SafepointSynchronize::is_at_safepoint()) {
     gclog_or_tty->print_cr("Chunk " PTR_FORMAT " allocation_total " SIZE_FORMAT
@@ -2129,7 +2266,6 @@
   assert(allocation_total() == sum_used_in_chunks_in_use(),
     err_msg("allocation total is not consistent %d vs %d",
             allocation_total(), sum_used_in_chunks_in_use()));
-#endif
 }
 
 #endif
@@ -2142,7 +2278,7 @@
   size_t capacity = 0;
 
   // Add up statistics for all chunks in this SpaceManager.
-  for (ChunkIndex index = SmallIndex;
+  for (ChunkIndex index = ZeroIndex;
        index < NumberOfInUseLists;
        index = next_chunk_index(index)) {
     for (Metachunk* curr = chunks_in_use(index);
@@ -2160,7 +2296,7 @@
     }
   }
 
-  size_t free = current_chunk()->free_word_size();
+  size_t free = current_chunk() == NULL ? 0 : current_chunk()->free_word_size();
   // Free space isn't wasted.
   waste -= free;
 
@@ -2171,25 +2307,18 @@
 
 #ifndef PRODUCT
 void SpaceManager::mangle_freed_chunks() {
-  for (ChunkIndex index = SmallIndex;
+  for (ChunkIndex index = ZeroIndex;
        index < NumberOfInUseLists;
        index = next_chunk_index(index)) {
     for (Metachunk* curr = chunks_in_use(index);
          curr != NULL;
          curr = curr->next()) {
-      // Try to detect incorrectly terminated small chunk
-      // list.
-      assert(index == MediumIndex || curr != chunks_in_use(MediumIndex),
-             err_msg("Mangling medium chunks in small chunks? "
-                     "curr " PTR_FORMAT " medium list " PTR_FORMAT,
-                     curr, chunks_in_use(MediumIndex)));
       curr->mangle();
     }
   }
 }
 #endif // PRODUCT
 
-
 // MetaspaceAux
 
 size_t MetaspaceAux::used_in_bytes(Metaspace::MetadataType mdtype) {
@@ -2236,7 +2365,7 @@
   return reserved * BytesPerWord;
 }
 
-size_t MetaspaceAux::min_chunk_size() { return SpaceManager::MediumChunk; }
+size_t MetaspaceAux::min_chunk_size() { return Metaspace::first_chunk_word_size(); }
 
 size_t MetaspaceAux::free_chunks_total(Metaspace::MetadataType mdtype) {
   ChunkManager* chunk = (mdtype == Metaspace::ClassType) ?
@@ -2316,26 +2445,44 @@
 // Print total fragmentation for class and data metaspaces separately
 void MetaspaceAux::print_waste(outputStream* out) {
 
-  size_t small_waste = 0, medium_waste = 0, large_waste = 0;
-  size_t cls_small_waste = 0, cls_medium_waste = 0, cls_large_waste = 0;
+  size_t specialized_waste = 0, small_waste = 0, medium_waste = 0, large_waste = 0;
+  size_t specialized_count = 0, small_count = 0, medium_count = 0, large_count = 0;
+  size_t cls_specialized_waste = 0, cls_small_waste = 0, cls_medium_waste = 0, cls_large_waste = 0;
+  size_t cls_specialized_count = 0, cls_small_count = 0, cls_medium_count = 0, cls_large_count = 0;
 
   ClassLoaderDataGraphMetaspaceIterator iter;
   while (iter.repeat()) {
     Metaspace* msp = iter.get_next();
     if (msp != NULL) {
+      specialized_waste += msp->vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
+      specialized_count += msp->vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
       small_waste += msp->vsm()->sum_waste_in_chunks_in_use(SmallIndex);
+      small_count += msp->vsm()->sum_count_in_chunks_in_use(SmallIndex);
       medium_waste += msp->vsm()->sum_waste_in_chunks_in_use(MediumIndex);
+      medium_count += msp->vsm()->sum_count_in_chunks_in_use(MediumIndex);
       large_waste += msp->vsm()->sum_waste_in_chunks_in_use(HumongousIndex);
-
+      large_count += msp->vsm()->sum_count_in_chunks_in_use(HumongousIndex);
+
+      cls_specialized_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
+      cls_specialized_count += msp->class_vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
       cls_small_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SmallIndex);
+      cls_small_count += msp->class_vsm()->sum_count_in_chunks_in_use(SmallIndex);
       cls_medium_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(MediumIndex);
+      cls_medium_count += msp->class_vsm()->sum_count_in_chunks_in_use(MediumIndex);
       cls_large_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(HumongousIndex);
+      cls_large_count += msp->class_vsm()->sum_count_in_chunks_in_use(HumongousIndex);
     }
   }
   out->print_cr("Total fragmentation waste (words) doesn't count free space");
-  out->print("  data: small " SIZE_FORMAT " medium " SIZE_FORMAT,
-             small_waste, medium_waste);
-  out->print_cr(" class: small " SIZE_FORMAT, cls_small_waste);
+  out->print_cr("  data: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
+                        SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
+                        SIZE_FORMAT " medium(s) " SIZE_FORMAT,
+             specialized_count, specialized_waste, small_count,
+             small_waste, medium_count, medium_waste);
+  out->print_cr(" class: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
+                           SIZE_FORMAT " small(s) " SIZE_FORMAT,
+             cls_specialized_count, cls_specialized_waste,
+             cls_small_count, cls_small_waste);
 }
 
 // Dump global metaspace things from the end of ClassLoaderDataGraph
@@ -2354,13 +2501,10 @@
 // Metaspace methods
 
 size_t Metaspace::_first_chunk_word_size = 0;
-
-Metaspace::Metaspace(Mutex* lock, size_t word_size) {
-  initialize(lock, word_size);
-}
-
-Metaspace::Metaspace(Mutex* lock) {
-  initialize(lock);
+size_t Metaspace::_first_class_chunk_word_size = 0;
+
+Metaspace::Metaspace(Mutex* lock, MetaspaceType type) {
+  initialize(lock, type);
 }
 
 Metaspace::~Metaspace() {
@@ -2412,11 +2556,18 @@
       }
     }
 
-    // Initialize this before initializing the VirtualSpaceList
+    // Initialize these before initializing the VirtualSpaceList
     _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
+    _first_chunk_word_size = align_word_size_up(_first_chunk_word_size);
+    // Make the first class chunk bigger than a medium chunk so it's not put
+    // on the medium chunk list.   The next chunk will be small and progress
+    // from there.  This size calculated by -version.
+    _first_class_chunk_word_size = MIN2((size_t)MediumChunk*6,
+                                       (ClassMetaspaceSize/BytesPerWord)*2);
+    _first_class_chunk_word_size = align_word_size_up(_first_class_chunk_word_size);
     // Arbitrarily set the initial virtual space to a multiple
     // of the boot class loader size.
-    size_t word_size = VIRTUALSPACEMULTIPLIER * Metaspace::first_chunk_word_size();
+    size_t word_size = VIRTUALSPACEMULTIPLIER * first_chunk_word_size();
     // Initialize the list of virtual spaces.
     _space_list = new VirtualSpaceList(word_size);
   }
@@ -2431,23 +2582,8 @@
   _class_space_list = new VirtualSpaceList(rs);
 }
 
-
-void Metaspace::initialize(Mutex* lock, size_t initial_size) {
-  // Use SmallChunk size if not specified.   If specified, use this size for
-  // the data metaspace.
-  size_t word_size;
-  size_t class_word_size;
-  if (initial_size == 0) {
-    word_size = (size_t) SpaceManager::SmallChunk;
-    class_word_size = (size_t) SpaceManager::SmallChunk;
-  } else {
-    word_size = initial_size;
-    // Make the first class chunk bigger than a medium chunk so it's not put
-    // on the medium chunk list.   The next chunk will be small and progress
-    // from there.  This size calculated by -version.
-    class_word_size = MIN2((size_t)SpaceManager::MediumChunk*5,
-                           (ClassMetaspaceSize/BytesPerWord)*2);
-  }
+void Metaspace::initialize(Mutex* lock,
+                           MetaspaceType type) {
 
   assert(space_list() != NULL,
     "Metadata VirtualSpaceList has not been initialized");
@@ -2456,6 +2592,11 @@
   if (_vsm == NULL) {
     return;
   }
+  size_t word_size;
+  size_t class_word_size;
+  vsm()->get_initial_chunk_sizes(type,
+                                 &word_size,
+                                 &class_word_size);
 
   assert(class_space_list() != NULL,
     "Class VirtualSpaceList has not been initialized");
@@ -2470,7 +2611,8 @@
 
   // Allocate chunk for metadata objects
   Metachunk* new_chunk =
-     space_list()->current_virtual_space()->get_chunk_vs_with_expand(word_size);
+     space_list()->get_initialization_chunk(word_size,
+                                            vsm()->medium_chunk_bunch());
   assert(!DumpSharedSpaces || new_chunk != NULL, "should have enough space for both chunks");
   if (new_chunk != NULL) {
     // Add to this manager's list of chunks in use and current_chunk().
@@ -2479,12 +2621,18 @@
 
   // Allocate chunk for class metadata objects
   Metachunk* class_chunk =
-     class_space_list()->current_virtual_space()->get_chunk_vs_with_expand(class_word_size);
+     class_space_list()->get_initialization_chunk(class_word_size,
+                                                  class_vsm()->medium_chunk_bunch());
   if (class_chunk != NULL) {
     class_vsm()->add_chunk(class_chunk, true);
   }
 }
 
+size_t Metaspace::align_word_size_up(size_t word_size) {
+  size_t byte_size = word_size * wordSize;
+  return ReservedSpace::allocation_align_size_up(byte_size) / wordSize;
+}
+
 MetaWord* Metaspace::allocate(size_t word_size, MetadataType mdtype) {
   // DumpSharedSpaces doesn't use class metadata area (yet)
   if (mdtype == ClassType && !DumpSharedSpaces) {
@@ -2610,6 +2758,12 @@
 
     // If result is still null, we are out of memory.
     if (result == NULL) {
+      if (Verbose && TraceMetadataChunkAllocation) {
+        gclog_or_tty->print_cr("Metaspace allocation failed for size "
+          SIZE_FORMAT, word_size);
+        if (loader_data->metaspace_or_null() != NULL) loader_data->metaspace_or_null()->dump(gclog_or_tty);
+        MetaspaceAux::dump(gclog_or_tty);
+      }
       // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
       report_java_out_of_memory("Metadata space");
 
--- a/hotspot/src/share/vm/memory/metaspace.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/metaspace.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -87,11 +87,23 @@
 
  public:
   enum MetadataType {ClassType, NonClassType};
+  enum MetaspaceType {
+    StandardMetaspaceType,
+    BootMetaspaceType,
+    ROMetaspaceType,
+    ReadWriteMetaspaceType,
+    AnonymousMetaspaceType,
+    ReflectionMetaspaceType
+  };
 
  private:
-  void initialize(Mutex* lock, size_t initial_size = 0);
+  void initialize(Mutex* lock, MetaspaceType type);
+
+  // Align up the word size to the allocation word size
+  static size_t align_word_size_up(size_t);
 
   static size_t _first_chunk_word_size;
+  static size_t _first_class_chunk_word_size;
 
   SpaceManager* _vsm;
   SpaceManager* vsm() const { return _vsm; }
@@ -110,8 +122,7 @@
 
  public:
 
-  Metaspace(Mutex* lock, size_t initial_size);
-  Metaspace(Mutex* lock);
+  Metaspace(Mutex* lock, MetaspaceType type);
   ~Metaspace();
 
   // Initialize globals for Metaspace
@@ -119,6 +130,7 @@
   static void initialize_class_space(ReservedSpace rs);
 
   static size_t first_chunk_word_size() { return _first_chunk_word_size; }
+  static size_t first_class_chunk_word_size() { return _first_class_chunk_word_size; }
 
   char*  bottom() const;
   size_t used_words(MetadataType mdtype) const;
--- a/hotspot/src/share/vm/memory/metaspaceCounters.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/metaspaceCounters.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/metaspaceCounters.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/metaspaceCounters.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/memory/metaspaceShared.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/metaspaceShared.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -373,17 +373,44 @@
   md_top = wc.get_top();
 
   // Print shared spaces all the time
-  const char* fmt = "%s space: " PTR_FORMAT " out of " PTR_FORMAT " words allocated at " PTR_FORMAT ".";
+  const char* fmt = "%s space: %9d [ %4.1f%% of total] out of %9d bytes [%4.1f%% used] at " PTR_FORMAT;
   Metaspace* ro_space = _loader_data->ro_metaspace();
   Metaspace* rw_space = _loader_data->rw_metaspace();
-  tty->print_cr(fmt, "ro", ro_space->used_words(Metaspace::NonClassType),
-                ro_space->capacity_words(Metaspace::NonClassType),
-                ro_space->bottom());
-  tty->print_cr(fmt, "rw", rw_space->used_words(Metaspace::NonClassType),
-                rw_space->capacity_words(Metaspace::NonClassType),
-                rw_space->bottom());
-  tty->print_cr(fmt, "md", md_top - md_low, md_end-md_low, md_low);
-  tty->print_cr(fmt, "mc", mc_top - mc_low, mc_end-mc_low, mc_low);
+  const size_t BPW = BytesPerWord;
+
+  // Allocated size of each space (may not be all occupied)
+  const size_t ro_alloced = ro_space->capacity_words(Metaspace::NonClassType) * BPW;
+  const size_t rw_alloced = rw_space->capacity_words(Metaspace::NonClassType) * BPW;
+  const size_t md_alloced = md_end-md_low;
+  const size_t mc_alloced = mc_end-mc_low;
+  const size_t total_alloced = ro_alloced + rw_alloced + md_alloced + mc_alloced;
+
+  // Occupied size of each space.
+  const size_t ro_bytes = ro_space->used_words(Metaspace::NonClassType) * BPW;
+  const size_t rw_bytes = rw_space->used_words(Metaspace::NonClassType) * BPW;
+  const size_t md_bytes = size_t(md_top - md_low);
+  const size_t mc_bytes = size_t(mc_top - mc_low);
+
+  // Percent of total size
+  const size_t total_bytes = ro_bytes + rw_bytes + md_bytes + mc_bytes;
+  const double ro_t_perc = ro_bytes / double(total_bytes) * 100.0;
+  const double rw_t_perc = rw_bytes / double(total_bytes) * 100.0;
+  const double md_t_perc = md_bytes / double(total_bytes) * 100.0;
+  const double mc_t_perc = mc_bytes / double(total_bytes) * 100.0;
+
+  // Percent of fullness of each space
+  const double ro_u_perc = ro_bytes / double(ro_alloced) * 100.0;
+  const double rw_u_perc = rw_bytes / double(rw_alloced) * 100.0;
+  const double md_u_perc = md_bytes / double(md_alloced) * 100.0;
+  const double mc_u_perc = mc_bytes / double(mc_alloced) * 100.0;
+  const double total_u_perc = total_bytes / double(total_alloced) * 100.0;
+
+  tty->print_cr(fmt, "ro", ro_bytes, ro_t_perc, ro_alloced, ro_u_perc, ro_space->bottom());
+  tty->print_cr(fmt, "rw", rw_bytes, rw_t_perc, rw_alloced, rw_u_perc, rw_space->bottom());
+  tty->print_cr(fmt, "md", md_bytes, md_t_perc, md_alloced, md_u_perc, md_low);
+  tty->print_cr(fmt, "mc", mc_bytes, mc_t_perc, mc_alloced, mc_u_perc, mc_low);
+  tty->print_cr("total   : %9d [100.0%% of total] out of %9d bytes [%4.1f%% used]",
+                 total_bytes, total_alloced, total_u_perc);
 
   // Update the vtable pointers in all of the Klass objects in the
   // heap. They should point to newly generated vtable.
--- a/hotspot/src/share/vm/memory/space.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/space.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -411,7 +411,6 @@
     assert(q->forwardee() == NULL, "should be forwarded to NULL");
   }
 
-  VALIDATE_MARK_SWEEP_ONLY(MarkSweep::register_live_oop(q, size));
   compact_top += size;
 
   // we need to update the offset table so that the beginnings of objects can be
@@ -470,13 +469,10 @@
     if (oop(q)->is_gc_marked()) {
       // q is alive
 
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::track_interior_pointers(oop(q)));
       // point all the oops to the new location
       size_t size = oop(q)->adjust_pointers();
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::check_interior_pointers());
 
       debug_only(prev_q = q);
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::validate_live_oop(oop(q), size));
 
       q += size;
     } else {
--- a/hotspot/src/share/vm/memory/space.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/space.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -655,16 +655,10 @@
       assert(block_is_obj(q),                                                   \
              "should be at block boundaries, and should be looking at objs");   \
                                                                                 \
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::track_interior_pointers(oop(q)));     \
-                                                                                \
       /* point all the oops to the new location */                              \
       size_t size = oop(q)->adjust_pointers();                                  \
       size = adjust_obj_size(size);                                             \
                                                                                 \
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::check_interior_pointers());           \
-                                                                                \
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::validate_live_oop(oop(q), size));     \
-                                                                                \
       q += size;                                                                \
     }                                                                           \
                                                                                 \
@@ -685,12 +679,9 @@
     Prefetch::write(q, interval);                                               \
     if (oop(q)->is_gc_marked()) {                                               \
       /* q is alive */                                                          \
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::track_interior_pointers(oop(q)));     \
       /* point all the oops to the new location */                              \
       size_t size = oop(q)->adjust_pointers();                                  \
       size = adjust_obj_size(size);                                             \
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::check_interior_pointers());           \
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::validate_live_oop(oop(q), size));     \
       debug_only(prev_q = q);                                                   \
       q += size;                                                                \
     } else {                                                                    \
@@ -725,7 +716,6 @@
       size_t size = obj_size(q);                                                \
       assert(!oop(q)->is_gc_marked(),                                           \
              "should be unmarked (special dense prefix handling)");             \
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::live_oop_moved_to(q, size, q));       \
       debug_only(prev_q = q);                                                   \
       q += size;                                                                \
     }                                                                           \
@@ -759,8 +749,6 @@
       Prefetch::write(compaction_top, copy_interval);                           \
                                                                                 \
       /* copy object and reinit its mark */                                     \
-      VALIDATE_MARK_SWEEP_ONLY(MarkSweep::live_oop_moved_to(q, size,            \
-                                                            compaction_top));   \
       assert(q != compaction_top, "everything in this pass should be moving");  \
       Copy::aligned_conjoint_words(q, compaction_top, size);                    \
       oop(compaction_top)->init_mark();                                         \
--- a/hotspot/src/share/vm/memory/tenuredGeneration.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/tenuredGeneration.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -62,7 +62,7 @@
                                        _virtual_space.reserved_size(),
                                        _the_space, _gen_counters);
 #ifndef SERIALGC
-  if (UseParNewGC && ParallelGCThreads > 0) {
+  if (UseParNewGC) {
     typedef ParGCAllocBufferWithBOT* ParGCAllocBufferWithBOTPtr;
     _alloc_buffers = NEW_C_HEAP_ARRAY(ParGCAllocBufferWithBOTPtr,
                                       ParallelGCThreads, mtGC);
--- a/hotspot/src/share/vm/memory/universe.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/memory/universe.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -228,7 +228,7 @@
   if (size < alignment || size % alignment != 0) {
     ResourceMark rm;
     stringStream st;
-    st.print("Size of %s (%ld bytes) must be aligned to %ld bytes", name, size, alignment);
+    st.print("Size of %s (" UINTX_FORMAT " bytes) must be aligned to " UINTX_FORMAT " bytes", name, size, alignment);
     char* error = st.as_string();
     vm_exit_during_initialization(error);
   }
--- a/hotspot/src/share/vm/oops/constMethod.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/oops/constMethod.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -122,7 +122,12 @@
 class MethodParametersElement VALUE_OBJ_CLASS_SPEC {
  public:
   u2 name_cp_index;
-  u4 flags;
+  // This has to happen, otherwise it will cause SIGBUS from a
+  // misaligned u4 on some architectures (ie SPARC)
+  // because MethodParametersElements are only aligned mod 2
+  // within the ConstMethod container  u2 flags_hi;
+  u2 flags_hi;
+  u2 flags_lo;
 };
 
 
--- a/hotspot/src/share/vm/oops/constantPool.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/oops/constantPool.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -66,7 +66,7 @@
   set_pool_holder(NULL);
   set_flags(0);
   // only set to non-zero if constant pool is merged by RedefineClasses
-  set_orig_length(0);
+  set_version(0);
   set_lock(new Monitor(Monitor::nonleaf + 2, "A constant pool lock"));
   // all fields are initialized; needed for GC
   set_on_stack(false);
--- a/hotspot/src/share/vm/oops/constantPool.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/oops/constantPool.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -103,8 +103,8 @@
   union {
     // set for CDS to restore resolved references
     int                _resolved_reference_length;
-  // only set to non-zero if constant pool is merged by RedefineClasses
-  int                  _orig_length;
+    // keeps version number for redefined classes (used in backtrace)
+    int                _version;
   } _saved;
 
   Monitor*             _lock;
@@ -784,8 +784,11 @@
   static void copy_cp_to_impl(constantPoolHandle from_cp, int start_i, int end_i, constantPoolHandle to_cp, int to_i, TRAPS);
   static void copy_entry_to(constantPoolHandle from_cp, int from_i, constantPoolHandle to_cp, int to_i, TRAPS);
   int  find_matching_entry(int pattern_i, constantPoolHandle search_cp, TRAPS);
-  int  orig_length() const                { return _saved._orig_length; }
-  void set_orig_length(int orig_length)   { _saved._orig_length = orig_length; }
+  int  version() const                    { return _saved._version; }
+  void set_version(int version)           { _saved._version = version; }
+  void increment_and_save_version(int version) {
+    _saved._version = version >= 0 ? (version + 1) : version;  // keep overflow
+  }
 
   void set_resolved_reference_length(int length) { _saved._resolved_reference_length = length; }
   int  resolved_reference_length() const  { return _saved._resolved_reference_length; }
--- a/hotspot/src/share/vm/oops/instanceKlass.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/oops/instanceKlass.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -2890,11 +2890,7 @@
     st->print(BULLET"fake entry for mirror: ");
     mirrored_klass->print_value_on_maybe_null(st);
     st->cr();
-    st->print(BULLET"fake entry resolved_constructor: ");
-    Method* ctor = java_lang_Class::resolved_constructor(obj);
-    ctor->print_value_on_maybe_null(st);
     Klass* array_klass = java_lang_Class::array_klass(obj);
-    st->cr();
     st->print(BULLET"fake entry for array: ");
     array_klass->print_value_on_maybe_null(st);
     st->cr();
--- a/hotspot/src/share/vm/oops/instanceKlass.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/oops/instanceKlass.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -225,13 +225,17 @@
   u2              _java_fields_count;    // The number of declared Java fields
   int             _nonstatic_oop_map_size;// size in words of nonstatic oop map blocks
 
+  // _is_marked_dependent can be set concurrently, thus cannot be part of the
+  // _misc_flags.
   bool            _is_marked_dependent;  // used for marking during flushing and deoptimization
+
   enum {
     _misc_rewritten            = 1 << 0, // methods rewritten.
     _misc_has_nonstatic_fields = 1 << 1, // for sizing with UseCompressedOops
     _misc_should_verify_class  = 1 << 2, // allow caching of preverification
     _misc_is_anonymous         = 1 << 3, // has embedded _inner_classes field
-    _misc_is_contended         = 1 << 4  // marked with contended annotation
+    _misc_is_contended         = 1 << 4, // marked with contended annotation
+    _misc_has_default_methods  = 1 << 5  // class/superclass/implemented interfaces has default methods
   };
   u2              _misc_flags;
   u2              _minor_version;        // minor version number of class file
@@ -254,10 +258,6 @@
   jint            _cached_class_file_len;         // JVMTI: length of above
   JvmtiCachedClassFieldMap* _jvmti_cached_class_field_map;  // JVMTI: used during heap iteration
 
-  // true if class, superclass, or implemented interfaces have default methods
-  bool            _has_default_methods;
-
-  volatile u2     _idnum_allocated_count;         // JNI/JVMTI: increments with the addition of methods, old ids don't change
   // Method array.
   Array<Method*>* _methods;
   // Interface (Klass*s) this class declares locally to implement.
@@ -281,6 +281,8 @@
   //     ...
   Array<u2>*      _fields;
 
+  volatile u2     _idnum_allocated_count;         // JNI/JVMTI: increments with the addition of methods, old ids don't change
+
   // Class states are defined as ClassState (see above).
   // Place the _init_state here to utilize the unused 2-byte after
   // _idnum_allocated_count.
@@ -628,8 +630,16 @@
     return _jvmti_cached_class_field_map;
   }
 
-  bool has_default_methods() const { return _has_default_methods; }
-  void set_has_default_methods(bool b) { _has_default_methods = b; }
+  bool has_default_methods() const {
+    return (_misc_flags & _misc_has_default_methods) != 0;
+  }
+  void set_has_default_methods(bool b) {
+    if (b) {
+      _misc_flags |= _misc_has_default_methods;
+    } else {
+      _misc_flags &= ~_misc_has_default_methods;
+    }
+  }
 
   // for adding methods, ConstMethod::UNSET_IDNUM means no more ids available
   inline u2 next_method_idnum();
--- a/hotspot/src/share/vm/oops/method.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/oops/method.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -194,16 +194,16 @@
   return buf;
 }
 
-int  Method::fast_exception_handler_bci_for(KlassHandle ex_klass, int throw_bci, TRAPS) {
+int Method::fast_exception_handler_bci_for(methodHandle mh, KlassHandle ex_klass, int throw_bci, TRAPS) {
   // exception table holds quadruple entries of the form (beg_bci, end_bci, handler_bci, klass_index)
   // access exception table
-  ExceptionTable table(this);
+  ExceptionTable table(mh());
   int length = table.length();
   // iterate through all entries sequentially
-  constantPoolHandle pool(THREAD, constants());
+  constantPoolHandle pool(THREAD, mh->constants());
   for (int i = 0; i < length; i ++) {
     //reacquire the table in case a GC happened
-    ExceptionTable table(this);
+    ExceptionTable table(mh());
     int beg_bci = table.start_pc(i);
     int end_bci = table.end_pc(i);
     assert(beg_bci <= end_bci, "inconsistent exception table");
--- a/hotspot/src/share/vm/oops/method.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/oops/method.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -351,7 +351,7 @@
   // exception handler which caused the exception to be thrown, which
   // is needed for proper retries. See, for example,
   // InterpreterRuntime::exception_handler_for_exception.
-  int fast_exception_handler_bci_for(KlassHandle ex_klass, int throw_bci, TRAPS);
+  static int fast_exception_handler_bci_for(methodHandle mh, KlassHandle ex_klass, int throw_bci, TRAPS);
 
   // method data access
   MethodData* method_data() const              {
--- a/hotspot/src/share/vm/opto/bytecodeInfo.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/bytecodeInfo.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -46,7 +46,8 @@
   _method(callee),
   _site_invoke_ratio(site_invoke_ratio),
   _max_inline_level(max_inline_level),
-  _count_inline_bcs(method()->code_size_for_inlining())
+  _count_inline_bcs(method()->code_size_for_inlining()),
+  _subtrees(c->comp_arena(), 2, 0, NULL)
 {
   NOT_PRODUCT(_count_inlines = 0;)
   if (_caller_jvms != NULL) {
@@ -209,16 +210,18 @@
   if ( callee_method->dont_inline())                        return "don't inline by annotation";
   if ( callee_method->has_unloaded_classes_in_signature())  return "unloaded signature classes";
 
-  if (callee_method->force_inline() || callee_method->should_inline()) {
+  if (callee_method->should_inline()) {
     // ignore heuristic controls on inlining
     return NULL;
   }
 
   // Now perform checks which are heuristic
 
-  if (callee_method->has_compiled_code() &&
-      callee_method->instructions_size() > InlineSmallCode) {
+  if (!callee_method->force_inline()) {
+    if (callee_method->has_compiled_code() &&
+        callee_method->instructions_size() > InlineSmallCode) {
     return "already compiled into a big method";
+    }
   }
 
   // don't inline exception code unless the top method belongs to an
@@ -277,12 +280,15 @@
 //-----------------------------try_to_inline-----------------------------------
 // return NULL if ok, reason for not inlining otherwise
 // Relocated from "InliningClosure::try_to_inline"
-const char* InlineTree::try_to_inline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result) {
-
+const char* InlineTree::try_to_inline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result, bool& should_delay) {
   // Old algorithm had funny accumulating BC-size counters
   if (UseOldInlining && ClipInlining
       && (int)count_inline_bcs() >= DesiredMethodLimit) {
-    return "size > DesiredMethodLimit";
+    if (!callee_method->force_inline() || !IncrementalInline) {
+      return "size > DesiredMethodLimit";
+    } else if (!C->inlining_incrementally()) {
+      should_delay = true;
+    }
   }
 
   const char *msg = NULL;
@@ -303,8 +309,13 @@
   if (callee_method->code_size() > MaxTrivialSize) {
 
     // don't inline into giant methods
-    if (C->unique() > (uint)NodeCountInliningCutoff) {
-      return "NodeCountInliningCutoff";
+    if (C->over_inlining_cutoff()) {
+      if ((!callee_method->force_inline() && !caller_method->is_compiled_lambda_form())
+          || !IncrementalInline) {
+        return "NodeCountInliningCutoff";
+      } else {
+        should_delay = true;
+      }
     }
 
     if ((!UseInterpreter || CompileTheWorld) &&
@@ -323,7 +334,11 @@
     return "not an accessor";
   }
   if (inline_level() > _max_inline_level) {
-    return "inlining too deep";
+    if (!callee_method->force_inline() || !IncrementalInline) {
+      return "inlining too deep";
+    } else if (!C->inlining_incrementally()) {
+      should_delay = true;
+    }
   }
 
   // detect direct and indirect recursive inlining
@@ -348,7 +363,11 @@
 
   if (UseOldInlining && ClipInlining
       && (int)count_inline_bcs() + size >= DesiredMethodLimit) {
-    return "size > DesiredMethodLimit";
+    if (!callee_method->force_inline() || !IncrementalInline) {
+      return "size > DesiredMethodLimit";
+    } else if (!C->inlining_incrementally()) {
+      should_delay = true;
+    }
   }
 
   // ok, inline this method
@@ -413,8 +432,9 @@
 }
 
 //------------------------------ok_to_inline-----------------------------------
-WarmCallInfo* InlineTree::ok_to_inline(ciMethod* callee_method, JVMState* jvms, ciCallProfile& profile, WarmCallInfo* initial_wci) {
+WarmCallInfo* InlineTree::ok_to_inline(ciMethod* callee_method, JVMState* jvms, ciCallProfile& profile, WarmCallInfo* initial_wci, bool& should_delay) {
   assert(callee_method != NULL, "caller checks for optimized virtual!");
+  assert(!should_delay, "should be initialized to false");
 #ifdef ASSERT
   // Make sure the incoming jvms has the same information content as me.
   // This means that we can eventually make this whole class AllStatic.
@@ -444,7 +464,7 @@
 
   // Check if inlining policy says no.
   WarmCallInfo wci = *(initial_wci);
-  failure_msg = try_to_inline(callee_method, caller_method, caller_bci, profile, &wci);
+  failure_msg = try_to_inline(callee_method, caller_method, caller_bci, profile, &wci, should_delay);
   if (failure_msg != NULL && C->log() != NULL) {
     C->log()->inline_fail(failure_msg);
   }
--- a/hotspot/src/share/vm/opto/c2_globals.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/c2_globals.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -606,6 +606,16 @@
                                                                             \
   develop(bool, VerifyAliases, false,                                       \
           "perform extra checks on the results of alias analysis")          \
+                                                                            \
+  product(bool, IncrementalInline, true,                                    \
+          "do post parse inlining")                                         \
+                                                                            \
+  develop(bool, AlwaysIncrementalInline, false,                             \
+          "do all inlining incrementally")                                  \
+                                                                            \
+  product(intx, LiveNodeCountInliningCutoff, 20000,                         \
+          "max number of live nodes in a method")                           \
+
 
 C2_FLAGS(DECLARE_DEVELOPER_FLAG, DECLARE_PD_DEVELOPER_FLAG, DECLARE_PRODUCT_FLAG, DECLARE_PD_PRODUCT_FLAG, DECLARE_DIAGNOSTIC_FLAG, DECLARE_EXPERIMENTAL_FLAG, DECLARE_NOTPRODUCT_FLAG)
 
--- a/hotspot/src/share/vm/opto/callGenerator.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/callGenerator.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -262,8 +262,11 @@
 
 // Allow inlining decisions to be delayed
 class LateInlineCallGenerator : public DirectCallGenerator {
+ protected:
   CallGenerator* _inline_cg;
 
+  virtual bool do_late_inline_check(JVMState* jvms) { return true; }
+
  public:
   LateInlineCallGenerator(ciMethod* method, CallGenerator* inline_cg) :
     DirectCallGenerator(method, true), _inline_cg(inline_cg) {}
@@ -279,7 +282,9 @@
 
     // Record that this call site should be revisited once the main
     // parse is finished.
-    Compile::current()->add_late_inline(this);
+    if (!is_mh_late_inline()) {
+      C->add_late_inline(this);
+    }
 
     // Emit the CallStaticJava and request separate projections so
     // that the late inlining logic can distinguish between fall
@@ -287,15 +292,34 @@
     // as is done for allocations and macro expansion.
     return DirectCallGenerator::generate(jvms);
   }
+
+  virtual void print_inlining_late(const char* msg) {
+    CallNode* call = call_node();
+    Compile* C = Compile::current();
+    C->print_inlining_insert(this);
+    C->print_inlining(method(), call->jvms()->depth()-1, call->jvms()->bci(), msg);
+  }
+
 };
 
-
 void LateInlineCallGenerator::do_late_inline() {
   // Can't inline it
   if (call_node() == NULL || call_node()->outcnt() == 0 ||
       call_node()->in(0) == NULL || call_node()->in(0)->is_top())
     return;
 
+  for (int i1 = 0; i1 < method()->arg_size(); i1++) {
+    if (call_node()->in(TypeFunc::Parms + i1)->is_top()) {
+      assert(Compile::current()->inlining_incrementally(), "shouldn't happen during parsing");
+      return;
+    }
+  }
+
+  if (call_node()->in(TypeFunc::Memory)->is_top()) {
+    assert(Compile::current()->inlining_incrementally(), "shouldn't happen during parsing");
+    return;
+  }
+
   CallStaticJavaNode* call = call_node();
 
   // Make a clone of the JVMState that appropriate to use for driving a parse
@@ -324,6 +348,11 @@
     }
   }
 
+  if (!do_late_inline_check(jvms)) {
+    map->disconnect_inputs(NULL, C);
+    return;
+  }
+
   C->print_inlining_insert(this);
 
   CompileLog* log = C->log();
@@ -360,6 +389,10 @@
     result = (result_size == 1) ? kit.pop() : kit.pop_pair();
   }
 
+  C->set_has_loops(C->has_loops() || _inline_cg->method()->has_loops());
+  C->env()->notice_inlined_method(_inline_cg->method());
+  C->set_inlining_progress(true);
+
   kit.replace_call(call, result);
 }
 
@@ -368,6 +401,83 @@
   return new LateInlineCallGenerator(method, inline_cg);
 }
 
+class LateInlineMHCallGenerator : public LateInlineCallGenerator {
+  ciMethod* _caller;
+  int _attempt;
+  bool _input_not_const;
+
+  virtual bool do_late_inline_check(JVMState* jvms);
+  virtual bool already_attempted() const { return _attempt > 0; }
+
+ public:
+  LateInlineMHCallGenerator(ciMethod* caller, ciMethod* callee, bool input_not_const) :
+    LateInlineCallGenerator(callee, NULL), _caller(caller), _attempt(0), _input_not_const(input_not_const) {}
+
+  virtual bool is_mh_late_inline() const { return true; }
+
+  virtual JVMState* generate(JVMState* jvms) {
+    JVMState* new_jvms = LateInlineCallGenerator::generate(jvms);
+    if (_input_not_const) {
+      // inlining won't be possible so no need to enqueue right now.
+      call_node()->set_generator(this);
+    } else {
+      Compile::current()->add_late_inline(this);
+    }
+    return new_jvms;
+  }
+
+  virtual void print_inlining_late(const char* msg) {
+    if (!_input_not_const) return;
+    LateInlineCallGenerator::print_inlining_late(msg);
+  }
+};
+
+bool LateInlineMHCallGenerator::do_late_inline_check(JVMState* jvms) {
+
+  CallGenerator* cg = for_method_handle_inline(jvms, _caller, method(), _input_not_const);
+
+  if (!_input_not_const) {
+    _attempt++;
+  }
+
+  if (cg != NULL) {
+    assert(!cg->is_late_inline() && cg->is_inline(), "we're doing late inlining");
+    _inline_cg = cg;
+    Compile::current()->dec_number_of_mh_late_inlines();
+    return true;
+  }
+
+  call_node()->set_generator(this);
+  return false;
+}
+
+CallGenerator* CallGenerator::for_mh_late_inline(ciMethod* caller, ciMethod* callee, bool input_not_const) {
+  Compile::current()->inc_number_of_mh_late_inlines();
+  CallGenerator* cg = new LateInlineMHCallGenerator(caller, callee, input_not_const);
+  return cg;
+}
+
+class LateInlineStringCallGenerator : public LateInlineCallGenerator {
+
+ public:
+  LateInlineStringCallGenerator(ciMethod* method, CallGenerator* inline_cg) :
+    LateInlineCallGenerator(method, inline_cg) {}
+
+  virtual JVMState* generate(JVMState* jvms) {
+    Compile *C = Compile::current();
+    C->print_inlining_skip(this);
+
+    C->add_string_late_inline(this);
+
+    JVMState* new_jvms =  DirectCallGenerator::generate(jvms);
+    return new_jvms;
+  }
+};
+
+CallGenerator* CallGenerator::for_string_late_inline(ciMethod* method, CallGenerator* inline_cg) {
+  return new LateInlineStringCallGenerator(method, inline_cg);
+}
+
 
 //---------------------------WarmCallGenerator--------------------------------
 // Internal class which handles initial deferral of inlining decisions.
@@ -586,35 +696,53 @@
 }
 
 
-CallGenerator* CallGenerator::for_method_handle_call(JVMState* jvms, ciMethod* caller, ciMethod* callee) {
+CallGenerator* CallGenerator::for_method_handle_call(JVMState* jvms, ciMethod* caller, ciMethod* callee, bool delayed_forbidden) {
   assert(callee->is_method_handle_intrinsic() ||
          callee->is_compiled_lambda_form(), "for_method_handle_call mismatch");
-  CallGenerator* cg = CallGenerator::for_method_handle_inline(jvms, caller, callee);
-  if (cg != NULL)
-    return cg;
-  return CallGenerator::for_direct_call(callee);
+  bool input_not_const;
+  CallGenerator* cg = CallGenerator::for_method_handle_inline(jvms, caller, callee, input_not_const);
+  Compile* C = Compile::current();
+  if (cg != NULL) {
+    if (!delayed_forbidden && AlwaysIncrementalInline) {
+      return CallGenerator::for_late_inline(callee, cg);
+    } else {
+      return cg;
+    }
+  }
+  int bci = jvms->bci();
+  ciCallProfile profile = caller->call_profile_at_bci(bci);
+  int call_site_count = caller->scale_count(profile.count());
+
+  if (IncrementalInline && call_site_count > 0 &&
+      (input_not_const || !C->inlining_incrementally() || C->over_inlining_cutoff())) {
+    return CallGenerator::for_mh_late_inline(caller, callee, input_not_const);
+  } else {
+    // Out-of-line call.
+    return CallGenerator::for_direct_call(callee);
+  }
 }
 
-CallGenerator* CallGenerator::for_method_handle_inline(JVMState* jvms, ciMethod* caller, ciMethod* callee) {
+CallGenerator* CallGenerator::for_method_handle_inline(JVMState* jvms, ciMethod* caller, ciMethod* callee, bool& input_not_const) {
   GraphKit kit(jvms);
   PhaseGVN& gvn = kit.gvn();
   Compile* C = kit.C;
   vmIntrinsics::ID iid = callee->intrinsic_id();
+  input_not_const = true;
   switch (iid) {
   case vmIntrinsics::_invokeBasic:
     {
       // Get MethodHandle receiver:
       Node* receiver = kit.argument(0);
       if (receiver->Opcode() == Op_ConP) {
+        input_not_const = false;
         const TypeOopPtr* oop_ptr = receiver->bottom_type()->is_oopptr();
         ciMethod* target = oop_ptr->const_oop()->as_method_handle()->get_vmtarget();
         guarantee(!target->is_method_handle_intrinsic(), "should not happen");  // XXX remove
         const int vtable_index = Method::invalid_vtable_index;
-        CallGenerator* cg = C->call_generator(target, vtable_index, false, jvms, true, PROB_ALWAYS);
+        CallGenerator* cg = C->call_generator(target, vtable_index, false, jvms, true, PROB_ALWAYS, true, true);
+        assert(!cg->is_late_inline() || cg->is_mh_late_inline(), "no late inline here");
         if (cg != NULL && cg->is_inline())
           return cg;
-      } else {
-        if (PrintInlining)  C->print_inlining(callee, jvms->depth() - 1, jvms->bci(), "receiver not constant");
       }
     }
     break;
@@ -627,6 +755,7 @@
       // Get MemberName argument:
       Node* member_name = kit.argument(callee->arg_size() - 1);
       if (member_name->Opcode() == Op_ConP) {
+        input_not_const = false;
         const TypeOopPtr* oop_ptr = member_name->bottom_type()->is_oopptr();
         ciMethod* target = oop_ptr->const_oop()->as_member_name()->get_vmtarget();
 
@@ -659,9 +788,25 @@
             }
           }
         }
-        const int vtable_index = Method::invalid_vtable_index;
-        const bool call_is_virtual = target->is_abstract();  // FIXME workaround
-        CallGenerator* cg = C->call_generator(target, vtable_index, call_is_virtual, jvms, true, PROB_ALWAYS);
+
+        // Try to get the most accurate receiver type
+        const bool is_virtual              = (iid == vmIntrinsics::_linkToVirtual);
+        const bool is_virtual_or_interface = (is_virtual || iid == vmIntrinsics::_linkToInterface);
+        int  vtable_index       = Method::invalid_vtable_index;
+        bool call_does_dispatch = false;
+
+        if (is_virtual_or_interface) {
+          ciInstanceKlass* klass = target->holder();
+          Node*             receiver_node = kit.argument(0);
+          const TypeOopPtr* receiver_type = gvn.type(receiver_node)->isa_oopptr();
+          // call_does_dispatch and vtable_index are out-parameters.  They might be changed.
+          target = C->optimize_virtual_call(caller, jvms->bci(), klass, target, receiver_type,
+                                            is_virtual,
+                                            call_does_dispatch, vtable_index);  // out-parameters
+        }
+
+        CallGenerator* cg = C->call_generator(target, vtable_index, call_does_dispatch, jvms, true, PROB_ALWAYS, true, true);
+        assert(!cg->is_late_inline() || cg->is_mh_late_inline(), "no late inline here");
         if (cg != NULL && cg->is_inline())
           return cg;
       }
--- a/hotspot/src/share/vm/opto/callGenerator.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/callGenerator.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -68,6 +68,12 @@
 
   // is_late_inline: supports conversion of call into an inline
   virtual bool      is_late_inline() const      { return false; }
+  // same but for method handle calls
+  virtual bool      is_mh_late_inline() const   { return false; }
+
+  // for method handle calls: have we tried inlinining the call already?
+  virtual bool      already_attempted() const   { ShouldNotReachHere(); return false; }
+
   // Replace the call with an inline version of the code
   virtual void do_late_inline() { ShouldNotReachHere(); }
 
@@ -112,11 +118,13 @@
   static CallGenerator* for_virtual_call(ciMethod* m, int vtable_index);  // virtual, interface
   static CallGenerator* for_dynamic_call(ciMethod* m);   // invokedynamic
 
-  static CallGenerator* for_method_handle_call(  JVMState* jvms, ciMethod* caller, ciMethod* callee);
-  static CallGenerator* for_method_handle_inline(JVMState* jvms, ciMethod* caller, ciMethod* callee);
+  static CallGenerator* for_method_handle_call(  JVMState* jvms, ciMethod* caller, ciMethod* callee, bool delayed_forbidden);
+  static CallGenerator* for_method_handle_inline(JVMState* jvms, ciMethod* caller, ciMethod* callee, bool& input_not_const);
 
   // How to generate a replace a direct call with an inline version
   static CallGenerator* for_late_inline(ciMethod* m, CallGenerator* inline_cg);
+  static CallGenerator* for_mh_late_inline(ciMethod* caller, ciMethod* callee, bool input_not_const);
+  static CallGenerator* for_string_late_inline(ciMethod* m, CallGenerator* inline_cg);
 
   // How to make a call but defer the decision whether to inline or not.
   static CallGenerator* for_warm_call(WarmCallInfo* ci,
@@ -147,6 +155,8 @@
                                                 CallGenerator* cg);
   virtual Node* generate_predicate(JVMState* jvms) { return NULL; };
 
+  virtual void print_inlining_late(const char* msg) { ShouldNotReachHere(); }
+
   static void print_inlining(Compile* C, ciMethod* callee, int inline_level, int bci, const char* msg) {
     if (PrintInlining)
       C->print_inlining(callee, inline_level, bci, msg);
--- a/hotspot/src/share/vm/opto/callnode.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/callnode.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -25,6 +25,7 @@
 #include "precompiled.hpp"
 #include "ci/bcEscapeAnalyzer.hpp"
 #include "compiler/oopMap.hpp"
+#include "opto/callGenerator.hpp"
 #include "opto/callnode.hpp"
 #include "opto/escape.hpp"
 #include "opto/locknode.hpp"
@@ -775,16 +776,38 @@
   // and the exception object may not exist if an exception handler
   // swallows the exception but all the other must exist and be found.
   assert(projs->fallthrough_proj      != NULL, "must be found");
-  assert(projs->fallthrough_catchproj != NULL, "must be found");
-  assert(projs->fallthrough_memproj   != NULL, "must be found");
-  assert(projs->fallthrough_ioproj    != NULL, "must be found");
-  assert(projs->catchall_catchproj    != NULL, "must be found");
+  assert(Compile::current()->inlining_incrementally() || projs->fallthrough_catchproj != NULL, "must be found");
+  assert(Compile::current()->inlining_incrementally() || projs->fallthrough_memproj   != NULL, "must be found");
+  assert(Compile::current()->inlining_incrementally() || projs->fallthrough_ioproj    != NULL, "must be found");
+  assert(Compile::current()->inlining_incrementally() || projs->catchall_catchproj    != NULL, "must be found");
   if (separate_io_proj) {
-    assert(projs->catchall_memproj      != NULL, "must be found");
-    assert(projs->catchall_ioproj       != NULL, "must be found");
+    assert(Compile::current()->inlining_incrementally() || projs->catchall_memproj    != NULL, "must be found");
+    assert(Compile::current()->inlining_incrementally() || projs->catchall_ioproj     != NULL, "must be found");
   }
 }
 
+Node *CallNode::Ideal(PhaseGVN *phase, bool can_reshape) {
+  CallGenerator* cg = generator();
+  if (can_reshape && cg != NULL && cg->is_mh_late_inline() && !cg->already_attempted()) {
+    // Check whether this MH handle call becomes a candidate for inlining
+    ciMethod* callee = cg->method();
+    vmIntrinsics::ID iid = callee->intrinsic_id();
+    if (iid == vmIntrinsics::_invokeBasic) {
+      if (in(TypeFunc::Parms)->Opcode() == Op_ConP) {
+        phase->C->prepend_late_inline(cg);
+        set_generator(NULL);
+      }
+    } else {
+      assert(callee->has_member_arg(), "wrong type of call?");
+      if (in(TypeFunc::Parms + callee->arg_size() - 1)->Opcode() == Op_ConP) {
+        phase->C->prepend_late_inline(cg);
+        set_generator(NULL);
+      }
+    }
+  }
+  return SafePointNode::Ideal(phase, can_reshape);
+}
+
 
 //=============================================================================
 uint CallJavaNode::size_of() const { return sizeof(*this); }
--- a/hotspot/src/share/vm/opto/callnode.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/callnode.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -507,6 +507,7 @@
   Node* exobj;
 };
 
+class CallGenerator;
 
 //------------------------------CallNode---------------------------------------
 // Call nodes now subsume the function of debug nodes at callsites, so they
@@ -517,26 +518,31 @@
   const TypeFunc *_tf;        // Function type
   address      _entry_point;  // Address of method being called
   float        _cnt;          // Estimate of number of times called
+  CallGenerator* _generator;  // corresponding CallGenerator for some late inline calls
 
   CallNode(const TypeFunc* tf, address addr, const TypePtr* adr_type)
     : SafePointNode(tf->domain()->cnt(), NULL, adr_type),
       _tf(tf),
       _entry_point(addr),
-      _cnt(COUNT_UNKNOWN)
+      _cnt(COUNT_UNKNOWN),
+      _generator(NULL)
   {
     init_class_id(Class_Call);
   }
 
-  const TypeFunc* tf()        const { return _tf; }
-  const address entry_point() const { return _entry_point; }
-  const float   cnt()         const { return _cnt; }
+  const TypeFunc* tf()         const { return _tf; }
+  const address  entry_point() const { return _entry_point; }
+  const float    cnt()         const { return _cnt; }
+  CallGenerator* generator()   const { return _generator; }
 
-  void set_tf(const TypeFunc* tf) { _tf = tf; }
-  void set_entry_point(address p) { _entry_point = p; }
-  void set_cnt(float c)           { _cnt = c; }
+  void set_tf(const TypeFunc* tf)       { _tf = tf; }
+  void set_entry_point(address p)       { _entry_point = p; }
+  void set_cnt(float c)                 { _cnt = c; }
+  void set_generator(CallGenerator* cg) { _generator = cg; }
 
   virtual const Type *bottom_type() const;
   virtual const Type *Value( PhaseTransform *phase ) const;
+  virtual Node *Ideal(PhaseGVN *phase, bool can_reshape);
   virtual Node *Identity( PhaseTransform *phase ) { return this; }
   virtual uint        cmp( const Node &n ) const;
   virtual uint        size_of() const = 0;
--- a/hotspot/src/share/vm/opto/cfgnode.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/cfgnode.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -363,6 +363,49 @@
   return true; // The Region node is unreachable - it is dead.
 }
 
+bool RegionNode::try_clean_mem_phi(PhaseGVN *phase) {
+  // Incremental inlining + PhaseStringOpts sometimes produce:
+  //
+  // cmpP with 1 top input
+  //           |
+  //          If
+  //         /  \
+  //   IfFalse  IfTrue  /- Some Node
+  //         \  /      /    /
+  //        Region    / /-MergeMem
+  //             \---Phi
+  //
+  //
+  // It's expected by PhaseStringOpts that the Region goes away and is
+  // replaced by If's control input but because there's still a Phi,
+  // the Region stays in the graph. The top input from the cmpP is
+  // propagated forward and a subgraph that is useful goes away. The
+  // code below replaces the Phi with the MergeMem so that the Region
+  // is simplified.
+
+  PhiNode* phi = has_unique_phi();
+  if (phi && phi->type() == Type::MEMORY && req() == 3 && phi->is_diamond_phi(true)) {
+    MergeMemNode* m = NULL;
+    assert(phi->req() == 3, "same as region");
+    for (uint i = 1; i < 3; ++i) {
+      Node *mem = phi->in(i);
+      if (mem && mem->is_MergeMem() && in(i)->outcnt() == 1) {
+        // Nothing is control-dependent on path #i except the region itself.
+        m = mem->as_MergeMem();
+        uint j = 3 - i;
+        Node* other = phi->in(j);
+        if (other && other == m->base_memory()) {
+          // m is a successor memory to other, and is not pinned inside the diamond, so push it out.
+          // This will allow the diamond to collapse completely.
+          phase->is_IterGVN()->replace_node(phi, m);
+          return true;
+        }
+      }
+    }
+  }
+  return false;
+}
+
 //------------------------------Ideal------------------------------------------
 // Return a node which is more "ideal" than the current node.  Must preserve
 // the CFG, but we can still strip out dead paths.
@@ -375,6 +418,10 @@
   bool has_phis = false;
   if (can_reshape) {            // Need DU info to check for Phi users
     has_phis = (has_phi() != NULL);       // Cache result
+    if (has_phis && try_clean_mem_phi(phase)) {
+      has_phis = false;
+    }
+
     if (!has_phis) {            // No Phi users?  Nothing merging?
       for (uint i = 1; i < req()-1; i++) {
         Node *if1 = in(i);
@@ -1005,7 +1052,9 @@
 //------------------------------is_diamond_phi---------------------------------
 // Does this Phi represent a simple well-shaped diamond merge?  Return the
 // index of the true path or 0 otherwise.
-int PhiNode::is_diamond_phi() const {
+// If check_control_only is true, do not inspect the If node at the
+// top, and return -1 (not an edge number) on success.
+int PhiNode::is_diamond_phi(bool check_control_only) const {
   // Check for a 2-path merge
   Node *region = in(0);
   if( !region ) return 0;
@@ -1018,6 +1067,7 @@
   Node *iff = ifp1->in(0);
   if( !iff || !iff->is_If() ) return 0;
   if( iff != ifp2->in(0) ) return 0;
+  if (check_control_only)  return -1;
   // Check for a proper bool/cmp
   const Node *b = iff->in(1);
   if( !b->is_Bool() ) return 0;
--- a/hotspot/src/share/vm/opto/cfgnode.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/cfgnode.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -95,6 +95,7 @@
   virtual Node *Identity( PhaseTransform *phase );
   virtual Node *Ideal(PhaseGVN *phase, bool can_reshape);
   virtual const RegMask &out_RegMask() const;
+  bool try_clean_mem_phi(PhaseGVN *phase);
 };
 
 //------------------------------JProjNode--------------------------------------
@@ -181,7 +182,7 @@
   LoopSafety simple_data_loop_check(Node *in) const;
   // Is it unsafe data loop? It becomes a dead loop if this phi node removed.
   bool is_unsafe_data_reference(Node *in) const;
-  int  is_diamond_phi() const;
+  int  is_diamond_phi(bool check_control_only = false) const;
   virtual int Opcode() const;
   virtual bool pinned() const { return in(0) != 0; }
   virtual const TypePtr *adr_type() const { verify_adr_type(true); return _adr_type; }
--- a/hotspot/src/share/vm/opto/compile.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/compile.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -136,7 +136,7 @@
 
 void Compile::register_intrinsic(CallGenerator* cg) {
   if (_intrinsics == NULL) {
-    _intrinsics = new GrowableArray<CallGenerator*>(60);
+    _intrinsics = new (comp_arena())GrowableArray<CallGenerator*>(comp_arena(), 60, 0, NULL);
   }
   // This code is stolen from ciObjectFactory::insert.
   // Really, GrowableArray should have methods for
@@ -365,6 +365,21 @@
   }
 }
 
+void Compile::remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Unique_Node_List &useful) {
+  int shift = 0;
+  for (int i = 0; i < inlines->length(); i++) {
+    CallGenerator* cg = inlines->at(i);
+    CallNode* call = cg->call_node();
+    if (shift > 0) {
+      inlines->at_put(i-shift, cg);
+    }
+    if (!useful.member(call)) {
+      shift++;
+    }
+  }
+  inlines->trunc_to(inlines->length()-shift);
+}
+
 // Disconnect all useless nodes by disconnecting those at the boundary.
 void Compile::remove_useless_nodes(Unique_Node_List &useful) {
   uint next = 0;
@@ -394,6 +409,9 @@
       remove_macro_node(n);
     }
   }
+  // clean up the late inline lists
+  remove_useless_late_inlines(&_string_late_inlines, useful);
+  remove_useless_late_inlines(&_late_inlines, useful);
   debug_only(verify_graph_edges(true/*check for no_dead_code*/);)
 }
 
@@ -611,6 +629,12 @@
                   _printer(IdealGraphPrinter::printer()),
 #endif
                   _congraph(NULL),
+                  _late_inlines(comp_arena(), 2, 0, NULL),
+                  _string_late_inlines(comp_arena(), 2, 0, NULL),
+                  _late_inlines_pos(0),
+                  _number_of_mh_late_inlines(0),
+                  _inlining_progress(false),
+                  _inlining_incrementally(false),
                   _print_inlining_list(NULL),
                   _print_inlining(0) {
   C = this;
@@ -668,7 +692,7 @@
   PhaseGVN gvn(node_arena(), estimated_size);
   set_initial_gvn(&gvn);
 
-  if (PrintInlining) {
+  if (PrintInlining  || PrintIntrinsics NOT_PRODUCT( || PrintOptoInlining)) {
     _print_inlining_list = new (comp_arena())GrowableArray<PrintInliningBuffer>(comp_arena(), 1, 1, PrintInliningBuffer());
   }
   { // Scope for timing the parser
@@ -737,29 +761,13 @@
       rethrow_exceptions(kit.transfer_exceptions_into_jvms());
     }
 
-    if (!failing() && has_stringbuilder()) {
-      {
-        // remove useless nodes to make the usage analysis simpler
-        ResourceMark rm;
-        PhaseRemoveUseless pru(initial_gvn(), &for_igvn);
-      }
-
-      {
-        ResourceMark rm;
-        print_method("Before StringOpts", 3);
-        PhaseStringOpts pso(initial_gvn(), &for_igvn);
-        print_method("After StringOpts", 3);
-      }
-
-      // now inline anything that we skipped the first time around
-      while (_late_inlines.length() > 0) {
-        CallGenerator* cg = _late_inlines.pop();
-        cg->do_late_inline();
-        if (failing())  return;
-      }
+    assert(IncrementalInline || (_late_inlines.length() == 0 && !has_mh_late_inlines()), "incremental inlining is off");
+
+    if (_late_inlines.length() == 0 && !has_mh_late_inlines() && !failing() && has_stringbuilder()) {
+      inline_string_calls(true);
     }
-    assert(_late_inlines.length() == 0, "should have been processed");
-    dump_inlining();
+
+    if (failing())  return;
 
     print_method("Before RemoveUseless", 3);
 
@@ -906,6 +914,9 @@
     _dead_node_list(comp_arena()),
     _dead_node_count(0),
     _congraph(NULL),
+    _number_of_mh_late_inlines(0),
+    _inlining_progress(false),
+    _inlining_incrementally(false),
     _print_inlining_list(NULL),
     _print_inlining(0) {
   C = this;
@@ -1760,6 +1771,124 @@
   assert(predicate_count()==0, "should be clean!");
 }
 
+// StringOpts and late inlining of string methods
+void Compile::inline_string_calls(bool parse_time) {
+  {
+    // remove useless nodes to make the usage analysis simpler
+    ResourceMark rm;
+    PhaseRemoveUseless pru(initial_gvn(), for_igvn());
+  }
+
+  {
+    ResourceMark rm;
+    print_method("Before StringOpts", 3);
+    PhaseStringOpts pso(initial_gvn(), for_igvn());
+    print_method("After StringOpts", 3);
+  }
+
+  // now inline anything that we skipped the first time around
+  if (!parse_time) {
+    _late_inlines_pos = _late_inlines.length();
+  }
+
+  while (_string_late_inlines.length() > 0) {
+    CallGenerator* cg = _string_late_inlines.pop();
+    cg->do_late_inline();
+    if (failing())  return;
+  }
+  _string_late_inlines.trunc_to(0);
+}
+
+void Compile::inline_incrementally_one(PhaseIterGVN& igvn) {
+  assert(IncrementalInline, "incremental inlining should be on");
+  PhaseGVN* gvn = initial_gvn();
+
+  set_inlining_progress(false);
+  for_igvn()->clear();
+  gvn->replace_with(&igvn);
+
+  int i = 0;
+
+  for (; i <_late_inlines.length() && !inlining_progress(); i++) {
+    CallGenerator* cg = _late_inlines.at(i);
+    _late_inlines_pos = i+1;
+    cg->do_late_inline();
+    if (failing())  return;
+  }
+  int j = 0;
+  for (; i < _late_inlines.length(); i++, j++) {
+    _late_inlines.at_put(j, _late_inlines.at(i));
+  }
+  _late_inlines.trunc_to(j);
+
+  {
+    ResourceMark rm;
+    PhaseRemoveUseless pru(C->initial_gvn(), C->for_igvn());
+  }
+
+  igvn = PhaseIterGVN(gvn);
+}
+
+// Perform incremental inlining until bound on number of live nodes is reached
+void Compile::inline_incrementally(PhaseIterGVN& igvn) {
+  PhaseGVN* gvn = initial_gvn();
+
+  set_inlining_incrementally(true);
+  set_inlining_progress(true);
+  uint low_live_nodes = 0;
+
+  while(inlining_progress() && _late_inlines.length() > 0) {
+
+    if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
+      if (low_live_nodes < (uint)LiveNodeCountInliningCutoff * 8 / 10) {
+        // PhaseIdealLoop is expensive so we only try it once we are
+        // out of loop and we only try it again if the previous helped
+        // got the number of nodes down significantly
+        PhaseIdealLoop ideal_loop( igvn, false, true );
+        if (failing())  return;
+        low_live_nodes = live_nodes();
+        _major_progress = true;
+      }
+
+      if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
+        break;
+      }
+    }
+
+    inline_incrementally_one(igvn);
+
+    if (failing())  return;
+
+    igvn.optimize();
+
+    if (failing())  return;
+  }
+
+  assert( igvn._worklist.size() == 0, "should be done with igvn" );
+
+  if (_string_late_inlines.length() > 0) {
+    assert(has_stringbuilder(), "inconsistent");
+    for_igvn()->clear();
+    initial_gvn()->replace_with(&igvn);
+
+    inline_string_calls(false);
+
+    if (failing())  return;
+
+    {
+      ResourceMark rm;
+      PhaseRemoveUseless pru(initial_gvn(), for_igvn());
+    }
+
+    igvn = PhaseIterGVN(gvn);
+
+    igvn.optimize();
+  }
+
+  set_inlining_incrementally(false);
+}
+
+
 //------------------------------Optimize---------------------------------------
 // Given a graph, optimize it.
 void Compile::Optimize() {
@@ -1792,6 +1921,12 @@
 
   if (failing())  return;
 
+  inline_incrementally(igvn);
+
+  print_method("Incremental Inline", 2);
+
+  if (failing())  return;
+
   // Perform escape analysis
   if (_do_escape_analysis && ConnectionGraph::has_candidates(this)) {
     if (has_loops()) {
@@ -1914,6 +2049,7 @@
 
  } // (End scope of igvn; run destructor if necessary for asserts.)
 
+  dump_inlining();
   // A method with only infinite loops has no edges entering loops from root
   {
     NOT_PRODUCT( TracePhase t2("graphReshape", &_t_graphReshaping, TimeCompiler); )
@@ -3361,7 +3497,29 @@
 }
 
 void Compile::dump_inlining() {
-  if (PrintInlining) {
+  if (PrintInlining || PrintIntrinsics NOT_PRODUCT( || PrintOptoInlining)) {
+    // Print inlining message for candidates that we couldn't inline
+    // for lack of space or non constant receiver
+    for (int i = 0; i < _late_inlines.length(); i++) {
+      CallGenerator* cg = _late_inlines.at(i);
+      cg->print_inlining_late("live nodes > LiveNodeCountInliningCutoff");
+    }
+    Unique_Node_List useful;
+    useful.push(root());
+    for (uint next = 0; next < useful.size(); ++next) {
+      Node* n  = useful.at(next);
+      if (n->is_Call() && n->as_Call()->generator() != NULL && n->as_Call()->generator()->call_node() == n) {
+        CallNode* call = n->as_Call();
+        CallGenerator* cg = call->generator();
+        cg->print_inlining_late("receiver not constant");
+      }
+      uint max = n->len();
+      for ( uint i = 0; i < max; ++i ) {
+        Node *m = n->in(i);
+        if ( m == NULL ) continue;
+        useful.push(m);
+      }
+    }
     for (int i = 0; i < _print_inlining_list->length(); i++) {
       tty->print(_print_inlining_list->at(i).ss()->as_string());
     }
--- a/hotspot/src/share/vm/opto/compile.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/compile.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -72,6 +72,7 @@
 class JVMState;
 class TypeData;
 class TypePtr;
+class TypeOopPtr;
 class TypeFunc;
 class Unique_Node_List;
 class nmethod;
@@ -280,6 +281,8 @@
   int                   _orig_pc_slot_offset_in_bytes;
 
   int                   _major_progress;        // Count of something big happening
+  bool                  _inlining_progress;     // progress doing incremental inlining?
+  bool                  _inlining_incrementally;// Are we doing incremental inlining (post parse)
   bool                  _has_loops;             // True if the method _may_ have some loops
   bool                  _has_split_ifs;         // True if the method _may_ have some split-if
   bool                  _has_unsafe_access;     // True if the method _may_ produce faults in unsafe loads or stores.
@@ -367,8 +370,13 @@
   Unique_Node_List*     _for_igvn;              // Initial work-list for next round of Iterative GVN
   WarmCallInfo*         _warm_calls;            // Sorted work-list for heat-based inlining.
 
-  GrowableArray<CallGenerator*> _late_inlines;  // List of CallGenerators to be revisited after
-                                                // main parsing has finished.
+  GrowableArray<CallGenerator*> _late_inlines;        // List of CallGenerators to be revisited after
+                                                      // main parsing has finished.
+  GrowableArray<CallGenerator*> _string_late_inlines; // same but for string operations
+
+  int                           _late_inlines_pos;    // Where in the queue should the next late inlining candidate go (emulate depth first inlining)
+  uint                          _number_of_mh_late_inlines; // number of method handle late inlining still pending
+
 
   // Inlining may not happen in parse order which would make
   // PrintInlining output confusing. Keep track of PrintInlining
@@ -491,6 +499,10 @@
   int               fixed_slots() const         { assert(_fixed_slots >= 0, "");         return _fixed_slots; }
   void          set_fixed_slots(int n)          { _fixed_slots = n; }
   int               major_progress() const      { return _major_progress; }
+  void          set_inlining_progress(bool z)   { _inlining_progress = z; }
+  int               inlining_progress() const   { return _inlining_progress; }
+  void          set_inlining_incrementally(bool z) { _inlining_incrementally = z; }
+  int               inlining_incrementally() const { return _inlining_incrementally; }
   void          set_major_progress()            { _major_progress++; }
   void        clear_major_progress()            { _major_progress = 0; }
   int               num_loop_opts() const       { return _num_loop_opts; }
@@ -729,9 +741,17 @@
 
   // Decide how to build a call.
   // The profile factor is a discount to apply to this site's interp. profile.
-  CallGenerator*    call_generator(ciMethod* call_method, int vtable_index, bool call_is_virtual, JVMState* jvms, bool allow_inline, float profile_factor, bool allow_intrinsics = true);
+  CallGenerator*    call_generator(ciMethod* call_method, int vtable_index, bool call_does_dispatch, JVMState* jvms, bool allow_inline, float profile_factor, bool allow_intrinsics = true, bool delayed_forbidden = false);
   bool should_delay_inlining(ciMethod* call_method, JVMState* jvms);
 
+  // Helper functions to identify inlining potential at call-site
+  ciMethod* optimize_virtual_call(ciMethod* caller, int bci, ciInstanceKlass* klass,
+                                  ciMethod* callee, const TypeOopPtr* receiver_type,
+                                  bool is_virtual,
+                                  bool &call_does_dispatch, int &vtable_index);
+  ciMethod* optimize_inlining(ciMethod* caller, int bci, ciInstanceKlass* klass,
+                              ciMethod* callee, const TypeOopPtr* receiver_type);
+
   // Report if there were too many traps at a current method and bci.
   // Report if a trap was recorded, and/or PerMethodTrapLimit was exceeded.
   // If there is no MDO at all, report no trap unless told to assume it.
@@ -765,10 +785,39 @@
   WarmCallInfo* pop_warm_call();
 
   // Record this CallGenerator for inlining at the end of parsing.
-  void              add_late_inline(CallGenerator* cg) { _late_inlines.push(cg); }
+  void              add_late_inline(CallGenerator* cg)        {
+    _late_inlines.insert_before(_late_inlines_pos, cg);
+    _late_inlines_pos++;
+  }
+
+  void              prepend_late_inline(CallGenerator* cg)    {
+    _late_inlines.insert_before(0, cg);
+  }
+
+  void              add_string_late_inline(CallGenerator* cg) {
+    _string_late_inlines.push(cg);
+  }
+
+  void remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Unique_Node_List &useful);
 
   void dump_inlining();
 
+  bool over_inlining_cutoff() const {
+    if (!inlining_incrementally()) {
+      return unique() > (uint)NodeCountInliningCutoff;
+    } else {
+      return live_nodes() > (uint)LiveNodeCountInliningCutoff;
+    }
+  }
+
+  void inc_number_of_mh_late_inlines() { _number_of_mh_late_inlines++; }
+  void dec_number_of_mh_late_inlines() { assert(_number_of_mh_late_inlines > 0, "_number_of_mh_late_inlines < 0 !"); _number_of_mh_late_inlines--; }
+  bool has_mh_late_inlines() const     { return _number_of_mh_late_inlines > 0; }
+
+  void inline_incrementally_one(PhaseIterGVN& igvn);
+  void inline_incrementally(PhaseIterGVN& igvn);
+  void inline_string_calls(bool parse_time);
+
   // Matching, CFG layout, allocation, code generation
   PhaseCFG*         cfg()                       { return _cfg; }
   bool              select_24_bit_instr() const { return _select_24_bit_instr; }
--- a/hotspot/src/share/vm/opto/doCall.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/doCall.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -61,9 +61,9 @@
   }
 }
 
-CallGenerator* Compile::call_generator(ciMethod* callee, int vtable_index, bool call_is_virtual,
+CallGenerator* Compile::call_generator(ciMethod* callee, int vtable_index, bool call_does_dispatch,
                                        JVMState* jvms, bool allow_inline,
-                                       float prof_factor, bool allow_intrinsics) {
+                                       float prof_factor, bool allow_intrinsics, bool delayed_forbidden) {
   ciMethod*       caller   = jvms->method();
   int             bci      = jvms->bci();
   Bytecodes::Code bytecode = caller->java_code_at_bci(bci);
@@ -82,7 +82,7 @@
   // See how many times this site has been invoked.
   int site_count = profile.count();
   int receiver_count = -1;
-  if (call_is_virtual && UseTypeProfile && profile.has_receiver(0)) {
+  if (call_does_dispatch && UseTypeProfile && profile.has_receiver(0)) {
     // Receivers in the profile structure are ordered by call counts
     // so that the most called (major) receiver is profile.receiver(0).
     receiver_count = profile.receiver_count(0);
@@ -94,7 +94,7 @@
     int r2id = (rid != -1 && profile.has_receiver(1))? log->identify(profile.receiver(1)):-1;
     log->begin_elem("call method='%d' count='%d' prof_factor='%g'",
                     log->identify(callee), site_count, prof_factor);
-    if (call_is_virtual)  log->print(" virtual='1'");
+    if (call_does_dispatch)  log->print(" virtual='1'");
     if (allow_inline)     log->print(" inline='1'");
     if (receiver_count >= 0) {
       log->print(" receiver='%d' receiver_count='%d'", rid, receiver_count);
@@ -111,12 +111,12 @@
   // We do this before the strict f.p. check below because the
   // intrinsics handle strict f.p. correctly.
   if (allow_inline && allow_intrinsics) {
-    CallGenerator* cg = find_intrinsic(callee, call_is_virtual);
+    CallGenerator* cg = find_intrinsic(callee, call_does_dispatch);
     if (cg != NULL) {
       if (cg->is_predicted()) {
         // Code without intrinsic but, hopefully, inlined.
         CallGenerator* inline_cg = this->call_generator(callee,
-              vtable_index, call_is_virtual, jvms, allow_inline, prof_factor, false);
+              vtable_index, call_does_dispatch, jvms, allow_inline, prof_factor, false);
         if (inline_cg != NULL) {
           cg = CallGenerator::for_predicted_intrinsic(cg, inline_cg);
         }
@@ -130,7 +130,9 @@
   // MethodHandle.invoke* are native methods which obviously don't
   // have bytecodes and so normal inlining fails.
   if (callee->is_method_handle_intrinsic()) {
-    return CallGenerator::for_method_handle_call(jvms, caller, callee);
+    CallGenerator* cg = CallGenerator::for_method_handle_call(jvms, caller, callee, delayed_forbidden);
+    assert(cg == NULL || !delayed_forbidden || !cg->is_late_inline() || cg->is_mh_late_inline(), "unexpected CallGenerator");
+    return cg;
   }
 
   // Do not inline strict fp into non-strict code, or the reverse
@@ -147,7 +149,7 @@
     float expected_uses = past_uses;
 
     // Try inlining a bytecoded method:
-    if (!call_is_virtual) {
+    if (!call_does_dispatch) {
       InlineTree* ilt;
       if (UseOldInlining) {
         ilt = InlineTree::find_subtree_from_root(this->ilt(), jvms->caller(), jvms->method());
@@ -161,32 +163,39 @@
       WarmCallInfo scratch_ci;
       if (!UseOldInlining)
         scratch_ci.init(jvms, callee, profile, prof_factor);
-      WarmCallInfo* ci = ilt->ok_to_inline(callee, jvms, profile, &scratch_ci);
+      bool should_delay = false;
+      WarmCallInfo* ci = ilt->ok_to_inline(callee, jvms, profile, &scratch_ci, should_delay);
       assert(ci != &scratch_ci, "do not let this pointer escape");
       bool allow_inline   = (ci != NULL && !ci->is_cold());
       bool require_inline = (allow_inline && ci->is_hot());
 
       if (allow_inline) {
         CallGenerator* cg = CallGenerator::for_inline(callee, expected_uses);
-        if (require_inline && cg != NULL && should_delay_inlining(callee, jvms)) {
+
+        if (require_inline && cg != NULL) {
           // Delay the inlining of this method to give us the
           // opportunity to perform some high level optimizations
           // first.
-          return CallGenerator::for_late_inline(callee, cg);
+          if (should_delay_inlining(callee, jvms)) {
+            assert(!delayed_forbidden, "strange");
+            return CallGenerator::for_string_late_inline(callee, cg);
+          } else if ((should_delay || AlwaysIncrementalInline) && !delayed_forbidden) {
+            return CallGenerator::for_late_inline(callee, cg);
+          }
         }
-        if (cg == NULL) {
+        if (cg == NULL || should_delay) {
           // Fall through.
         } else if (require_inline || !InlineWarmCalls) {
           return cg;
         } else {
-          CallGenerator* cold_cg = call_generator(callee, vtable_index, call_is_virtual, jvms, false, prof_factor);
+          CallGenerator* cold_cg = call_generator(callee, vtable_index, call_does_dispatch, jvms, false, prof_factor);
           return CallGenerator::for_warm_call(ci, cold_cg, cg);
         }
       }
     }
 
     // Try using the type profile.
-    if (call_is_virtual && site_count > 0 && receiver_count > 0) {
+    if (call_does_dispatch && site_count > 0 && receiver_count > 0) {
       // The major receiver's count >= TypeProfileMajorReceiverPercent of site_count.
       bool have_major_receiver = (100.*profile.receiver_prob(0) >= (float)TypeProfileMajorReceiverPercent);
       ciMethod* receiver_method = NULL;
@@ -200,7 +209,7 @@
       if (receiver_method != NULL) {
         // The single majority receiver sufficiently outweighs the minority.
         CallGenerator* hit_cg = this->call_generator(receiver_method,
-              vtable_index, !call_is_virtual, jvms, allow_inline, prof_factor);
+              vtable_index, !call_does_dispatch, jvms, allow_inline, prof_factor);
         if (hit_cg != NULL) {
           // Look up second receiver.
           CallGenerator* next_hit_cg = NULL;
@@ -210,7 +219,7 @@
                                                                profile.receiver(1));
             if (next_receiver_method != NULL) {
               next_hit_cg = this->call_generator(next_receiver_method,
-                                  vtable_index, !call_is_virtual, jvms,
+                                  vtable_index, !call_does_dispatch, jvms,
                                   allow_inline, prof_factor);
               if (next_hit_cg != NULL && !next_hit_cg->is_inline() &&
                   have_major_receiver && UseOnlyInlinedBimorphic) {
@@ -256,7 +265,7 @@
 
   // There was no special inlining tactic, or it bailed out.
   // Use a more generic tactic, like a simple call.
-  if (call_is_virtual) {
+  if (call_does_dispatch) {
     return CallGenerator::for_virtual_call(callee, vtable_index);
   } else {
     // Class Hierarchy Analysis or Type Profile reveals a unique target,
@@ -388,6 +397,7 @@
   // orig_callee is the resolved callee which's signature includes the
   // appendix argument.
   const int nargs = orig_callee->arg_size();
+  const bool is_signature_polymorphic = MethodHandles::is_signature_polymorphic(orig_callee->intrinsic_id());
 
   // Push appendix argument (MethodType, CallSite, etc.), if one.
   if (iter().has_appendix()) {
@@ -404,25 +414,18 @@
   // Then we may introduce a run-time check and inline on the path where it succeeds.
   // The other path may uncommon_trap, check for another receiver, or do a v-call.
 
-  // Choose call strategy.
-  bool call_is_virtual = is_virtual_or_interface;
-  int vtable_index = Method::invalid_vtable_index;
-  ciMethod* callee = orig_callee;
+  // Try to get the most accurate receiver type
+  ciMethod* callee             = orig_callee;
+  int       vtable_index       = Method::invalid_vtable_index;
+  bool      call_does_dispatch = false;
 
-  // Try to get the most accurate receiver type
   if (is_virtual_or_interface) {
     Node*             receiver_node = stack(sp() - nargs);
     const TypeOopPtr* receiver_type = _gvn.type(receiver_node)->isa_oopptr();
-    ciMethod* optimized_virtual_method = optimize_inlining(method(), bci(), klass, orig_callee, receiver_type);
-
-    // Have the call been sufficiently improved such that it is no longer a virtual?
-    if (optimized_virtual_method != NULL) {
-      callee          = optimized_virtual_method;
-      call_is_virtual = false;
-    } else if (!UseInlineCaches && is_virtual && callee->is_loaded()) {
-      // We can make a vtable call at this site
-      vtable_index = callee->resolve_vtable_index(method()->holder(), klass);
-    }
+    // call_does_dispatch and vtable_index are out-parameters.  They might be changed.
+    callee = C->optimize_virtual_call(method(), bci(), klass, orig_callee, receiver_type,
+                                      is_virtual,
+                                      call_does_dispatch, vtable_index);  // out-parameters
   }
 
   // Note:  It's OK to try to inline a virtual call.
@@ -438,7 +441,7 @@
   // Decide call tactic.
   // This call checks with CHA, the interpreter profile, intrinsics table, etc.
   // It decides whether inlining is desirable or not.
-  CallGenerator* cg = C->call_generator(callee, vtable_index, call_is_virtual, jvms, try_inline, prof_factor());
+  CallGenerator* cg = C->call_generator(callee, vtable_index, call_does_dispatch, jvms, try_inline, prof_factor());
 
   // NOTE:  Don't use orig_callee and callee after this point!  Use cg->method() instead.
   orig_callee = callee = NULL;
@@ -478,7 +481,7 @@
     // the call site, perhaps because it did not match a pattern the
     // intrinsic was expecting to optimize. Should always be possible to
     // get a normal java call that may inline in that case
-    cg = C->call_generator(cg->method(), vtable_index, call_is_virtual, jvms, try_inline, prof_factor(), /* allow_intrinsics= */ false);
+    cg = C->call_generator(cg->method(), vtable_index, call_does_dispatch, jvms, try_inline, prof_factor(), /* allow_intrinsics= */ false);
     if ((new_jvms = cg->generate(jvms)) == NULL) {
       guarantee(failing(), "call failed to generate:  calls should work");
       return;
@@ -513,55 +516,50 @@
     round_double_result(cg->method());
 
     ciType* rtype = cg->method()->return_type();
-    if (Bytecodes::has_optional_appendix(iter().cur_bc_raw())) {
+    ciType* ctype = declared_signature->return_type();
+
+    if (Bytecodes::has_optional_appendix(iter().cur_bc_raw()) || is_signature_polymorphic) {
       // Be careful here with return types.
-      ciType* ctype = declared_signature->return_type();
       if (ctype != rtype) {
         BasicType rt = rtype->basic_type();
         BasicType ct = ctype->basic_type();
-        Node* retnode = peek();
         if (ct == T_VOID) {
           // It's OK for a method  to return a value that is discarded.
           // The discarding does not require any special action from the caller.
           // The Java code knows this, at VerifyType.isNullConversion.
           pop_node(rt);  // whatever it was, pop it
-          retnode = top();
         } else if (rt == T_INT || is_subword_type(rt)) {
-          // FIXME: This logic should be factored out.
-          if (ct == T_BOOLEAN) {
-            retnode = _gvn.transform( new (C) AndINode(retnode, intcon(0x1)) );
-          } else if (ct == T_CHAR) {
-            retnode = _gvn.transform( new (C) AndINode(retnode, intcon(0xFFFF)) );
-          } else if (ct == T_BYTE) {
-            retnode = _gvn.transform( new (C) LShiftINode(retnode, intcon(24)) );
-            retnode = _gvn.transform( new (C) RShiftINode(retnode, intcon(24)) );
-          } else if (ct == T_SHORT) {
-            retnode = _gvn.transform( new (C) LShiftINode(retnode, intcon(16)) );
-            retnode = _gvn.transform( new (C) RShiftINode(retnode, intcon(16)) );
-          } else {
-            assert(ct == T_INT, err_msg_res("rt=%s, ct=%s", type2name(rt), type2name(ct)));
-          }
+          // Nothing.  These cases are handled in lambda form bytecode.
+          assert(ct == T_INT || is_subword_type(ct), err_msg_res("must match: rt=%s, ct=%s", type2name(rt), type2name(ct)));
         } else if (rt == T_OBJECT || rt == T_ARRAY) {
           assert(ct == T_OBJECT || ct == T_ARRAY, err_msg_res("rt=%s, ct=%s", type2name(rt), type2name(ct)));
           if (ctype->is_loaded()) {
             const TypeOopPtr* arg_type = TypeOopPtr::make_from_klass(rtype->as_klass());
             const Type*       sig_type = TypeOopPtr::make_from_klass(ctype->as_klass());
             if (arg_type != NULL && !arg_type->higher_equal(sig_type)) {
+              Node* retnode = pop();
               Node* cast_obj = _gvn.transform(new (C) CheckCastPPNode(control(), retnode, sig_type));
-              pop();
               push(cast_obj);
             }
           }
         } else {
-          assert(ct == rt, err_msg("unexpected mismatch rt=%d, ct=%d", rt, ct));
+          assert(rt == ct, err_msg_res("unexpected mismatch: rt=%s, ct=%s", type2name(rt), type2name(ct)));
           // push a zero; it's better than getting an oop/int mismatch
-          retnode = pop_node(rt);
-          retnode = zerocon(ct);
+          pop_node(rt);
+          Node* retnode = zerocon(ct);
           push_node(ct, retnode);
         }
         // Now that the value is well-behaved, continue with the call-site type.
         rtype = ctype;
       }
+    } else {
+      // Symbolic resolution enforces the types to be the same.
+      // NOTE: We must relax the assert for unloaded types because two
+      // different ciType instances of the same unloaded class type
+      // can appear to be "loaded" by different loaders (depending on
+      // the accessing class).
+      assert(!rtype->is_loaded() || !ctype->is_loaded() || rtype == ctype,
+             err_msg_res("mismatched return types: rtype=%s, ctype=%s", rtype->name(), ctype->name()));
     }
 
     // If the return type of the method is not loaded, assert that the
@@ -879,17 +877,39 @@
 #endif //PRODUCT
 
 
+ciMethod* Compile::optimize_virtual_call(ciMethod* caller, int bci, ciInstanceKlass* klass,
+                                         ciMethod* callee, const TypeOopPtr* receiver_type,
+                                         bool is_virtual,
+                                         bool& call_does_dispatch, int& vtable_index) {
+  // Set default values for out-parameters.
+  call_does_dispatch = true;
+  vtable_index       = Method::invalid_vtable_index;
+
+  // Choose call strategy.
+  ciMethod* optimized_virtual_method = optimize_inlining(caller, bci, klass, callee, receiver_type);
+
+  // Have the call been sufficiently improved such that it is no longer a virtual?
+  if (optimized_virtual_method != NULL) {
+    callee             = optimized_virtual_method;
+    call_does_dispatch = false;
+  } else if (!UseInlineCaches && is_virtual && callee->is_loaded()) {
+    // We can make a vtable call at this site
+    vtable_index = callee->resolve_vtable_index(caller->holder(), klass);
+  }
+  return callee;
+}
+
 // Identify possible target method and inlining style
-ciMethod* Parse::optimize_inlining(ciMethod* caller, int bci, ciInstanceKlass* klass,
-                                   ciMethod *dest_method, const TypeOopPtr* receiver_type) {
+ciMethod* Compile::optimize_inlining(ciMethod* caller, int bci, ciInstanceKlass* klass,
+                                     ciMethod* callee, const TypeOopPtr* receiver_type) {
   // only use for virtual or interface calls
 
   // If it is obviously final, do not bother to call find_monomorphic_target,
   // because the class hierarchy checks are not needed, and may fail due to
   // incompletely loaded classes.  Since we do our own class loading checks
   // in this module, we may confidently bind to any method.
-  if (dest_method->can_be_statically_bound()) {
-    return dest_method;
+  if (callee->can_be_statically_bound()) {
+    return callee;
   }
 
   // Attempt to improve the receiver
@@ -898,8 +918,8 @@
   if (receiver_type != NULL) {
     // Array methods are all inherited from Object, and are monomorphic.
     if (receiver_type->isa_aryptr() &&
-        dest_method->holder() == env()->Object_klass()) {
-      return dest_method;
+        callee->holder() == env()->Object_klass()) {
+      return callee;
     }
 
     // All other interesting cases are instance klasses.
@@ -919,7 +939,7 @@
   }
 
   ciInstanceKlass*   calling_klass = caller->holder();
-  ciMethod* cha_monomorphic_target = dest_method->find_monomorphic_target(calling_klass, klass, actual_receiver);
+  ciMethod* cha_monomorphic_target = callee->find_monomorphic_target(calling_klass, klass, actual_receiver);
   if (cha_monomorphic_target != NULL) {
     assert(!cha_monomorphic_target->is_abstract(), "");
     // Look at the method-receiver type.  Does it add "too much information"?
@@ -937,10 +957,10 @@
         cha_monomorphic_target->print();
         tty->cr();
       }
-      if (C->log() != NULL) {
-        C->log()->elem("missed_CHA_opportunity klass='%d' method='%d'",
-                       C->log()->identify(klass),
-                       C->log()->identify(cha_monomorphic_target));
+      if (log() != NULL) {
+        log()->elem("missed_CHA_opportunity klass='%d' method='%d'",
+                       log()->identify(klass),
+                       log()->identify(cha_monomorphic_target));
       }
       cha_monomorphic_target = NULL;
     }
@@ -952,7 +972,7 @@
     // by dynamic class loading.  Be sure to test the "static" receiver
     // dest_method here, as opposed to the actual receiver, which may
     // falsely lead us to believe that the receiver is final or private.
-    C->dependencies()->assert_unique_concrete_method(actual_receiver, cha_monomorphic_target);
+    dependencies()->assert_unique_concrete_method(actual_receiver, cha_monomorphic_target);
     return cha_monomorphic_target;
   }
 
@@ -961,7 +981,7 @@
   if (actual_receiver_is_exact) {
     // In case of evolution, there is a dependence on every inlined method, since each
     // such method can be changed when its class is redefined.
-    ciMethod* exact_method = dest_method->resolve_invoke(calling_klass, actual_receiver);
+    ciMethod* exact_method = callee->resolve_invoke(calling_klass, actual_receiver);
     if (exact_method != NULL) {
 #ifndef PRODUCT
       if (PrintOpto) {
--- a/hotspot/src/share/vm/opto/graphKit.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/graphKit.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1794,10 +1794,15 @@
 
   if (ejvms == NULL) {
     // No exception edges to simply kill off those paths
-    C->gvn_replace_by(callprojs.catchall_catchproj, C->top());
-    C->gvn_replace_by(callprojs.catchall_memproj,   C->top());
-    C->gvn_replace_by(callprojs.catchall_ioproj,    C->top());
-
+    if (callprojs.catchall_catchproj != NULL) {
+      C->gvn_replace_by(callprojs.catchall_catchproj, C->top());
+    }
+    if (callprojs.catchall_memproj != NULL) {
+      C->gvn_replace_by(callprojs.catchall_memproj,   C->top());
+    }
+    if (callprojs.catchall_ioproj != NULL) {
+      C->gvn_replace_by(callprojs.catchall_ioproj,    C->top());
+    }
     // Replace the old exception object with top
     if (callprojs.exobj != NULL) {
       C->gvn_replace_by(callprojs.exobj, C->top());
@@ -1809,10 +1814,15 @@
     SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
 
     Node* ex_oop = ekit.use_exception_state(ex_map);
-
-    C->gvn_replace_by(callprojs.catchall_catchproj, ekit.control());
-    C->gvn_replace_by(callprojs.catchall_memproj,   ekit.reset_memory());
-    C->gvn_replace_by(callprojs.catchall_ioproj,    ekit.i_o());
+    if (callprojs.catchall_catchproj != NULL) {
+      C->gvn_replace_by(callprojs.catchall_catchproj, ekit.control());
+    }
+    if (callprojs.catchall_memproj != NULL) {
+      C->gvn_replace_by(callprojs.catchall_memproj,   ekit.reset_memory());
+    }
+    if (callprojs.catchall_ioproj != NULL) {
+      C->gvn_replace_by(callprojs.catchall_ioproj,    ekit.i_o());
+    }
 
     // Replace the old exception object with the newly created one
     if (callprojs.exobj != NULL) {
--- a/hotspot/src/share/vm/opto/idealGraphPrinter.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/idealGraphPrinter.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -547,7 +547,7 @@
 
         // max. 2 chars allowed
         if (value >= -9 && value <= 99) {
-          sprintf(buffer, INT64_FORMAT, value);
+          sprintf(buffer, JLONG_FORMAT, value);
           print_prop(short_name, buffer);
         } else {
           print_prop(short_name, "L");
--- a/hotspot/src/share/vm/opto/library_call.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/library_call.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -3559,7 +3559,6 @@
 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
-  return false;
   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
 
   // Get the arguments.
--- a/hotspot/src/share/vm/opto/memnode.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/memnode.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -2725,10 +2725,8 @@
     zend  = phase->transform( new(C) URShiftXNode(zend,  shift) );
   }
 
+  // Bulk clear double-words
   Node* zsize = phase->transform( new(C) SubXNode(zend, zbase) );
-  Node* zinit = phase->zerocon((unit == BytesPerLong) ? T_LONG : T_INT);
-
-  // Bulk clear double-words
   Node* adr = phase->transform( new(C) AddPNode(dest, dest, start_offset) );
   mem = new (C) ClearArrayNode(ctl, mem, zsize, adr);
   return phase->transform(mem);
--- a/hotspot/src/share/vm/opto/parse.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/parse.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -70,7 +70,7 @@
   InlineTree *build_inline_tree_for_callee(ciMethod* callee_method,
                                            JVMState* caller_jvms,
                                            int caller_bci);
-  const char* try_to_inline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result);
+  const char* try_to_inline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result, bool& should_delay);
   const char* should_inline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result) const;
   const char* should_not_inline(ciMethod* callee_method, ciMethod* caller_method, WarmCallInfo* wci_result) const;
   void        print_inlining(ciMethod *callee_method, int caller_bci, const char *failure_msg) const;
@@ -107,7 +107,7 @@
   // and may be accessed by find_subtree_from_root.
   // The call_method is the dest_method for a special or static invocation.
   // The call_method is an optimized virtual method candidate otherwise.
-  WarmCallInfo* ok_to_inline(ciMethod *call_method, JVMState* caller_jvms, ciCallProfile& profile, WarmCallInfo* wci);
+  WarmCallInfo* ok_to_inline(ciMethod *call_method, JVMState* caller_jvms, ciCallProfile& profile, WarmCallInfo* wci, bool& should_delay);
 
   // Information about inlined method
   JVMState*   caller_jvms()       const { return _caller_jvms; }
@@ -469,10 +469,6 @@
   // Helper function to uncommon-trap or bailout for non-compilable call-sites
   bool can_not_compile_call_site(ciMethod *dest_method, ciInstanceKlass *klass);
 
-  // Helper function to identify inlining potential at call-site
-  ciMethod* optimize_inlining(ciMethod* caller, int bci, ciInstanceKlass* klass,
-                              ciMethod *dest_method, const TypeOopPtr* receiver_type);
-
   // Helper function to setup for type-profile based inlining
   bool prepare_type_profile_inline(ciInstanceKlass* prof_klass, ciMethod* prof_method);
 
--- a/hotspot/src/share/vm/opto/parse1.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/parse1.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1404,7 +1404,8 @@
 
     do_one_bytecode();
 
-    assert(!have_se || stopped() || failing() || (sp() - pre_bc_sp) == depth, "correct depth prediction");
+    assert(!have_se || stopped() || failing() || (sp() - pre_bc_sp) == depth,
+           err_msg_res("incorrect depth prediction: sp=%d, pre_bc_sp=%d, depth=%d", sp(), pre_bc_sp, depth));
 
     do_exceptions();
 
--- a/hotspot/src/share/vm/opto/phaseX.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/phaseX.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -75,6 +75,13 @@
   // nh->_sentinel must be in the current node space
 }
 
+void NodeHash::replace_with(NodeHash *nh) {
+  debug_only(_table = (Node**)badAddress);   // interact correctly w/ operator=
+  // just copy in all the fields
+  *this = *nh;
+  // nh->_sentinel must be in the current node space
+}
+
 //------------------------------hash_find--------------------------------------
 // Find in hash table
 Node *NodeHash::hash_find( const Node *n ) {
--- a/hotspot/src/share/vm/opto/phaseX.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/phaseX.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -92,6 +92,7 @@
   }
 
   void   remove_useless_nodes(VectorSet &useful); // replace with sentinel
+  void replace_with(NodeHash* nh);
 
   Node  *sentinel() { return _sentinel; }
 
@@ -386,6 +387,11 @@
   Node  *transform( Node *n );
   Node  *transform_no_reclaim( Node *n );
 
+  void replace_with(PhaseGVN* gvn) {
+    _table.replace_with(&gvn->_table);
+    _types = gvn->_types;
+  }
+
   // Check for a simple dead loop when a data node references itself.
   DEBUG_ONLY(void dead_loop_check(Node *n);)
 };
--- a/hotspot/src/share/vm/opto/stringopts.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/stringopts.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -265,7 +265,8 @@
     } else if (n->is_IfTrue()) {
       Compile* C = _stringopts->C;
       C->gvn_replace_by(n, n->in(0)->in(0));
-      C->gvn_replace_by(n->in(0), C->top());
+      // get rid of the other projection
+      C->gvn_replace_by(n->in(0)->as_If()->proj_out(false), C->top());
     }
   }
 }
@@ -439,7 +440,7 @@
       }
       // Find the constructor call
       Node* result = alloc->result_cast();
-      if (result == NULL || !result->is_CheckCastPP()) {
+      if (result == NULL || !result->is_CheckCastPP() || alloc->in(TypeFunc::Memory)->is_top()) {
         // strange looking allocation
 #ifndef PRODUCT
         if (PrintOptimizeStringConcat) {
@@ -834,6 +835,9 @@
           ptr->in(1)->in(0) != NULL && ptr->in(1)->in(0)->is_If()) {
         // Simple diamond.
         // XXX should check for possibly merging stores.  simple data merges are ok.
+        // The IGVN will make this simple diamond go away when it
+        // transforms the Region. Make sure it sees it.
+        Compile::current()->record_for_igvn(ptr);
         ptr = ptr->in(1)->in(0)->in(0);
         continue;
       }
--- a/hotspot/src/share/vm/opto/type.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/opto/type.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -1542,10 +1542,10 @@
 static const char* longnamenear(jlong x, const char* xname, char* buf, jlong n) {
   if (n > x) {
     if (n >= x + 10000)  return NULL;
-    sprintf(buf, "%s+" INT64_FORMAT, xname, n - x);
+    sprintf(buf, "%s+" JLONG_FORMAT, xname, n - x);
   } else if (n < x) {
     if (n <= x - 10000)  return NULL;
-    sprintf(buf, "%s-" INT64_FORMAT, xname, x - n);
+    sprintf(buf, "%s-" JLONG_FORMAT, xname, x - n);
   } else {
     return xname;
   }
@@ -1557,11 +1557,11 @@
   if (n == min_jlong)
     return "min";
   else if (n < min_jlong + 10000)
-    sprintf(buf, "min+" INT64_FORMAT, n - min_jlong);
+    sprintf(buf, "min+" JLONG_FORMAT, n - min_jlong);
   else if (n == max_jlong)
     return "max";
   else if (n > max_jlong - 10000)
-    sprintf(buf, "max-" INT64_FORMAT, max_jlong - n);
+    sprintf(buf, "max-" JLONG_FORMAT, max_jlong - n);
   else if ((str = longnamenear(max_juint, "maxuint", buf, n)) != NULL)
     return str;
   else if ((str = longnamenear(max_jint, "maxint", buf, n)) != NULL)
@@ -1569,7 +1569,7 @@
   else if ((str = longnamenear(min_jint, "minint", buf, n)) != NULL)
     return str;
   else
-    sprintf(buf, INT64_FORMAT, n);
+    sprintf(buf, JLONG_FORMAT, n);
   return buf;
 }
 
--- a/hotspot/src/share/vm/prims/jvm.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/prims/jvm.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -484,15 +484,6 @@
 JVM_END
 
 
-JVM_ENTRY(void, JVM_PrintStackTrace(JNIEnv *env, jobject receiver, jobject printable))
-  JVMWrapper("JVM_PrintStackTrace");
-  // Note: This is no longer used in Merlin, but we still support it for compatibility.
-  oop exception = JNIHandles::resolve_non_null(receiver);
-  oop stream    = JNIHandles::resolve_non_null(printable);
-  java_lang_Throwable::print_stack_trace(exception, stream);
-JVM_END
-
-
 JVM_ENTRY(jint, JVM_GetStackTraceDepth(JNIEnv *env, jobject throwable))
   JVMWrapper("JVM_GetStackTraceDepth");
   oop exception = JNIHandles::resolve(throwable);
@@ -1582,13 +1573,22 @@
   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
     if (k->oop_is_instance()) {
-      typeArrayOop a = Annotations::make_java_array(InstanceKlass::cast(k)->type_annotations()->class_annotations(), CHECK_NULL);
-      return (jbyteArray) JNIHandles::make_local(env, a);
+      Annotations* type_annotations = InstanceKlass::cast(k)->type_annotations();
+      if (type_annotations != NULL) {
+        typeArrayOop a = Annotations::make_java_array(type_annotations->class_annotations(), CHECK_NULL);
+        return (jbyteArray) JNIHandles::make_local(env, a);
+      }
     }
   }
   return NULL;
 JVM_END
 
+static void bounds_check(constantPoolHandle cp, jint index, TRAPS) {
+  if (!cp->is_within_bounds(index)) {
+    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");
+  }
+}
+
 JVM_ENTRY(jobjectArray, JVM_GetMethodParameters(JNIEnv *env, jobject method))
 {
   JVMWrapper("JVM_GetMethodParameters");
@@ -1598,15 +1598,31 @@
   Handle reflected_method (THREAD, JNIHandles::resolve_non_null(method));
   const int num_params = mh->method_parameters_length();
 
-  if(0 != num_params) {
+  if (0 != num_params) {
+    // make sure all the symbols are properly formatted
+    for (int i = 0; i < num_params; i++) {
+      MethodParametersElement* params = mh->method_parameters_start();
+      int index = params[i].name_cp_index;
+      bounds_check(mh->constants(), index, CHECK_NULL);
+
+      if (0 != index && !mh->constants()->tag_at(index).is_utf8()) {
+        THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
+                    "Wrong type at constant pool index");
+      }
+
+    }
+
     objArrayOop result_oop = oopFactory::new_objArray(SystemDictionary::reflect_Parameter_klass(), num_params, CHECK_NULL);
     objArrayHandle result (THREAD, result_oop);
 
-    for(int i = 0; i < num_params; i++) {
+    for (int i = 0; i < num_params; i++) {
       MethodParametersElement* params = mh->method_parameters_start();
-      Symbol* const sym = mh->constants()->symbol_at(params[i].name_cp_index);
+      // For a 0 index, give a NULL symbol
+      Symbol* const sym = 0 != params[i].name_cp_index ?
+        mh->constants()->symbol_at(params[i].name_cp_index) : NULL;
+      int flags = build_int_from_shorts(params[i].flags_lo, params[i].flags_hi);
       oop param = Reflection::new_parameter(reflected_method, i, sym,
-                                            params[i].flags, CHECK_NULL);
+                                            flags, CHECK_NULL);
       result->obj_at_put(i, param);
     }
     return (jobjectArray)JNIHandles::make_local(env, result());
@@ -1830,13 +1846,6 @@
 JVM_END
 
 
-static void bounds_check(constantPoolHandle cp, jint index, TRAPS) {
-  if (!cp->is_within_bounds(index)) {
-    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");
-  }
-}
-
-
 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject obj, jobject unused, jint index))
 {
   JVMWrapper("JVM_ConstantPoolGetClassAt");
@@ -1851,7 +1860,6 @@
 }
 JVM_END
 
-
 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
 {
   JVMWrapper("JVM_ConstantPoolGetClassAtIfLoaded");
--- a/hotspot/src/share/vm/prims/jvm.h	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/prims/jvm.h	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -212,9 +212,6 @@
 JNIEXPORT void JNICALL
 JVM_FillInStackTrace(JNIEnv *env, jobject throwable);
 
-JNIEXPORT void JNICALL
-JVM_PrintStackTrace(JNIEnv *env, jobject throwable, jobject printable);
-
 JNIEXPORT jint JNICALL
 JVM_GetStackTraceDepth(JNIEnv *env, jobject throwable);
 
--- a/hotspot/src/share/vm/prims/jvmtiExport.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/prims/jvmtiExport.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1305,15 +1305,21 @@
         vframeStream st(thread);
         assert(!st.at_end(), "cannot be at end");
         Method* current_method = NULL;
+        // A GC may occur during the Method::fast_exception_handler_bci_for()
+        // call below if it needs to load the constraint class. Using a
+        // methodHandle to keep the 'current_method' from being deallocated
+        // if GC happens.
+        methodHandle current_mh = methodHandle(thread, current_method);
         int current_bci = -1;
         do {
           current_method = st.method();
+          current_mh = methodHandle(thread, current_method);
           current_bci = st.bci();
           do {
             should_repeat = false;
             KlassHandle eh_klass(thread, exception_handle()->klass());
-            current_bci = current_method->fast_exception_handler_bci_for(
-              eh_klass, current_bci, THREAD);
+            current_bci = Method::fast_exception_handler_bci_for(
+              current_mh, eh_klass, current_bci, THREAD);
             if (HAS_PENDING_EXCEPTION) {
               exception_handle = Handle(thread, PENDING_EXCEPTION);
               CLEAR_PENDING_EXCEPTION;
@@ -1328,8 +1334,7 @@
           catch_jmethodID = 0;
           current_bci = 0;
         } else {
-          catch_jmethodID = jem.to_jmethodID(
-                                     methodHandle(thread, current_method));
+          catch_jmethodID = jem.to_jmethodID(current_mh);
         }
 
         JvmtiJavaThreadEventTransition jet(thread);
--- a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1334,20 +1334,8 @@
     return JVMTI_ERROR_INTERNAL;
   }
 
-  int orig_length = old_cp->orig_length();
-  if (orig_length == 0) {
-    // This old_cp is an actual original constant pool. We save
-    // the original length in the merged constant pool so that
-    // merge_constant_pools() can be more efficient. If a constant
-    // pool has a non-zero orig_length() value, then that constant
-    // pool was created by a merge operation in RedefineClasses.
-    merge_cp->set_orig_length(old_cp->length());
-  } else {
-    // This old_cp is a merged constant pool from a previous
-    // RedefineClasses() calls so just copy the orig_length()
-    // value.
-    merge_cp->set_orig_length(old_cp->orig_length());
-  }
+  // Update the version number of the constant pool
+  merge_cp->increment_and_save_version(old_cp->version());
 
   ResourceMark rm(THREAD);
   _index_map_count = 0;
@@ -2417,18 +2405,19 @@
        int scratch_cp_length, TRAPS) {
   assert(scratch_cp->length() >= scratch_cp_length, "sanity check");
 
-    // scratch_cp is a merged constant pool and has enough space for a
-    // worst case merge situation. We want to associate the minimum
-    // sized constant pool with the klass to save space.
-    constantPoolHandle smaller_cp(THREAD,
-    ConstantPool::allocate(loader_data, scratch_cp_length,
-                                   THREAD));
-    // preserve orig_length() value in the smaller copy
-    int orig_length = scratch_cp->orig_length();
-    assert(orig_length != 0, "sanity check");
-    smaller_cp->set_orig_length(orig_length);
-    scratch_cp->copy_cp_to(1, scratch_cp_length - 1, smaller_cp, 1, THREAD);
-    scratch_cp = smaller_cp;
+  // scratch_cp is a merged constant pool and has enough space for a
+  // worst case merge situation. We want to associate the minimum
+  // sized constant pool with the klass to save space.
+  constantPoolHandle smaller_cp(THREAD,
+          ConstantPool::allocate(loader_data, scratch_cp_length, THREAD));
+
+  // preserve version() value in the smaller copy
+  int version = scratch_cp->version();
+  assert(version != 0, "sanity check");
+  smaller_cp->set_version(version);
+
+  scratch_cp->copy_cp_to(1, scratch_cp_length - 1, smaller_cp, 1, THREAD);
+  scratch_cp = smaller_cp;
 
   // attach new constant pool to klass
   scratch_cp->set_pool_holder(scratch_class());
--- a/hotspot/src/share/vm/runtime/aprofiler.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/aprofiler.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -129,7 +129,7 @@
   assert(!is_active(), "AllocationProfiler cannot be active while printing profile");
 
   tty->cr();
-  tty->print_cr("Allocation profile (sizes in bytes, cutoff = %ld bytes):", cutoff * BytesPerWord);
+  tty->print_cr("Allocation profile (sizes in bytes, cutoff = " SIZE_FORMAT " bytes):", cutoff * BytesPerWord);
   tty->cr();
 
   // Print regular instance klasses and basic type array klasses
--- a/hotspot/src/share/vm/runtime/arguments.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/arguments.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -532,7 +532,7 @@
 // Parses a memory size specification string.
 static bool atomull(const char *s, julong* result) {
   julong n = 0;
-  int args_read = sscanf(s, os::julong_format_specifier(), &n);
+  int args_read = sscanf(s, JULONG_FORMAT, &n);
   if (args_read != 1) {
     return false;
   }
@@ -1083,10 +1083,6 @@
   }
 }
 
-// If the user has chosen ParallelGCThreads > 0, we set UseParNewGC
-// if it's not explictly set or unset. If the user has chosen
-// UseParNewGC and not explicitly set ParallelGCThreads we
-// set it, unless this is a single cpu machine.
 void Arguments::set_parnew_gc_flags() {
   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
          "control point invariant");
@@ -1095,42 +1091,41 @@
   // Turn off AdaptiveSizePolicy for parnew until it is complete.
   disable_adaptive_size_policy("UseParNewGC");
 
-  if (ParallelGCThreads == 0) {
-    FLAG_SET_DEFAULT(ParallelGCThreads,
-                     Abstract_VM_Version::parallel_worker_threads());
-    if (ParallelGCThreads == 1) {
-      FLAG_SET_DEFAULT(UseParNewGC, false);
-      FLAG_SET_DEFAULT(ParallelGCThreads, 0);
-    }
+  if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
+    FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
+    assert(ParallelGCThreads > 0, "We should always have at least one thread by default");
+  } else if (ParallelGCThreads == 0) {
+    jio_fprintf(defaultStream::error_stream(),
+        "The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");
+    vm_exit(1);
+  }
+
+  // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
+  // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
+  // we set them to 1024 and 1024.
+  // See CR 6362902.
+  if (FLAG_IS_DEFAULT(YoungPLABSize)) {
+    FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
   }
-  if (UseParNewGC) {
-    // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
-    // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
-    // we set them to 1024 and 1024.
-    // See CR 6362902.
-    if (FLAG_IS_DEFAULT(YoungPLABSize)) {
-      FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
+  if (FLAG_IS_DEFAULT(OldPLABSize)) {
+    FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
+  }
+
+  // AlwaysTenure flag should make ParNew promote all at first collection.
+  // See CR 6362902.
+  if (AlwaysTenure) {
+    FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0);
+  }
+  // When using compressed oops, we use local overflow stacks,
+  // rather than using a global overflow list chained through
+  // the klass word of the object's pre-image.
+  if (UseCompressedOops && !ParGCUseLocalOverflow) {
+    if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
+      warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
     }
-    if (FLAG_IS_DEFAULT(OldPLABSize)) {
-      FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
-    }
-
-    // AlwaysTenure flag should make ParNew promote all at first collection.
-    // See CR 6362902.
-    if (AlwaysTenure) {
-      FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0);
-    }
-    // When using compressed oops, we use local overflow stacks,
-    // rather than using a global overflow list chained through
-    // the klass word of the object's pre-image.
-    if (UseCompressedOops && !ParGCUseLocalOverflow) {
-      if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
-        warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
-      }
-      FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
-    }
-    assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
+    FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
   }
+  assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
 }
 
 // Adjust some sizes to suit CMS and/or ParNew needs; these work well on
@@ -1459,30 +1454,34 @@
 
   // If no heap maximum was requested explicitly, use some reasonable fraction
   // of the physical memory, up to a maximum of 1GB.
-  if (UseParallelGC) {
-    FLAG_SET_DEFAULT(ParallelGCThreads,
-                     Abstract_VM_Version::parallel_worker_threads());
-
-    // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
-    // SurvivorRatio has been set, reset their default values to SurvivorRatio +
-    // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
-    // See CR 6362902 for details.
-    if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
-      if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
-         FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
-      }
-      if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
-        FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
-      }
+  FLAG_SET_DEFAULT(ParallelGCThreads,
+                   Abstract_VM_Version::parallel_worker_threads());
+  if (ParallelGCThreads == 0) {
+    jio_fprintf(defaultStream::error_stream(),
+        "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
+    vm_exit(1);
+  }
+
+
+  // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
+  // SurvivorRatio has been set, reset their default values to SurvivorRatio +
+  // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
+  // See CR 6362902 for details.
+  if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
+    if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
+       FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
     }
-
-    if (UseParallelOldGC) {
-      // Par compact uses lower default values since they are treated as
-      // minimums.  These are different defaults because of the different
-      // interpretation and are not ergonomically set.
-      if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
-        FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
-      }
+    if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
+      FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
+    }
+  }
+
+  if (UseParallelOldGC) {
+    // Par compact uses lower default values since they are treated as
+    // minimums.  These are different defaults because of the different
+    // interpretation and are not ergonomically set.
+    if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
+      FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
     }
   }
 }
@@ -1783,6 +1782,24 @@
   return status;
 }
 
+void Arguments::check_deprecated_gcs() {
+  if (UseConcMarkSweepGC && !UseParNewGC) {
+    warning("Using the DefNew young collector with the CMS collector is deprecated "
+        "and will likely be removed in a future release");
+  }
+
+  if (UseParNewGC && !UseConcMarkSweepGC) {
+    // !UseConcMarkSweepGC means that we are using serial old gc. Unfortunately we don't
+    // set up UseSerialGC properly, so that can't be used in the check here.
+    warning("Using the ParNew young collector with the Serial old collector is deprecated "
+        "and will likely be removed in a future release");
+  }
+
+  if (CMSIncrementalMode) {
+    warning("Using incremental CMS is deprecated and will likely be removed in a future release");
+  }
+}
+
 // Check stack pages settings
 bool Arguments::check_stack_pages()
 {
@@ -3241,6 +3258,7 @@
   } else if (UseG1GC) {
     set_g1_gc_flags();
   }
+  check_deprecated_gcs();
 #endif // INCLUDE_ALTERNATE_GCS
 
 #ifdef SERIALGC
@@ -3285,6 +3303,18 @@
   if (!EliminateLocks) {
     EliminateNestedLocks = false;
   }
+  if (!Inline) {
+    IncrementalInline = false;
+  }
+#ifndef PRODUCT
+  if (!IncrementalInline) {
+    AlwaysIncrementalInline = false;
+  }
+#endif
+  if (IncrementalInline && FLAG_IS_DEFAULT(MaxNodeLimit)) {
+    // incremental inlining: bump MaxNodeLimit
+    FLAG_SET_DEFAULT(MaxNodeLimit, (intx)75000);
+  }
 #endif
 
   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
--- a/hotspot/src/share/vm/runtime/arguments.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/arguments.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -413,6 +413,7 @@
   static jint adjust_after_os();
   // Check for consistency in the selection of the garbage collector.
   static bool check_gc_consistency();
+  static void check_deprecated_gcs();
   // Check consistecy or otherwise of VM argument settings
   static bool check_vm_args_consistency();
   // Check stack pages settings
--- a/hotspot/src/share/vm/runtime/globals.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/globals.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -929,11 +929,14 @@
           "Starts debugger when an implicit OS (e.g., NULL) "               \
           "exception happens")                                              \
                                                                             \
-  notproduct(bool, PrintCodeCache, false,                                   \
-          "Print the compiled_code cache when exiting")                     \
+  product(bool, PrintCodeCache, false,                                      \
+          "Print the code cache memory usage when exiting")                 \
                                                                             \
   develop(bool, PrintCodeCache2, false,                                     \
-          "Print detailed info on the compiled_code cache when exiting")    \
+          "Print detailed usage info on the code cache when exiting")       \
+                                                                            \
+  product(bool, PrintCodeCacheOnCompilation, false,                         \
+          "Print the code cache memory usage each time a method is compiled") \
                                                                             \
   diagnostic(bool, PrintStubCode, false,                                    \
           "Print generated stub code")                                      \
@@ -969,18 +972,6 @@
   notproduct(uintx, WarnOnStalledSpinLock, 0,                               \
           "Prints warnings for stalled SpinLocks")                          \
                                                                             \
-  develop(bool, InitializeJavaLangSystem, true,                             \
-          "Initialize java.lang.System - turn off for individual "          \
-          "method debugging")                                               \
-                                                                            \
-  develop(bool, InitializeJavaLangString, true,                             \
-          "Initialize java.lang.String - turn off for individual "          \
-          "method debugging")                                               \
-                                                                            \
-  develop(bool, InitializeJavaLangExceptionsErrors, true,                   \
-          "Initialize various error and exception classes - turn off for "  \
-          "individual method debugging")                                    \
-                                                                            \
   product(bool, RegisterFinalizersAtInit, true,                             \
           "Register finalizable objects at end of Object.<init> or "        \
           "after allocation")                                               \
@@ -1101,13 +1092,6 @@
   product(bool, ReduceSignalUsage, false,                                   \
           "Reduce the use of OS signals in Java and/or the VM")             \
                                                                             \
-  notproduct(bool, ValidateMarkSweep, false,                                \
-          "Do extra validation during MarkSweep collection")                \
-                                                                            \
-  notproduct(bool, RecordMarkSweepCompaction, false,                        \
-          "Enable GC-to-GC recording and querying of compaction during "    \
-          "MarkSweep")                                                      \
-                                                                            \
   develop_pd(bool, ShareVtableStubs,                                        \
           "Share vtable stubs (smaller code but worse branch prediction")   \
                                                                             \
@@ -1618,7 +1602,7 @@
   develop(bool, CMSTraceThreadState, false,                                 \
           "Trace the CMS thread state (enable the trace_state() method)")   \
                                                                             \
-  product(bool, CMSClassUnloadingEnabled, false,                            \
+  product(bool, CMSClassUnloadingEnabled, true,                             \
           "Whether class unloading enabled when using CMS GC")              \
                                                                             \
   product(uintx, CMSClassUnloadingMaxInterval, 0,                           \
@@ -2229,7 +2213,8 @@
   develop(bool, TraceClassLoaderData, false,                                \
           "Trace class loader loader_data lifetime")                        \
                                                                             \
-  product(uintx, InitialBootClassLoaderMetaspaceSize, 3*M,                  \
+  product(uintx, InitialBootClassLoaderMetaspaceSize,                       \
+          NOT_LP64(2200*K) LP64_ONLY(4*M),                                  \
           "Initial size of the boot class loader data metaspace")           \
                                                                             \
   product(bool, TraceGen0Time, false,                                       \
--- a/hotspot/src/share/vm/runtime/java.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/java.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -368,6 +368,12 @@
   if (CITime) {
     CompileBroker::print_times();
   }
+
+  if (PrintCodeCache) {
+    MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
+    CodeCache::print();
+  }
+
 #ifdef COMPILER2
   if (PrintPreciseBiasedLockingStatistics) {
     OptoRuntime::print_named_counters();
--- a/hotspot/src/share/vm/runtime/objectMonitor.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/objectMonitor.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -653,8 +653,7 @@
     assert (_succ != Self, "invariant") ;
     if (_Responsible == Self) {
         _Responsible = NULL ;
-        // Dekker pivot-point.
-        // Consider OrderAccess::storeload() here
+        OrderAccess::fence(); // Dekker pivot-point
 
         // We may leave threads on cxq|EntryList without a designated
         // "Responsible" thread.  This is benign.  When this thread subsequently
@@ -674,10 +673,6 @@
         //
         // The MEMBAR, above, prevents the LD of cxq|EntryList in the subsequent
         // exit operation from floating above the ST Responsible=null.
-        //
-        // In *practice* however, EnterI() is always followed by some atomic
-        // operation such as the decrement of _count in ::enter().  Those atomics
-        // obviate the need for the explicit MEMBAR, above.
     }
 
     // We've acquired ownership with CAS().
--- a/hotspot/src/share/vm/runtime/objectMonitor.inline.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/objectMonitor.inline.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -101,10 +101,12 @@
   return _count;
 }
 
+// Do NOT set _count = 0. There is a race such that _count could
+// be set while inflating prior to setting _owner
+// Just use Atomic::inc/dec and assert 0 when monitor put on free list
 inline void ObjectMonitor::set_owner(void* owner) {
   _owner = owner;
   _recursions = 0;
-  _count = 0;
 }
 
 
--- a/hotspot/src/share/vm/runtime/os.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/os.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -641,10 +641,6 @@
 
   static struct hostent* get_host_by_name(char* name);
 
-  // Printing 64 bit integers
-  static const char* jlong_format_specifier();
-  static const char* julong_format_specifier();
-
   // Support for signals (see JVM_RaiseSignal, JVM_RegisterSignal)
   static void  signal_init();
   static void  signal_init_pd();
--- a/hotspot/src/share/vm/runtime/os_ext.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/os_ext.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/runtime/perfData.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/perfData.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -192,7 +192,7 @@
 }
 
 int PerfLong::format(char* buffer, int length) {
-  return jio_snprintf(buffer, length,"%lld", *(jlong*)_valuep);
+  return jio_snprintf(buffer, length, JLONG_FORMAT, *(jlong*)_valuep);
 }
 
 PerfLongVariant::PerfLongVariant(CounterNS ns, const char* namep, Units u,
--- a/hotspot/src/share/vm/runtime/reflection.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/reflection.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -862,7 +862,15 @@
 
 oop Reflection::new_parameter(Handle method, int index, Symbol* sym,
                               int flags, TRAPS) {
-  Handle name = java_lang_String::create_from_symbol(sym, CHECK_NULL);
+  Handle name;
+
+  // A null symbol here translates to the empty string
+  if(NULL != sym) {
+    name = java_lang_String::create_from_symbol(sym, CHECK_NULL);
+  } else {
+    name = java_lang_String::create_from_str("", CHECK_NULL);
+  }
+
   Handle rh = java_lang_reflect_Parameter::create(CHECK_NULL);
   java_lang_reflect_Parameter::set_name(rh(), name());
   java_lang_reflect_Parameter::set_modifiers(rh(), flags);
--- a/hotspot/src/share/vm/runtime/sharedRuntime.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/sharedRuntime.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -643,7 +643,8 @@
       bool skip_scope_increment = false;
       // exception handler lookup
       KlassHandle ek (THREAD, exception->klass());
-      handler_bci = sd->method()->fast_exception_handler_bci_for(ek, bci, THREAD);
+      methodHandle mh(THREAD, sd->method());
+      handler_bci = Method::fast_exception_handler_bci_for(mh, ek, bci, THREAD);
       if (HAS_PENDING_EXCEPTION) {
         recursive_exception = true;
         // We threw an exception while trying to find the exception handler.
--- a/hotspot/src/share/vm/runtime/synchronizer.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/synchronizer.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -333,7 +333,9 @@
 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) {
   TEVENT (jni_exit) ;
   if (UseBiasedLocking) {
-    BiasedLocking::revoke_and_rebias(obj, false, THREAD);
+    Handle h_obj(THREAD, obj);
+    BiasedLocking::revoke_and_rebias(h_obj, false, THREAD);
+    obj = h_obj();
   }
   assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 
--- a/hotspot/src/share/vm/runtime/thread.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/thread.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1716,7 +1716,6 @@
 // cleanup_failed_attach_current_thread as well.
 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
   assert(this == JavaThread::current(),  "thread consistency check");
-  if (!InitializeJavaLangSystem) return;
 
   HandleMark hm(this);
   Handle uncaught_exception(this, this->pending_exception());
@@ -3469,11 +3468,7 @@
       create_vm_init_libraries();
     }
 
-    if (InitializeJavaLangString) {
-      initialize_class(vmSymbols::java_lang_String(), CHECK_0);
-    } else {
-      warning("java.lang.String not initialized");
-    }
+    initialize_class(vmSymbols::java_lang_String(), CHECK_0);
 
     if (AggressiveOpts) {
       {
@@ -3514,53 +3509,39 @@
     }
 
     // Initialize java_lang.System (needed before creating the thread)
-    if (InitializeJavaLangSystem) {
-      initialize_class(vmSymbols::java_lang_System(), CHECK_0);
-      initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0);
-      Handle thread_group = create_initial_thread_group(CHECK_0);
-      Universe::set_main_thread_group(thread_group());
-      initialize_class(vmSymbols::java_lang_Thread(), CHECK_0);
-      oop thread_object = create_initial_thread(thread_group, main_thread, CHECK_0);
-      main_thread->set_threadObj(thread_object);
-      // Set thread status to running since main thread has
-      // been started and running.
-      java_lang_Thread::set_thread_status(thread_object,
-                                          java_lang_Thread::RUNNABLE);
-
-      // The VM creates & returns objects of this class. Make sure it's initialized.
-      initialize_class(vmSymbols::java_lang_Class(), CHECK_0);
-
-      // The VM preresolves methods to these classes. Make sure that they get initialized
-      initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK_0);
-      initialize_class(vmSymbols::java_lang_ref_Finalizer(),  CHECK_0);
-      call_initializeSystemClass(CHECK_0);
-
-      // get the Java runtime name after java.lang.System is initialized
-      JDK_Version::set_runtime_name(get_java_runtime_name(THREAD));
-      JDK_Version::set_runtime_version(get_java_runtime_version(THREAD));
-    } else {
-      warning("java.lang.System not initialized");
-    }
+    initialize_class(vmSymbols::java_lang_System(), CHECK_0);
+    initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0);
+    Handle thread_group = create_initial_thread_group(CHECK_0);
+    Universe::set_main_thread_group(thread_group());
+    initialize_class(vmSymbols::java_lang_Thread(), CHECK_0);
+    oop thread_object = create_initial_thread(thread_group, main_thread, CHECK_0);
+    main_thread->set_threadObj(thread_object);
+    // Set thread status to running since main thread has
+    // been started and running.
+    java_lang_Thread::set_thread_status(thread_object,
+                                        java_lang_Thread::RUNNABLE);
+
+    // The VM creates & returns objects of this class. Make sure it's initialized.
+    initialize_class(vmSymbols::java_lang_Class(), CHECK_0);
+
+    // The VM preresolves methods to these classes. Make sure that they get initialized
+    initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK_0);
+    initialize_class(vmSymbols::java_lang_ref_Finalizer(),  CHECK_0);
+    call_initializeSystemClass(CHECK_0);
+
+    // get the Java runtime name after java.lang.System is initialized
+    JDK_Version::set_runtime_name(get_java_runtime_name(THREAD));
+    JDK_Version::set_runtime_version(get_java_runtime_version(THREAD));
 
     // an instance of OutOfMemory exception has been allocated earlier
-    if (InitializeJavaLangExceptionsErrors) {
-      initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK_0);
-      initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK_0);
-      initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK_0);
-      initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK_0);
-      initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK_0);
-      initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK_0);
-      initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK_0);
-      initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK_0);
-    } else {
-      warning("java.lang.OutOfMemoryError has not been initialized");
-      warning("java.lang.NullPointerException has not been initialized");
-      warning("java.lang.ClassCastException has not been initialized");
-      warning("java.lang.ArrayStoreException has not been initialized");
-      warning("java.lang.ArithmeticException has not been initialized");
-      warning("java.lang.StackOverflowError has not been initialized");
-      warning("java.lang.IllegalArgumentException has not been initialized");
-    }
+    initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK_0);
+    initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK_0);
+    initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK_0);
+    initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK_0);
+    initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK_0);
+    initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK_0);
+    initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK_0);
+    initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK_0);
   }
 
   // See        : bugid 4211085.
--- a/hotspot/src/share/vm/runtime/virtualspace.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/virtualspace.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -868,8 +868,8 @@
   tty->print   ("Virtual space:");
   if (special()) tty->print(" (pinned in memory)");
   tty->cr();
-  tty->print_cr(" - committed: %ld", committed_size());
-  tty->print_cr(" - reserved:  %ld", reserved_size());
+  tty->print_cr(" - committed: " SIZE_FORMAT, committed_size());
+  tty->print_cr(" - reserved:  " SIZE_FORMAT, reserved_size());
   tty->print_cr(" - [low, high]:     [" INTPTR_FORMAT ", " INTPTR_FORMAT "]",  low(), high());
   tty->print_cr(" - [low_b, high_b]: [" INTPTR_FORMAT ", " INTPTR_FORMAT "]",  low_boundary(), high_boundary());
 }
--- a/hotspot/src/share/vm/runtime/vmStructs.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/vmStructs.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -717,7 +717,6 @@
   nonstatic_field(ClassLoaderData,             _next,                                         ClassLoaderData*)                      \
                                                                                                                                      \
   static_field(ClassLoaderDataGraph,           _head,                                         ClassLoaderData*)                      \
-  nonstatic_field(ClassLoaderDataGraph,        _unloading,                                    ClassLoaderData*)                      \
                                                                                                                                      \
   /*******************/                                                                                                              \
   /* GrowableArrays  */                                                                                                              \
@@ -1199,7 +1198,6 @@
   /*********************************/                                                                                                \
                                                                                                                                      \
   static_field(java_lang_Class,                _klass_offset,                                 int)                                   \
-  static_field(java_lang_Class,                _resolved_constructor_offset,                  int)                                   \
   static_field(java_lang_Class,                _array_klass_offset,                           int)                                   \
   static_field(java_lang_Class,                _oop_size_offset,                              int)                                   \
   static_field(java_lang_Class,                _static_oop_field_count_offset,                int)                                   \
@@ -2293,6 +2291,7 @@
   /*************************************/                                 \
                                                                           \
   declare_preprocessor_constant("FIELDINFO_TAG_SIZE", FIELDINFO_TAG_SIZE) \
+  declare_preprocessor_constant("FIELDINFO_TAG_MASK", FIELDINFO_TAG_MASK) \
   declare_preprocessor_constant("FIELDINFO_TAG_OFFSET", FIELDINFO_TAG_OFFSET) \
                                                                           \
   /************************************************/                      \
@@ -2575,7 +2574,8 @@
 
 // This macro checks the type of a VMStructEntry by comparing pointer types
 #define CHECK_NONSTATIC_VM_STRUCT_ENTRY(typeName, fieldName, type)                 \
- {typeName *dummyObj = NULL; type* dummy = &dummyObj->fieldName; }
+ {typeName *dummyObj = NULL; type* dummy = &dummyObj->fieldName;                   \
+  assert(offset_of(typeName, fieldName) < sizeof(typeName), "Illegal nonstatic struct entry, field offset too large"); }
 
 // This macro checks the type of a volatile VMStructEntry by comparing pointer types
 #define CHECK_VOLATILE_NONSTATIC_VM_STRUCT_ENTRY(typeName, fieldName, type)        \
--- a/hotspot/src/share/vm/runtime/vmThread.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/runtime/vmThread.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -570,7 +570,11 @@
   if (!t->is_VM_thread()) {
     SkipGCALot sgcalot(t);    // avoid re-entrant attempts to gc-a-lot
     // JavaThread or WatcherThread
-    t->check_for_valid_safepoint_state(true);
+    bool concurrent = op->evaluate_concurrently();
+    // only blocking VM operations need to verify the caller's safepoint state:
+    if (!concurrent) {
+      t->check_for_valid_safepoint_state(true);
+    }
 
     // New request from Java thread, evaluate prologue
     if (!op->doit_prologue()) {
@@ -582,7 +586,6 @@
 
     // It does not make sense to execute the epilogue, if the VM operation object is getting
     // deallocated by the VM thread.
-    bool concurrent     = op->evaluate_concurrently();
     bool execute_epilog = !op->is_cheap_allocated();
     assert(!concurrent || op->is_cheap_allocated(), "concurrent => cheap_allocated");
 
--- a/hotspot/src/share/vm/services/diagnosticArgument.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/services/diagnosticArgument.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -86,7 +86,7 @@
 
 template <> void DCmdArgument<jlong>::parse_value(const char* str,
                                                   size_t len, TRAPS) {
-    if (str == NULL || sscanf(str, INT64_FORMAT, &_value) != 1) {
+    if (str == NULL || sscanf(str, JLONG_FORMAT, &_value) != 1) {
     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
       "Integer parsing error in diagnostic command arguments\n");
   }
@@ -171,7 +171,7 @@
               "Integer parsing error nanotime value: syntax error");
   }
 
-  int argc = sscanf(str, INT64_FORMAT , &_value._time);
+  int argc = sscanf(str, JLONG_FORMAT, &_value._time);
   if (argc != 1) {
     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
               "Integer parsing error nanotime value: syntax error");
--- a/hotspot/src/share/vm/services/diagnosticCommand_ext.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/services/diagnosticCommand_ext.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,6 +1,6 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. DO
- * NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License version 2 only, as
--- a/hotspot/src/share/vm/services/heapDumper.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/services/heapDumper.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -1866,7 +1866,7 @@
     if (error() == NULL) {
       char msg[256];
       sprintf(msg, "Heap dump file created [%s bytes in %3.3f secs]",
-        os::jlong_format_specifier(), timer()->seconds());
+        JLONG_FORMAT, timer()->seconds());
       tty->print_cr(msg, writer.bytes_written());
     } else {
       tty->print_cr("Dump file is incomplete: %s", writer.error());
--- a/hotspot/src/share/vm/services/lowMemoryDetector.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/services/lowMemoryDetector.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -353,7 +353,7 @@
 
 #ifndef PRODUCT
 void SensorInfo::print() {
-  tty->print_cr("%s count = %ld pending_triggers = %ld pending_clears = %ld",
+  tty->print_cr("%s count = " SIZE_FORMAT " pending_triggers = %ld pending_clears = %ld",
                 (_sensor_on ? "on" : "off"),
                 _sensor_count, _pending_trigger_count, _pending_clear_count);
 }
--- a/hotspot/src/share/vm/services/memReporter.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/services/memReporter.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/services/memReporter.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/services/memReporter.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/hotspot/src/share/vm/shark/sharkBlock.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/shark/sharkBlock.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1032,7 +1032,7 @@
     check_null(value);
     object = value->generic_value();
   }
-  if (is_get && field->is_constant()) {
+  if (is_get && field->is_constant() && field->is_static()) {
     SharkConstant *constant = SharkConstant::for_field(iter());
     if (constant->is_loaded())
       value = constant->value(builder());
@@ -1044,10 +1044,17 @@
     BasicType   basic_type = field->type()->basic_type();
     Type *stack_type = SharkType::to_stackType(basic_type);
     Type *field_type = SharkType::to_arrayType(basic_type);
-
+    Type *type = field_type;
+    if (field->is_volatile()) {
+      if (field_type == SharkType::jfloat_type()) {
+        type = SharkType::jint_type();
+      } else if (field_type == SharkType::jdouble_type()) {
+        type = SharkType::jlong_type();
+      }
+    }
     Value *addr = builder()->CreateAddressOfStructEntry(
       object, in_ByteSize(field->offset_in_bytes()),
-      PointerType::getUnqual(field_type),
+      PointerType::getUnqual(type),
       "addr");
 
     // Do the access
@@ -1055,6 +1062,7 @@
       Value* field_value;
       if (field->is_volatile()) {
         field_value = builder()->CreateAtomicLoad(addr);
+        field_value = builder()->CreateBitCast(field_value, field_type);
       } else {
         field_value = builder()->CreateLoad(addr);
       }
@@ -1074,6 +1082,7 @@
       }
 
       if (field->is_volatile()) {
+        field_value = builder()->CreateBitCast(field_value, type);
         builder()->CreateAtomicStore(field_value, addr);
       } else {
         builder()->CreateStore(field_value, addr);
--- a/hotspot/src/share/vm/shark/sharkCompiler.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/shark/sharkCompiler.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -185,6 +185,9 @@
 
   // Build the LLVM IR for the method
   Function *function = SharkFunction::build(env, &builder, flow, name);
+  if (env->failing()) {
+    return;
+  }
 
   // Generate native code.  It's unpleasant that we have to drop into
   // the VM to do this -- it blocks safepoints -- but I can't see any
--- a/hotspot/src/share/vm/shark/sharkCompiler.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/shark/sharkCompiler.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -46,6 +46,9 @@
   // Missing feature tests
   bool supports_native() { return true; }
   bool supports_osr()    { return true; }
+  bool can_compile_method(methodHandle method)  {
+    return ! (method->is_method_handle_intrinsic() || method->is_compiled_lambda_form());
+  }
 
   // Customization
   bool needs_adapters()  { return false; }
--- a/hotspot/src/share/vm/shark/sharkConstant.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/shark/sharkConstant.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -37,7 +37,12 @@
   ciType *type = NULL;
   if (constant.basic_type() == T_OBJECT) {
     ciEnv *env = ciEnv::current();
-    assert(constant.as_object()->klass() == env->String_klass() || constant.as_object()->klass() == env->Class_klass(), "should be");
+
+    assert(constant.as_object()->klass() == env->String_klass()
+           || constant.as_object()->klass() == env->Class_klass()
+           || constant.as_object()->klass()->is_subtype_of(env->MethodType_klass())
+           || constant.as_object()->klass()->is_subtype_of(env->MethodHandle_klass()), "should be");
+
     type = constant.as_object()->klass();
   }
   return new SharkConstant(constant, type);
--- a/hotspot/src/share/vm/shark/sharkFunction.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/shark/sharkFunction.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -77,6 +77,10 @@
   // Walk the tree from the start block to determine which
   // blocks are entered and which blocks require phis
   SharkTopLevelBlock *start_block = block(flow()->start_block_num());
+  if (is_osr() && start_block->stack_depth_at_entry() != 0) {
+    env()->record_method_not_compilable("can't compile OSR block with incoming stack-depth > 0");
+    return;
+  }
   assert(start_block->start() == flow()->start_bci(), "blocks out of order");
   start_block->enter();
 
--- a/hotspot/src/share/vm/shark/sharkInliner.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/shark/sharkInliner.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -725,7 +725,7 @@
   // Push the result if necessary
   if (is_get) {
     bool result_pushed = false;
-    if (field->is_constant()) {
+    if (field->is_constant() && field->is_static()) {
       SharkConstant *sc = SharkConstant::for_field(iter());
       if (sc->is_loaded()) {
         push(sc->is_nonzero());
--- a/hotspot/src/share/vm/shark/sharkInvariants.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/shark/sharkInvariants.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -68,7 +68,7 @@
   //
   // Accessing this directly is kind of ugly, so it's private.  Add
   // new accessors below if you need something from it.
- private:
+ protected:
   ciEnv* env() const {
     assert(_env != NULL, "env not available");
     return _env;
@@ -99,12 +99,14 @@
   DebugInformationRecorder* debug_info() const {
     return env()->debug_info();
   }
+  SharkCodeBuffer* code_buffer() const {
+    return builder()->code_buffer();
+  }
+
+ public:
   Dependencies* dependencies() const {
     return env()->dependencies();
   }
-  SharkCodeBuffer* code_buffer() const {
-    return builder()->code_buffer();
-  }
 
   // Commonly used classes
  protected:
--- a/hotspot/src/share/vm/shark/sharkTopLevelBlock.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/shark/sharkTopLevelBlock.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -113,7 +113,19 @@
       ciSignature* sig;
       method = iter()->get_method(will_link, &sig);
       assert(will_link, "typeflow responsibility");
-
+      // We can't compile calls to method handle intrinsics, because we use
+      // the interpreter entry points and they expect the top frame to be an
+      // interpreter frame. We need to implement the intrinsics for Shark.
+      if (method->is_method_handle_intrinsic() || method->is_compiled_lambda_form()) {
+        if (SharkPerformanceWarnings) {
+          warning("JSR292 optimization not yet implemented in Shark");
+        }
+        set_trap(
+          Deoptimization::make_trap_request(
+            Deoptimization::Reason_unhandled,
+            Deoptimization::Action_make_not_compilable), bci());
+          return;
+      }
       if (!method->holder()->is_linked()) {
         set_trap(
           Deoptimization::make_trap_request(
@@ -158,6 +170,16 @@
         return;
       }
       break;
+    case Bytecodes::_invokedynamic:
+    case Bytecodes::_invokehandle:
+      if (SharkPerformanceWarnings) {
+        warning("JSR292 optimization not yet implemented in Shark");
+      }
+      set_trap(
+        Deoptimization::make_trap_request(
+          Deoptimization::Reason_unhandled,
+          Deoptimization::Action_make_not_compilable), bci());
+      return;
     }
   }
 
@@ -1030,7 +1052,6 @@
       dest_method->holder() == java_lang_Object_klass())
     return dest_method;
 
-#ifdef SHARK_CAN_DEOPTIMIZE_ANYWHERE
   // This code can replace a virtual call with a direct call if this
   // class is the only one in the entire set of loaded classes that
   // implements this method.  This makes the compiled code dependent
@@ -1064,6 +1085,8 @@
   if (monomorphic_target != NULL) {
     assert(!monomorphic_target->is_abstract(), "shouldn't be");
 
+    function()->dependencies()->assert_unique_concrete_method(actual_receiver, monomorphic_target);
+
     // Opto has a bunch of type checking here that I don't
     // understand.  It's to inhibit casting in one direction,
     // possibly because objects in Opto can have inexact
@@ -1097,7 +1120,6 @@
   // with non-monomorphic targets if the receiver has an exact
   // type.  We don't mark types this way, so we can't do this.
 
-#endif // SHARK_CAN_DEOPTIMIZE_ANYWHERE
 
   return NULL;
 }
@@ -1298,8 +1320,9 @@
 
   // Try to inline the call
   if (!call_is_virtual) {
-    if (SharkInliner::attempt_inline(call_method, current_state()))
+    if (SharkInliner::attempt_inline(call_method, current_state())) {
       return;
+    }
   }
 
   // Find the method we are calling
--- a/hotspot/src/share/vm/utilities/debug.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/utilities/debug.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -612,21 +612,6 @@
   Events::print();
 }
 
-// Given a heap address that was valid before the most recent GC, if
-// the oop that used to contain it is still live, prints the new
-// location of the oop and the address. Useful for tracking down
-// certain kinds of naked oop and oop map bugs.
-extern "C" void pnl(intptr_t old_heap_addr) {
-  // Print New Location of old heap address
-  Command c("pnl");
-#ifndef VALIDATE_MARK_SWEEP
-  tty->print_cr("Requires build with VALIDATE_MARK_SWEEP defined (debug build) and RecordMarkSweepCompaction enabled");
-#else
-  MarkSweep::print_new_location_of_heap_address((HeapWord*) old_heap_addr);
-#endif
-}
-
-
 extern "C" Method* findm(intptr_t pc) {
   Command c("findm");
   nmethod* nm = CodeCache::find_nmethod((address)pc);
--- a/hotspot/src/share/vm/utilities/globalDefinitions.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/utilities/globalDefinitions.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -1250,6 +1250,14 @@
 
 #define PTR64_FORMAT           "0x%016" PRIx64
 
+// Format jlong, if necessary
+#ifndef JLONG_FORMAT
+#define JLONG_FORMAT           INT64_FORMAT
+#endif
+#ifndef JULONG_FORMAT
+#define JULONG_FORMAT          UINT64_FORMAT
+#endif
+
 // Format pointers which change size between 32- and 64-bit.
 #ifdef  _LP64
 #define INTPTR_FORMAT "0x%016" PRIxPTR
--- a/hotspot/src/share/vm/utilities/globalDefinitions_gcc.hpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/utilities/globalDefinitions_gcc.hpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -306,4 +306,8 @@
 #endif
 #define offsetof(klass,field) offset_of(klass,field)
 
+#if defined(_LP64) && defined(__APPLE__)
+#define JLONG_FORMAT           "%ld"
+#endif // _LP64 && __APPLE__
+
 #endif // SHARE_VM_UTILITIES_GLOBALDEFINITIONS_GCC_HPP
--- a/hotspot/src/share/vm/utilities/ostream.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/utilities/ostream.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -243,13 +243,11 @@
 }
 
 void outputStream::print_jlong(jlong value) {
-  // N.B. Same as INT64_FORMAT
-  print(os::jlong_format_specifier(), value);
+  print(JLONG_FORMAT, value);
 }
 
 void outputStream::print_julong(julong value) {
-  // N.B. Same as UINT64_FORMAT
-  print(os::julong_format_specifier(), value);
+  print(JULONG_FORMAT, value);
 }
 
 /**
--- a/hotspot/src/share/vm/utilities/taskqueue.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/utilities/taskqueue.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -239,8 +239,8 @@
 
 #ifdef TRACESPINNING
 void ParallelTaskTerminator::print_termination_counts() {
-  gclog_or_tty->print_cr("ParallelTaskTerminator Total yields: %lld  "
-    "Total spins: %lld  Total peeks: %lld",
+  gclog_or_tty->print_cr("ParallelTaskTerminator Total yields: " UINT32_FORMAT
+    " Total spins: " UINT32_FORMAT " Total peeks: " UINT32_FORMAT,
     total_yields(),
     total_spins(),
     total_peeks());
--- a/hotspot/src/share/vm/utilities/vmError.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/src/share/vm/utilities/vmError.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -702,7 +702,7 @@
 
      if (_verbose && Universe::is_fully_initialized()) {
        // print code cache information before vm abort
-       CodeCache::print_bounds(st);
+       CodeCache::print_summary(st);
        st->cr();
      }
 
--- a/hotspot/test/compiler/7190310/Test7190310.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/test/compiler/7190310/Test7190310.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,16 @@
  */
 
 /*
- * Manual test
+ * @test
+ * @bug 7190310
+ * @summary Inlining WeakReference.get(), and hoisting $referent may lead to non-terminating loops
+ * @run main/othervm/timeout=600 -Xbatch Test7190310
+ */
+
+/*
+ * Note bug exhibits as infinite loop, timeout is helpful.
+ * It should normally finish pretty quickly, but on some especially slow machines
+ * it may not.  The companion _unsafe test lacks a timeout, but that is okay.
  */
 
 import java.lang.ref.*;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/8005419/Test8005419.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8005419
+ * @summary Improve intrinsics code performance on x86 by using AVX2
+ * @run main/othervm -Xbatch -Xmx64m Test8005419
+ *
+ */
+
+public class Test8005419 {
+    public static int SIZE = 64;
+
+    public static void main(String[] args) {
+        char[] a = new char[SIZE];
+        char[] b = new char[SIZE];
+
+        for (int i = 16; i < SIZE; i++) {
+          a[i] = (char)i;
+          b[i] = (char)i;
+        }
+        String s1 = new String(a);
+        String s2 = new String(b);
+
+        // Warm up
+        boolean failed = false;
+        int result = 0;
+        for (int i = 0; i < 10000; i++) {
+          result += test(s1, s2);
+        }
+        for (int i = 0; i < 10000; i++) {
+          result += test(s1, s2);
+        }
+        for (int i = 0; i < 10000; i++) {
+          result += test(s1, s2);
+        }
+        if (result != 0) failed = true;
+
+        System.out.println("Start testing");
+        // Compare same string
+        result = test(s1, s1);
+        if (result != 0) {
+          failed = true;
+          System.out.println("Failed same: result = " + result + ", expected 0");
+        }
+        // Compare equal strings
+        for (int i = 1; i <= SIZE; i++) {
+          s1 = new String(a, 0, i);
+          s2 = new String(b, 0, i);
+          result = test(s1, s2);
+          if (result != 0) {
+            failed = true;
+            System.out.println("Failed equals s1[" + i + "], s2[" + i + "]: result = " + result + ", expected 0");
+          }
+        }
+        // Compare equal strings but different sizes
+        for (int i = 1; i <= SIZE; i++) {
+          s1 = new String(a, 0, i);
+          for (int j = 1; j <= SIZE; j++) {
+            s2 = new String(b, 0, j);
+            result = test(s1, s2);
+            if (result != (i-j)) {
+              failed = true;
+              System.out.println("Failed diff size s1[" + i + "], s2[" + j + "]: result = " + result + ", expected " + (i-j));
+            }
+          }
+        }
+        // Compare strings with one char different and different sizes
+        for (int i = 1; i <= SIZE; i++) {
+          s1 = new String(a, 0, i);
+          for (int j = 0; j < i; j++) {
+            b[j] -= 3; // change char
+            s2 = new String(b, 0, i);
+            result = test(s1, s2);
+            int chdiff = a[j] - b[j];
+            if (result != chdiff) {
+              failed = true;
+              System.out.println("Failed diff char s1[" + i + "], s2[" + i + "]: result = " + result + ", expected " + chdiff);
+            }
+            result = test(s2, s1);
+            chdiff = b[j] - a[j];
+            if (result != chdiff) {
+              failed = true;
+              System.out.println("Failed diff char s2[" + i + "], s1[" + i + "]: result = " + result + ", expected " + chdiff);
+            }
+            b[j] += 3; // restore
+          }
+        }
+        if (failed) {
+          System.out.println("FAILED");
+          System.exit(97);
+        }
+        System.out.println("PASSED");
+    }
+
+    private static int test(String str1, String str2) {
+        return str1.compareTo(str2);
+    }
+}
--- a/hotspot/test/runtime/7158804/Test7158804.sh	Tue Jan 22 14:27:41 2013 -0500
+++ b/hotspot/test/runtime/7158804/Test7158804.sh	Tue Jan 22 11:54:16 2013 -0800
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 
--- a/jaxp/.hgtags	Tue Jan 22 14:27:41 2013 -0500
+++ b/jaxp/.hgtags	Tue Jan 22 11:54:16 2013 -0800
@@ -190,3 +190,8 @@
 e6af1ad464e3d9b1154b9f9ed9a5373b97d129fc jdk8-b66
 83df3493ca3cf0be077f1d0dd90119456f266f54 jdk8-b67
 b854e70084214e9dcf1b37373f6e4b1a68760e03 jdk8-b68
+789a855de959f7e9600e57759c6c3dbb0b24d78b jdk8-b69
+6ec9edffc286c9c9ac96c9cd2050b01cb5d514a8 jdk8-b70
+499be952a291cec1dc774a84a238941d6faf772d jdk8-b71
+bdf2af722a6b54fca47d8c51d17a1b8f41dd7a3e jdk8-b72
+84946404d1e1de003ed2bf218ef8d48906a90e37 jdk8-b73
--- a/jaxp/makefiles/BuildJaxp.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jaxp/makefiles/BuildJaxp.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -47,11 +47,23 @@
 $(eval $(call SetupJavaCompilation,BUILD_JAXP,\
 		SETUP:=GENERATE_NEWBYTECODE_DEBUG,\
 		SRC:=$(JAXP_TOPDIR)/src,\
-		CLEAN:=.properties,\
 		BIN:=$(JAXP_OUTPUTDIR)/classes,\
 		SRCZIP:=$(JAXP_OUTPUTDIR)/dist/lib/src.zip))
 
-$(eval $(call SetupArchive,ARCHIVE_JAXP,$(BUILD_JAXP),\
+# Imitate the property cleaning mechanism in the old build. This will likely be replaced 
+# by the unified functionality in JavaCompilation.gmk, but keep it the same as old build
+# for now, even though it actually breaks properties containing # in the value.
+# Using nawk to avoid solaris sed.
+$(JAXP_OUTPUTDIR)/classes/%.properties: $(JAXP_TOPDIR)/src/%.properties
+	$(MKDIR) -p $(@D)
+	$(RM) $@ $@.tmp
+	$(CAT) $< | LANG=C $(NAWK) '{ sub(/#.*$$/,"#"); print }' > $@.tmp
+	$(MV) $@.tmp $@
+
+SRC_PROP_FILES := $(shell $(FIND) $(JAXP_TOPDIR)/src -name "*.properties")
+TARGET_PROP_FILES := $(patsubst $(JAXP_TOPDIR)/src/%,$(JAXP_OUTPUTDIR)/classes/%,$(SRC_PROP_FILES))
+
+$(eval $(call SetupArchive,ARCHIVE_JAXP,$(BUILD_JAXP) $(TARGET_PROP_FILES),\
 		SRCS:=$(JAXP_OUTPUTDIR)/classes,\
 		SUFFIXES:=.class .properties,\
 		JAR:=$(JAXP_OUTPUTDIR)/dist/lib/classes.jar))
--- a/jaxp/src/com/sun/org/apache/xalan/internal/XalanConstants.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/XalanConstants.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jaxp/src/com/sun/org/apache/xalan/internal/utils/FactoryImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/utils/FactoryImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xslt/EnvironmentCheck.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xslt/EnvironmentCheck.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1005,7 +1005,7 @@
     {
       Class clazz = ObjectFactory.findProviderClass(DOM_CLASS, true);
 
-      Method method = clazz.getMethod(DOM_LEVEL3_METHOD, null);
+      Method method = clazz.getMethod(DOM_LEVEL3_METHOD, (Class<?>[])null);
 
       // If we succeeded, we have loaded interfaces from a
       //  level 3 DOM somewhere
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/Version.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/Version.java	Tue Jan 22 11:54:16 2013 -0800
@@ -74,7 +74,7 @@
 
     /** Version string.
      * @deprecated  getVersion() should be used instead.  */
-    public static String fVersion = "Xerces-J 2.7.1";
+    public static final String fVersion = getVersion();
 
     private static final String fImmutableVersion = "Xerces-J 2.7.1";
 
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -193,9 +193,12 @@
                 null,
     };
 
-    protected static final char [] cdata = {'[','C','D','A','T','A','['};
-    protected static final char [] xmlDecl = {'<','?','x','m','l'};
-    protected static final char [] endTag = {'<','/'};
+    private static final char [] cdata = {'[','C','D','A','T','A','['};
+    private static final char [] endTag = {'<','/'};
+
+    //this variable is also used by XMLDocumentScannerImpl in the same package
+    static final char [] xmlDecl = {'<','?','x','m','l'};
+
     // debugging
 
     /** Debug scanner state. */
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java	Tue Jan 22 11:54:16 2013 -0800
@@ -71,7 +71,7 @@
     /** Listeners which should know when load is being called */
     private Vector listeners = new Vector();
 
-    public static final boolean [] VALID_NAMES = new boolean[127];
+    private static final boolean [] VALID_NAMES = new boolean[127];
 
     /**
      * Debug printing of buffer. This debugging flag works best when you
--- a/jaxp/src/javax/xml/transform/FactoryFinder.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jaxp/src/javax/xml/transform/FactoryFinder.java	Tue Jan 22 11:54:16 2013 -0800
@@ -210,7 +210,7 @@
                 providerClass.getDeclaredMethod(
                     "newTransformerFactoryNoServiceLoader"
                 );
-                return creationMethod.invoke(null, null);
+                return creationMethod.invoke(null, (Object[])null);
             } catch (NoSuchMethodException exc) {
                 return null;
             } catch (Exception exc) {
--- a/jaxp/src/javax/xml/validation/SchemaFactoryFinder.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jaxp/src/javax/xml/validation/SchemaFactoryFinder.java	Tue Jan 22 11:54:16 2013 -0800
@@ -357,7 +357,7 @@
                 providerClass.getDeclaredMethod(
                     "newXMLSchemaFactoryNoServiceLoader"
                 );
-                return creationMethod.invoke(null, null);
+                return creationMethod.invoke(null, (Object[])null);
             } catch (NoSuchMethodException exc) {
                 return null;
             } catch (Exception exc) {
--- a/jaxp/src/javax/xml/xpath/XPathFactoryFinder.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jaxp/src/javax/xml/xpath/XPathFactoryFinder.java	Tue Jan 22 11:54:16 2013 -0800
@@ -333,7 +333,7 @@
                 providerClass.getDeclaredMethod(
                     "newXPathFactoryNoServiceLoader"
                 );
-                return creationMethod.invoke(null, null);
+                return creationMethod.invoke(null, (Object[])null);
             } catch (NoSuchMethodException exc) {
                 return null;
             } catch (Exception exc) {
--- a/jaxws/.hgtags	Tue Jan 22 14:27:41 2013 -0500
+++ b/jaxws/.hgtags	Tue Jan 22 11:54:16 2013 -0800
@@ -190,3 +190,8 @@
 3eb7f11cb4e000555c1b6f0f1a10fe2919633c8e jdk8-b66
 eb06aa51dfc225614dba2d89ae7ca6cedddff982 jdk8-b67
 d3fe408f3a9ad250bc9a4e9365bdfc3f28c1d3f4 jdk8-b68
+756323c990115a9c0341d67b10f2d52c6370e35d jdk8-b69
+3b1c2733d47ee9f8c530925df4041c59f9ee5a31 jdk8-b70
+f577a39c9fb3d5820248c13c2cc74a192a9313e0 jdk8-b71
+d9707230294d54e695e745a90de6112909100f12 jdk8-b72
+c606f644a5d9118c14b5822738bf23c300f14f24 jdk8-b73
--- a/jaxws/makefiles/BuildJaxws.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jaxws/makefiles/BuildJaxws.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -48,14 +48,12 @@
 $(eval $(call SetupJavaCompilation,BUILD_JAF,\
 		SETUP:=GENERATE_NEWBYTECODE_DEBUG,\
 		SRC:=$(JAXWS_TOPDIR)/src/share/jaf_classes,\
-		CLEAN:=.properties,\
 		COPY:="dummy",\
 		BIN:=$(JAXWS_OUTPUTDIR)/jaf_classes))
 
 $(eval $(call SetupJavaCompilation,BUILD_JAXWS,\
 		SETUP:=GENERATE_NEWBYTECODE_DEBUG,\
 		SRC:=$(JAXWS_TOPDIR)/src/share/jaxws_classes,\
-		CLEAN:=.properties,\
 		BIN:=$(JAXWS_OUTPUTDIR)/jaxws_classes,\
 		COPY:=.xsd,\
 		COPY_FILES:=$(JAXWS_TOPDIR)/src/share/jaxws_classes/com/sun/tools/internal/xjc/runtime/JAXBContextFactory.java \
@@ -76,7 +74,31 @@
 BUILD_JAXWS += $(JAXWS_OUTPUTDIR)/jaxws_classes/META-INF/services/com.sun.tools.internal.ws.wscompile.Plugin \
                $(JAXWS_OUTPUTDIR)/jaxws_classes/META-INF/services/com.sun.tools.internal.xjc.Plugin
 
-$(eval $(call SetupArchive,ARCHIVE_JAXWS,$(BUILD_JAXWS) $(BUILD_JAF),\
+# Imitate the property cleaning mechanism in the old build. This will likely be replaced 
+# by the unified functionality in JavaCompilation.gmk, but keep it the same as old build
+# for now, even though it actually breaks properties containing # in the value.
+# Using nawk to avoid solaris sed.
+$(JAXWS_OUTPUTDIR)/jaxws_classes/%.properties: $(JAXWS_TOPDIR)/src/share/jaxws_classes/%.properties
+	$(MKDIR) -p $(@D)
+	$(RM) $@ $@.tmp
+	$(CAT) $< | LANG=C $(NAWK) '{ sub(/#.*$$/,"#"); print }' > $@.tmp
+	$(MV) $@.tmp $@
+
+JAXWS_SRC_PROP_FILES := $(shell $(FIND) $(JAXWS_TOPDIR)/src/share/jaxws_classes -name "*.properties")
+TARGET_PROP_FILES := $(patsubst $(JAXWS_TOPDIR)/src/share/jaxws_classes/%,\
+                       $(JAXWS_OUTPUTDIR)/jaxws_classes/%,$(JAXWS_SRC_PROP_FILES))
+
+$(JAXWS_OUTPUTDIR)/jaf_classes/%.properties: $(JAXWS_TOPDIR)/src/share/jaf_classes/%.properties
+	$(MKDIR) -p $(@D)
+	$(RM) $@ $@.tmp
+	$(CAT) $< | LANG=C $(NAWK) '{ sub(/#.*$$/,"#"); print }' > $@.tmp
+	$(MV) $@.tmp $@
+
+JAF_SRC_PROP_FILES := $(shell $(FIND) $(JAXWS_TOPDIR)/src/share/jaf_classes -name "*.properties")
+TARGET_PROP_FILES += $(patsubst $(JAXWS_TOPDIR)/src/share/jaf_classes/%,\
+                       $(JAXWS_OUTPUTDIR)/jaf_classes/%,$(JAF_SRC_PROP_FILES))
+
+$(eval $(call SetupArchive,ARCHIVE_JAXWS,$(BUILD_JAXWS) $(BUILD_JAF) $(TARGET_PROP_FILES),\
 		SRCS:=$(JAXWS_OUTPUTDIR)/jaxws_classes $(JAXWS_OUTPUTDIR)/jaf_classes,\
 		SUFFIXES:=.class .properties .xsd .java \
 			  com.sun.mirror.apt.AnnotationProcessorFactory \
--- a/jdk/.hgtags	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/.hgtags	Tue Jan 22 11:54:16 2013 -0800
@@ -190,3 +190,8 @@
 4d337fae2250135729ee9ed2bf8baf3c60da5d6d jdk8-b66
 ce9b02a3a17edd1983201002cfa0f364e4ab7524 jdk8-b67
 53fb43e4d614c92310e1fb00ec41d1960fd9facf jdk8-b68
+a8012d8d7e9c5035de0bdd4887dc9f7c54008f21 jdk8-b69
+a996b57e554198f4592a5f3c30f2f9f4075e545d jdk8-b70
+2a5af0f766d0acd68a81fb08fe11fd66795f86af jdk8-b71
+32a57e645e012a1f0665c075969ca598e0dbb948 jdk8-b72
+733885f57e14cc27f5a5ff0dffe641d2fa3c704a jdk8-b73
--- a/jdk/make/common/Release.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/make/common/Release.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -366,6 +366,7 @@
 	com/sun/source          \
 	com/sun/tools/classfile \
 	com/sun/tools/doclets   \
+	com/sun/tools/doclint   \
 	com/sun/tools/example/debug/expr \
 	com/sun/tools/example/debug/tty  \
 	com/sun/tools/extcheck  \
@@ -374,6 +375,7 @@
 	com/sun/tools/javadoc   \
 	com/sun/tools/javah     \
 	com/sun/tools/javap     \
+	com/sun/tools/jdeps     \
 	com/sun/tools/corba     \
 	com/sun/tools/internal/xjc       \
 	com/sun/tools/internal/ws       \
@@ -456,6 +458,7 @@
 	javadoc$(EXE_SUFFIX) \
 	javah$(EXE_SUFFIX) \
 	javap$(EXE_SUFFIX) \
+	jdeps$(EXE_SUFFIX) \
 	jcmd$(EXE_SUFFIX) \
 	jdb$(EXE_SUFFIX) \
 	jps$(EXE_SUFFIX) \
@@ -563,6 +566,7 @@
 	$(ECHO) "sun/tools/javac/" >> $@
 	$(ECHO) "com/sun/tools/classfile/" >> $@
 	$(ECHO) "com/sun/tools/javap/" >> $@
+	$(ECHO) "com/sun/tools/jdeps/" >> $@
 	$(ECHO) "sun/tools/jcmd/" >> $@
 	$(ECHO) "sun/tools/jconsole/" >> $@
 	$(ECHO) "sun/tools/jps/" >> $@
--- a/jdk/make/common/internal/Defs-langtools.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/make/common/internal/Defs-langtools.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -35,6 +35,7 @@
       com/sun/source                \
       com/sun/tools/classfile       \
       com/sun/tools/doclets         \
+      com/sun/tools/doclint         \
       com/sun/tools/javac           \
       com/sun/tools/javadoc         \
       com/sun/tools/javah           \
--- a/jdk/make/common/shared/Defs-windows.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/make/common/shared/Defs-windows.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -549,7 +549,10 @@
   _WSCRIPT2 :=$(DEVTOOLS_PATH)wscript.exe
   WSCRIPT  :=$(call FileExists,$(_WSCRIPT1),$(_WSCRIPT2))
 endif
+# If CONFIGURE_BUILD is defined, checks were already done by configure.
+ifndef CONFIGURE_BUILD
 WSCRIPT:=$(call AltCheckSpaces,WSCRIPT)
+endif #! CONFIGURE_BUILD
 # batch mode no modal dialogs on errors, please.
 WSCRIPT += -B
 
@@ -562,7 +565,10 @@
   _CSCRIPT2 :=$(DEVTOOLS_PATH)cscript.exe
   CSCRIPT  :=$(call FileExists,$(_CSCRIPT1),$(_CSCRIPT2))
 endif
+# If CONFIGURE_BUILD is defined, checks were already done by configure.
+ifndef CONFIGURE_BUILD
 CSCRIPT:=$(call AltCheckSpaces,CSCRIPT)
+endif #! CONFIGURE_BUILD
 
 # CABARC: path to cabarc.exe (used in creating install bundles)
 ifdef ALT_CABARC
@@ -584,7 +590,10 @@
   _MSICERT2 :=$(DEVTOOLS_PATH)msicert.exe
   MSICERT   :=$(call FileExists,$(_MSICERT1),$(_MSICERT2))
 endif
+# If CONFIGURE_BUILD is defined, checks were already done by configure.
+ifndef CONFIGURE_BUILD
 MSICERT:=$(call AltCheckSpaces,MSICERT)
+endif #! CONFIGURE_BUILD
 
 # Import JDK images allow for partial builds, components not built are
 #    imported (or copied from) these import areas when needed.
--- a/jdk/make/docs/NON_CORE_PKGS.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/make/docs/NON_CORE_PKGS.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -76,7 +76,8 @@
 
 JCONSOLE_PKGS    = com.sun.tools.jconsole
 
-TREEAPI_PKGS 	 = com.sun.source.tree \
+TREEAPI_PKGS 	 = com.sun.source.doctree \
+		   com.sun.source.tree \
 		   com.sun.source.util
 
 SMARTCARDIO_PKGS = javax.smartcardio
--- a/jdk/make/java/java/FILES_java.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/make/java/java/FILES_java.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -294,6 +294,7 @@
 	java/util/IdentityHashMap.java \
 	java/util/EnumMap.java \
     java/util/Arrays.java \
+    java/util/ArraysParallelSortHelpers.java \
     java/util/DualPivotQuicksort.java \
     java/util/TimSort.java \
     java/util/ComparableTimSort.java \
@@ -322,6 +323,7 @@
     java/util/concurrent/CopyOnWriteArrayList.java \
     java/util/concurrent/CopyOnWriteArraySet.java \
     java/util/concurrent/CountDownLatch.java \
+    java/util/concurrent/CountedCompleter.java \
     java/util/concurrent/CyclicBarrier.java \
     java/util/concurrent/DelayQueue.java \
     java/util/concurrent/Delayed.java \
--- a/jdk/make/javax/swing/beaninfo/SwingBeans.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/make/javax/swing/beaninfo/SwingBeans.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -124,10 +124,10 @@
 $(BEANSRCDIR)/%BeanInfo.java: $(FAKESRC)/$(SWINGPKG)/%.java
 	@$(ECHO) $< >> $(TEMPDIR)/.beans.list
 
-$(BEANSRCDIR)/SwingBeanInfoBase.java: $(DOCLETSRC)/beaninfo/SwingBeanInfoBase.java
+$(BEANSRCDIR)/SwingBeanInfoBase.java: $(DOCLETSRC)/javax/swing/SwingBeanInfoBase.java
 	$(CP) $< $@
 
-$(BEANSRCDIR)/BeanInfoUtils.java: $(DOCLETSRC)/beaninfo/BeanInfoUtils.java
+$(BEANSRCDIR)/BeanInfoUtils.java: $(DOCLETSRC)/sun/swing/BeanInfoUtils.java
 	$(CP) $< $@
 
 #
--- a/jdk/make/jdk/Makefile	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/make/jdk/Makefile	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -23,16 +23,18 @@
 # questions.
 #
 
-#
-# Makefile for building all of java
-#
-
 BUILDDIR = ..
+PACKAGE = jdk
 PRODUCT = jdk
+JAVAC_LINT_OPTIONS=-Xlint:all
 include $(BUILDDIR)/common/Defs.gmk
 
-SUBDIRS = asm
-include $(BUILDDIR)/common/Subdirs.gmk
+#
+# Files to compile
+#
+AUTO_FILES_JAVA_DIRS = jdk
 
-all build clean clobber::
-	$(SUBDIRS-loop)
+#
+# Rules
+#
+include $(BUILDDIR)/common/Classes.gmk
--- a/jdk/make/jdk/asm/Makefile	Tue Jan 22 14:27:41 2013 -0500
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,40 +0,0 @@
-#
-# Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.  Oracle designates this
-# particular file as subject to the "Classpath" exception as provided
-# by Oracle in the LICENSE file that accompanied this code.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-BUILDDIR = ../..
-PACKAGE = jdk.internal.org.objectweb.asm
-PRODUCT = jdk
-JAVAC_LINT_OPTIONS=-Xlint:all
-include $(BUILDDIR)/common/Defs.gmk
-
-#
-# Files to compile
-#
-AUTO_FILES_JAVA_DIRS = jdk/internal/org/objectweb/asm
-
-#
-# Rules
-#
-include $(BUILDDIR)/common/Classes.gmk
--- a/jdk/make/launchers/Makefile	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/make/launchers/Makefile	Tue Jan 22 11:54:16 2013 -0800
@@ -63,6 +63,7 @@
 $(call make-launcher, javadoc, com.sun.tools.javadoc.Main, , )
 $(call make-launcher, javah, com.sun.tools.javah.Main, , )
 $(call make-launcher, javap, com.sun.tools.javap.Main, , )
+$(call make-launcher, jdeps, com.sun.tools.jdeps.Main, , )
 $(call make-launcher, jcmd, sun.tools.jcmd.JCmd, , )
 $(call make-launcher, jconsole, sun.tools.jconsole.JConsole, \
   -J-Djconsole.showOutputViewer, )
--- a/jdk/make/launchers/Makefile.launcher	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/make/launchers/Makefile.launcher	Tue Jan 22 11:54:16 2013 -0800
@@ -62,6 +62,10 @@
   WILDCARDS=true
   NEVER_ACT_AS_SERVER_CLASS_MACHINE=true
 endif
+ifeq ($(PROGRAM),jdeps)
+  WILDCARDS=true
+  NEVER_ACT_AS_SERVER_CLASS_MACHINE=true
+endif
 ifeq ($(PROGRAM),javah)
   WILDCARDS=true
   NEVER_ACT_AS_SERVER_CLASS_MACHINE=true
--- a/jdk/make/netbeans/jmx/build.properties	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/make/netbeans/jmx/build.properties	Tue Jan 22 11:54:16 2013 -0800
@@ -38,6 +38,7 @@
     com/sun/jmx/snmp/
 
 jtreg.tests=\
+    com/sun/jmx/ \
     com/sun/management/ \
     java/lang/management/ \
     javax/management/
--- a/jdk/make/tools/swing-beans/beaninfo/BeanInfoUtils.java	Tue Jan 22 14:27:41 2013 -0500
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,293 +0,0 @@
-/*
- * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.swing;
-
-import java.beans.*;
-import java.lang.reflect.Method;
-
-public class BeanInfoUtils
-{
-    /* The values of these createPropertyDescriptor() and
-     * createBeanDescriptor() keywords are the names of the
-     * properties they're used to set.
-     */
-    public static final String BOUND = "bound";
-    public static final String CONSTRAINED = "constrained";
-    public static final String PROPERTYEDITORCLASS = "propertyEditorClass";
-    public static final String READMETHOD = "readMethod";
-    public static final String WRITEMETHOD = "writeMethod";
-    public static final String DISPLAYNAME = "displayName";
-    public static final String EXPERT = "expert";
-    public static final String HIDDEN = "hidden";
-    public static final String PREFERRED = "preferred";
-    public static final String SHORTDESCRIPTION = "shortDescription";
-    public static final String CUSTOMIZERCLASS = "customizerClass";
-
-    static private void initFeatureDescriptor(FeatureDescriptor fd, String key, Object value)
-    {
-        if (DISPLAYNAME.equals(key)) {
-            fd.setDisplayName((String)value);
-        }
-
-        if (EXPERT.equals(key)) {
-            fd.setExpert(((Boolean)value).booleanValue());
-        }
-
-        if (HIDDEN.equals(key)) {
-            fd.setHidden(((Boolean)value).booleanValue());
-        }
-
-        if (PREFERRED.equals(key)) {
-            fd.setPreferred(((Boolean)value).booleanValue());
-        }
-
-        else if (SHORTDESCRIPTION.equals(key)) {
-            fd.setShortDescription((String)value);
-        }
-
-        /* Otherwise assume that we have an arbitrary FeatureDescriptor
-         * "attribute".
-         */
-        else {
-            fd.setValue(key, value);
-        }
-    }
-
-    /**
-     * Create a beans PropertyDescriptor given an of keyword/value
-     * arguments.  The following sample call shows all of the supported
-     * keywords:
-     *<pre>
-     *      createPropertyDescriptor("contentPane", new Object[] {
-     *                     BOUND, Boolean.TRUE,
-     *               CONSTRAINED, Boolean.TRUE,
-     *       PROPERTYEDITORCLASS, package.MyEditor.class,
-     *                READMETHOD, "getContentPane",
-     *               WRITEMETHOD, "setContentPane",
-     *               DISPLAYNAME, "contentPane",
-     *                    EXPERT, Boolean.FALSE,
-     *                    HIDDEN, Boolean.FALSE,
-     *                 PREFERRED, Boolean.TRUE,
-     *          SHORTDESCRIPTION, "A top level window with a window manager border",
-     *         "random attribute","random object value"
-     *        }
-     *     );
-     * </pre>
-     * The keywords correspond to <code>java.beans.PropertyDescriptor</code> and
-     * <code>java.beans.FeatureDescriptor</code> properties, e.g. providing a value
-     * for displayName is comparable to <code>FeatureDescriptor.setDisplayName()</code>.
-     * Using createPropertyDescriptor instead of the PropertyDescriptor
-     * constructor and set methods is preferrable in that it regularizes
-     * the code in a <code>java.beans.BeanInfo.getPropertyDescriptors()</code>
-     * method implementation.  One can use <code>createPropertyDescriptor</code>
-     * to set <code>FeatureDescriptor</code> attributes, as in "random attribute"
-     * "random object value".
-     * <p>
-     * All properties should provide a reasonable value for the
-     * <code>SHORTDESCRIPTION</code> keyword and should set <code>BOUND</code>
-     * to <code>Boolean.TRUE</code> if neccessary.  The remaining keywords
-     * are optional.  There's no need to provide values for keywords like
-     * READMETHOD if the correct value can be computed, i.e. if the properties
-     * get/is method follows the standard beans pattern.
-     * <p>
-     * The PREFERRED keyword is not supported by the JDK1.1 java.beans package.
-     * It's still worth setting it to true for properties that are most
-     * likely to be interested to the average developer, e.g. AbstractButton.title
-     * is a preferred property, AbstractButton.focusPainted is not.
-     *
-     * @see java.beans#BeanInfo
-     * @see java.beans#PropertyDescriptor
-     * @see java.beans#FeatureDescriptor
-     */
-    public static PropertyDescriptor createPropertyDescriptor(Class cls, String name, Object[] args)
-    {
-        PropertyDescriptor pd = null;
-        try {
-            pd = new PropertyDescriptor(name, cls);
-        } catch (IntrospectionException e) {
-            // Try creating a read-only property, in case setter isn't defined.
-            try {
-                pd = createReadOnlyPropertyDescriptor(name, cls);
-            } catch (IntrospectionException ie) {
-                throwError(ie, "Can't create PropertyDescriptor for " + name + " ");
-            }
-        }
-
-        for(int i = 0; i < args.length; i += 2) {
-            String key = (String)args[i];
-            Object value = args[i + 1];
-
-            if (BOUND.equals(key)) {
-                pd.setBound(((Boolean)value).booleanValue());
-            }
-
-            else if (CONSTRAINED.equals(key)) {
-                pd.setConstrained(((Boolean)value).booleanValue());
-            }
-
-            else if (PROPERTYEDITORCLASS.equals(key)) {
-                pd.setPropertyEditorClass((Class)value);
-            }
-
-            else if (READMETHOD.equals(key)) {
-                String methodName = (String)value;
-                Method method;
-                try {
-                    method = cls.getMethod(methodName, new Class[0]);
-                    pd.setReadMethod(method);
-                }
-                catch(Exception e) {
-                    throwError(e, cls + " no such method as \"" + methodName + "\"");
-                }
-            }
-
-            else if (WRITEMETHOD.equals(key)) {
-                String methodName = (String)value;
-                Method method;
-                try {
-                    Class type = pd.getPropertyType();
-                    method = cls.getMethod(methodName, new Class[]{type});
-                    pd.setWriteMethod(method);
-                }
-                catch(Exception e) {
-                    throwError(e, cls + " no such method as \"" + methodName + "\"");
-                }
-            }
-
-            else {
-                initFeatureDescriptor(pd, key, value);
-            }
-        }
-
-        return pd;
-    }
-
-
-    /**
-     * Create a BeanDescriptor object given an of keyword/value
-     * arguments.  The following sample call shows all of the supported
-     * keywords:
-     *<pre>
-     *      createBeanDescriptor(JWindow..class, new Object[] {
-     *           CUSTOMIZERCLASS, package.MyCustomizer.class,
-     *               DISPLAYNAME, "JFrame",
-     *                    EXPERT, Boolean.FALSE,
-     *                    HIDDEN, Boolean.FALSE,
-     *                 PREFERRED, Boolean.TRUE,
-     *          SHORTDESCRIPTION, "A top level window with a window manager border",
-     *         "random attribute","random object value"
-     *        }
-     *     );
-     * </pre>
-     * The keywords correspond to <code>java.beans.BeanDescriptor</code> and
-     * <code>java.beans.FeatureDescriptor</code> properties, e.g. providing a value
-     * for displayName is comparable to <code>FeatureDescriptor.setDisplayName()</code>.
-     * Using createBeanDescriptor instead of the BeanDescriptor
-     * constructor and set methods is preferrable in that it regularizes
-     * the code in a <code>java.beans.BeanInfo.getBeanDescriptor()</code>
-     * method implementation.  One can use <code>createBeanDescriptor</code>
-     * to set <code>FeatureDescriptor</code> attributes, as in "random attribute"
-     * "random object value".
-     *
-     * @see java.beans#BeanInfo
-     * @see java.beans#PropertyDescriptor
-     */
-    public static BeanDescriptor createBeanDescriptor(Class cls, Object[] args)
-    {
-        Class customizerClass = null;
-
-        /* For reasons I don't understand, customizerClass is a
-         * readOnly property.  So we have to find it and pass it
-         * to the constructor here.
-         */
-        for(int i = 0; i < args.length; i += 2) {
-            if (CUSTOMIZERCLASS.equals((String)args[i])) {
-                customizerClass = (Class)args[i + 1];
-                break;
-            }
-        }
-
-        BeanDescriptor bd = new BeanDescriptor(cls, customizerClass);
-
-        for(int i = 0; i < args.length; i += 2) {
-            String key = (String)args[i];
-            Object value = args[i + 1];
-            initFeatureDescriptor(bd, key, value);
-        }
-
-        return bd;
-    }
-
-    static private PropertyDescriptor createReadOnlyPropertyDescriptor(
-        String name, Class cls) throws IntrospectionException {
-
-        Method readMethod = null;
-        String base = capitalize(name);
-        Class[] parameters = new Class[0];
-
-        // Is it a boolean?
-        try {
-            readMethod = cls.getMethod("is" + base, parameters);
-        } catch (Exception ex) {}
-        if (readMethod == null) {
-            try {
-                // Try normal accessor pattern.
-                readMethod = cls.getMethod("get" + base, parameters);
-            } catch (Exception ex2) {}
-        }
-        if (readMethod != null) {
-            return new PropertyDescriptor(name, readMethod, null);
-        }
-
-        try {
-            // Try indexed accessor pattern.
-            parameters = new Class[1];
-            parameters[0] = int.class;
-            readMethod = cls.getMethod("get" + base, parameters);
-        } catch (NoSuchMethodException nsme) {
-            throw new IntrospectionException(
-                "cannot find accessor method for " + name + " property.");
-        }
-        return new IndexedPropertyDescriptor(name, null, null, readMethod, null);
-    }
-
-    // Modified methods from java.beans.Introspector
-    private static String capitalize(String s) {
-        if (s.length() == 0) {
-            return s;
-        }
-        char chars[] = s.toCharArray();
-        chars[0] = Character.toUpperCase(chars[0]);
-        return new String(chars);
-    }
-
-    /**
-     * Fatal errors are handled by calling this method.
-     */
-    public static void throwError(Exception e, String s) {
-        throw new Error(e.toString() + " " + s);
-    }
-}
--- a/jdk/make/tools/swing-beans/beaninfo/SwingBeanInfoBase.java	Tue Jan 22 14:27:41 2013 -0500
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,82 +0,0 @@
-/*
- * Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package javax.swing;
-
-import java.beans.*;
-import java.lang.reflect.*;
-import java.awt.Image;
-
-/**
- * The superclass for all Swing BeanInfo classes.  It provides
- * default implementations of <code>getIcon</code> and
- * <code>getDefaultPropertyIndex</code> as well as utility
- * methods, like createPropertyDescriptor, for writing BeanInfo
- * implementations.  This classes is intended to be used along
- * with <code>GenSwingBeanInfo</code> a BeanInfo class code generator.
- *
- * @see GenSwingBeanInfo
- * @author Hans Muller
- */
-public class SwingBeanInfoBase extends SimpleBeanInfo
-{
-    /**
-     * The default index is always 0.  In other words the first property
-     * listed in the getPropertyDescriptors() method is the one
-     * to show a (JFC builder) user in a situation where just a single
-     * property will be shown.
-     */
-    public int getDefaultPropertyIndex() {
-        return 0;
-    }
-
-    /**
-     * Returns a generic Swing icon, all icon "kinds" are supported.
-     * Subclasses should defer to this method when they don't have
-     * a particular beans icon kind.
-     */
-    public Image getIcon(int kind) {
-        // PENDING(hmuller) need generic swing icon images.
-        return null;
-    }
-
-    /**
-     * Returns the BeanInfo for the superclass of our bean, so that
-     * its PropertyDescriptors will be included.
-     */
-    public BeanInfo[] getAdditionalBeanInfo() {
-        Class superClass = getBeanDescriptor().getBeanClass().getSuperclass();
-        BeanInfo superBeanInfo = null;
-        try {
-            superBeanInfo = Introspector.getBeanInfo(superClass);
-        } catch (IntrospectionException ie) {}
-        if (superBeanInfo != null) {
-            BeanInfo[] ret = new BeanInfo[1];
-            ret[0] = superBeanInfo;
-            return ret;
-        }
-        return null;
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/tools/swing-beans/javax/swing/SwingBeanInfoBase.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package javax.swing;
+
+import java.beans.*;
+import java.lang.reflect.*;
+import java.awt.Image;
+
+/**
+ * The superclass for all Swing BeanInfo classes.  It provides
+ * default implementations of <code>getIcon</code> and
+ * <code>getDefaultPropertyIndex</code> as well as utility
+ * methods, like createPropertyDescriptor, for writing BeanInfo
+ * implementations.  This classes is intended to be used along
+ * with <code>GenSwingBeanInfo</code> a BeanInfo class code generator.
+ *
+ * @see GenSwingBeanInfo
+ * @author Hans Muller
+ */
+public class SwingBeanInfoBase extends SimpleBeanInfo
+{
+    /**
+     * The default index is always 0.  In other words the first property
+     * listed in the getPropertyDescriptors() method is the one
+     * to show a (JFC builder) user in a situation where just a single
+     * property will be shown.
+     */
+    public int getDefaultPropertyIndex() {
+        return 0;
+    }
+
+    /**
+     * Returns a generic Swing icon, all icon "kinds" are supported.
+     * Subclasses should defer to this method when they don't have
+     * a particular beans icon kind.
+     */
+    public Image getIcon(int kind) {
+        // PENDING(hmuller) need generic swing icon images.
+        return null;
+    }
+
+    /**
+     * Returns the BeanInfo for the superclass of our bean, so that
+     * its PropertyDescriptors will be included.
+     */
+    public BeanInfo[] getAdditionalBeanInfo() {
+        Class superClass = getBeanDescriptor().getBeanClass().getSuperclass();
+        BeanInfo superBeanInfo = null;
+        try {
+            superBeanInfo = Introspector.getBeanInfo(superClass);
+        } catch (IntrospectionException ie) {}
+        if (superBeanInfo != null) {
+            BeanInfo[] ret = new BeanInfo[1];
+            ret[0] = superBeanInfo;
+            return ret;
+        }
+        return null;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/make/tools/swing-beans/sun/swing/BeanInfoUtils.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,293 @@
+/*
+ * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.swing;
+
+import java.beans.*;
+import java.lang.reflect.Method;
+
+public class BeanInfoUtils
+{
+    /* The values of these createPropertyDescriptor() and
+     * createBeanDescriptor() keywords are the names of the
+     * properties they're used to set.
+     */
+    public static final String BOUND = "bound";
+    public static final String CONSTRAINED = "constrained";
+    public static final String PROPERTYEDITORCLASS = "propertyEditorClass";
+    public static final String READMETHOD = "readMethod";
+    public static final String WRITEMETHOD = "writeMethod";
+    public static final String DISPLAYNAME = "displayName";
+    public static final String EXPERT = "expert";
+    public static final String HIDDEN = "hidden";
+    public static final String PREFERRED = "preferred";
+    public static final String SHORTDESCRIPTION = "shortDescription";
+    public static final String CUSTOMIZERCLASS = "customizerClass";
+
+    static private void initFeatureDescriptor(FeatureDescriptor fd, String key, Object value)
+    {
+        if (DISPLAYNAME.equals(key)) {
+            fd.setDisplayName((String)value);
+        }
+
+        if (EXPERT.equals(key)) {
+            fd.setExpert(((Boolean)value).booleanValue());
+        }
+
+        if (HIDDEN.equals(key)) {
+            fd.setHidden(((Boolean)value).booleanValue());
+        }
+
+        if (PREFERRED.equals(key)) {
+            fd.setPreferred(((Boolean)value).booleanValue());
+        }
+
+        else if (SHORTDESCRIPTION.equals(key)) {
+            fd.setShortDescription((String)value);
+        }
+
+        /* Otherwise assume that we have an arbitrary FeatureDescriptor
+         * "attribute".
+         */
+        else {
+            fd.setValue(key, value);
+        }
+    }
+
+    /**
+     * Create a beans PropertyDescriptor given an of keyword/value
+     * arguments.  The following sample call shows all of the supported
+     * keywords:
+     *<pre>
+     *      createPropertyDescriptor("contentPane", new Object[] {
+     *                     BOUND, Boolean.TRUE,
+     *               CONSTRAINED, Boolean.TRUE,
+     *       PROPERTYEDITORCLASS, package.MyEditor.class,
+     *                READMETHOD, "getContentPane",
+     *               WRITEMETHOD, "setContentPane",
+     *               DISPLAYNAME, "contentPane",
+     *                    EXPERT, Boolean.FALSE,
+     *                    HIDDEN, Boolean.FALSE,
+     *                 PREFERRED, Boolean.TRUE,
+     *          SHORTDESCRIPTION, "A top level window with a window manager border",
+     *         "random attribute","random object value"
+     *        }
+     *     );
+     * </pre>
+     * The keywords correspond to <code>java.beans.PropertyDescriptor</code> and
+     * <code>java.beans.FeatureDescriptor</code> properties, e.g. providing a value
+     * for displayName is comparable to <code>FeatureDescriptor.setDisplayName()</code>.
+     * Using createPropertyDescriptor instead of the PropertyDescriptor
+     * constructor and set methods is preferrable in that it regularizes
+     * the code in a <code>java.beans.BeanInfo.getPropertyDescriptors()</code>
+     * method implementation.  One can use <code>createPropertyDescriptor</code>
+     * to set <code>FeatureDescriptor</code> attributes, as in "random attribute"
+     * "random object value".
+     * <p>
+     * All properties should provide a reasonable value for the
+     * <code>SHORTDESCRIPTION</code> keyword and should set <code>BOUND</code>
+     * to <code>Boolean.TRUE</code> if neccessary.  The remaining keywords
+     * are optional.  There's no need to provide values for keywords like
+     * READMETHOD if the correct value can be computed, i.e. if the properties
+     * get/is method follows the standard beans pattern.
+     * <p>
+     * The PREFERRED keyword is not supported by the JDK1.1 java.beans package.
+     * It's still worth setting it to true for properties that are most
+     * likely to be interested to the average developer, e.g. AbstractButton.title
+     * is a preferred property, AbstractButton.focusPainted is not.
+     *
+     * @see java.beans#BeanInfo
+     * @see java.beans#PropertyDescriptor
+     * @see java.beans#FeatureDescriptor
+     */
+    public static PropertyDescriptor createPropertyDescriptor(Class cls, String name, Object[] args)
+    {
+        PropertyDescriptor pd = null;
+        try {
+            pd = new PropertyDescriptor(name, cls);
+        } catch (IntrospectionException e) {
+            // Try creating a read-only property, in case setter isn't defined.
+            try {
+                pd = createReadOnlyPropertyDescriptor(name, cls);
+            } catch (IntrospectionException ie) {
+                throwError(ie, "Can't create PropertyDescriptor for " + name + " ");
+            }
+        }
+
+        for(int i = 0; i < args.length; i += 2) {
+            String key = (String)args[i];
+            Object value = args[i + 1];
+
+            if (BOUND.equals(key)) {
+                pd.setBound(((Boolean)value).booleanValue());
+            }
+
+            else if (CONSTRAINED.equals(key)) {
+                pd.setConstrained(((Boolean)value).booleanValue());
+            }
+
+            else if (PROPERTYEDITORCLASS.equals(key)) {
+                pd.setPropertyEditorClass((Class)value);
+            }
+
+            else if (READMETHOD.equals(key)) {
+                String methodName = (String)value;
+                Method method;
+                try {
+                    method = cls.getMethod(methodName, new Class[0]);
+                    pd.setReadMethod(method);
+                }
+                catch(Exception e) {
+                    throwError(e, cls + " no such method as \"" + methodName + "\"");
+                }
+            }
+
+            else if (WRITEMETHOD.equals(key)) {
+                String methodName = (String)value;
+                Method method;
+                try {
+                    Class type = pd.getPropertyType();
+                    method = cls.getMethod(methodName, new Class[]{type});
+                    pd.setWriteMethod(method);
+                }
+                catch(Exception e) {
+                    throwError(e, cls + " no such method as \"" + methodName + "\"");
+                }
+            }
+
+            else {
+                initFeatureDescriptor(pd, key, value);
+            }
+        }
+
+        return pd;
+    }
+
+
+    /**
+     * Create a BeanDescriptor object given an of keyword/value
+     * arguments.  The following sample call shows all of the supported
+     * keywords:
+     *<pre>
+     *      createBeanDescriptor(JWindow..class, new Object[] {
+     *           CUSTOMIZERCLASS, package.MyCustomizer.class,
+     *               DISPLAYNAME, "JFrame",
+     *                    EXPERT, Boolean.FALSE,
+     *                    HIDDEN, Boolean.FALSE,
+     *                 PREFERRED, Boolean.TRUE,
+     *          SHORTDESCRIPTION, "A top level window with a window manager border",
+     *         "random attribute","random object value"
+     *        }
+     *     );
+     * </pre>
+     * The keywords correspond to <code>java.beans.BeanDescriptor</code> and
+     * <code>java.beans.FeatureDescriptor</code> properties, e.g. providing a value
+     * for displayName is comparable to <code>FeatureDescriptor.setDisplayName()</code>.
+     * Using createBeanDescriptor instead of the BeanDescriptor
+     * constructor and set methods is preferrable in that it regularizes
+     * the code in a <code>java.beans.BeanInfo.getBeanDescriptor()</code>
+     * method implementation.  One can use <code>createBeanDescriptor</code>
+     * to set <code>FeatureDescriptor</code> attributes, as in "random attribute"
+     * "random object value".
+     *
+     * @see java.beans#BeanInfo
+     * @see java.beans#PropertyDescriptor
+     */
+    public static BeanDescriptor createBeanDescriptor(Class cls, Object[] args)
+    {
+        Class customizerClass = null;
+
+        /* For reasons I don't understand, customizerClass is a
+         * readOnly property.  So we have to find it and pass it
+         * to the constructor here.
+         */
+        for(int i = 0; i < args.length; i += 2) {
+            if (CUSTOMIZERCLASS.equals((String)args[i])) {
+                customizerClass = (Class)args[i + 1];
+                break;
+            }
+        }
+
+        BeanDescriptor bd = new BeanDescriptor(cls, customizerClass);
+
+        for(int i = 0; i < args.length; i += 2) {
+            String key = (String)args[i];
+            Object value = args[i + 1];
+            initFeatureDescriptor(bd, key, value);
+        }
+
+        return bd;
+    }
+
+    static private PropertyDescriptor createReadOnlyPropertyDescriptor(
+        String name, Class cls) throws IntrospectionException {
+
+        Method readMethod = null;
+        String base = capitalize(name);
+        Class[] parameters = new Class[0];
+
+        // Is it a boolean?
+        try {
+            readMethod = cls.getMethod("is" + base, parameters);
+        } catch (Exception ex) {}
+        if (readMethod == null) {
+            try {
+                // Try normal accessor pattern.
+                readMethod = cls.getMethod("get" + base, parameters);
+            } catch (Exception ex2) {}
+        }
+        if (readMethod != null) {
+            return new PropertyDescriptor(name, readMethod, null);
+        }
+
+        try {
+            // Try indexed accessor pattern.
+            parameters = new Class[1];
+            parameters[0] = int.class;
+            readMethod = cls.getMethod("get" + base, parameters);
+        } catch (NoSuchMethodException nsme) {
+            throw new IntrospectionException(
+                "cannot find accessor method for " + name + " property.");
+        }
+        return new IndexedPropertyDescriptor(name, null, null, readMethod, null);
+    }
+
+    // Modified methods from java.beans.Introspector
+    private static String capitalize(String s) {
+        if (s.length() == 0) {
+            return s;
+        }
+        char chars[] = s.toCharArray();
+        chars[0] = Character.toUpperCase(chars[0]);
+        return new String(chars);
+    }
+
+    /**
+     * Fatal errors are handled by calling this method.
+     */
+    public static void throwError(Exception e, String s) {
+        throw new Error(e.toString() + " " + s);
+    }
+}
--- a/jdk/makefiles/BuildJdk.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/BuildJdk.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -39,10 +39,7 @@
 # Setup the java compilers for the JDK build.
 include Setup.gmk
 
-# Setup the build tools.
-include Tools.gmk
-
-import: $(BUILD_TOOLS) import-only
+import: import-only
 import-only:
 #       Import (corba jaxp jaxws langtools hotspot)
 	+$(MAKE) -f Import.gmk
@@ -91,17 +88,19 @@
 # into packages, or installed.
 images:
 	+$(MAKE) -f CreateJars.gmk
-	+$(MAKE) -f Images.gmk 
+	+$(MAKE) -f Images.gmk
+ifeq ($(OPENJDK_TARGET_OS), macosx)
+	+$(MAKE) -f Bundles.gmk
+endif
 
 overlay-images:
 	+$(MAKE) -f CompileLaunchers.gmk OVERLAY_IMAGES=true
 	+$(MAKE) -f Images.gmk overlay-images
 
-# Create platform specific image layouts
-bundles:
-	+$(MAKE) -f Bundles.gmk
+sign-jars:
+	+$(MAKE) -f SignJars.gmk
 
-BINARIES:=$(notdir $(wildcard $(IMAGES_OUTPUTDIR)/j2sdk-image/bin/*))
+BINARIES:=$(notdir $(wildcard $(JDK_IMAGE_DIR)/bin/*))
 INSTALLDIR:=openjdk-$(RELEASE)
 
 # Install the jdk image, in a very crude way. Not taking into
@@ -111,7 +110,7 @@
 	echo and creating $(words $(BINARIES)) links from $(INSTALL_PREFIX)/bin into the jdk.
 	$(MKDIR) -p $(INSTALL_PREFIX)/jvm/$(INSTALLDIR)
 	$(RM) -r $(INSTALL_PREFIX)/jvm/$(INSTALLDIR)/*
-	$(CP) -rp $(IMAGES_OUTPUTDIR)/j2sdk-image/* $(INSTALL_PREFIX)/jvm/$(INSTALLDIR)
+	$(CP) -rp $(JDK_IMAGE_DIR)/* $(INSTALL_PREFIX)/jvm/$(INSTALLDIR)
 	$(MKDIR) -p $(INSTALL_PREFIX)/bin
 	$(RM) $(addprefix $(INSTALL_PREFIX)/bin/,$(BINARIES))
 	$(foreach b,$(BINARIES),$(LN) -s $(INSTALL_PREFIX)/jvm/$(INSTALLDIR)/bin/$b $(INSTALL_PREFIX)/bin/$b &&) true
--- a/jdk/makefiles/Bundles.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/Bundles.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -33,9 +33,7 @@
 
 bundles: jre-bundle jdk-bundle
 
-
-JDK_BUNDLE_DIR := $(IMAGES_OUTPUTDIR)/j2sdk-bundle/jdk$(JDK_VERSION).jdk/Contents
-JRE_BUNDLE_DIR := $(IMAGES_OUTPUTDIR)/j2re-bundle/jre$(JDK_VERSION).jre/Contents
+# JDK_BUNDLE_DIR and JRE_BUNDLE_DIR are defined in SPEC.
 
 MACOSX_SRC := $(JDK_TOPDIR)/src/macosx
 
@@ -70,30 +68,31 @@
 endif
 
 
-JDK_FILE_LIST := $(shell $(FIND) $(IMAGES_OUTPUTDIR)/j2sdk-image ! -type d)
-JRE_FILE_LIST := $(shell $(FIND) $(IMAGES_OUTPUTDIR)/j2re-image ! -type d)
+JDK_FILE_LIST := $(shell $(FIND) $(JDK_IMAGE_DIR))
+JRE_FILE_LIST := $(shell $(FIND) $(JRE_IMAGE_DIR))
 
-JDK_TARGET_LIST := $(subst $(IMAGES_OUTPUTDIR)/j2sdk-image,$(JDK_BUNDLE_DIR)/Home,$(JDK_FILE_LIST))
-JRE_TARGET_LIST := $(subst $(IMAGES_OUTPUTDIR)/j2re-image,$(JRE_BUNDLE_DIR)/Home,$(JRE_FILE_LIST))
+JDK_TARGET_LIST := $(subst $(JDK_IMAGE_DIR)/,$(JDK_BUNDLE_DIR)/Home/,$(JDK_FILE_LIST))
+JRE_TARGET_LIST := $(subst $(JRE_IMAGE_DIR)/,$(JRE_BUNDLE_DIR)/Home/,$(JRE_FILE_LIST))
 
 # The old builds implementation of this did not preserve symlinks so
 # make sure they are followed and the contents copied instead.
-# To fix this, just replace copy with install-file macro.
-$(JDK_BUNDLE_DIR)/Home/%: $(IMAGES_OUTPUTDIR)/j2sdk-image/%
+# To fix this, remove -L
+# Copy empty directories (jre/lib/applet).
+$(JDK_BUNDLE_DIR)/Home/%: $(JDK_IMAGE_DIR)/%
 	$(ECHO) Copying $(patsubst $(OUTPUT_ROOT)/%,%,$@)
 	$(MKDIR) -p $(@D)
-	$(CP) -f -R -L '$<' '$@'
+	if [ -d "$<" ]; then $(MKDIR) -p $@; else $(CP) -f -R -L '$<' '$@'; fi
 
-$(JRE_BUNDLE_DIR)/Home/%: $(IMAGES_OUTPUTDIR)/j2re-image/%
+$(JRE_BUNDLE_DIR)/Home/%: $(JRE_IMAGE_DIR)/%
 	$(ECHO) Copying $(patsubst $(OUTPUT_ROOT)/%,%,$@)
 	$(MKDIR) -p $(@D)
-	$(CP) -f -R -L '$<' '$@'
+	if [ -d "$<" ]; then $(MKDIR) -p $@; else $(CP) -f -R -L '$<' '$@'; fi
 
 $(JDK_BUNDLE_DIR)/MacOS/libjli.dylib:
 	$(ECHO) Creating link $(patsubst $(OUTPUT_ROOT)/%,%,$@)
 	$(MKDIR) -p $(@D)
 	$(RM) $@
-	$(LN) -s ../Home/lib/jli/libjli.dylib $@
+	$(LN) -s ../Home/jre/lib/jli/libjli.dylib $@
 
 $(JRE_BUNDLE_DIR)/MacOS/libjli.dylib:
 	$(ECHO) Creating link $(patsubst $(OUTPUT_ROOT)/%,%,$@)
--- a/jdk/makefiles/CompileDemos.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/CompileDemos.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -33,6 +33,9 @@
 # Setup the java compilers for the JDK build.
 include Setup.gmk
 
+# Prepare the find cache. Only used if running on windows.
+$(eval $(call FillCacheFind,$(JDK_TOPDIR)/src))
+
 # Append demo goals to this variable.
 BUILD_DEMOS=
 
@@ -185,7 +188,7 @@
 
     BUILD_DEMOS += $(patsubst $(JDK_TOPDIR)/src/closed/share/demo/nbproject/%,\
 			$(JDK_OUTPUTDIR)/demo/nbproject/%,\
-			$(shell $(FIND) $(JDK_TOPDIR)/src/closed/share/demo/nbproject/ -type f))
+			$(call CacheFind,$(JDK_TOPDIR)/src/closed/share/demo/nbproject))
     $(JDK_OUTPUTDIR)/demo/nbproject/% : $(JDK_TOPDIR)/src/closed/share/demo/nbproject/%
 		$(MKDIR) -p $(@D)
 		$(CP) $< $@
@@ -317,7 +320,7 @@
 
 # The jpda demo (com/sun/tools/example) is oddly enough stored in src/share/classes.
 # At least, we do not need to compile the jpda demo, just jar/zip up the sources.
-JPDA_SOURCES:=$(shell $(FIND) $(JDK_TOPDIR)/src/share/classes/com/sun/tools/example -type f)
+JPDA_SOURCES:=$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/tools/example)
 # The number of files are few enough so that we can use echo safely below to list them.
 JPDA_FILES:=$(subst $(JDK_TOPDIR)/src/share/classes/,,$(JPDA_SOURCES))
 
@@ -363,7 +366,7 @@
 # The netbeans project files are copied into the demo directory.
 BUILD_DEMOS += $(patsubst $(JDK_TOPDIR)/src/share/demo/nbproject/%,\
 		$(JDK_OUTPUTDIR)/demo/nbproject/%,\
-		$(shell $(FIND) $(JDK_TOPDIR)/src/share/demo/nbproject/ -type f))
+		$(call CacheFind,$(JDK_TOPDIR)/src/share/demo/nbproject))
 
 $(JDK_OUTPUTDIR)/demo/nbproject/% : $(JDK_TOPDIR)/src/share/demo/nbproject/%
 	$(MKDIR) -p $(@D)
@@ -439,7 +442,7 @@
 ##################################################################################################
 
 ifndef OPENJDK
-    DB_DEMO_ZIPFILE := $(shell $(FIND) $(JDK_TOPDIR)/src/closed/share/db -name "*demo*.zip")
+    DB_DEMO_ZIPFILE := $(wildcard $(JDK_TOPDIR)/src/closed/share/db/*demo*.zip)
 
     $(JDK_OUTPUTDIR)/demo/_the.db.unzipped: $(DB_DEMO_ZIPFILE)
 	$(MKDIR) -p $(@D)
--- a/jdk/makefiles/CompileJavaClasses.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/CompileJavaClasses.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -42,8 +42,7 @@
 		com/sun/tools/example/trace\
 		com/sun/tools/example/debug/bdi\
 		com/sun/tools/example/debug/event\
-		com/sun/tools/example/debug/gui \
-		com/oracle/security
+		com/sun/tools/example/debug/gui
 
 ifdef OPENJDK
     EXCLUDES+=	sun/dc \
@@ -86,6 +85,8 @@
         sun/nio/ch/SolarisEventPort.java \
 	sun/tools/attach/SolarisAttachProvider.java \
 	sun/tools/attach/SolarisVirtualMachine.java
+
+   EXCLUDES += com/oracle/security
 endif
 
 # In the old build, this isn't excluded on macosx, even though it probably
@@ -227,14 +228,20 @@
 	sun/nio/ch/SimpleAsynchronousFileChannelImpl.java
 endif
 
-# Exclude nimbus files from rt.jar
+# These files do not appear in the build result of the old build. This
+# is because they are generated sources, but the AUTO_JAVA_FILES won't
+# pick them up since they aren't generated when the source dirs are 
+# searched and they aren't referenced by any other classes so they won't
+# be picked up by implicit compilation. On a rebuild, they are picked up
+# and compiled. Exclude them here to produce the same rt.jar as the old 
+# build does when building just once.
 EXFILES+=javax/swing/plaf/nimbus/InternalFrameTitlePanePainter.java \
-				 javax/swing/plaf/nimbus/OptionPaneMessageAreaPainter.java \
-				 javax/swing/plaf/nimbus/ScrollBarPainter.java \
-				 javax/swing/plaf/nimbus/SliderPainter.java \
-				 javax/swing/plaf/nimbus/SpinnerPainter.java \
-				 javax/swing/plaf/nimbus/SplitPanePainter.java \
-				 javax/swing/plaf/nimbus/TabbedPanePainter.java
+	 javax/swing/plaf/nimbus/OptionPaneMessageAreaPainter.java \
+	 javax/swing/plaf/nimbus/ScrollBarPainter.java \
+	 javax/swing/plaf/nimbus/SliderPainter.java \
+	 javax/swing/plaf/nimbus/SpinnerPainter.java \
+	 javax/swing/plaf/nimbus/SplitPanePainter.java \
+	 javax/swing/plaf/nimbus/TabbedPanePainter.java
 
 # Acquire a list of files that should be copied straight over to the classes.
 include CopyIntoClasses.gmk
@@ -285,6 +292,7 @@
 		     $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/classes \
 		     $(MACOSX_SRC_DIRS) \
 		     $(JDK_OUTPUTDIR)/gensrc \
+		     $(JDK_OUTPUTDIR)/gensrc_no_srczip \
 		     $(CLOSED_SRC_DIRS),\
 		INCLUDES:=$(JDK_USER_DEFINED_FILTER),\
 		EXCLUDES:=$(EXCLUDES),\
@@ -295,35 +303,6 @@
 		HEADERS:=$(JDK_OUTPUTDIR)/gensrc_headers))
 
 ##########################################################################################
-# Special handling of header file generation for classes in the jigsaw base module which
-# currently can't add the annotaion GenerateNativeHeaders. For these specific classes the
-# java file and the class have the same names which enables shortcutting the dependencies.
-
-JDK_BASE_HEADER_CLASSES:=java.lang.Integer \
-			 java.lang.Long \
-			 java.net.SocketOptions \
-			 sun.nio.ch.IOStatus \
-			 java.io.FileSystem
-
-JDK_BASE_HEADER_JAVA_FILES:=$(patsubst %,$(JDK_TOPDIR)/src/share/classes/%.java,\
-				$(subst .,/,$(JDK_BASE_HEADER_CLASSES)))
-
-ifeq ($(OPENJDK_TARGET_OS),windows)
-    JDK_BASE_HEADER_CLASSES_WINDOWS:=sun.nio.ch.PollArrayWrapper
-    JDK_BASE_HEADER_CLASSES+=$(JDK_BASE_HEADER_CLASSES_WINDOWS)
-    JDK_BASE_HEADER_JAVA_FILES+=$(patsubst %,$(JDK_TOPDIR)/src/windows/classes/%.java,\
-				$(subst .,/,$(JDK_BASE_HEADER_CLASSES_WINDOWS)))
-endif
-
-# Set prereqs to the java files since make doesn't know about the class files. Add BUILD_JDK
-# as an order only dependency to avoid race with the java compilation.
-$(JDK_OUTPUTDIR)/gensrc_headers/_the.jdk.base.headers: $(JDK_BASE_HEADER_JAVA_FILES) | $(BUILD_JDK)
-	$(ECHO) Generating headers for jdk base classes
-	$(JAVAH) -bootclasspath $(JDK_OUTPUTDIR)/classes -d $(JDK_OUTPUTDIR)/gensrc_headers \
-		$(JDK_BASE_HEADER_CLASSES)
-	$(TOUCH) $@
-
-##########################################################################################
 
 ifndef OPENJDK
 
@@ -387,7 +366,6 @@
 
 # copy with -a to preserve timestamps so dependencies down the line aren't messed up
 all: $(BUILD_JDK) $(BUILD_ALTCLASSES) $(BUILD_JOBJC) $(BUILD_JOBJC_HEADERS) $(COPY_EXTRA) \
-	$(JDK_OUTPUTDIR)/classes/META-INF/services/com.sun.tools.xjc.Plugin \
-	$(JDK_OUTPUTDIR)/gensrc_headers/_the.jdk.base.headers
+	$(JDK_OUTPUTDIR)/classes/META-INF/services/com.sun.tools.xjc.Plugin
 
 .PHONY: all
--- a/jdk/makefiles/CompileLaunchers.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/CompileLaunchers.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -32,6 +32,9 @@
 # Setup the java compilers for the JDK build.
 include Setup.gmk
 
+# Prepare the find cache. Only used on windows.
+$(eval $(call FillCacheFind,$(JDK_TOPDIR)/src/share/bin))
+
 # Build tools
 include Tools.gmk
 
@@ -267,6 +270,11 @@
     -DNEVER_ACT_AS_SERVER_CLASS_MACHINE \
     -DJAVA_ARGS='{ "-J-ms8m"$(COMMA) "com.sun.tools.javap.Main"$(COMMA) }'))
 
+$(eval $(call SetupLauncher,jdeps,\
+    -DEXPAND_CLASSPATH_WILDCARDS \
+    -DNEVER_ACT_AS_SERVER_CLASS_MACHINE \
+    -DJAVA_ARGS='{ "-J-ms8m"$(COMMA) "com.sun.tools.jdeps.Main"$(COMMA) }'))
+
 BUILD_LAUNCHER_jconsole_CFLAGS_windows:=-DJAVAW
 BUILD_LAUNCHER_jconsole_LDFLAGS_windows:=user32.lib
 
--- a/jdk/makefiles/CompileNativeLibraries.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/CompileNativeLibraries.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -35,6 +35,9 @@
 # Copy files (can now depend on $(COPY_FILES))
 include CopyFiles.gmk
 
+# Prepare the find cache. Only used if running on windows.
+$(eval $(call FillCacheFind,$(JDK_TOPDIR)/src))
+
 # Build tools
 include Tools.gmk
 
@@ -90,14 +93,11 @@
 		ARFLAGS:=$(ARFLAGS),\
 		OBJECT_DIR:=$(JDK_OUTPUTDIR)/objs/libfdlibm))
 
-BUILD_LIBRARIES += $(BUILD_LIBFDLIBM)
-
 else
-#
-# On macosx they do partial (incremental) linking of fdlibm
-#   code it here...rather than add support to NativeCompilation
-#   as this is firt time I see it
-$(eval $(call SetupNativeCompilation,BUILD_LIBFDLIBM,\
+
+# On macosx the old build does partial (incremental) linking of fdlibm instead of
+# a plain static library.
+$(eval $(call SetupNativeCompilation,BUILD_LIBFDLIBM_MAC,\
                 LIBRARY:=fdlibm,\
                 OUTPUT_DIR:=$(JDK_OUTPUTDIR)/objs/libfdlibm,\
                 SRC:=$(JDK_TOPDIR)/src/share/native/java/lang/fdlibm/src,\
@@ -107,11 +107,12 @@
 		LDFLAGS:=-nostdlib -r -arch x86_64,\
 		OBJECT_DIR:=$(JDK_OUTPUTDIR)/objs/libfdlibm))
 
-$(JDK_OUTPUTDIR)/objs/$(LIBRARY_PREFIX)fdlibm$(STATIC_LIBRARY_SUFFIX) : $(BUILD_LIBFDLIBM)
+BUILD_LIBFDLIBM := $(JDK_OUTPUTDIR)/objs/$(LIBRARY_PREFIX)fdlibm$(STATIC_LIBRARY_SUFFIX)
+$(BUILD_LIBFDLIBM) : $(BUILD_LIBFDLIBM_MAC)
 	$(CP) -a $< $@
 
-BUILD_LIBRARIES += $(JDK_OUTPUTDIR)/objs/$(LIBRARY_PREFIX)fdlibm$(STATIC_LIBRARY_SUFFIX)
 endif
+BUILD_LIBRARIES += $(BUILD_LIBFDLIBM)
 
 ##########################################################################################
 
@@ -2609,7 +2610,6 @@
 		LIBRARY:=sunmscapi,\
                 OUTPUT_DIR:=$(INSTALL_LIBRARIES_HERE),\
 		SRC:=$(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/sun/security/mscapi,\
-		INCLUDE_FILES:=security.cpp, \
 		LANG:=C++,\
 		OPTIMIZATION:=LOW, \
 		CFLAGS:=$(CFLAGS_JDKLIB) \
--- a/jdk/makefiles/CopyFiles.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/CopyFiles.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -317,7 +317,7 @@
 		$(MKDIR) -p $(@D)
 		$(RM) $(JVMCFG)
 		$(PRINTF) "-client KNOWN\n">$(JVMCFG)
-		$(PRINTF) "-server IGNORE\n">>$(JVMCFG)
+		$(PRINTF) "-server ALIASED_TO -client\n">>$(JVMCFG)
 		$(PRINTF) "-hotspot ALIASED_TO -client\n">>$(JVMCFG)
 		$(PRINTF) "-classic WARN\n">>$(JVMCFG)
 		$(PRINTF) "-native ERROR\n">>$(JVMCFG)
--- a/jdk/makefiles/CopyIntoClasses.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/CopyIntoClasses.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -169,7 +169,7 @@
 # are uncommented and the configuration file is stored in the output META-INF directory.
 
 # Make sure the output directory is created.
-$(shell $(MKDIR) -p $(JDK_OUTPUTDIR)/classes/META-INF/services)
+$(eval $(call MakeDir,$(JDK_OUTPUTDIR)/classes/META-INF/services))
 # Find all META-INF/services/* files
 ALL_META-INF_DIRS_share:=$(shell $(FIND) $(JDK_TOPDIR)/src/share/classes -type d -a -name META-INF)
 ALL_META-INF_DIRS_targetapi:=$(shell $(FIND) $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/classes -type d -a -name META-INF)
--- a/jdk/makefiles/CreateJars.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/CreateJars.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -30,6 +30,9 @@
 
 default: all
 
+# Prepare the find cache. Only used if running on windows.
+$(eval $(call FillCacheFind,$(JDK_OUTPUTDIR)/classes))
+
 include Tools.gmk
 
 #
@@ -126,81 +129,22 @@
 
 # Exclude list for rt.jar and resources.jar
 RT_JAR_EXCLUDES := \
+	com/oracle/security \
+	com/sun/codemodel \
+	com/sun/crypto/provider \
+	com/sun/istack/internal/tools \
+	com/sun/jarsigner \
 	com/sun/javadoc \
 	com/sun/jdi \
-	com/sun/jarsigner \
+	com/sun/net/ssl/internal/ssl \
 	com/sun/source \
-	com/sun/istack/internal/tools \
-	META-INF/services/com.sun.jdi.connect.Connector \
-	META-INF/services/com.sun.jdi.connect.spi.TransportService \
-	META-INF/services/com.sun.tools.xjc.Plugin \
 	com/sun/tools \
-	sun/jvmstat \
-	sun/nio/cs/ext \
-	sun/awt/HKSCS.class \
-	sun/awt/motif/X11GB2312\$$$$Decoder.class \
-	sun/awt/motif/X11GB2312\$$$$Encoder.class \
-	sun/awt/motif/X11GB2312.class \
-	sun/awt/motif/X11GBK\$$$$Encoder.class \
-	sun/awt/motif/X11GBK.class \
-	sun/awt/motif/X11KSC5601\$$$$Decoder.class \
-	sun/awt/motif/X11KSC5601\$$$$Encoder.class \
-	sun/awt/motif/X11KSC5601.class \
-	META-INF/services/java.nio.charset.spi.CharsetProvider \
-	sun/rmi/rmic \
-	sun/tools/asm \
-	sun/tools/java \
-	sun/tools/javac \
-	com/sun/tools/classfile \
-	com/sun/tools/javap \
-	sun/tools/jcmd \
-	sun/tools/jconsole \
-	sun/tools/jps \
-	sun/tools/jstat \
-	sun/tools/jstatd \
-	sun/tools/native2ascii \
-	sun/tools/serialver \
-	sun/tools/tree \
-	sun/tools/util \
-	sun/security/tools/jarsigner \
-	sun/security/provider/Sun.class \
-	sun/security/rsa/SunRsaSign.class \
-	sun/security/ssl \
-	sun/security/ec/ECDHKeyAgreement.class \
-	sun/security/ec/ECDSASignature\$$$$Raw.class \
-	sun/security/ec/ECDSASignature\$$$$SHA1.class \
-	sun/security/ec/ECDSASignature\$$$$SHA224.class \
-	sun/security/ec/ECDSASignature\$$$$SHA256.class \
-	sun/security/ec/ECDSASignature\$$$$SHA384.class \
-	sun/security/ec/ECDSASignature\$$$$SHA512.class \
-	sun/security/ec/ECDSASignature.class \
-	sun/security/ec/ECKeyFactory.class \
-	sun/security/ec/ECKeyPairGenerator.class \
-	sun/security/ec/SunEC\$$$$1.class \
-	sun/security/ec/SunEC.class \
-	sun/security/ec/SunECEntries.class \
-	sun/security/mscapi \
-	sun/security/pkcs11 \
-	com/sun/net/ssl/internal/ssl \
-	javax/crypto \
-	sun/security/internal \
-	com/sun/crypto/provider \
-	META-INF/services/com.sun.tools.attach.spi.AttachProvider \
-	com/sun/tools/attach \
-	org/relaxng/datatype \
-	com/sun/codemodel \
 	com/sun/xml/internal/dtdparser \
 	com/sun/xml/internal/rngom \
 	com/sun/xml/internal/xsom \
-	com/sun/tools/script/shell \
-	sun/tools/attach \
-	sun/tools/jstack \
-	sun/tools/jinfo \
-	sun/tools/jmap \
-	sun/net/spi/nameservice/dns \
-	META-INF/services/sun.net.spi.nameservice.NameServiceDescriptor \
+	javax/crypto \
+	javax/swing/AbstractButtonBeanInfo.class \
 	javax/swing/beaninfo \
-	javax/swing/AbstractButtonBeanInfo.class \
 	javax/swing/BoxBeanInfo.class \
 	javax/swing/JAppletBeanInfo.class \
 	javax/swing/JButtonBeanInfo.class \
@@ -246,11 +190,67 @@
 	javax/swing/JWindowBeanInfo.class \
 	javax/swing/SwingBeanInfoBase.class \
 	javax/swing/text/JTextComponentBeanInfo.class \
+	META-INF/services/com.sun.jdi.connect.Connector \
+	META-INF/services/com.sun.jdi.connect.spi.TransportService \
+	META-INF/services/com.sun.tools.attach.spi.AttachProvider \
+	META-INF/services/com.sun.tools.xjc.Plugin \
+	META-INF/services/java.nio.charset.spi.CharsetProvider \
+	META-INF/services/sun.net.spi.nameservice.NameServiceDescriptor \
+	org/relaxng/datatype \
+	sun/awt/HKSCS.class \
+	sun/awt/motif/X11GB2312.class \
+	sun/awt/motif/X11GB2312\$$$$Decoder.class \
+	sun/awt/motif/X11GB2312\$$$$Encoder.class \
+	sun/awt/motif/X11GBK.class \
+	sun/awt/motif/X11GBK\$$$$Encoder.class \
+	sun/awt/motif/X11KSC5601.class \
+	sun/awt/motif/X11KSC5601\$$$$Decoder.class \
+	sun/awt/motif/X11KSC5601\$$$$Encoder.class \
+	sun/jvmstat \
+	sun/net/spi/nameservice/dns \
+	sun/nio/cs/ext \
+	sun/rmi/rmic \
+	sun/security/ec/ECDHKeyAgreement.class \
+	sun/security/ec/ECDSASignature.class \
+	sun/security/ec/ECDSASignature\$$$$Raw.class \
+	sun/security/ec/ECDSASignature\$$$$SHA1.class \
+	sun/security/ec/ECDSASignature\$$$$SHA224.class \
+	sun/security/ec/ECDSASignature\$$$$SHA256.class \
+	sun/security/ec/ECDSASignature\$$$$SHA384.class \
+	sun/security/ec/ECDSASignature\$$$$SHA512.class \
+	sun/security/ec/ECKeyFactory.class \
+	sun/security/ec/ECKeyPairGenerator.class \
+	sun/security/ec/SunEC\$$$$1.class \
+	sun/security/ec/SunEC.class \
+	sun/security/ec/SunECEntries.class \
+	sun/security/internal \
+	sun/security/mscapi \
+	sun/security/pkcs11 \
+	sun/security/provider/Sun.class \
+	sun/security/rsa/SunRsaSign.class \
+	sun/security/ssl \
+	sun/security/tools/jarsigner \
 	sun/swing/BeanInfoUtils.class \
-	$(LOCALEDATA_INCLUDES) \
 	sun/text/resources/cldr \
+	sun/tools/asm \
+	sun/tools/attach \
+	sun/tools/java \
+	sun/tools/javac \
+	sun/tools/jcmd \
+	sun/tools/jconsole \
+	sun/tools/jinfo \
+	sun/tools/jmap \
+	sun/tools/jps \
+	sun/tools/jstack \
+	sun/tools/jstat \
+	sun/tools/jstatd \
+	sun/tools/native2ascii \
+	sun/tools/serialver \
+	sun/tools/tree \
+	sun/tools/util \
+	sun/util/cldr/CLDRLocaleDataMetaInfo.class \
 	sun/util/resources/cldr \
-	sun/util/cldr/CLDRLocaleDataMetaInfo.class
+	$(LOCALEDATA_INCLUDES)
 
 # These files should never be put into rt.jar
 # but due to a misstake...some are put there if embedded
@@ -275,8 +275,8 @@
 endif
 
 # Find all files in the classes dir to use as dependencies. This could be more fine granular.
-ALL_FILES_IN_CLASSES := $(shell $(FIND) $(JDK_OUTPUTDIR)/classes -type f \
-			| $(GREP) -v -e '/_the\.*' -e '^_the\.*' -e 'javac_state')
+ALL_FILES_IN_CLASSES := $(call not-containing,_the.,$(filter-out %javac_state,\
+                        $(call CacheFind,$(JDK_OUTPUTDIR)/classes)))
 
 RT_JAR_MANIFEST_FILE := $(IMAGES_OUTPUTDIR)/lib/_the.rt.jar_manifest
 RESOURCE_JAR_MANIFEST_FILE := $(IMAGES_OUTPUTDIR)/lib/_the.resources.jar_manifest
@@ -437,60 +437,61 @@
 	$(MV) $@.tmp $@
 
 ##########################################################################################
+# For all security jars, always build the jar, but for closed, install the prebuilt signed
+# version instead of the newly built jar. For open, signing is not needed. See SignJars.gmk
+# for more information.
 
 SUNPKCS11_JAR_DST := $(IMAGES_OUTPUTDIR)/lib/ext/sunpkcs11.jar
+SUNPKCS11_JAR_UNSIGNED := $(IMAGES_OUTPUTDIR)/unsigned/sunpkcs11.jar
+
+$(eval $(call SetupArchive,BUILD_SUNPKCS11_JAR,,\
+	SRCS:=$(JDK_OUTPUTDIR)/classes, \
+	SUFFIXES:=.class,\
+	INCLUDES:=sun/security/pkcs11,\
+	JAR:=$(SUNPKCS11_JAR_UNSIGNED), \
+        MANIFEST:=$(JCE_MANIFEST), \
+	SKIP_METAINF := true))
+
+$(SUNPKCS11_JAR_UNSIGNED): $(JCE_MANIFEST)
 
 ifndef OPENJDK
-
     SUNPKCS11_JAR_SRC := $(JDK_TOPDIR)/make/closed/tools/crypto/pkcs11/sunpkcs11.jar
-
     $(SUNPKCS11_JAR_DST) : $(SUNPKCS11_JAR_SRC)
 	@$(ECHO) $(LOG_INFO) "\n>>>Installing prebuilt SunPKCS11 provider..."
 	$(install-file)
-
 else
-
-    $(eval $(call SetupArchive,BUILD_SUNPKCS11_JAR,,\
-	SRCS:=$(JDK_OUTPUTDIR)/classes, \
-	SUFFIXES:=.class,\
-	INCLUDES:=sun/security/pkcs11,\
-	JAR:=$(SUNPKCS11_JAR_DST), \
-        MANIFEST:=$(JCE_MANIFEST), \
-	SKIP_METAINF := true))
-
-    $(SUNPKCS11_JAR_DST): $(JCE_MANIFEST)
-
+    $(SUNPKCS11_JAR_DST) : $(SUNPKCS11_JAR_UNSIGNED)
+	$(install-file)
 endif
 
-JARS += $(SUNPKCS11_JAR_DST)
+JARS += $(SUNPKCS11_JAR_DST) $(SUNPKCS11_JAR_UNSIGNED)
 
 ##########################################################################################
 
 SUNEC_JAR_DST := $(IMAGES_OUTPUTDIR)/lib/ext/sunec.jar
+SUNEC_JAR_UNSIGNED := $(IMAGES_OUTPUTDIR)/unsigned/sunec.jar
+
+$(eval $(call SetupArchive,BUILD_SUNEC_JAR,,\
+		SRCS:=$(JDK_OUTPUTDIR)/classes, \
+		SUFFIXES:=.class,\
+		INCLUDES:=sun/security/ec,\
+		JAR:=$(SUNEC_JAR_UNSIGNED), \
+                MANIFEST:=$(JCE_MANIFEST), \
+		SKIP_METAINF := true))
+
+$(SUNEC_JAR_UNSIGNED): $(JCE_MANIFEST)
 
 ifndef OPENJDK
-
     SUNEC_JAR_SRC := $(JDK_TOPDIR)/make/closed/tools/crypto/ec/sunec.jar
-
     $(SUNEC_JAR_DST) : $(SUNEC_JAR_SRC)
 	@$(ECHO) $(LOG_INFO) "\n>>>Installing prebuilt SunEC provider..."
 	$(install-file)
-
 else
-
-    $(eval $(call SetupArchive,BUILD_SUNEC_JAR,,\
-		SRCS:=$(JDK_OUTPUTDIR)/classes, \
-		SUFFIXES:=.class,\
-		INCLUDES:=sun/security/ec,\
-		JAR:=$(SUNEC_JAR_DST), \
-                MANIFEST:=$(JCE_MANIFEST), \
-		SKIP_METAINF := true))
-
-    $(SUNEC_JAR_DST): $(JCE_MANIFEST)
-
+    $(SUNEC_JAR_DST) : $(SUNEC_JAR_UNSIGNED)
+	$(install-file)
 endif
 
-JARS += $(SUNEC_JAR_DST)
+JARS += $(SUNEC_JAR_DST) $(SUNEC_JAR_UNSIGNED)
 
 ##########################################################################################
 
@@ -508,162 +509,166 @@
 ##########################################################################################
 
 SUNJCE_PROVIDER_JAR_DST := $(IMAGES_OUTPUTDIR)/lib/ext/sunjce_provider.jar
-
-ifndef OPENJDK
-    SUNJCE_PROVIDER_JAR_SRC := $(JDK_TOPDIR)/make/closed/tools/crypto/jce/sunjce_provider.jar
+SUNJCE_PROVIDER_JAR_UNSIGNED := $(IMAGES_OUTPUTDIR)/unsigned/sunjce_provider.jar
 
-    $(SUNJCE_PROVIDER_JAR_DST) : $(SUNJCE_PROVIDER_JAR_SRC)
-	@$(ECHO) $(LOG_INFO) "\n>>>Installing prebuilt SunJCE provider..."
-	$(install-file)
-
-else
-
-    $(eval $(call SetupArchive,BUILD_SUNJCE_PROVIDER_JAR,,\
+$(eval $(call SetupArchive,BUILD_SUNJCE_PROVIDER_JAR,,\
 		SRCS:=$(JDK_OUTPUTDIR)/classes, \
 		SUFFIXES:=.class,\
 		INCLUDES:= com/sun/crypto/provider,\
-		JAR:=$(SUNJCE_PROVIDER_JAR_DST), \
+		JAR:=$(SUNJCE_PROVIDER_JAR_UNSIGNED), \
                 MANIFEST:=$(JCE_MANIFEST), \
 		SKIP_METAINF := true))
 
-    $(SUNJCE_PROVIDER_JAR_DST): $(JCE_MANIFEST)
+$(SUNJCE_PROVIDER_JAR_UNSIGNED): $(JCE_MANIFEST)
 
+ifndef OPENJDK
+    SUNJCE_PROVIDER_JAR_SRC := $(JDK_TOPDIR)/make/closed/tools/crypto/jce/sunjce_provider.jar
+    $(SUNJCE_PROVIDER_JAR_DST) : $(SUNJCE_PROVIDER_JAR_SRC)
+	@$(ECHO) $(LOG_INFO) "\n>>>Installing prebuilt SunJCE provider..."
+	$(install-file)
+else
+    $(SUNJCE_PROVIDER_JAR_DST) : $(SUNJCE_PROVIDER_JAR_UNSIGNED)
+	$(install-file)
 endif
 
-JARS += $(SUNJCE_PROVIDER_JAR_DST)
+JARS += $(SUNJCE_PROVIDER_JAR_DST) $(SUNJCE_PROVIDER_JAR_UNSIGNED)
+
+##########################################################################################
 
 JCE_JAR_DST := $(IMAGES_OUTPUTDIR)/lib/jce.jar
+JCE_JAR_UNSIGNED := $(IMAGES_OUTPUTDIR)/unsigned/jce.jar
+
+$(eval $(call SetupArchive,BUILD_JCE_JAR,,\
+		SRCS:=$(JDK_OUTPUTDIR)/classes, \
+		SUFFIXES:=.class,\
+		INCLUDES:= javax/crypto sun/security/internal,\
+		JAR:=$(JCE_JAR_UNSIGNED), \
+                MANIFEST:=$(JCE_MANIFEST), \
+		SKIP_METAINF := true))
+
+$(JCE_JAR_UNSIGNED): $(JCE_MANIFEST)
 
 ifndef OPENJDK
-
     JCE_JAR_SRC := $(JDK_TOPDIR)/make/closed/tools/crypto/jce/jce.jar
-
     $(JCE_JAR_DST) : $(JCE_JAR_SRC)
 	@$(ECHO) $(LOG_INFO) "\n>>>Installing prebuilt jce.jar..."
 	$(install-file)
-
 else
-
-    $(eval $(call SetupArchive,BUILD_JCE_JAR,,\
-		SRCS:=$(JDK_OUTPUTDIR)/classes, \
-		SUFFIXES:=.class,\
-		INCLUDES:= javax/crypto sun/security/internal,\
-		JAR:=$(JCE_JAR_DST), \
-                MANIFEST:=$(JCE_MANIFEST), \
-		SKIP_METAINF := true))
-
-    $(JCE_JAR_DST): $(JCE_MANIFEST)
-
+    $(JCE_JAR_DST) : $(JCE_JAR_UNSIGNED)
+	$(install-file)
 endif
 
-JARS += $(JCE_JAR_DST)
+JARS += $(JCE_JAR_DST) $(JCE_JAR_UNSIGNED)
 
 ##########################################################################################
 
 US_EXPORT_POLICY_JAR_DST := $(IMAGES_OUTPUTDIR)/lib/security/US_export_policy.jar
+US_EXPORT_POLICY_JAR_UNSIGNED := $(IMAGES_OUTPUTDIR)/unsigned/US_export_policy.jar
+
+#
+# TODO fix so that SetupArchive does not write files into SRCS
+#   then we don't need this extra copying
+#
+# NOTE:  We currently do not place restrictions on our limited export
+# policy.  This was not a typo.
+#
+US_EXPORT_POLICY_JAR_SRC_DIR := $(JDK_TOPDIR)/make/javax/crypto/policy/unlimited
+US_EXPORT_POLICY_JAR_TMP := $(IMAGES_OUTPUTDIR)/US_export_policy_jar.tmp
+
+$(US_EXPORT_POLICY_JAR_TMP)/% : $(US_EXPORT_POLICY_JAR_SRC_DIR)/%
+	$(install-file)
+
+US_EXPORT_POLICY_JAR_DEPS := $(US_EXPORT_POLICY_JAR_TMP)/default_US_export.policy
+
+$(eval $(call SetupArchive,BUILD_US_EXPORT_POLICY_JAR,$(US_EXPORT_POLICY_JAR_DEPS),\
+		SRCS:=$(US_EXPORT_POLICY_JAR_TMP), \
+		SUFFIXES:= .policy,\
+		JAR:=$(US_EXPORT_POLICY_JAR_UNSIGNED), \
+		EXTRA_MANIFEST_ATTR := Crypto-Strength: unlimited, \
+		SKIP_METAINF := true))
 
 ifndef OPENJDK
-
-
     $(US_EXPORT_POLICY_JAR_DST): $(JDK_TOPDIR)/make/closed/tools/crypto/jce/US_export_policy.jar
 	$(ECHO) $(LOG_INFO) Copying $(@F)
 	$(install-file)
-
 else
-
-    #
-    # TODO fix so that SetupArchive does not write files into SRCS
-    #   then we don't need this extra copying
-    #
-    # NOTE:  We currently do not place restrictions on our limited export
-    # policy.  This was not a typo.
-    #
-    US_EXPORT_POLICY_JAR_SRC_DIR := $(JDK_TOPDIR)/make/javax/crypto/policy/unlimited
-    US_EXPORT_POLICY_JAR_TMP := $(IMAGES_OUTPUTDIR)/US_export_policy_jar.tmp
-
-    $(US_EXPORT_POLICY_JAR_TMP)/% : $(US_EXPORT_POLICY_JAR_SRC_DIR)/%
+    $(US_EXPORT_POLICY_JAR_DST): $(US_EXPORT_POLICY_JAR_UNSIGNED)
 	$(install-file)
-
-    US_EXPORT_POLICY_JAR_DEPS := $(US_EXPORT_POLICY_JAR_TMP)/default_US_export.policy
-
-    $(eval $(call SetupArchive,BUILD_US_EXPORT_POLICY_JAR,$(US_EXPORT_POLICY_JAR_DEPS),\
-		SRCS:=$(US_EXPORT_POLICY_JAR_TMP), \
-		SUFFIXES:= .policy,\
-		JAR:=$(US_EXPORT_POLICY_JAR_DST), \
-		EXTRA_MANIFEST_ATTR := Crypto-Strength: unlimited, \
-		SKIP_METAINF := true))
-
 endif
 
-JARS += $(US_EXPORT_POLICY_JAR_DST)
+JARS += $(US_EXPORT_POLICY_JAR_DST) $(US_EXPORT_POLICY_JAR_UNSIGNED)
 
 ##########################################################################################
 
 LOCAL_POLICY_JAR_DST := $(IMAGES_OUTPUTDIR)/lib/security/local_policy.jar
+LOCAL_POLICY_JAR_UNSIGNED := $(IMAGES_OUTPUTDIR)/unsigned/local_policy.jar
+
+#
+# TODO fix so that SetupArchive does not write files into SRCS
+#   then we don't need this extra copying
+#
+LOCAL_POLICY_JAR_TMP := $(IMAGES_OUTPUTDIR)/local_policy_jar.tmp
+
+ifeq ($(UNLIMITED_CRYPTO), true)
+    LOCAL_POLICY_JAR_SRC_DIR := $(JDK_TOPDIR)/make/javax/crypto/policy/unlimited
+    LOCAL_POLICY_JAR_DEPS := $(LOCAL_POLICY_JAR_TMP)/default_local.policy
+    LOCAL_POLICY_JAR_ATTR := Crypto-Strength: unlimited
+else
+    LOCAL_POLICY_JAR_SRC_DIR := $(JDK_TOPDIR)/make/javax/crypto/policy/limited
+    LOCAL_POLICY_JAR_DEPS := $(LOCAL_POLICY_JAR_TMP)/exempt_local.policy \
+                             $(LOCAL_POLICY_JAR_TMP)/default_local.policy
+    LOCAL_POLICY_JAR_ATTR := Crypto-Strength: limited
+endif
+
+$(LOCAL_POLICY_JAR_TMP)/% : $(LOCAL_POLICY_JAR_SRC_DIR)/%
+	$(install-file)
+
+$(eval $(call SetupArchive,BUILD_LOCAL_POLICY_JAR,$(LOCAL_POLICY_JAR_DEPS),\
+		SRCS:=$(LOCAL_POLICY_JAR_TMP),\
+		SUFFIXES:= .policy,\
+		JAR:=$(LOCAL_POLICY_JAR_UNSIGNED), \
+		EXTRA_MANIFEST_ATTR := $(LOCAL_POLICY_JAR_ATTR), \
+		SKIP_METAINF := true))
 
 ifndef OPENJDK
-
     $(LOCAL_POLICY_JAR_DST): $(JDK_TOPDIR)/make/closed/tools/crypto/jce/local_policy.jar
 	$(ECHO) $(LOG_INFO) Copying $(@F)
 	$(install-file)
-
 else
-
-    #
-    # TODO fix so that SetupArchive does not write files into SRCS
-    #   then we don't need this extra copying
-    #
-    LOCAL_POLICY_JAR_TMP := $(IMAGES_OUTPUTDIR)/local_policy_jar.tmp
-
-    ifeq ($(UNLIMITED_CRYPTO), true)
-        LOCAL_POLICY_JAR_SRC_DIR := $(JDK_TOPDIR)/make/javax/crypto/policy/unlimited
-        LOCAL_POLICY_JAR_DEPS := $(LOCAL_POLICY_JAR_TMP)/default_local.policy
-        LOCAL_POLICY_JAR_ATTR := Crypto-Strength: unlimited
-    else
-        LOCAL_POLICY_JAR_SRC_DIR := $(JDK_TOPDIR)/make/javax/crypto/policy/limited
-        LOCAL_POLICY_JAR_DEPS := $(LOCAL_POLICY_JAR_TMP)/exempt_local.policy \
-                                 $(LOCAL_POLICY_JAR_TMP)/default_local.policy
-        LOCAL_POLICY_JAR_ATTR := Crypto-Strength: limited
-    endif
-
-    $(LOCAL_POLICY_JAR_TMP)/% : $(LOCAL_POLICY_JAR_SRC_DIR)/%
+    $(LOCAL_POLICY_JAR_DST): $(LOCAL_POLICY_JAR_UNSIGNED)
 	$(install-file)
-
-    $(eval $(call SetupArchive,BUILD_LOCAL_POLICY_JAR,$(LOCAL_POLICY_JAR_DEPS),\
-		SRCS:=$(LOCAL_POLICY_JAR_TMP),\
-		SUFFIXES:= .policy,\
-		JAR:=$(LOCAL_POLICY_JAR_DST), \
-		EXTRA_MANIFEST_ATTR := $(LOCAL_POLICY_JAR_ATTR), \
-		SKIP_METAINF := true))
-
 endif
 
-JARS += $(LOCAL_POLICY_JAR_DST)
+JARS += $(LOCAL_POLICY_JAR_DST) $(LOCAL_POLICY_JAR_UNSIGNED)
 
 ##########################################################################################
 
 ifeq ($(OPENJDK_TARGET_OS),windows)
 
 SUNMSCAPI_JAR_DST := $(IMAGES_OUTPUTDIR)/lib/ext/sunmscapi.jar
-
-ifndef OPENJDK
-SUNMSCAPI_JAR_SRC := $(JDK_TOPDIR)/make/closed/tools/crypto/mscapi/sunmscapi.jar
-
-$(SUNMSCAPI_JAR_DST) : $(SUNMSCAPI_JAR_SRC)
-	@$(ECHO) $(LOG_INFO) "\n>>>Installing prebuilt SunMSCAPI provider..."
-	$(install-file)
-
-else
+SUNMSCAPI_JAR_UNSIGNED := $(IMAGES_OUTPUTDIR)/unsigned/sunmscapi.jar
 
 $(eval $(call SetupArchive,BUILD_SUNMSCAPI_JAR,,\
 		SRCS:=$(JDK_OUTPUTDIR)/classes, \
 		SUFFIXES:=.class,\
 		INCLUDES:= sun/security/mscapi,\
-		JAR:=$(SUNMSCAPI_JAR_DST), \
+		JAR:=$(SUNMSCAPI_JAR_UNSIGNED), \
+		MANIFEST:=$(JCE_MANIFEST), \
 		SKIP_METAINF:=true))
+
+$(SUNMSCAPI_JAR_UNSIGNED): $(JCE_MANIFEST)
+
+ifndef OPENJDK
+    SUNMSCAPI_JAR_SRC := $(JDK_TOPDIR)/make/closed/tools/crypto/mscapi/sunmscapi.jar
+    $(SUNMSCAPI_JAR_DST) : $(SUNMSCAPI_JAR_SRC)
+	@$(ECHO) $(LOG_INFO) "\n>>>Installing prebuilt SunMSCAPI provider..."
+	$(install-file)
+else
+    $(SUNMSCAPI_JAR_DST) : $(SUNMSCAPI_JAR_UNSIGNED)
+	$(install-file)
 endif
 
-JARS += $(SUNMSCAPI_JAR_DST)
+JARS += $(SUNMSCAPI_JAR_DST) $(SUNMSCAPI_JAR_UNSIGNED)
 
 endif
 
@@ -673,13 +678,24 @@
 ifndef OPENJDK
 
 UCRYPTO_JAR_DST := $(IMAGES_OUTPUTDIR)/lib/ext/ucrypto.jar
+UCRYPTO_JAR_UNSIGNED := $(IMAGES_OUTPUTDIR)/unsigned/ucrypto.jar
 UCRYPTO_JAR_SRC := $(JDK_TOPDIR)/make/closed/tools/crypto/ucrypto/ucrypto.jar
 
+$(eval $(call SetupArchive,BUILD_UCRYPTO_JAR,,\
+		SRCS:=$(JDK_OUTPUTDIR)/classes, \
+		SUFFIXES:=.class,\
+		INCLUDES:=com/oracle/security/ucrypto,\
+		JAR:=$(UCRYPTO_JAR_UNSIGNED), \
+		MANIFEST:=$(JCE_MANIFEST), \
+		SKIP_METAINF:=true))
+
+$(UCRYPTO_JAR_UNSIGNED): $(JCE_MANIFEST)
+
 $(UCRYPTO_JAR_DST) : $(UCRYPTO_JAR_SRC)
 	@$(ECHO) $(LOG_INFO) "\n>>>Installing prebuilt OracleUcrypto provider..."
 	$(install-file)
 
-JARS += $(UCRYPTO_JAR_DST)
+JARS += $(UCRYPTO_JAR_DST) $(UCRYPTO_JAR_UNSIGNED)
 
 endif
 endif
@@ -707,55 +723,57 @@
 ##########################################################################################
 
 TOOLS_JAR_INCLUDES := \
+        com/sun/codemodel       \
+	com/sun/istack/internal/tools       \
+	com/sun/jarsigner	\
+	com/sun/javadoc		\
+	com/sun/jdi		\
+	com/sun/source          \
+	com/sun/tools/attach	\
+	com/sun/tools/classfile \
+	com/sun/tools/corba     \
+	com/sun/tools/doclets   \
+	com/sun/tools/doclint   \
+	com/sun/tools/example/debug/expr \
+	com/sun/tools/example/debug/tty  \
+	com/sun/tools/extcheck  \
+	com/sun/tools/hat       \
+        com/sun/tools/internal/jxc             \
+	com/sun/tools/internal/jxc/ap   \
+	com/sun/tools/internal/ws       \
+	com/sun/tools/internal/ws/wscompile/plugin/at_generated \
+	com/sun/tools/internal/xjc       \
+	com/sun/tools/javac     \
+	com/sun/tools/javadoc   \
+	com/sun/tools/javah     \
+	com/sun/tools/javap     \
+	com/sun/tools/jdeps	\
+	com/sun/tools/jdi	\
+	com/sun/tools/script/shell	\
+	com/sun/xml/internal/dtdparser \
+        com/sun/xml/internal/rngom       \
+        com/sun/xml/internal/xsom       \
+        org/relaxng/datatype   \
+	sun/applet		\
+	sun/jvmstat		\
+	sun/rmi/rmic		\
+	sun/security/tools/jarsigner \
 	sun/tools/asm		\
+	sun/tools/attach	\
 	sun/tools/jar		\
 	sun/tools/java		\
 	sun/tools/javac		\
 	sun/tools/jcmd		\
+	sun/tools/jinfo         \
+	sun/tools/jmap		\
 	sun/tools/jps		\
+	sun/tools/jstack        \
 	sun/tools/jstat		\
 	sun/tools/jstatd	\
 	sun/tools/native2ascii	\
 	sun/tools/serialver	\
 	sun/tools/tree		\
-	sun/tools/util		\
-	sun/security/tools/jarsigner \
-	sun/rmi/rmic		\
-	sun/applet		\
-	sun/jvmstat		\
-	com/sun/javadoc		\
-	com/sun/jdi		\
-	com/sun/jarsigner	\
-	com/sun/source          \
-	com/sun/tools/classfile \
-	com/sun/tools/doclets   \
-	com/sun/tools/example/debug/expr \
-	com/sun/tools/example/debug/tty  \
-	com/sun/tools/extcheck  \
-	com/sun/tools/hat       \
-	com/sun/tools/javac     \
-	com/sun/tools/javadoc   \
-	com/sun/tools/javah     \
-	com/sun/tools/javap     \
-	com/sun/tools/corba     \
-	com/sun/tools/internal/xjc       \
-	com/sun/tools/internal/ws       \
-	com/sun/istack/internal/tools       \
-	com/sun/tools/internal/jxc/ap   \
-	com/sun/tools/internal/ws/wscompile/plugin/at_generated \
-        com/sun/codemodel       \
-        com/sun/tools/internal/jxc             \
-        com/sun/xml/internal/rngom       \
-        com/sun/xml/internal/xsom       \
-        org/relaxng/datatype   \
-	com/sun/xml/internal/dtdparser \
-	com/sun/tools/jdi	\
-	com/sun/tools/script/shell	\
-	com/sun/tools/attach	\
-	sun/tools/attach	\
-	sun/tools/jstack        \
-	sun/tools/jinfo         \
-	sun/tools/jmap
+	sun/tools/util
 
 # The sjavac tools is not ready for public consumption.
 TOOLS_JAR_EXCLUDES=com/sun/tools/sjavac
@@ -819,7 +837,7 @@
 	    $(CORE_PKGS) $(NON_CORE_PKGS) $(EXCLUDE_PROPWARN_PKGS) $(EXPORTED_PRIVATE_PKGS)
 	$(TOUCH) $@
 
-$(shell $(MKDIR) -p $(IMAGES_OUTPUTDIR)/symbols)
+$(eval $(call MakeDir,$(IMAGES_OUTPUTDIR)/symbols))
 $(eval $(call SetupArchive,BUILD_CT_SYM,$(IMAGES_OUTPUTDIR)/symbols/_the.symbols,\
 		SRCS:=$(IMAGES_OUTPUTDIR)/symbols,\
 		INCLUDES:=META-INF/sym,\
@@ -831,6 +849,19 @@
 ##########################################################################################
 
 SRC_ZIP_INCLUDES = \
+	com/sun/corba			\
+	com/sun/image/codec/jpeg	\
+	com/sun/imageio                 \
+	com/sun/java_cup		\
+	com/sun/javadoc			\
+	com/sun/java/swing		\
+	com/sun/jlex	        	\
+	com/sun/jmx			\
+	com/sun/naming			\
+	com/sun/org/apache		\
+	com/sun/security/auth		\
+	com/sun/security/jgss		\
+	com/sun/source			\
 	java/applet			\
 	java/awt			\
 	java/beans			\
@@ -844,34 +875,21 @@
 	java/sql			\
 	java/text			\
 	java/util			\
-	com/sun/corba			\
-	com/sun/image/codec/jpeg	\
-	com/sun/imageio                 \
-	com/sun/java/swing		\
-	com/sun/javadoc			\
-	com/sun/jmx			\
-	com/sun/source			\
-	com/sun/naming			\
-	com/sun/security/auth		\
-	com/sun/security/jgss		\
 	javax/accessibility		\
 	javax/annotation		\
-	javax/script			\
 	javax/imageio			\
 	javax/lang			\
 	javax/management		\
 	javax/naming			\
 	javax/print			\
 	javax/rmi			\
+	javax/script			\
 	javax/security			\
 	javax/sound			\
 	javax/sql			\
 	javax/swing			\
 	javax/tools			\
 	javax/xml			\
-	com/sun/org/apache		\
-	com/sun/java_cup		\
-	com/sun/jlex	        	\
 	org/ietf			\
 	org/omg				\
 	org/w3c/dom			\
@@ -964,6 +982,62 @@
 JARS += $(IMAGES_OUTPUTDIR)/lib/sa-jdi.jar
 
 ##########################################################################################
+#
+# sec-bin.zip is used by builds where the corresponding sources are not available
+#
+$(eval $(call SetupZipArchive,BUILD_SEC_BIN_ZIP,\
+		SRC:=$(JDK_OUTPUTDIR),\
+		INCLUDES:=classes/javax/net \
+			  classes/javax/security/cert \
+			  classes/com/sun/net/ssl \
+			  classes/com/sun/security/cert \
+			  classes/sun/net/www/protocol/https \
+			  classes/sun/security/pkcs12 \
+			  classes/sun/security/ssl \
+			  classes/sun/security/krb5 \
+			  classes/sun/security/krb5/internal \
+			  classes/sun/security/krb5/internal/ccache \
+			  classes/sun/security/krb5/internal/crypto \
+			  classes/sun/security/krb5/internal/ktab \
+			  classes/sun/security/krb5/internal/rcache \
+			  classes/sun/security/krb5/internal/util,\
+		INCLUDE_FILES:=classes/sun/security/jgss/spi/GSSContextSpi.class,\
+		EXCLUDES:=classes/sun/security/krb5/internal/tools,\
+		ZIP:=$(IMAGES_OUTPUTDIR)/sec-bin.zip))
+
+JARS += $(IMAGES_OUTPUTDIR)/sec-bin.zip
+
+##########################################################################################
+#
+# Windows specific binary security packages.
+#
+ifeq ($(OPENJDK_TARGET_OS),windows)
+    # sec-windows-bin.zip is used by builds where the corresponding sources are not available
+    $(eval $(call SetupZipArchive,BUILD_SEC_WINDOWS_BIN_ZIP,\
+		SRC:=$(JDK_OUTPUTDIR),\
+		INCLUDES:=classes/sun/security/krb5/internal/tools,\
+		ZIP:=$(IMAGES_OUTPUTDIR)/sec-windows-bin.zip))
+
+    JARS += $(IMAGES_OUTPUTDIR)/sec-windows-bin.zip
+
+    # JGSS files contain the native Kerberos library
+    ifeq ($(OPENJDK_TARGET_CPU),x86_64)
+        JGSS_ZIP_NAME=jgss-windows-x64-bin.zip
+    else
+        JGSS_ZIP_NAME=jgss-windows-i586-bin.zip
+    endif
+
+    $(eval $(call SetupZipArchive,BUILD_JGSS_BIN_ZIP,\
+		SRC:=$(JDK_OUTPUTDIR),\
+		INCLUDE_FILES:=bin/w2k_lsa_auth.dll \
+			       bin/w2k_lsa_auth.map \
+			       bin/w2k_lsa_auth.pdb,\
+		ZIP:=$(IMAGES_OUTPUTDIR)/$(JGSS_ZIP_NAME)))
+
+    JARS += $(IMAGES_OUTPUTDIR)/$(JGSS_ZIP_NAME)
+endif
+
+##########################################################################################
 
 -include $(CUSTOM_MAKE_DIR)/CreateJars.gmk
 
--- a/jdk/makefiles/GensrcProperties.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/GensrcProperties.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -23,6 +23,9 @@
 # questions.
 #
 
+# Prepare the find cache. This is only used on windows.
+$(eval $(call FillCacheFind,$(JDK_TOPDIR)/src/share/classes $(JDK_TOPDIR)/src/windows/classes))
+
 # All .properties files to be compiled are appended to this variable.
 ALL_COMPILED_PROPSOURCES:=
 # All generated .java files from compilation are appended to this variable.
@@ -117,44 +120,54 @@
 #com/apple/laf/resources
 ifeq ($(OPENJDK_TARGET_OS),macosx)
     $(eval $(call add_properties_to_compile,COM_APPLE_LAF,\
-	$(shell find $(JDK_TOPDIR)/src/macosx/classes/com/apple/laf/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/macosx/classes/com/apple/laf/resources)),\
+	ListResourceBundle))
 endif
 
 #com/sun/accessibility/internal/resources
 $(eval $(call add_properties_to_compile,COM_SUN_ACCESSIBILITY,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/accessibility/internal/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/accessibility/internal/resources)),\
+	ListResourceBundle))
 $(eval $(call add_properties_to_compile,COM_SUN_ACCESSIBILITY_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/accessibility/internal/resources -name "*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/accessibility/internal/resources)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 #com/sun/imageio/plugins/common
 $(eval $(call add_properties_to_clean,COM_SUN_IMAGEIO,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/imageio -name "*.properties")))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/imageio))))
 #com/sun/java/swing/plaf/gtk/resources
 ifneq ($(OPENJDK_TARGET_OS), windows)
 # Only compile GTK resource bundles on Solaris/Linux
 $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_GTK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/gtk/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/gtk/resources)),\
+	ListResourceBundle))
 $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_GTK_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/gtk/resources -name "*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/gtk/resources)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 endif
 #com/sun/java/swing/plaf/motif/resources
 $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_MOTIF,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/motif/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/motif/resources)),\
+	ListResourceBundle))
 $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_MOTIF_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/motif/resources -name "*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/motif/resources)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 #com/sun/java/swing/plaf/windows/resources
 $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_WINDOWS,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/windows/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/windows/resources)),\
+	ListResourceBundle))
 $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_WINDOWS_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/windows/resources -name "*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/java/swing/plaf/windows/resources)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 #com/sun/java/util/jar/pack
 $(eval $(call add_properties_to_clean,JNDI_COSNAMING,\
 	$(JDK_TOPDIR)/src/share/classes/com/sun/java/util/jar/pack/intrinsic.properties))
@@ -169,138 +182,171 @@
 #FIXME: The "xmlsecurity*.properties" pattern is not ideal; we might want to find
 #a better way to select the properties files that are needed.
 $(eval $(call add_properties_to_clean,XML_SECURITY,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/org/apache/xml/internal/security/resource -name "xmlsecurity*.properties")))
+	$(filter $(JDK_TOPDIR)/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity%.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/org/apache/xml/internal/security/resource))))
 
 #com/sun/rowset
 $(eval $(call add_properties_to_clean,COM_SUN_ROWSET,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/rowset -name "*.properties")))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/rowset))))
 $(eval $(call add_properties_to_clean,COM_SUN_ROWSET_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/rowset -name "*zh_TW.properties"),\
+	$(filter %zh_TW.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/rowset)),\
 	%zh_TW,%zh_HK))
 
 #com/sun/servicetag/resources
 #com/sun/swing/internal/plaf/basic/resources
 $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_BASIC,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/basic/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/basic/resources)),\
+	ListResourceBundle))
 $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_BASIC_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/basic/resources -name "*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/basic/resources)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 #com/sun/swing/internal/plaf/metal/resources
 $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_METAL,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/metal/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/metal/resources)),\
+	ListResourceBundle))
 $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_METAL_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/metal/resources -name "*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter %.properties,$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/metal/resources)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 #com/sun/swing/internal/plaf/synth/resources
 $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_SYNTH,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/synth/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/synth/resources)),\
+	ListResourceBundle))
 $(eval $(call add_properties_to_compile,COM_SUN_SWING_PLAF_SYNTH_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/synth/resources -name "*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/swing/internal/plaf/synth/resources)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 
 #com/sun/tools/jdi/resources
 $(eval $(call add_properties_to_compile,COM_SUN_TOOLS_JDI,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/com/sun/tools/jdi/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/com/sun/tools/jdi/resources)),\
+	ListResourceBundle))
 
 #com/sun/tools/script/shell
 #java/util
 #javax/sql/rowset
 $(eval $(call add_properties_to_clean,JAVAX_SQL_ROWSET,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/javax/sql/rowset -name "*.properties")))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/javax/sql/rowset))))
 #sun/awt/resources
 $(eval $(call add_properties_to_compile,SUN_AWT,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/awt/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/awt/resources)),\
+	ListResourceBundle))
 $(eval $(call add_properties_to_compile,SUN_AWT_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/awt/resources -name "*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/awt/resources)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 #sun/awt/windows/
 ifeq ($(OPENJDK_TARGET_OS),windows)
     $(eval $(call add_properties_to_compile,SUN_AWT,\
-	$(shell find $(JDK_TOPDIR)/src/windows/classes/sun/awt/windows -name "awtLocalization*.properties"),\
-		ListResourceBundle))
+	$(filter $(JDK_TOPDIR)/src/windows/classes/sun/awt/windows/awtLocalization%.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/windows/classes/sun/awt/windows)),\
+	ListResourceBundle))
     $(eval $(call add_properties_to_compile,SUN_AWT_HK,\
-	$(shell find $(JDK_TOPDIR)/src/windows/classes/sun/awt/windows -name "awtLocalization*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter $(JDK_TOPDIR)/src/windows/classes/sun/awt/windows/awtLocalization%.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/windows/classes/sun/awt/windows)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 endif
 
 #sun/launcher/resources
 $(eval $(call add_properties_to_compile,SUN_LAUNCHER,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/launcher/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/launcher/resources)),\
+	ListResourceBundle))
 $(eval $(call add_properties_to_compile,SUN_LAUNCHER_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/launcher/resources -name "*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/launcher/resources)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 #sun/management/resources
 $(eval $(call add_properties_to_compile,SUN_MANAGEMENT,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/management/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/management/resources)),\
+	ListResourceBundle))
 $(eval $(call add_properties_to_compile,SUN_MANAGEMENT_KH,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/management/resources -name "*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/management/resources)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 #sun/print
 #sun/print/resources
 $(eval $(call add_properties_to_compile,SUN_PRINT,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/print/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/print/resources)),\
+	ListResourceBundle))
 $(eval $(call add_properties_to_compile,SUN_PRINT_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/print/resources -name "*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/print/resources)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 #sun/rmi/registry/resources
 $(eval $(call add_properties_to_clean,SUN_RMI_REGISTRY,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/rmi/registry/resources -name "*.properties")))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/rmi/registry/resources))))
 $(eval $(call add_properties_to_clean,SUN_RMI_REGISTRY_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/rmi/registry/resources -name "*zh_TW.properties"),\
+	$(filter %zh_TW.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/rmi/registry/resources)),\
 	%zh_TW,%zh_HK))
 
 #sun/rmi/rmic/resources
 $(eval $(call add_properties_to_clean,SUN_RMI_RMIC,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/rmi/rmic/resources -name "*.properties")))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/rmi/rmic/resources))))
 
 #sun/rmi/server/resources
 $(eval $(call add_properties_to_clean,SUN_RMI_SERVER,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/rmi/server/resources -name "*.properties")))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/rmi/server/resources))))
 $(eval $(call add_properties_to_clean,SUN_RMI_SERVER_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/rmi/server/resources -name "*zh_TW.properties"),\
+	$(filter %zh_TW.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/rmi/server/resources)),\
 	%zh_TW,%zh_HK))
 
 # sun/tools/jar/resources
 $(eval $(call add_properties_to_compile,SUN_TOOLS_JAR,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/tools/jar/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/tools/jar/resources)),\
+	ListResourceBundle))
 $(eval $(call add_properties_to_compile,SUN_TOOLS_JAR_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/tools/jar/resources -name "*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/tools/jar/resources)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 
 #sun/tools/javac/resources
 # It's unclear if the other localized property files here are supposed to be copied or not
 # but the old build system didn't copy them.
 $(eval $(call add_properties_to_clean,SUN_TOOLS_SERIALVER,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/tools/javac/resources -name "javac.properties")))
+	$(filter %javac.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/tools/javac/resources))))
 
 #sun/tools/jconsole/resources
 $(eval $(call add_properties_to_clean,SUN_TOOLS_JCONSOLE,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/tools/jconsole/resources -name "*.properties")))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/tools/jconsole/resources))))
 
 #sun/tools/serialver
 $(eval $(call add_properties_to_clean,SUN_TOOLS_SERIALVER,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/tools/serialver -name "*.properties"),,,resources))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/tools/serialver)),,,resources))
 
 #sun/util/logging/resources
 $(eval $(call add_properties_to_compile,SUN_UTIL_LOGGING,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/util/logging/resources -name "*.properties"),\
-		ListResourceBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/util/logging/resources)),\
+	ListResourceBundle))
 $(eval $(call add_properties_to_compile,SUN_UTIL_LOGGING_HK,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/util/logging/resources -name "*.properties"),\
-		ListResourceBundle,%zh_TW,%zh_HK))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/util/logging/resources)),\
+	ListResourceBundle,%zh_TW,%zh_HK))
 # sun/util/resources
 $(eval $(call add_properties_to_compile,SUN_UTIL,\
-	$(shell find $(JDK_TOPDIR)/src/share/classes/sun/util/resources -name "*.properties"),\
-		sun.util.resources.LocaleNamesBundle))
+	$(filter %.properties,\
+	$(call CacheFind,$(JDK_TOPDIR)/src/share/classes/sun/util/resources)),\
+	sun.util.resources.LocaleNamesBundle))
 
 # Now setup the rule for the generation of the resource bundles.
 $(JDK_OUTPUTDIR)/gensrc/_the.compiled_properties : $(ALL_COMPILED_PROPSOURCES) $(BUILD_TOOLS)
--- a/jdk/makefiles/GensrcSwing.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/GensrcSwing.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -45,7 +45,6 @@
 # Generate beaninfo java files
 #
 
-BEAN_GENSRC_DIR = $(JDK_OUTPUTDIR)/gensrc/javax/swing/beaninfo
 DOCLETSRC_DIR = $(JDK_TOPDIR)/make/tools/swing-beans
 
 # javax.swing package
@@ -69,25 +68,31 @@
 # Dummy variable so far, in the old build system it was false by default
 SWINGBEAN_DEBUG_FLAG = false
 # GenDocletBeanInfo is compiled in Tools.gmk and picks up from $(JDK_OUTPUTDIR)/btclasses
-$(JDK_OUTPUTDIR)/gensrc/_the.generated_beaninfo: $(BEANS_SRC) $(BEAN_GENSRC_DIR)/SwingBeanInfoBase.java $(BEAN_GENSRC_DIR)/BeanInfoUtils.java $(BUILD_TOOLS)
+$(JDK_OUTPUTDIR)/gensrc_no_srczip/_the.generated_beaninfo: $(BEANS_SRC) $(JDK_OUTPUTDIR)/gensrc_no_srczip/javax/swing/SwingBeanInfoBase.java $(JDK_OUTPUTDIR)/gensrc/sun/swing/BeanInfoUtils.java $(BUILD_TOOLS)
 	$(ECHO) Generating beaninfo
-	$(JAVA) -Djava.awt.headless=true -jar $(JAVADOC_JARS) -doclet GenDocletBeanInfo -x $(SWINGBEAN_DEBUG_FLAG) -d $(BEAN_GENSRC_DIR) -t $(DOCLETSRC_DIR)/SwingBeanInfo.template -docletpath $(JDK_OUTPUTDIR)/btclasses \
+	$(MKDIR) -p $(JDK_OUTPUTDIR)/gensrc_no_srczip/javax/swing
+	$(JAVA) -Djava.awt.headless=true -jar $(JAVADOC_JARS) -doclet GenDocletBeanInfo \
+	-x $(SWINGBEAN_DEBUG_FLAG) -d $(JDK_OUTPUTDIR)/gensrc_no_srczip/javax/swing \
+	-t $(DOCLETSRC_DIR)/SwingBeanInfo.template -docletpath $(JDK_OUTPUTDIR)/btclasses \
 	-XDignore.symbol.file=true \
 	-classpath $(JDK_OUTPUTDIR)/btclasses $(BEANS_SRC) $(LOG_INFO)
+#       Move the JTextComponent into its proper package directory.
+	$(MKDIR) -p $(JDK_OUTPUTDIR)/gensrc_no_srczip/javax/swing/text
+	$(MV) $(JDK_OUTPUTDIR)/gensrc_no_srczip/javax/swing/JTextComponentBeanInfo.java $(JDK_OUTPUTDIR)/gensrc_no_srczip/javax/swing/text/JTextComponentBeanInfo.java 
 	$(TOUCH) $@
 
 # This file is the part of dt.jar
-# For some reason it is under $(JDK_TOPDIR)/make/tools/swing-beans/beaninfo
+# For some reason it is under $(JDK_TOPDIR)/make/tools/swing-beans/javax/swing
 # Should it be moved under $(JDK_TOPDIR)/src/share/classes/javax/swing instead?
-$(BEAN_GENSRC_DIR)/SwingBeanInfoBase.java: $(DOCLETSRC_DIR)/beaninfo/SwingBeanInfoBase.java
+$(JDK_OUTPUTDIR)/gensrc_no_srczip/javax/swing/SwingBeanInfoBase.java: $(DOCLETSRC_DIR)/javax/swing/SwingBeanInfoBase.java
 	$(MKDIR) -p $(@D)
 	$(CP) $< $@
 
 # This file is the part of dt.jar 
-# For some reason it is under $(JDK_TOPDIR)/make/tools/swing-beans/beaninfo
+# For some reason it is under $(JDK_TOPDIR)/make/tools/swing-beans/sun/swing
 # Should it be moved under $(JDK_TOPDIR)/src/share/classes/sun/swing instead?
-$(BEAN_GENSRC_DIR)/BeanInfoUtils.java: $(DOCLETSRC_DIR)/beaninfo/BeanInfoUtils.java
+$(JDK_OUTPUTDIR)/gensrc/sun/swing/BeanInfoUtils.java: $(DOCLETSRC_DIR)/sun/swing/BeanInfoUtils.java
 	$(MKDIR) -p $(@D)
 	$(CP) $< $@
 
-GENSRC_SWING_BEANINFO = $(JDK_OUTPUTDIR)/gensrc/_the.generated_beaninfo
+GENSRC_SWING_BEANINFO = $(JDK_OUTPUTDIR)/gensrc_no_srczip/_the.generated_beaninfo
--- a/jdk/makefiles/GensrcX11Wrappers.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/GensrcX11Wrappers.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -23,84 +23,95 @@
 # questions.
 #
 
+# This file is responsible for extracting the x11 native struct offsets to
+# the xawt Java library. The tool needs to be run on the os/arch that
+# will host the final jvm, thus the tool cannot be used when cross compiling.
 
-# This file is responsible for extracting the x11 native struct offsets to
-# the xawt Java library. This is done by compiling and running a native
-# binary, which dumps output to a text file. The offsets differ on 32 and 64
-# bit systems, so care must be taken here.
+# To enable cross compiling, the two versions of the generated offset file,
+# sizes.32 and sizes.64 are committed into the source code repository.
+# These are the ones used.
 
-# Note: Some of the more complex logic here is most likely not needed anymore.
+# However when not cross compiling, the offset generator tool is built and
+# run, to verify that it still generates the same sizes.32 and sizes.64.
 
 GENSRC_X11WRAPPERS :=
+# Put temporary c-code and executable to calculate offsets here.
+# Also put verification offset file here as well.
 GENSRC_X11WRAPPERS_TMP := $(JDK_OUTPUTDIR)/gensrc_x11wrappers
-GENSRC_X11WRAPPERS_DST := $(JDK_OUTPUTDIR)/gensrc
+# Put the generated Java classes used to interface X11 from awt here.
+GENSRC_X11WRAPPERS_DST := $(JDK_OUTPUTDIR)/gensrc/sun/awt/X11
 
-GENSRC_SIZER_SRC := $(JDK_TOPDIR)/src/solaris/classes/sun/awt/X11/generator
+# The pre-calculated offset file are stored here:
+GENSRC_SIZER_DIR := $(JDK_TOPDIR)/src/solaris/classes/sun/awt/X11/generator
 
-# Normal case is to generate version according to target bits
-GENSRC_SIZES := sizes.$(OPENJDK_TARGET_CPU_BITS)
-
+# Normal case is to generate only according to target bits
+GENSRC_X11_VERSION := $(OPENJDK_TARGET_CPU_BITS)
 ifeq ($(OPENJDK_TARGET_CPU_BITS), 64)
-ifneq ($(OPENJDK_TARGET_OS), linux)
-# On all 64-bit systems except Linux, generate both 32 and 64 bit versions
-GENSRC_SIZES := sizes.32 sizes.64
-endif
+  ifneq ($(OPENJDK_TARGET_OS), linux)
+  # On all 64-bit systems except Linux, generate both 32 and 64 bit versions
+  GENSRC_X11_VERSION := 32 64
+  endif
 else
-ifeq ($(OPENJDK_TARGET_OS), solaris)
-# As a special case, solaris 32-bit also generates the 64-bit version
-GENSRC_SIZES := sizes.32 sizes.64
-endif
+  ifeq ($(OPENJDK_TARGET_OS), solaris)
+  # As a special case, solaris 32-bit also generates the 64-bit version
+  GENSRC_X11_VERSION := 32 64
+  endif
 endif
 
-##########################################################################################
+GENSRC_X11_SIZES_USED := $(addprefix $(GENSRC_X11WRAPPERS_TMP)/sizes.,$(GENSRC_X11_VERSION))
+
+# Copy only the sizes.* files that are actually needed. WrapperGenerator picks up any it finds from the 
+# file prefix it is given so those not needed need to be hidden.
+$(GENSRC_X11WRAPPERS_TMP)/sizes.%: $(GENSRC_SIZER_DIR)/sizes.%
+	$(MKDIR) -p $(@D)
+	$(RM) '$@'
+	$(SORT) $< > $@
 
-$(GENSRC_X11WRAPPERS_TMP)/sizer/sizer.%.c : $(GENSRC_SIZER_SRC)/xlibtypes.txt
+# Run the tool on the offset files copied from the source repository to generate several Java classes 
+# used in awt.
+$(JDK_OUTPUTDIR)/gensrc/_the.generated.x11 : $(GENSRC_X11_SIZES_USED) $(BUILD_TOOLS)
+	$(MKDIR) -p $(GENSRC_X11WRAPPERS_DST)
+	$(TOOL_WRAPPERGENERATOR) $(GENSRC_X11WRAPPERS_DST) $(GENSRC_SIZER_DIR)/xlibtypes.txt "gen" $(GENSRC_X11WRAPPERS_TMP)/sizes
+	$(TOUCH) $@
+
+GENSRC_X11WRAPPERS += $(JDK_OUTPUTDIR)/gensrc/_the.generated.x11
+
+ifneq ($(COMPILE_TYPE),cross)
+    # This is not a cross compile, regenerate the offset file, so that we
+    # can compare it with the version in the source code repository.
+
+    # Generate the C code for the program that will output the offset file.
+    $(GENSRC_X11WRAPPERS_TMP)/sizer.%.c : $(GENSRC_SIZER_DIR)/xlibtypes.txt $(BUILD_TOOLS)
 	$(ECHO) "Generating X11 wrapper ($*-bit version)"
 	$(MKDIR) -p $(@D)
-	$(RM) $@
-	$(TOOL_WRAPPERGENERATOR) $(@D) $< "sizer" $*
+	$(TOOL_WRAPPERGENERATOR) $(@D) $(GENSRC_SIZER_DIR)/xlibtypes.txt "sizer" $*
 
-$(GENSRC_X11WRAPPERS_TMP)/sizer/sizer.%.exe : $(GENSRC_X11WRAPPERS_TMP)/sizer/sizer.%.c
+    # Compile the C code into an executable.
+    $(GENSRC_X11WRAPPERS_TMP)/sizer.%.exe : $(GENSRC_X11WRAPPERS_TMP)/sizer.%.c
 	$(MKDIR) -p $(@D)
-	$(RM) $@ $@.tmp
-	(cd $(@D) && $(BUILD_CC) -m$* -o $@.tmp $< \
+	(cd $(@D) && $(CC) -m$* -o $@ $< \
               $(X_CFLAGS) \
               $(X_LIBS) \
               -I$(JDK_OUTPUTDIR)/include \
               -I$(JDK_TOPDIR)/src/share/javavm/export \
               -I$(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/javavm/export \
-              -I$(JDK_TOPDIR)//src/share/native/common \
+              -I$(JDK_TOPDIR)/src/share/native/common \
               -I$(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/common \
               -I$(JDK_TOPDIR)/src/solaris/native/sun/awt \
 	      -I$(JDK_TOPDIR)/src/share/native/sun/awt/debug \
 	      -I$(JDK_TOPDIR)/src/share/native/sun/awt/image/cvutils -lc)
-	$(MV) $@.tmp $@
+
+    .PRECIOUS: $(GENSRC_X11WRAPPERS_TMP)/sizer.%.exe $(GENSRC_X11WRAPPERS_TMP)/sizer.%.c
 
-# Run the generated sizer binary to create the sizes text file
-$(GENSRC_X11WRAPPERS_TMP)/sizer/sizes.% : $(GENSRC_X11WRAPPERS_TMP)/sizer/sizer.%.exe
+    # Run the executable create the offset file and check that it is identical
+    # to the offset file in the source code repository.
+    $(GENSRC_X11WRAPPERS_TMP)/sizes.%.verification : $(GENSRC_X11WRAPPERS_TMP)/sizer.%.exe
 	$(MKDIR) -p $(@D)
-	$(RM) $@ $@.tmp
-	$< > $@.tmp
-	$(MV) $@.tmp $@
+	$(GENSRC_X11WRAPPERS_TMP)/sizer.$*.exe | $(SORT) > $@.tmp
+	$(ECHO) Verifying $(GENSRC_X11WRAPPERS_TMP)/sizes.$*.verification.tmp to $(GENSRC_X11WRAPPERS_TMP)/sizes.$*
+	$(DIFF) $(GENSRC_X11WRAPPERS_TMP)/sizes.$*.verification.tmp $(GENSRC_X11WRAPPERS_TMP)/sizes.$*
+	mv $@.tmp $@
 
-ifeq ($(OPENJDK_TARGET_OS)-$(OPENJDK_TARGET_CPU), solaris-x86)
-  # On solaris-x86 we also need to create the 64-bit version, but we can't run a 64-bit binary
-  # As a workaround, copy this from a pre-generated file.
-$(GENSRC_X11WRAPPERS_TMP)/sizer/sizes.64 : $(JDK_TOPDIR)/src/solaris/classes/sun/awt/X11/generator/sizes.64-solaris-i386
-	$(MKDIR) -p $(@D)
-	$(RM) $@
-	$(CP) $< $@
+    GENSRC_X11WRAPPERS += $(GENSRC_X11WRAPPERS_TMP)/sizes.$(OPENJDK_TARGET_CPU_BITS).verification
 endif
 
-$(GENSRC_X11WRAPPERS_DST)/_the.generated.x11 : $(foreach S,$(GENSRC_SIZES),$(GENSRC_X11WRAPPERS_TMP)/sizer/$(S))
-	$(RM) $@
-	$(MKDIR) -p $(@D)/sun/awt/X11
-	$(TOOL_WRAPPERGENERATOR) $(@D)/sun/awt/X11 $(GENSRC_SIZER_SRC)/xlibtypes.txt "gen" $(GENSRC_X11WRAPPERS_TMP)/sizer/sizes
-ifeq ($(OPENJDK_TARGET_OS)-$(OPENJDK_TARGET_CPU), solaris-x86_64)
-  # On solaris-x86_64, as a safety measure, compare the generated file with the checked-in version 
-	$(ECHO) COMPARING $(GENSRC_X11WRAPPERS_TMP)/sizer/sizes.64 and $(GENSRC_SIZER_SRC)/sizes.64-solaris-i386
-	$(DIFF) $(GENSRC_X11WRAPPERS_TMP)/sizer/sizes.64 $(GENSRC_SIZER_SRC)/sizes.64-solaris-i386
-endif
-	$(TOUCH) $@
-
-GENSRC_X11WRAPPERS += $(GENSRC_X11WRAPPERS_DST)/_the.generated.x11
--- a/jdk/makefiles/Images.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/Images.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -30,6 +30,15 @@
 
 default: images
 
+# Prepare the find cache. Only used if running on windows.
+$(eval $(call FillCacheFind,\
+    $(wildcard $(JDK_OUTPUTDIR)/bin \
+               $(JDK_OUTPUTDIR)/lib \
+               $(IMAGES_OUTPUTDIR)/lib \
+               $(JDK_OUTPUTDIR)/include \
+               $(JDK_OUTPUTDIR)/sample \
+               $(JDK_OUTPUTDIR)/demo)))
+
 include Tools.gmk
 
 # Note: This double-colon rule is intentional, to support
@@ -68,12 +77,6 @@
   $4 += $2/$$($2_$3_FILE)
 endef
 
-JDK_IMAGE_DIR:=$(IMAGES_OUTPUTDIR)/j2sdk-image
-JRE_IMAGE_DIR:=$(IMAGES_OUTPUTDIR)/j2re-image
-
-JDK_OVERLAY_IMAGE_DIR:=$(IMAGES_OUTPUTDIR)/j2sdk-overlay-image
-JRE_OVERLAY_IMAGE_DIR:=$(IMAGES_OUTPUTDIR)/j2re-overlay-image
-
 ################################################################################
 #
 # JRE and JDK build rules
@@ -100,6 +103,7 @@
 	javadoc$(EXE_SUFFIX) \
 	javah$(EXE_SUFFIX) \
 	javap$(EXE_SUFFIX) \
+	jdeps$(EXE_SUFFIX) \
 	jcmd$(EXE_SUFFIX) \
 	jdb$(EXE_SUFFIX) \
 	jps$(EXE_SUFFIX) \
@@ -132,7 +136,7 @@
 	$(SALIB_NAME)
 
 # Find all files in bin dir
-ALL_BIN_LIST := $(shell $(FIND) $(JDK_OUTPUTDIR)/bin -type f)
+ALL_BIN_LIST := $(call CacheFind,$(JDK_OUTPUTDIR)/bin)
 
 # Prevent sjavac from entering the images.
 ALL_BIN_LIST := $(filter-out %/sjavac,$(ALL_BIN_LIST))
@@ -144,7 +148,7 @@
 else
 # On windows, the libraries are in the bin dir, only filter out debuginfo files
 # for executables. "java" is both a library and executable.
-    ALL_BIN_EXEC_FILES := $(filter-out java.exe,$(notdir $(shell $(FIND) $(JDK_OUTPUTDIR)/bin -type f -name "*.exe")))
+    ALL_BIN_EXEC_FILES := $(filter-out java.exe,$(notdir $(filter %.exe,$(ALL_BIN_LIST))))
     ALL_BIN_DEBUG_FILTER := $(addprefix %,$(patsubst %.exe,%.debuginfo,$(ALL_BIN_EXEC_FILES)) \
 					   $(patsubst %.exe,%.diz,$(ALL_BIN_EXEC_FILES))) %.pdb
     ALL_BIN_LIST := $(filter-out $(ALL_BIN_DEBUG_FILTER),$(ALL_BIN_LIST))
@@ -212,13 +216,13 @@
 
 # Find all files to copy from $(JDK_OUTPUTDIR)/lib
 # Jar files are not expected to be here
-ALL_JDKOUT_LIB_LIST := $(shell $(FIND) $(JDK_OUTPUTDIR)/lib \( -type f -o -type l \) -a ! \
-                       \( -name "_the*" -o -name "javac_state " -o -name "*.jar" \) )
+ALL_JDKOUT_LIB_LIST := $(call not-containing,_the.,$(filter-out %.jar,\
+                            $(call CacheFind,$(JDK_OUTPUTDIR)/lib)))
 # Find all files to copy from $(IMAGES_OUTPUTDIR)/lib
 # This is were the jar files are and might not exist if building overlay-images
 ifneq ($(wildcard $(IMAGES_OUTPUTDIR)/lib),)
-    ALL_IMAGES_LIB_LIST := $(shell $(FIND) $(IMAGES_OUTPUTDIR)/lib \( -type f -o -type l \) -a ! \
-                       \( -name "_the*" -o -name "javac_state " \) )
+    ALL_IMAGES_LIB_LIST := $(call not-containing,_the.,\
+                            $(call CacheFind,$(IMAGES_OUTPUTDIR)/lib))
 endif
 
 # Filter files to copy for each destination
@@ -493,13 +497,13 @@
 
     JDK_OVERLAY_DEMO_TARGETS += $$($1_TARGET)
 endef
-JDK_OVERLAY_DEMO_SOURCES := $(shell $(FIND) $(JDK_OUTPUTDIR)/demo -name "*$(SHARED_LIBRARY_SUFFIX)")
+JDK_OVERLAY_DEMO_SOURCES := $(filter %$(SHARED_LIBRARY_SUFFIX),$(call CacheFind,$(JDK_OUTPUTDIR)/demo))
 $(foreach lib,$(JDK_OVERLAY_DEMO_SOURCES),$(eval $(call CreateOverlayDemoRule,$(lib))))
 
 ################################################################################
 # /sample dir
 
-$(foreach f,$(shell $(FIND) $(JDK_OUTPUTDIR)/sample -type f),\
+$(foreach f,$(call CacheFind,$(JDK_OUTPUTDIR)/sample),\
     $(eval $(call AddFileToCopy,$(JDK_OUTPUTDIR),$(JDK_IMAGE_DIR),$f,JDK_SAMPLE_TARGETS)))
 
 ################################################################################
@@ -518,7 +522,7 @@
 	$(install-file)
 
     JDK_DB_TARGETS := $(patsubst $(JDK_TOPDIR)/src/closed/share/db/%,$(IMAGES_OUTPUTDIR)/_unzip/%.unzipped,\
-			$(shell $(FIND) $(JDK_TOPDIR)/src/closed/share/db -name "*.zip" ! -name "*demo*")) \
+			$(call not-containing,demo,$(wildcard $(JDK_TOPDIR)/src/closed/share/db/*.zip))) \
 		      $(JDK_IMAGE_DIR)/db/README-JDK.html
 
 endif
@@ -526,7 +530,7 @@
 ################################################################################
 # /include dir
 
-$(foreach f,$(shell $(FIND) $(JDK_OUTPUTDIR)/include -type f),\
+$(foreach f,$(call CacheFind,$(JDK_OUTPUTDIR)/include),\
     $(eval $(call AddFileToCopy,$(JDK_OUTPUTDIR),$(JDK_IMAGE_DIR),$f,JDK_INCLUDE_TARGETS)))
 
 ################################################################################
@@ -625,8 +629,7 @@
 
 ifneq ($(POST_STRIP_CMD),)
     ifeq ($(OPENJDK_TARGET_OS), windows)
-        EXEC_LIST_BIN:=$(shell $(FIND) $(JDK_OUTPUTDIR)/bin -type f -name \*.exe \
-		-o -name \*.dll | $(EGREP) -v -i "$(MSVCR_DLL)")
+        EXEC_LIST_BIN:=$(filter-out %$(notdir $(MSVCR_DLL)),$(filter %.exe %.dll,$(ALL_BIN_LIST)))
     else
         # Find all executables in JDK_OUTPUTDIR since they exist when this makefile is parsed
         EXEC_LIST_BIN:=$(shell $(FILE) `$(FIND) $(JDK_OUTPUTDIR)/bin -type f -name \*$(EXE_SUFFIX)` \
--- a/jdk/makefiles/Import.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/Import.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -170,18 +170,11 @@
 $(INSTALL_LIBRARIES_HERE)/server/%.diz : $(INSTALL_LIBRARIES_HERE)/%.diz
 	$(MKDIR) -p $(@D)
 	$(RM) $@
-ifeq (REALLY_WEIRD,1)
-	$(LN) -s ../$(@F) $@
-else
-#
-# TODO: Check if this is what they really want...a zip containing a symlink
-#
 	$(RM) $@.tmp $(basename $@).debuginfo
 	$(LN) -s ../$(basename $(@F)).debuginfo $(basename $@).debuginfo
-	$(ZIP) -q -y $@.tmp $(basename $@).debuginfo
+	$(CD) $(@D) && $(ZIP) -q -y $@.tmp $(basename $(@F)).debuginfo
 	$(RM) $(basename $@).debuginfo
 	$(MV) $@.tmp $@
-endif
 
 $(INSTALL_LIBRARIES_HERE)/client/%$(SHARED_LIBRARY_SUFFIX) : $(INSTALL_LIBRARIES_HERE)/%$(SHARED_LIBRARY_SUFFIX)
 	$(MKDIR) -p $(@D)
@@ -196,18 +189,11 @@
 $(INSTALL_LIBRARIES_HERE)/client/%.diz : $(INSTALL_LIBRARIES_HERE)/%.diz
 	$(MKDIR) -p $(@D)
 	$(RM) $@
-ifeq (REALLY_WEIRD,1)
-	$(LN) -s ../$(@F) $@
-else
-#
-# TODO: Check if this is what they really want...a zip containing a symlink
-#
 	$(RM) $@.tmp $(basename $@).debuginfo
 	$(LN) -s ../$(basename $(@F)).debuginfo $(basename $@).debuginfo
-	$(ZIP) -q -y $@.tmp $(basename $@).debuginfo
+	$(CD) $(@D) && $(ZIP) -q -y $@.tmp $(basename $(@F)).debuginfo
 	$(RM) $(basename $@).debuginfo
 	$(MV) $@.tmp $@
-endif
 
 #######
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/makefiles/SignJars.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,104 @@
+#
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+include $(SPEC)
+include MakeBase.gmk
+
+# (The terms "OpenJDK" and "JDK" below refer to OpenJDK and Oracle JDK 
+# builds respectively.)
+#
+# JCE builds are very different between OpenJDK and JDK.  The OpenJDK JCE
+# jar files do not require signing, but those for JDK do.  If an unsigned
+# jar file is installed into JDK, things will break when the crypto
+# routines are called.
+#
+# All jars are created in CreateJars.gmk. This Makefile does the signing
+# of the jars for JDK.
+#
+# For JDK, the binaries use pre-built/pre-signed binary files stored in
+# the closed workspace that are not shipped in the OpenJDK workspaces.
+# We still build the JDK files to verify the files compile, and in
+# preparation for possible signing.  Developers working on JCE in JDK
+# must sign the JCE files before testing.  The JCE signing key is kept
+# separate from the JDK workspace to prevent its disclosure.
+#
+# SPECIAL NOTE TO JCE/JDK developers:  The source files must eventually
+# be built, signed, and then the resulting jar files MUST BE CHECKED
+# INTO THE CLOSED PART OF THE WORKSPACE*.  This separate step *MUST NOT
+# BE FORGOTTEN*, otherwise a bug fixed in the source code will not be
+# reflected in the shipped binaries.  The "sign-jars" target in the top
+# level Makefile should be used to generate the required files.
+#
+
+# Default target
+all:
+
+ifndef OPENJDK
+
+README-MAKEFILE_WARNING := \
+    "\nPlease read makefiles/SignJars.gmk for further build instructions.\n"
+
+#
+# Location for JCE codesigning key.
+#
+SIGNING_KEY_DIR    := /security/ws/JCE-signing/src
+SIGNING_KEYSTORE   := $(SIGNING_KEY_DIR)/KeyStore.jks
+SIGNING_PASSPHRASE := $(SIGNING_KEY_DIR)/passphrase.txt
+SIGNING_ALIAS      := oracle_jce_rsa
+
+#
+# Defines for signing the various jar files.
+#
+check-keystore:
+	@if [ ! -f $(SIGNING_KEYSTORE) -o ! -f $(SIGNING_PASSPHRASE) ]; then \
+	    $(PRINTF) "\n$(SIGNING_KEYSTORE): Signing mechanism *NOT* available..."; \
+	    $(PRINTF) $(README-MAKEFILE_WARNING); \
+	    exit 2; \
+	fi
+
+$(JCE_OUTPUTDIR)/%: $(IMAGES_OUTPUTDIR)/unsigned/%
+	$(MKDIR) -p $(@D)
+	$(CP) $< $@
+	$(JARSIGNER) -keystore $(SIGNING_KEYSTORE) \
+	    $@ $(SIGNING_ALIAS) < $(SIGNING_PASSPHRASE)
+	@$(PRINTF) "\nJar codesigning finished.\n"
+
+JAR_LIST := jce.jar \
+            local_policy.jar \
+            sunec.jar \
+            sunjce_provider.jar \
+            sunpkcs11.jar \
+            US_export_policy.jar
+
+SIGNED_JARS := $(addprefix $(JCE_OUTPUTDIR)/,$(JAR_LIST))
+
+$(SIGNED_JARS): check-keystore
+
+all: $(SIGNED_JARS)
+	@$(PRINTF) "\n***The jar files built by the 'jar-sign' target must***"
+	@$(PRINTF) "\n***still be checked into the closed workspace!     ***"
+	@$(PRINTF)  $(README-MAKEFILE_WARNING)
+
+endif  # !OPENJDK
--- a/jdk/makefiles/Tools.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/makefiles/Tools.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -23,15 +23,25 @@
 # questions.
 #
 
+# Cache all finds needed for this file. Only used on windows.
+$(eval $(call FillCacheFind,$(JDK_TOPDIR)/make/tools \
+    $(JDK_TOPDIR)/src/solaris/classes \
+    $(JDK_TOPDIR)/makefiles/sun))
+
+TOOLS_SRC:=$(JDK_TOPDIR)/make/tools/src \
+           $(JDK_TOPDIR)/makefiles/sun/awt/X11 \
+           $(JDK_TOPDIR)/makefiles/sun/osxapp \
+           $(JDK_TOPDIR)/make/tools/swing-beans
+
+ifneq ($(OPENJDK_TARGET_OS),windows)
+  TOOLS_SRC+=$(JDK_TOPDIR)/src/solaris/classes/sun/awt/X11/generator
+endif
+
 # The exception handling of swing beaninfo which have the own tool directory
 ifeq (,$(BUILD_TOOLS))
 $(eval $(call SetupJavaCompilation,BUILD_TOOLS,\
                 SETUP:=GENERATE_OLDBYTECODE,\
-		SRC:=$(JDK_TOPDIR)/make/tools/src \
-                     $(JDK_TOPDIR)/src/solaris/classes/sun/awt/X11/generator \
-                     $(JDK_TOPDIR)/makefiles/sun/awt/X11 \
-                     $(JDK_TOPDIR)/makefiles/sun/osxapp \
-                     $(JDK_TOPDIR)/make/tools/swing-beans,\
+		SRC:=$(TOOLS_SRC),\
 		BIN:=$(JDK_OUTPUTDIR)/btclasses))
 
 endif
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java	Tue Jan 22 11:54:16 2013 -0800
@@ -119,7 +119,9 @@
 
     public void handleWindowFocusEvent(boolean parentWindowActive) {
         this.parentWindowActive = parentWindowActive;
-        if (focused) {
+        // ignore focus "lost" native request as it may mistakenly
+        // deactivate active window (see 8001161)
+        if (focused && parentWindowActive) {
             responder.handleWindowFocusEvent(parentWindowActive, null);
         }
     }
--- a/jdk/src/macosx/native/sun/font/CCharToGlyphMapper.m	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/macosx/native/sun/font/CCharToGlyphMapper.m	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
+ * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
  */
 
 #import <JavaNativeFoundation/JavaNativeFoundation.h>
--- a/jdk/src/share/classes/com/sun/crypto/provider/AESCipher.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/AESCipher.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,7 @@
 import javax.crypto.*;
 import javax.crypto.spec.*;
 import javax.crypto.BadPaddingException;
+import java.nio.ByteBuffer;
 
 /**
  * This class implements the AES algorithm in its various modes
@@ -127,6 +128,21 @@
             super(32, "CFB", "NOPADDING");
         }
     }
+    public static final class AES128_GCM_NoPadding extends OidImpl {
+        public AES128_GCM_NoPadding() {
+            super(16, "GCM", "NOPADDING");
+        }
+    }
+    public static final class AES192_GCM_NoPadding extends OidImpl {
+        public AES192_GCM_NoPadding() {
+            super(24, "GCM", "NOPADDING");
+        }
+    }
+    public static final class AES256_GCM_NoPadding extends OidImpl {
+        public AES256_GCM_NoPadding() {
+            super(32, "GCM", "NOPADDING");
+        }
+    }
 
     // utility method used by AESCipher and AESWrapCipher
     static final void checkKeySize(Key key, int fixedKeySize)
@@ -531,4 +547,79 @@
         return core.unwrap(wrappedKey, wrappedKeyAlgorithm,
                            wrappedKeyType);
     }
+
+    /**
+     * Continues a multi-part update of the Additional Authentication
+     * Data (AAD), using a subset of the provided buffer.
+     * <p>
+     * Calls to this method provide AAD to the cipher when operating in
+     * modes such as AEAD (GCM/CCM).  If this cipher is operating in
+     * either GCM or CCM mode, all AAD must be supplied before beginning
+     * operations on the ciphertext (via the {@code update} and {@code
+     * doFinal} methods).
+     *
+     * @param src the buffer containing the AAD
+     * @param offset the offset in {@code src} where the AAD input starts
+     * @param len the number of AAD bytes
+     *
+     * @throws IllegalStateException if this cipher is in a wrong state
+     * (e.g., has not been initialized), does not accept AAD, or if
+     * operating in either GCM or CCM mode and one of the {@code update}
+     * methods has already been called for the active
+     * encryption/decryption operation
+     * @throws UnsupportedOperationException if this method
+     * has not been overridden by an implementation
+     *
+     * @since 1.8
+     */
+    @Override
+    protected void engineUpdateAAD(byte[] src, int offset, int len) {
+        core.updateAAD(src, offset, len);
+    }
+
+    /**
+     * Continues a multi-part update of the Additional Authentication
+     * Data (AAD).
+     * <p>
+     * Calls to this method provide AAD to the cipher when operating in
+     * modes such as AEAD (GCM/CCM).  If this cipher is operating in
+     * either GCM or CCM mode, all AAD must be supplied before beginning
+     * operations on the ciphertext (via the {@code update} and {@code
+     * doFinal} methods).
+     * <p>
+     * All {@code src.remaining()} bytes starting at
+     * {@code src.position()} are processed.
+     * Upon return, the input buffer's position will be equal
+     * to its limit; its limit will not have changed.
+     *
+     * @param src the buffer containing the AAD
+     *
+     * @throws IllegalStateException if this cipher is in a wrong state
+     * (e.g., has not been initialized), does not accept AAD, or if
+     * operating in either GCM or CCM mode and one of the {@code update}
+     * methods has already been called for the active
+     * encryption/decryption operation
+     * @throws UnsupportedOperationException if this method
+     * has not been overridden by an implementation
+     *
+     * @since 1.8
+     */
+    @Override
+    protected void engineUpdateAAD(ByteBuffer src) {
+        if (src != null) {
+            int aadLen = src.limit() - src.position();
+            if (aadLen != 0) {
+                if (src.hasArray()) {
+                    int aadOfs = src.arrayOffset() + src.position();
+                    core.updateAAD(src.array(), aadOfs, aadLen);
+                    src.position(src.limit());
+                } else {
+                    byte[] aad = new byte[aadLen];
+                    src.get(aad);
+                    core.updateAAD(aad, 0, aadLen);
+                }
+            }
+        }
+    }
 }
+
--- a/jdk/src/share/classes/com/sun/crypto/provider/AESKeyGenerator.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/AESKeyGenerator.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -106,7 +106,7 @@
         SecretKeySpec aesKey = null;
 
         if (this.random == null) {
-            this.random = SunJCE.RANDOM;
+            this.random = SunJCE.getRandom();
         }
 
         byte[] keyBytes = new byte[keySize];
--- a/jdk/src/share/classes/com/sun/crypto/provider/BlowfishKeyGenerator.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/BlowfishKeyGenerator.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -104,7 +104,7 @@
      */
     protected SecretKey engineGenerateKey() {
         if (this.random == null) {
-            this.random = SunJCE.RANDOM;
+            this.random = SunJCE.getRandom();
         }
 
         byte[] keyBytes = new byte[this.keysize];
--- a/jdk/src/share/classes/com/sun/crypto/provider/CipherCore.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/CipherCore.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
 
 package com.sun.crypto.provider;
 
+import java.util.Arrays;
 import java.util.Locale;
 
 import java.security.*;
@@ -59,7 +60,7 @@
     private byte[] buffer = null;
 
     /*
-     * internal buffer
+     * block size of cipher in bytes
      */
     private int blockSize = 0;
 
@@ -76,10 +77,12 @@
     /*
      * minimum number of bytes in the buffer required for
      * FeedbackCipher.encryptFinal()/decryptFinal() call.
-     * update() must buffer this many bytes before before starting
+     * update() must buffer this many bytes before starting
      * to encrypt/decrypt data.
-     * currently, only CTS mode has a non-zero value due to its special
-     * handling on the last two blocks (the last one may be incomplete).
+     * currently, only the following cases have non-zero values:
+     * 1) CTS mode - due to its special handling on the last two blocks
+     * (the last one may be incomplete).
+     * 2) GCM mode + decryption - due to its trailing tag bytes
      */
     private int minBytes = 0;
 
@@ -121,6 +124,24 @@
     private static final int PCBC_MODE = 4;
     private static final int CTR_MODE = 5;
     private static final int CTS_MODE = 6;
+    private static final int GCM_MODE = 7;
+
+    /*
+     * variables used for performing the GCM (key+iv) uniqueness check.
+     * To use GCM mode safely, the cipher object must be re-initialized
+     * with a different combination of key + iv values for each
+     * encryption operation. However, checking all past key + iv values
+     * isn't feasible. Thus, we only do a per-instance check of the
+     * key + iv values used in previous encryption.
+     * For decryption operations, no checking is necessary.
+     * NOTE: this key+iv check have to be done inside CipherCore class
+     * since CipherCore class buffers potential tag bytes in GCM mode
+     * and may not call GaloisCounterMode when there isn't sufficient
+     * input to process.
+     */
+    private boolean requireReinit = false;
+    private byte[] lastEncKey = null;
+    private byte[] lastEncIv = null;
 
     /**
      * Creates an instance of CipherCore with default ECB mode and
@@ -149,7 +170,7 @@
      * @param mode the cipher mode
      *
      * @exception NoSuchAlgorithmException if the requested cipher mode does
-     * not exist
+     * not exist for this cipher
      */
     void setMode(String mode) throws NoSuchAlgorithmException {
         if (mode == null)
@@ -165,30 +186,34 @@
         if (modeUpperCase.equals("CBC")) {
             cipherMode = CBC_MODE;
             cipher = new CipherBlockChaining(rawImpl);
-        }
-        else if (modeUpperCase.equals("CTS")) {
+        } else if (modeUpperCase.equals("CTS")) {
             cipherMode = CTS_MODE;
             cipher = new CipherTextStealing(rawImpl);
             minBytes = blockSize+1;
             padding = null;
-        }
-        else if (modeUpperCase.equals("CTR")) {
+        } else if (modeUpperCase.equals("CTR")) {
             cipherMode = CTR_MODE;
             cipher = new CounterMode(rawImpl);
             unitBytes = 1;
             padding = null;
-        }
-        else if (modeUpperCase.startsWith("CFB")) {
+        }  else if (modeUpperCase.startsWith("GCM")) {
+            // can only be used for block ciphers w/ 128-bit block size
+            if (blockSize != 16) {
+                throw new NoSuchAlgorithmException
+                    ("GCM mode can only be used for AES cipher");
+            }
+            cipherMode = GCM_MODE;
+            cipher = new GaloisCounterMode(rawImpl);
+            padding = null;
+        } else if (modeUpperCase.startsWith("CFB")) {
             cipherMode = CFB_MODE;
             unitBytes = getNumOfUnit(mode, "CFB".length(), blockSize);
             cipher = new CipherFeedback(rawImpl, unitBytes);
-        }
-        else if (modeUpperCase.startsWith("OFB")) {
+        } else if (modeUpperCase.startsWith("OFB")) {
             cipherMode = OFB_MODE;
             unitBytes = getNumOfUnit(mode, "OFB".length(), blockSize);
             cipher = new OutputFeedback(rawImpl, unitBytes);
-        }
-        else if (modeUpperCase.equals("PCBC")) {
+        } else if (modeUpperCase.equals("PCBC")) {
             cipherMode = PCBC_MODE;
             cipher = new PCBC(rawImpl);
         }
@@ -219,6 +244,7 @@
         return result;
     }
 
+
     /**
      * Sets the padding mechanism of this cipher.
      *
@@ -242,11 +268,27 @@
                                              + " not implemented");
         }
         if ((padding != null) &&
-            ((cipherMode == CTR_MODE) || (cipherMode == CTS_MODE))) {
+            ((cipherMode == CTR_MODE) || (cipherMode == CTS_MODE)
+             || (cipherMode == GCM_MODE))) {
             padding = null;
-            throw new NoSuchPaddingException
-                ((cipherMode == CTR_MODE? "CTR":"CTS") +
-                 " mode must be used with NoPadding");
+            String modeStr = null;
+            switch (cipherMode) {
+            case CTR_MODE:
+                modeStr = "CTR";
+                break;
+            case GCM_MODE:
+                modeStr = "GCM";
+                break;
+            case CTS_MODE:
+                modeStr = "CTS";
+                break;
+            default:
+                // should never happen
+            }
+            if (modeStr != null) {
+                throw new NoSuchPaddingException
+                    (modeStr + " mode must be used with NoPadding");
+            }
         }
     }
 
@@ -257,7 +299,7 @@
      * <code>inputLen</code> (in bytes).
      *
      * <p>This call takes into account any unprocessed (buffered) data from a
-     * previous <code>update</code> call, and padding.
+     * previous <code>update</code> call, padding, and AEAD tagging.
      *
      * <p>The actual output length of the next <code>update</code> or
      * <code>doFinal</code> call may be smaller than the length returned by
@@ -270,23 +312,60 @@
     int getOutputSize(int inputLen) {
         int totalLen = buffered + inputLen;
 
-        if (padding == null)
-            return totalLen;
+        // GCM: this call may be for either update() or doFinal(), so have to
+        // return the larger value of both
+        // Encryption: based on doFinal value: inputLen + tag
+        // Decryption: based on update value: inputLen
+        if (!decrypting && (cipherMode == GCM_MODE)) {
+            return (totalLen + ((GaloisCounterMode) cipher).getTagLen());
+        }
 
-        if (decrypting)
+        if (padding == null) {
             return totalLen;
+        }
+
+        if (decrypting) {
+            return totalLen;
+        }
 
         if (unitBytes != blockSize) {
-            if (totalLen < diffBlocksize)
+            if (totalLen < diffBlocksize) {
                 return diffBlocksize;
-            else
+            } else {
                 return (totalLen + blockSize -
                         ((totalLen - diffBlocksize) % blockSize));
+            }
         } else {
             return totalLen + padding.padLength(totalLen);
         }
     }
 
+    private int getOutputSizeByOperation(int inputLen, boolean isDoFinal) {
+        int totalLen = 0;
+        switch (cipherMode) {
+        case GCM_MODE:
+            totalLen = buffered + inputLen;
+            if (isDoFinal) {
+                int tagLen = ((GaloisCounterMode) cipher).getTagLen();
+                if (decrypting) {
+                    // need to get the actual value from cipher??
+                    // deduct tagLen
+                    totalLen -= tagLen;
+                } else {
+                    totalLen += tagLen;
+                }
+            }
+            if (totalLen < 0) {
+                totalLen = 0;
+            }
+            break;
+        default:
+             totalLen  = getOutputSize(inputLen);
+             break;
+        }
+        return totalLen;
+    }
+
     /**
      * Returns the initialization vector (IV) in a new buffer.
      *
@@ -318,34 +397,49 @@
      * does not use any parameters.
      */
     AlgorithmParameters getParameters(String algName) {
+        if (cipherMode == ECB_MODE) {
+            return null;
+        }
         AlgorithmParameters params = null;
-        if (cipherMode == ECB_MODE) return null;
+        AlgorithmParameterSpec spec;
         byte[] iv = getIV();
-        if (iv != null) {
-            AlgorithmParameterSpec ivSpec;
-            if (algName.equals("RC2")) {
-                RC2Crypt rawImpl = (RC2Crypt) cipher.getEmbeddedCipher();
-                ivSpec = new RC2ParameterSpec(rawImpl.getEffectiveKeyBits(),
-                                              iv);
+        if (iv == null) {
+            // generate spec using default value
+            if (cipherMode == GCM_MODE) {
+                iv = new byte[GaloisCounterMode.DEFAULT_IV_LEN];
             } else {
-                ivSpec = new IvParameterSpec(iv);
+                iv = new byte[blockSize];
             }
-            try {
-                params = AlgorithmParameters.getInstance(algName, "SunJCE");
-            } catch (NoSuchAlgorithmException nsae) {
-                // should never happen
-                throw new RuntimeException("Cannot find " + algName +
-                    " AlgorithmParameters implementation in SunJCE provider");
-            } catch (NoSuchProviderException nspe) {
-                // should never happen
-                throw new RuntimeException("Cannot find SunJCE provider");
-            }
-            try {
-                params.init(ivSpec);
-            } catch (InvalidParameterSpecException ipse) {
-                // should never happen
-                throw new RuntimeException("IvParameterSpec not supported");
-            }
+            SunJCE.getRandom().nextBytes(iv);
+        }
+        if (cipherMode == GCM_MODE) {
+            algName = "GCM";
+            spec = new GCMParameterSpec
+                (((GaloisCounterMode) cipher).getTagLen()*8, iv);
+        } else {
+           if (algName.equals("RC2")) {
+               RC2Crypt rawImpl = (RC2Crypt) cipher.getEmbeddedCipher();
+               spec = new RC2ParameterSpec
+                   (rawImpl.getEffectiveKeyBits(), iv);
+           } else {
+               spec = new IvParameterSpec(iv);
+           }
+        }
+        try {
+            params = AlgorithmParameters.getInstance(algName, "SunJCE");
+        } catch (NoSuchAlgorithmException nsae) {
+            // should never happen
+            throw new RuntimeException("Cannot find " + algName +
+                " AlgorithmParameters implementation in SunJCE provider");
+        } catch (NoSuchProviderException nspe) {
+            // should never happen
+            throw new RuntimeException("Cannot find SunJCE provider");
+        }
+        try {
+            params.init(spec);
+        } catch (InvalidParameterSpecException ipse) {
+            // should never happen
+            throw new RuntimeException(spec.getClass() + " not supported");
         }
         return params;
     }
@@ -420,44 +514,63 @@
                   || (opmode == Cipher.UNWRAP_MODE);
 
         byte[] keyBytes = getKeyBytes(key);
-
-        byte[] ivBytes;
-        if (params == null) {
-            ivBytes = null;
-        } else if (params instanceof IvParameterSpec) {
-            ivBytes = ((IvParameterSpec)params).getIV();
-            if ((ivBytes == null) || (ivBytes.length != blockSize)) {
-                throw new InvalidAlgorithmParameterException
-                    ("Wrong IV length: must be " + blockSize +
-                    " bytes long");
+        int tagLen = -1;
+        byte[] ivBytes = null;
+        if (params != null) {
+            if (cipherMode == GCM_MODE) {
+                if (params instanceof GCMParameterSpec) {
+                    tagLen = ((GCMParameterSpec)params).getTLen();
+                    if (tagLen < 96 || tagLen > 128 || ((tagLen & 0x07) != 0)) {
+                        throw new InvalidAlgorithmParameterException
+                            ("Unsupported TLen value; must be one of " +
+                             "{128, 120, 112, 104, 96}");
+                    }
+                    tagLen = tagLen >> 3;
+                    ivBytes = ((GCMParameterSpec)params).getIV();
+                } else {
+                    throw new InvalidAlgorithmParameterException
+                        ("Unsupported parameter: " + params);
+               }
+            } else {
+                if (params instanceof IvParameterSpec) {
+                    ivBytes = ((IvParameterSpec)params).getIV();
+                    if ((ivBytes == null) || (ivBytes.length != blockSize)) {
+                        throw new InvalidAlgorithmParameterException
+                            ("Wrong IV length: must be " + blockSize +
+                             " bytes long");
+                    }
+                } else if (params instanceof RC2ParameterSpec) {
+                    ivBytes = ((RC2ParameterSpec)params).getIV();
+                    if ((ivBytes != null) && (ivBytes.length != blockSize)) {
+                        throw new InvalidAlgorithmParameterException
+                            ("Wrong IV length: must be " + blockSize +
+                             " bytes long");
+                    }
+                } else {
+                    throw new InvalidAlgorithmParameterException
+                        ("Unsupported parameter: " + params);
+                }
             }
-        } else if (params instanceof RC2ParameterSpec) {
-            ivBytes = ((RC2ParameterSpec)params).getIV();
-            if ((ivBytes != null) && (ivBytes.length != blockSize)) {
-                throw new InvalidAlgorithmParameterException
-                    ("Wrong IV length: must be " + blockSize +
-                    " bytes long");
-            }
-        } else {
-            throw new InvalidAlgorithmParameterException("Wrong parameter "
-                                                         + "type: IV "
-                                                         + "expected");
         }
-
         if (cipherMode == ECB_MODE) {
             if (ivBytes != null) {
                 throw new InvalidAlgorithmParameterException
                                                 ("ECB mode cannot use IV");
             }
-        } else if (ivBytes == null) {
+        } else if (ivBytes == null)  {
             if (decrypting) {
                 throw new InvalidAlgorithmParameterException("Parameters "
                                                              + "missing");
             }
+
             if (random == null) {
-                random = SunJCE.RANDOM;
+                random = SunJCE.getRandom();
             }
-            ivBytes = new byte[blockSize];
+            if (cipherMode == GCM_MODE) {
+                ivBytes = new byte[GaloisCounterMode.DEFAULT_IV_LEN];
+            } else {
+                ivBytes = new byte[blockSize];
+            }
             random.nextBytes(ivBytes);
         }
 
@@ -466,23 +579,57 @@
 
         String algorithm = key.getAlgorithm();
 
-        cipher.init(decrypting, algorithm, keyBytes, ivBytes);
+        // GCM mode needs additional handling
+        if (cipherMode == GCM_MODE) {
+            if(tagLen == -1) {
+                tagLen = GaloisCounterMode.DEFAULT_TAG_LEN;
+            }
+            if (decrypting) {
+                minBytes = tagLen;
+            } else {
+                // check key+iv for encryption in GCM mode
+                requireReinit =
+                    Arrays.equals(ivBytes, lastEncIv) &&
+                    Arrays.equals(keyBytes, lastEncKey);
+                if (requireReinit) {
+                    throw new InvalidAlgorithmParameterException
+                        ("Cannot reuse iv for GCM encryption");
+                }
+                lastEncIv = ivBytes;
+                lastEncKey = keyBytes;
+            }
+            ((GaloisCounterMode) cipher).init
+                (decrypting, algorithm, keyBytes, ivBytes, tagLen);
+        } else {
+            cipher.init(decrypting, algorithm, keyBytes, ivBytes);
+        }
+        // skip checking key+iv from now on until after doFinal()
+        requireReinit = false;
     }
 
     void init(int opmode, Key key, AlgorithmParameters params,
               SecureRandom random)
         throws InvalidKeyException, InvalidAlgorithmParameterException {
-        IvParameterSpec ivSpec = null;
+        AlgorithmParameterSpec spec = null;
+        String paramType = null;
         if (params != null) {
             try {
-                ivSpec = params.getParameterSpec(IvParameterSpec.class);
+                if (cipherMode == GCM_MODE) {
+                    paramType = "GCM";
+                    spec = params.getParameterSpec(GCMParameterSpec.class);
+                } else {
+                    // NOTE: RC2 parameters are always handled through
+                    // init(..., AlgorithmParameterSpec,...) method, so
+                    // we can assume IvParameterSpec type here.
+                    paramType = "IV";
+                    spec = params.getParameterSpec(IvParameterSpec.class);
+                }
             } catch (InvalidParameterSpecException ipse) {
-                throw new InvalidAlgorithmParameterException("Wrong parameter "
-                                                             + "type: IV "
-                                                             + "expected");
+                throw new InvalidAlgorithmParameterException
+                    ("Wrong parameter type: " + paramType + " expected");
             }
         }
-        init(opmode, key, ivSpec, random);
+        init(opmode, key, spec, random);
     }
 
     /**
@@ -504,6 +651,7 @@
         return keyBytes;
     }
 
+
     /**
      * Continues a multiple-part encryption or decryption operation
      * (depending on how this cipher was initialized), processing another data
@@ -524,22 +672,25 @@
      * (e.g., has not been initialized)
      */
     byte[] update(byte[] input, int inputOffset, int inputLen) {
+        if (requireReinit) {
+            throw new IllegalStateException
+                ("Must use either different key or iv for GCM encryption");
+        }
+
         byte[] output = null;
-        byte[] out = null;
         try {
-            output = new byte[getOutputSize(inputLen)];
+            output = new byte[getOutputSizeByOperation(inputLen, false)];
             int len = update(input, inputOffset, inputLen, output,
                              0);
             if (len == output.length) {
-                out = output;
+                return output;
             } else {
-                out = new byte[len];
-                System.arraycopy(output, 0, out, 0, len);
+                return Arrays.copyOf(output, len);
             }
         } catch (ShortBufferException e) {
-            // never thrown
+            // should never happen
+            throw new ProviderException("Unexpected exception", e);
         }
-        return out;
     }
 
     /**
@@ -567,6 +718,11 @@
      */
     int update(byte[] input, int inputOffset, int inputLen, byte[] output,
                int outputOffset) throws ShortBufferException {
+        if (requireReinit) {
+            throw new IllegalStateException
+                ("Must use either different key or iv for GCM encryption");
+        }
+
         // figure out how much can be sent to crypto function
         int len = buffered + inputLen - minBytes;
         if (padding != null && decrypting) {
@@ -582,6 +738,7 @@
                                            + "(at least) " + len
                                            + " bytes long");
         }
+
         if (len != 0) {
             // there is some work to do
             byte[] in = new byte[len];
@@ -600,7 +757,6 @@
                 System.arraycopy(input, inputOffset, in,
                                  bufferedConsumed, inputConsumed);
             }
-
             if (decrypting) {
                 cipher.decrypt(in, 0, len, output, outputOffset);
             } else {
@@ -611,11 +767,12 @@
             // the total input length a multiple of blocksize when
             // padding is applied
             if (unitBytes != blockSize) {
-                if (len < diffBlocksize)
+                if (len < diffBlocksize) {
                     diffBlocksize -= len;
-                else
+                } else {
                     diffBlocksize = blockSize -
                         ((len - diffBlocksize) % blockSize);
+                }
             }
 
             inputLen -= inputConsumed;
@@ -669,21 +826,18 @@
     byte[] doFinal(byte[] input, int inputOffset, int inputLen)
         throws IllegalBlockSizeException, BadPaddingException {
         byte[] output = null;
-        byte[] out = null;
         try {
-            output = new byte[getOutputSize(inputLen)];
+            output = new byte[getOutputSizeByOperation(inputLen, true)];
             int len = doFinal(input, inputOffset, inputLen, output, 0);
             if (len < output.length) {
-                out = new byte[len];
-                if (len != 0)
-                    System.arraycopy(output, 0, out, 0, len);
+                return Arrays.copyOf(output, len);
             } else {
-                out = output;
+                return output;
             }
         } catch (ShortBufferException e) {
             // never thrown
+            throw new ProviderException("Unexpected exception", e);
         }
-        return out;
     }
 
     /**
@@ -726,6 +880,10 @@
                 int outputOffset)
         throws IllegalBlockSizeException, ShortBufferException,
                BadPaddingException {
+        if (requireReinit) {
+            throw new IllegalStateException
+                ("Must use either different key or iv for GCM encryption");
+        }
 
         // calculate the total input length
         int totalLen = buffered + inputLen;
@@ -752,8 +910,9 @@
         }
 
         // if encrypting and padding not null, add padding
-        if (!decrypting && padding != null)
+        if (!decrypting && padding != null) {
             paddedLen += paddingLen;
+        }
 
         // check output buffer capacity.
         // if we are decrypting with padding applied, we can perform this
@@ -763,8 +922,8 @@
             throw new ShortBufferException("Output buffer is null");
         }
         int outputCapacity = output.length - outputOffset;
-        if (((!decrypting) || (padding == null)) &&
-            (outputCapacity < paddedLen) ||
+
+        if (((!decrypting) && (outputCapacity < paddedLen)) ||
             (decrypting && (outputCapacity < (paddedLen - blockSize)))) {
             throw new ShortBufferException("Output buffer too short: "
                                            + outputCapacity + " bytes given, "
@@ -812,6 +971,7 @@
                 }
                 totalLen = padStart;
             }
+
             if ((output.length - outputOffset) < totalLen) {
                 // restore so users can retry with a larger buffer
                 cipher.restore();
@@ -824,8 +984,13 @@
                 output[outputOffset + i] = outWithPadding[i];
             }
         } else { // encrypting
-            totalLen = finalNoPadding(finalBuf, finalOffset, output,
-                                      outputOffset, paddedLen);
+            try {
+                totalLen = finalNoPadding(finalBuf, finalOffset, output,
+                                          outputOffset, paddedLen);
+            } finally {
+                // reset after doFinal() for GCM encryption
+                requireReinit = (cipherMode == GCM_MODE);
+            }
         }
 
         buffered = 0;
@@ -836,33 +1001,33 @@
         return totalLen;
     }
 
-    private int finalNoPadding(byte[] in, int inOff, byte[] out, int outOff,
+    private int finalNoPadding(byte[] in, int inOfs, byte[] out, int outOfs,
                                int len)
-        throws IllegalBlockSizeException
-    {
-        if (in == null || len == 0)
-            return 0;
+        throws IllegalBlockSizeException, AEADBadTagException {
 
-        if ((cipherMode != CFB_MODE) && (cipherMode != OFB_MODE)
-            && ((len % unitBytes) != 0) && (cipherMode != CTS_MODE)) {
-            if (padding != null) {
-                throw new IllegalBlockSizeException
-                    ("Input length (with padding) not multiple of " +
-                     unitBytes + " bytes");
-            } else {
-                throw new IllegalBlockSizeException
-                    ("Input length not multiple of " + unitBytes
-                     + " bytes");
-            }
+        if ((cipherMode != GCM_MODE) && (in == null || len == 0)) {
+            return 0;
         }
-
+        if ((cipherMode != CFB_MODE) && (cipherMode != OFB_MODE) &&
+            (cipherMode != GCM_MODE) &&
+            ((len % unitBytes) != 0) && (cipherMode != CTS_MODE)) {
+                if (padding != null) {
+                    throw new IllegalBlockSizeException
+                        ("Input length (with padding) not multiple of " +
+                         unitBytes + " bytes");
+                } else {
+                    throw new IllegalBlockSizeException
+                        ("Input length not multiple of " + unitBytes
+                         + " bytes");
+                }
+        }
+        int outLen = 0;
         if (decrypting) {
-            cipher.decryptFinal(in, inOff, len, out, outOff);
+            outLen = cipher.decryptFinal(in, inOfs, len, out, outOfs);
         } else {
-            cipher.encryptFinal(in, inOff, len, out, outOff);
+            outLen = cipher.encryptFinal(in, inOfs, len, out, outOfs);
         }
-
-        return len;
+        return outLen;
     }
 
     // Note: Wrap() and Unwrap() are the same in
@@ -939,4 +1104,36 @@
         return ConstructKeys.constructKey(encodedKey, wrappedKeyAlgorithm,
                                           wrappedKeyType);
     }
+
+    /**
+     * Continues a multi-part update of the Additional Authentication
+     * Data (AAD), using a subset of the provided buffer.
+     * <p>
+     * Calls to this method provide AAD to the cipher when operating in
+     * modes such as AEAD (GCM/CCM).  If this cipher is operating in
+     * either GCM or CCM mode, all AAD must be supplied before beginning
+     * operations on the ciphertext (via the {@code update} and {@code
+     * doFinal} methods).
+     *
+     * @param src the buffer containing the AAD
+     * @param offset the offset in {@code src} where the AAD input starts
+     * @param len the number of AAD bytes
+     *
+     * @throws IllegalStateException if this cipher is in a wrong state
+     * (e.g., has not been initialized), does not accept AAD, or if
+     * operating in either GCM or CCM mode and one of the {@code update}
+     * methods has already been called for the active
+     * encryption/decryption operation
+     * @throws UnsupportedOperationException if this method
+     * has not been overridden by an implementation
+     *
+     * @since 1.8
+     */
+    void updateAAD(byte[] src, int offset, int len) {
+        if (requireReinit) {
+            throw new IllegalStateException
+                ("Must use either different key or iv for GCM encryption");
+        }
+        cipher.updateAAD(src, offset, len);
+    }
 }
--- a/jdk/src/share/classes/com/sun/crypto/provider/CipherTextStealing.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/CipherTextStealing.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2007, 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
@@ -83,9 +83,10 @@
      * @param plainLen the length of the input data
      * @param cipher the buffer for the result
      * @param cipherOffset the offset in <code>cipher</code>
+     * @return the number of bytes placed into <code>cipher</code>
      */
-    void encryptFinal(byte[] plain, int plainOffset, int plainLen,
-                      byte[] cipher, int cipherOffset)
+    int encryptFinal(byte[] plain, int plainOffset, int plainLen,
+                     byte[] cipher, int cipherOffset)
         throws IllegalBlockSizeException {
 
         if (plainLen < blockSize) {
@@ -134,6 +135,7 @@
                 embeddedCipher.encryptBlock(tmp2, 0, cipher, cipherOffset);
             }
         }
+        return plainLen;
     }
 
     /**
@@ -158,9 +160,10 @@
      * @param cipherLen the length of the input data
      * @param plain the buffer for the result
      * @param plainOffset the offset in <code>plain</code>
+     * @return the number of bytes placed into <code>plain</code>
      */
-    void decryptFinal(byte[] cipher, int cipherOffset, int cipherLen,
-                      byte[] plain, int plainOffset)
+    int decryptFinal(byte[] cipher, int cipherOffset, int cipherLen,
+                     byte[] plain, int plainOffset)
         throws IllegalBlockSizeException {
         if (cipherLen < blockSize) {
             throw new IllegalBlockSizeException("input is too short!");
@@ -211,5 +214,6 @@
                 }
             }
         }
+        return cipherLen;
     }
 }
--- a/jdk/src/share/classes/com/sun/crypto/provider/DESKeyGenerator.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DESKeyGenerator.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2009, 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
@@ -102,7 +102,7 @@
         DESKey desKey = null;
 
         if (this.random == null) {
-            this.random = SunJCE.RANDOM;
+            this.random = SunJCE.getRandom();
         }
 
         try {
--- a/jdk/src/share/classes/com/sun/crypto/provider/DESedeKeyGenerator.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DESedeKeyGenerator.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2009, 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
@@ -105,7 +105,7 @@
      */
     protected SecretKey engineGenerateKey() {
         if (this.random == null) {
-            this.random = SunJCE.RANDOM;
+            this.random = SunJCE.getRandom();
         }
 
         byte[] rawkey = new byte[DESedeKeySpec.DES_EDE_KEY_LEN];
--- a/jdk/src/share/classes/com/sun/crypto/provider/DESedeWrapCipher.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DESedeWrapCipher.java	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -217,7 +217,7 @@
             if (params == null) {
                 iv = new byte[8];
                 if (random == null) {
-                    random = SunJCE.RANDOM;
+                    random = SunJCE.getRandom();
                 }
                 random.nextBytes(iv);
             }
--- a/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -140,7 +140,7 @@
      */
     public KeyPair generateKeyPair() {
         if (random == null) {
-            random = SunJCE.RANDOM;
+            random = SunJCE.getRandom();
         }
 
         if (params == null) {
--- a/jdk/src/share/classes/com/sun/crypto/provider/DHParameterGenerator.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DHParameterGenerator.java	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -131,7 +131,7 @@
         }
 
         if (this.random == null)
-            this.random = SunJCE.RANDOM;
+            this.random = SunJCE.getRandom();
 
         try {
             AlgorithmParameterGenerator paramGen;
--- a/jdk/src/share/classes/com/sun/crypto/provider/FeedbackCipher.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/FeedbackCipher.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2007, 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
@@ -26,7 +26,7 @@
 package com.sun.crypto.provider;
 
 import java.security.InvalidKeyException;
-import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.*;
 
 /**
  * This class represents a block cipher in one of its modes. It wraps
@@ -150,11 +150,13 @@
      * @param plainLen the length of the input data
      * @param cipher the buffer for the encryption result
      * @param cipherOffset the offset in <code>cipher</code>
+     * @return the number of bytes placed into <code>cipher</code>
      */
-     void encryptFinal(byte[] plain, int plainOffset, int plainLen,
-                       byte[] cipher, int cipherOffset)
+     int encryptFinal(byte[] plain, int plainOffset, int plainLen,
+                      byte[] cipher, int cipherOffset)
          throws IllegalBlockSizeException {
          encrypt(plain, plainOffset, plainLen, cipher, cipherOffset);
+         return plainLen;
      }
     /**
      * Performs decryption operation.
@@ -190,10 +192,40 @@
      * @param cipherLen the length of the input data
      * @param plain the buffer for the decryption result
      * @param plainOffset the offset in <code>plain</code>
+     * @return the number of bytes placed into <code>plain</code>
      */
-     void decryptFinal(byte[] cipher, int cipherOffset, int cipherLen,
-                       byte[] plain, int plainOffset)
-         throws IllegalBlockSizeException {
+     int decryptFinal(byte[] cipher, int cipherOffset, int cipherLen,
+                      byte[] plain, int plainOffset)
+         throws IllegalBlockSizeException, AEADBadTagException {
          decrypt(cipher, cipherOffset, cipherLen, plain, plainOffset);
+         return cipherLen;
      }
+
+    /**
+     * Continues a multi-part update of the Additional Authentication
+     * Data (AAD), using a subset of the provided buffer. If this
+     * cipher is operating in either GCM or CCM mode, all AAD must be
+     * supplied before beginning operations on the ciphertext (via the
+     * {@code update} and {@code doFinal} methods).
+     * <p>
+     * NOTE: Given most modes do not accept AAD, default impl for this
+     * method throws IllegalStateException.
+     *
+     * @param src the buffer containing the AAD
+     * @param offset the offset in {@code src} where the AAD input starts
+     * @param len the number of AAD bytes
+     *
+     * @throws IllegalStateException if this cipher is in a wrong state
+     * (e.g., has not been initialized), does not accept AAD, or if
+     * operating in either GCM or CCM mode and one of the {@code update}
+     * methods has already been called for the active
+     * encryption/decryption operation
+     * @throws UnsupportedOperationException if this method
+     * has not been overridden by an implementation
+     *
+     * @since 1.8
+     */
+    void updateAAD(byte[] src, int offset, int len) {
+        throw new IllegalStateException("No AAD accepted");
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/crypto/provider/GCMParameters.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.crypto.provider;
+
+import java.io.IOException;
+import java.security.AlgorithmParametersSpi;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.InvalidParameterSpecException;
+import javax.crypto.spec.GCMParameterSpec;
+import sun.misc.HexDumpEncoder;
+import sun.security.util.*;
+
+/**
+ * This class implements the parameter set used with
+ * GCM encryption, which is defined in RFC 5084 as follows:
+ *
+ * <pre>
+ *    GCMParameters ::= SEQUENCE {
+ *      aes-iv      OCTET STRING, -- recommended size is 12 octets
+ *      aes-tLen    AES-GCM-ICVlen DEFAULT 12 }
+ *
+ *    AES-GCM-ICVlen ::= INTEGER (12 | 13 | 14 | 15 | 16)
+ *
+ * </pre>
+ *
+ * @author Valerie Peng
+ * @since 1.8
+ */
+public final class GCMParameters extends AlgorithmParametersSpi {
+
+    // the iv
+    private byte[] iv;
+    // the tag length in bytes
+    private int tLen;
+
+    public GCMParameters() {}
+
+    protected void engineInit(AlgorithmParameterSpec paramSpec)
+        throws InvalidParameterSpecException {
+
+        if (!(paramSpec instanceof GCMParameterSpec)) {
+            throw new InvalidParameterSpecException
+                ("Inappropriate parameter specification");
+        }
+        GCMParameterSpec gps = (GCMParameterSpec) paramSpec;
+        // need to convert from bits to bytes for ASN.1 encoding
+        this.tLen = gps.getTLen()/8;
+        this.iv = gps.getIV();
+    }
+
+    protected void engineInit(byte[] encoded) throws IOException {
+        DerValue val = new DerValue(encoded);
+        // check if IV or params
+        if (val.tag == DerValue.tag_Sequence) {
+            byte[] iv = val.data.getOctetString();
+            int tLen;
+            if (val.data.available() != 0) {
+                tLen = val.data.getInteger();
+                if (tLen < 12 || tLen > 16 ) {
+                    throw new IOException
+                        ("GCM parameter parsing error: unsupported tag len: " +
+                         tLen);
+                }
+                if (val.data.available() != 0) {
+                    throw new IOException
+                        ("GCM parameter parsing error: extra data");
+                }
+            } else {
+                tLen = 12;
+            }
+            this.iv = iv.clone();
+            this.tLen = tLen;
+        } else {
+            throw new IOException("GCM parameter parsing error: no SEQ tag");
+        }
+    }
+
+    protected void engineInit(byte[] encoded, String decodingMethod)
+        throws IOException {
+        engineInit(encoded);
+    }
+
+    protected <T extends AlgorithmParameterSpec>
+            T engineGetParameterSpec(Class<T> paramSpec)
+        throws InvalidParameterSpecException {
+
+        if (GCMParameterSpec.class.isAssignableFrom(paramSpec)) {
+            return paramSpec.cast(new GCMParameterSpec(tLen * 8, iv));
+        } else {
+            throw new InvalidParameterSpecException
+                ("Inappropriate parameter specification");
+        }
+    }
+
+    protected byte[] engineGetEncoded() throws IOException {
+        DerOutputStream out = new DerOutputStream();
+        DerOutputStream bytes = new DerOutputStream();
+
+        bytes.putOctetString(iv);
+        bytes.putInteger(tLen);
+        out.write(DerValue.tag_Sequence, bytes);
+        return out.toByteArray();
+    }
+
+    protected byte[] engineGetEncoded(String encodingMethod)
+        throws IOException {
+        return engineGetEncoded();
+    }
+
+    /*
+     * Returns a formatted string describing the parameters.
+     */
+    protected String engineToString() {
+        String LINE_SEP = System.getProperty("line.separator");
+        HexDumpEncoder encoder = new HexDumpEncoder();
+        StringBuilder sb
+            = new StringBuilder(LINE_SEP + "    iv:" + LINE_SEP + "["
+                + encoder.encodeBuffer(iv) + "]");
+
+        sb.append(LINE_SEP + "tLen(bits):" + LINE_SEP + tLen*8 + LINE_SEP);
+        return sb.toString();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/crypto/provider/GCTR.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * (C) Copyright IBM Corp. 2013
+ */
+
+package com.sun.crypto.provider;
+
+import java.security.*;
+import javax.crypto.*;
+import static com.sun.crypto.provider.AESConstants.AES_BLOCK_SIZE;
+
+/**
+ * This class represents the GCTR function defined in NIST 800-38D
+ * under section 6.5. It needs to be constructed w/ an initialized
+ * cipher object, and initial counter block(ICB). Given an input X
+ * of arbitrary length, it processes and returns an output which has
+ * the same length as X.
+ *
+ * <p>This function is used in the implementation of GCM mode.
+ *
+ * @since 1.8
+ */
+final class GCTR {
+
+    // these fields should not change after the object has been constructed
+    private final SymmetricCipher aes;
+    private final byte[] icb;
+
+    // the current counter value
+    private byte[] counter;
+
+    // needed for save/restore calls
+    private byte[] counterSave;
+
+    // NOTE: cipher should already be initialized
+    GCTR(SymmetricCipher cipher, byte[] initialCounterBlk) {
+        this.aes = cipher;
+        this.icb = initialCounterBlk;
+        this.counter = icb.clone();
+    }
+
+    // input must be multiples of 128-bit blocks when calling update
+    int update(byte[] in, int inOfs, int inLen, byte[] out, int outOfs) {
+        if (inLen - inOfs > in.length) {
+            throw new RuntimeException("input length out of bound");
+        }
+        if (inLen < 0 || inLen % AES_BLOCK_SIZE != 0) {
+            throw new RuntimeException("input length unsupported");
+        }
+        if (out.length - outOfs < inLen) {
+            throw new RuntimeException("output buffer too small");
+        }
+
+        byte[] encryptedCntr = new byte[AES_BLOCK_SIZE];
+
+        int numOfCompleteBlocks = inLen / AES_BLOCK_SIZE;
+        for (int i = 0; i < numOfCompleteBlocks; i++) {
+            aes.encryptBlock(counter, 0, encryptedCntr, 0);
+            for (int n = 0; n < AES_BLOCK_SIZE; n++) {
+                int index = (i * AES_BLOCK_SIZE + n);
+                out[outOfs + index] =
+                    (byte) ((in[inOfs + index] ^ encryptedCntr[n]));
+            }
+            GaloisCounterMode.increment32(counter);
+        }
+        return inLen;
+    }
+
+    // input can be arbitrary size when calling doFinal
+    protected int doFinal(byte[] in, int inOfs, int inLen, byte[] out,
+                          int outOfs) throws IllegalBlockSizeException {
+        try {
+            if (inLen < 0) {
+                throw new IllegalBlockSizeException("Negative input size!");
+            } else if (inLen > 0) {
+                int lastBlockSize = inLen % AES_BLOCK_SIZE;
+                // process the complete blocks first
+                update(in, inOfs, inLen - lastBlockSize, out, outOfs);
+                if (lastBlockSize != 0) {
+                    // do the last partial block
+                    byte[] encryptedCntr = new byte[AES_BLOCK_SIZE];
+                    aes.encryptBlock(counter, 0, encryptedCntr, 0);
+
+                    int processed = inLen - lastBlockSize;
+                    for (int n = 0; n < lastBlockSize; n++) {
+                        out[outOfs + processed + n] =
+                            (byte) ((in[inOfs + processed + n] ^
+                                     encryptedCntr[n]));
+                    }
+                }
+            }
+        } finally {
+            reset();
+        }
+        return inLen;
+    }
+
+    /**
+     * Resets the current counter to its initial value.
+     * This is used after the doFinal() is called so this object can be
+     * reused w/o explicit re-initialization.
+     */
+    void reset() {
+        System.arraycopy(icb, 0, counter, 0, icb.length);
+    }
+
+    /**
+     * Save the current content of this object.
+     */
+    void save() {
+        this.counterSave = this.counter.clone();
+    }
+
+    /**
+     * Restores the content of this object to the previous saved one.
+     */
+    void restore() {
+        this.counter = this.counterSave;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/crypto/provider/GHASH.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ * (C) Copyright IBM Corp. 2013
+ */
+
+package com.sun.crypto.provider;
+
+import java.util.Arrays;
+import java.security.*;
+import static com.sun.crypto.provider.AESConstants.AES_BLOCK_SIZE;
+
+/**
+ * This class represents the GHASH function defined in NIST 800-38D
+ * under section 6.4. It needs to be constructed w/ a hash subkey, i.e.
+ * block H. Given input of 128-bit blocks, it will process and output
+ * a 128-bit block.
+ *
+ * <p>This function is used in the implementation of GCM mode.
+ *
+ * @since 1.8
+ */
+final class GHASH {
+
+    private static final byte P128 = (byte) 0xe1; //reduction polynomial
+
+    private static boolean getBit(byte[] b, int pos) {
+        int p = pos / 8;
+        pos %= 8;
+        int i = (b[p] >>> (7 - pos)) & 1;
+        return i != 0;
+    }
+
+    private static void shift(byte[] b) {
+        byte temp, temp2;
+        temp2 = 0;
+        for (int i = 0; i < b.length; i++) {
+            temp = (byte) ((b[i] & 0x01) << 7);
+            b[i] = (byte) ((b[i] & 0xff) >>> 1);
+            b[i] = (byte) (b[i] | temp2);
+            temp2 = temp;
+        }
+    }
+
+    // Given block X and Y, returns the muliplication of X * Y
+    private static byte[] blockMult(byte[] x, byte[] y) {
+        if (x.length != AES_BLOCK_SIZE || y.length != AES_BLOCK_SIZE) {
+            throw new RuntimeException("illegal input sizes");
+        }
+        byte[] z = new byte[AES_BLOCK_SIZE];
+        byte[] v = y.clone();
+        // calculate Z1-Z127 and V1-V127
+        for (int i = 0; i < 127; i++) {
+            // Zi+1 = Zi if bit i of x is 0
+            if (getBit(x, i)) {
+                for (int n = 0; n < z.length; n++) {
+                    z[n] ^= v[n];
+                }
+            }
+            boolean lastBitOfV = getBit(v, 127);
+            shift(v);
+            if (lastBitOfV) v[0] ^= P128;
+        }
+        // calculate Z128
+        if (getBit(x, 127)) {
+            for (int n = 0; n < z.length; n++) {
+                z[n] ^= v[n];
+            }
+        }
+        return z;
+    }
+
+    // hash subkey H; should not change after the object has been constructed
+    private final byte[] subkeyH;
+
+    // buffer for storing hash
+    private byte[] state;
+
+    // variables for save/restore calls
+    private byte[] stateSave = null;
+
+    /**
+     * Initializes the cipher in the specified mode with the given key
+     * and iv.
+     *
+     * @param subkeyH the hash subkey
+     *
+     * @exception ProviderException if the given key is inappropriate for
+     * initializing this digest
+     */
+    GHASH(byte[] subkeyH) throws ProviderException {
+        if ((subkeyH == null) || subkeyH.length != AES_BLOCK_SIZE) {
+            throw new ProviderException("Internal error");
+        }
+        this.subkeyH = subkeyH;
+        this.state = new byte[AES_BLOCK_SIZE];
+    }
+
+    /**
+     * Resets the GHASH object to its original state, i.e. blank w/
+     * the same subkey H. Used after digest() is called and to re-use
+     * this object for different data w/ the same H.
+     */
+    void reset() {
+        Arrays.fill(state, (byte) 0);
+    }
+
+    /**
+     * Save the current snapshot of this GHASH object.
+     */
+    void save() {
+        stateSave = state.clone();
+    }
+
+    /**
+     * Restores this object using the saved snapshot.
+     */
+    void restore() {
+        state = stateSave;
+    }
+
+    private void processBlock(byte[] data, int ofs) {
+        if (data.length - ofs < AES_BLOCK_SIZE) {
+            throw new RuntimeException("need complete block");
+        }
+        for (int n = 0; n < state.length; n++) {
+            state[n] ^= data[ofs + n];
+        }
+        state = blockMult(state, subkeyH);
+    }
+
+    void update(byte[] in) {
+        update(in, 0, in.length);
+    }
+
+    void update(byte[] in, int inOfs, int inLen) {
+        if (inLen - inOfs > in.length) {
+            throw new RuntimeException("input length out of bound");
+        }
+        if (inLen % AES_BLOCK_SIZE != 0) {
+            throw new RuntimeException("input length unsupported");
+        }
+
+        for (int i = inOfs; i < (inOfs + inLen); i += AES_BLOCK_SIZE) {
+            processBlock(in, i);
+        }
+    }
+
+    byte[] digest() {
+        try {
+            return state.clone();
+        } finally {
+            reset();
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/crypto/provider/GaloisCounterMode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,501 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.S
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.crypto.provider;
+
+import java.util.Arrays;
+import java.io.*;
+import java.security.*;
+import javax.crypto.*;
+import static com.sun.crypto.provider.AESConstants.AES_BLOCK_SIZE;
+
+/**
+ * This class represents ciphers in GaloisCounter (GCM) mode.
+ *
+ * <p>This mode currently should only be used w/ AES cipher.
+ * Although no checking is done here, caller should only
+ * pass AES Cipher to the constructor.
+ *
+ * <p>NOTE: This class does not deal with buffering or padding.
+ *
+ * @since 1.8
+ */
+final class GaloisCounterMode extends FeedbackCipher {
+
+    static int DEFAULT_TAG_LEN = AES_BLOCK_SIZE;
+    static int DEFAULT_IV_LEN = 12; // in bytes
+
+    // buffer for AAD data; if null, meaning update has been called
+    private ByteArrayOutputStream aadBuffer = new ByteArrayOutputStream();
+    private int sizeOfAAD = 0;
+
+    // in bytes; need to convert to bits (default value 128) when needed
+    private int tagLenBytes = DEFAULT_TAG_LEN;
+
+    // these following 2 fields can only be initialized after init() is
+    // called, e.g. after cipher key k is set, and STAY UNCHANGED
+    private byte[] subkeyH = null;
+    private byte[] preCounterBlock = null;
+
+    private GCTR gctrPAndC = null;
+    private GHASH ghashAllToS = null;
+
+    // length of total data, i.e. len(C)
+    private int processed = 0;
+
+    // additional variables for save/restore calls
+    private byte[] aadBufferSave = null;
+    private int sizeOfAADSave = 0;
+    private int processedSave = 0;
+
+    // value must be 16-byte long; used by GCTR and GHASH as well
+    static void increment32(byte[] value) {
+        if (value.length != AES_BLOCK_SIZE) {
+            throw new RuntimeException("Unexpected counter block length");
+        }
+        // start from last byte and only go over 4 bytes, i.e. total 32 bits
+        int n = value.length - 1;
+        while ((n >= value.length - 4) && (++value[n] == 0)) {
+            n--;
+        }
+    }
+
+    // ivLen in bits
+    private static byte[] getLengthBlock(int ivLen) {
+        byte[] out = new byte[AES_BLOCK_SIZE];
+        out[12] = (byte)(ivLen >>> 24);
+        out[13] = (byte)(ivLen >>> 16);
+        out[14] = (byte)(ivLen >>> 8);
+        out[15] = (byte)ivLen;
+        return out;
+    }
+
+    // aLen and cLen both in bits
+    private static byte[] getLengthBlock(int aLen, int cLen) {
+        byte[] out = new byte[AES_BLOCK_SIZE];
+        out[4] = (byte)(aLen >>> 24);
+        out[5] = (byte)(aLen >>> 16);
+        out[6] = (byte)(aLen >>> 8);
+        out[7] = (byte)aLen;
+        out[12] = (byte)(cLen >>> 24);
+        out[13] = (byte)(cLen >>> 16);
+        out[14] = (byte)(cLen >>> 8);
+        out[15] = (byte)cLen;
+        return out;
+    }
+
+    private static byte[] expandToOneBlock(byte[] in, int inOfs, int len) {
+        if (len > AES_BLOCK_SIZE) {
+            throw new ProviderException("input " + len + " too long");
+        }
+        if (len == AES_BLOCK_SIZE && inOfs == 0) {
+            return in;
+        } else {
+            byte[] paddedIn = new byte[AES_BLOCK_SIZE];
+            System.arraycopy(in, inOfs, paddedIn, 0, len);
+            return paddedIn;
+        }
+    }
+
+    private static byte[] getJ0(byte[] iv, byte[] subkeyH) {
+        byte[] j0;
+        if (iv.length == 12) { // 96 bits
+            j0 = expandToOneBlock(iv, 0, iv.length);
+            j0[AES_BLOCK_SIZE - 1] = 1;
+        } else {
+            GHASH g = new GHASH(subkeyH);
+            int lastLen = iv.length % AES_BLOCK_SIZE;
+            if (lastLen != 0) {
+                g.update(iv, 0, iv.length - lastLen);
+                byte[] padded =
+                    expandToOneBlock(iv, iv.length - lastLen, lastLen);
+                g.update(padded);
+            } else {
+                g.update(iv);
+            }
+            byte[] lengthBlock = getLengthBlock(iv.length*8);
+            g.update(lengthBlock);
+            j0 = g.digest();
+        }
+        return j0;
+    }
+
+    GaloisCounterMode(SymmetricCipher embeddedCipher) {
+        super(embeddedCipher);
+        aadBuffer = new ByteArrayOutputStream();
+    }
+
+    /**
+     * Gets the name of the feedback mechanism
+     *
+     * @return the name of the feedback mechanism
+     */
+    String getFeedback() {
+        return "GCM";
+    }
+
+    /**
+     * Resets the cipher object to its original state.
+     * This is used when doFinal is called in the Cipher class, so that the
+     * cipher can be reused (with its original key and iv).
+     */
+    void reset() {
+        if (aadBuffer == null) {
+            aadBuffer = new ByteArrayOutputStream();
+        } else {
+            aadBuffer.reset();
+        }
+        if (gctrPAndC != null) gctrPAndC.reset();
+        if (ghashAllToS != null) ghashAllToS.reset();
+        processed = 0;
+        sizeOfAAD = 0;
+    }
+
+    /**
+     * Save the current content of this cipher.
+     */
+    void save() {
+        processedSave = processed;
+        sizeOfAADSave = sizeOfAAD;
+        aadBufferSave =
+            ((aadBuffer == null || aadBuffer.size() == 0)?
+             null : aadBuffer.toByteArray());
+        if (gctrPAndC != null) gctrPAndC.save();
+        if (ghashAllToS != null) ghashAllToS.save();
+    }
+
+    /**
+     * Restores the content of this cipher to the previous saved one.
+     */
+    void restore() {
+        processed = processedSave;
+        sizeOfAAD = sizeOfAADSave;
+        if (aadBuffer != null) {
+            aadBuffer.reset();
+            if (aadBufferSave != null) {
+                aadBuffer.write(aadBufferSave, 0, aadBufferSave.length);
+            }
+        }
+       if (gctrPAndC != null) gctrPAndC.restore();
+       if (ghashAllToS != null) ghashAllToS.restore();
+    }
+
+    /**
+     * Initializes the cipher in the specified mode with the given key
+     * and iv.
+     *
+     * @param decrypting flag indicating encryption or decryption
+     * @param algorithm the algorithm name
+     * @param key the key
+     * @param iv the iv
+     * @param tagLenBytes the length of tag in bytes
+     *
+     * @exception InvalidKeyException if the given key is inappropriate for
+     * initializing this cipher
+     */
+    void init(boolean decrypting, String algorithm, byte[] key, byte[] iv)
+            throws InvalidKeyException {
+        init(decrypting, algorithm, key, iv, DEFAULT_TAG_LEN);
+    }
+
+    /**
+     * Initializes the cipher in the specified mode with the given key
+     * and iv.
+     *
+     * @param decrypting flag indicating encryption or decryption
+     * @param algorithm the algorithm name
+     * @param key the key
+     * @param iv the iv
+     * @param tagLenBytes the length of tag in bytes
+     *
+     * @exception InvalidKeyException if the given key is inappropriate for
+     * initializing this cipher
+     */
+    void init(boolean decrypting, String algorithm, byte[] keyValue,
+              byte[] ivValue, int tagLenBytes)
+              throws InvalidKeyException {
+        if (keyValue == null || ivValue == null) {
+            throw new InvalidKeyException("Internal error");
+        }
+
+        // always encrypt mode for embedded cipher
+        this.embeddedCipher.init(false, algorithm, keyValue);
+        this.subkeyH = new byte[AES_BLOCK_SIZE];
+        this.embeddedCipher.encryptBlock(new byte[AES_BLOCK_SIZE], 0,
+                this.subkeyH, 0);
+
+        this.iv = ivValue.clone();
+        preCounterBlock = getJ0(iv, subkeyH);
+        byte[] j0Plus1 = preCounterBlock.clone();
+        increment32(j0Plus1);
+        gctrPAndC = new GCTR(embeddedCipher, j0Plus1);
+        ghashAllToS = new GHASH(subkeyH);
+
+        this.tagLenBytes = tagLenBytes;
+        if (aadBuffer == null) {
+            aadBuffer = new ByteArrayOutputStream();
+        } else {
+            aadBuffer.reset();
+        }
+        processed = 0;
+        sizeOfAAD = 0;
+    }
+
+    /**
+     * Continues a multi-part update of the Additional Authentication
+     * Data (AAD), using a subset of the provided buffer. If this
+     * cipher is operating in either GCM or CCM mode, all AAD must be
+     * supplied before beginning operations on the ciphertext (via the
+     * {@code update} and {@code doFinal} methods).
+     * <p>
+     * NOTE: Given most modes do not accept AAD, default impl for this
+     * method throws IllegalStateException.
+     *
+     * @param src the buffer containing the AAD
+     * @param offset the offset in {@code src} where the AAD input starts
+     * @param len the number of AAD bytes
+     *
+     * @throws IllegalStateException if this cipher is in a wrong state
+     * (e.g., has not been initialized), does not accept AAD, or if
+     * operating in either GCM or CCM mode and one of the {@code update}
+     * methods has already been called for the active
+     * encryption/decryption operation
+     * @throws UnsupportedOperationException if this method
+     * has not been overridden by an implementation
+     *
+     * @since 1.8
+     */
+    void updateAAD(byte[] src, int offset, int len) {
+        if (aadBuffer != null) {
+            aadBuffer.write(src, offset, len);
+        } else {
+            // update has already been called
+            throw new IllegalStateException
+                ("Update has been called; no more AAD data");
+        }
+    }
+
+    // Feed the AAD data to GHASH, pad if necessary
+    void processAAD() {
+        if (aadBuffer != null) {
+            byte[] aad = aadBuffer.toByteArray();
+            sizeOfAAD = aad.length;
+            aadBuffer = null;
+
+            int lastLen = aad.length % AES_BLOCK_SIZE;
+            if (lastLen != 0) {
+                ghashAllToS.update(aad, 0, aad.length - lastLen);
+                byte[] padded = expandToOneBlock(aad, aad.length - lastLen,
+                                                 lastLen);
+                ghashAllToS.update(padded);
+            } else {
+                ghashAllToS.update(aad);
+            }
+        }
+    }
+
+    // Utility to process the last block; used by encryptFinal and decryptFinal
+    void doLastBlock(byte[] in, int inOfs, int len, byte[] out, int outOfs,
+                     boolean isEncrypt) throws IllegalBlockSizeException {
+        // process data in 'in'
+        gctrPAndC.doFinal(in, inOfs, len, out, outOfs);
+        processed += len;
+
+        byte[] ct;
+        int ctOfs;
+        if (isEncrypt) {
+            ct = out;
+            ctOfs = outOfs;
+        } else {
+            ct = in;
+            ctOfs = inOfs;
+        }
+        int lastLen = len  % AES_BLOCK_SIZE;
+        if (lastLen != 0) {
+            ghashAllToS.update(ct, ctOfs, len - lastLen);
+            byte[] padded =
+                expandToOneBlock(ct, (ctOfs + len - lastLen), lastLen);
+            ghashAllToS.update(padded);
+        } else {
+            ghashAllToS.update(ct, ctOfs, len);
+        }
+    }
+
+
+    /**
+     * Performs encryption operation.
+     *
+     * <p>The input plain text <code>in</code>, starting at <code>inOff</code>
+     * and ending at <code>(inOff + len - 1)</code>, is encrypted. The result
+     * is stored in <code>out</code>, starting at <code>outOfs</code>.
+     *
+     * <p>It is the application's responsibility to make sure that
+     * <code>len</code> is a multiple of the embedded cipher's block size,
+     * otherwise, a ProviderException will be thrown.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
+     *
+     * @param in the buffer with the input data to be encrypted
+     * @param inOfs the offset in <code>in</code>
+     * @param len the length of the input data
+     * @param out the buffer for the result
+     * @param outOfs the offset in <code>out</code>
+     */
+    void encrypt(byte[] in, int inOfs, int len, byte[] out, int outOfs) {
+        processAAD();
+        if (len > 0) {
+            gctrPAndC.update(in, inOfs, len, out, outOfs);
+            processed += len;
+            ghashAllToS.update(out, outOfs, len);
+        }
+    }
+
+    /**
+     * Performs encryption operation for the last time.
+     *
+     * <p>NOTE: <code>len</code> may not be multiple of the embedded
+     * cipher's block size for this call.
+     *
+     * @param in the input buffer with the data to be encrypted
+     * @param inOfs the offset in <code>in</code>
+     * @param len the length of the input data
+     * @param out the buffer for the encryption result
+     * @param outOfs the offset in <code>out</code>
+     * @return the number of bytes placed into the <code>out</code> buffer
+     */
+     int encryptFinal(byte[] in, int inOfs, int len, byte[] out, int outOfs)
+         throws IllegalBlockSizeException {
+         if (out.length - outOfs < (len + tagLenBytes)) {
+             throw new RuntimeException("Output buffer too small");
+         }
+
+         processAAD();
+         if (len > 0) {
+             //ByteUtil.dumpArray(Arrays.copyOfRange(in, inOfs, inOfs + len));
+             doLastBlock(in, inOfs, len, out, outOfs, true);
+         }
+
+         byte[] lengthBlock = getLengthBlock(sizeOfAAD*8, processed*8);
+         ghashAllToS.update(lengthBlock);
+         byte[] s = ghashAllToS.digest();
+         byte[] sOut = new byte[s.length];
+         GCTR gctrForSToTag = new GCTR(embeddedCipher, this.preCounterBlock);
+         gctrForSToTag.doFinal(s, 0, s.length, sOut, 0);
+
+         System.arraycopy(sOut, 0, out, (outOfs + len), tagLenBytes);
+         return (len + tagLenBytes);
+     }
+
+    /**
+     * Performs decryption operation.
+     *
+     * <p>The input cipher text <code>in</code>, starting at
+     * <code>inOfs</code> and ending at <code>(inOfs + len - 1)</code>,
+     * is decrypted. The result is stored in <code>out</code>, starting at
+     * <code>outOfs</code>.
+     *
+     * <p>It is the application's responsibility to make sure that
+     * <code>len</code> is a multiple of the embedded cipher's block
+     * size, as any excess bytes are ignored.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
+     *
+     * @param in the buffer with the input data to be decrypted
+     * @param inOfs the offset in <code>in</code>
+     * @param len the length of the input data
+     * @param out the buffer for the result
+     * @param outOfs the offset in <code>out</code>
+     */
+    void decrypt(byte[] in, int inOfs, int len, byte[] out, int outOfs) {
+        processAAD();
+
+        if (len > 0) { // must be at least AES_BLOCK_SIZE bytes long
+            gctrPAndC.update(in, inOfs, len, out, outOfs);
+            processed += len;
+            ghashAllToS.update(in, inOfs, len);
+        }
+    }
+
+    /**
+     * Performs decryption operation for the last time.
+     *
+     * <p>NOTE: For cipher feedback modes which does not perform
+     * special handling for the last few blocks, this is essentially
+     * the same as <code>encrypt(...)</code>. Given most modes do
+     * not do special handling, the default impl for this method is
+     * to simply call <code>decrypt(...)</code>.
+     *
+     * @param in the input buffer with the data to be decrypted
+     * @param inOfs the offset in <code>cipher</code>
+     * @param len the length of the input data
+     * @param out the buffer for the decryption result
+     * @param outOfs the offset in <code>plain</code>
+     * @return the number of bytes placed into the <code>out</code> buffer
+     */
+     int decryptFinal(byte[] in, int inOfs, int len,
+                      byte[] out, int outOfs)
+         throws IllegalBlockSizeException, AEADBadTagException {
+         if (len < tagLenBytes) {
+             throw new RuntimeException("Input buffer too short - need tag");
+         }
+         if (out.length - outOfs < (len - tagLenBytes)) {
+             throw new RuntimeException("Output buffer too small");
+         }
+         processAAD();
+
+         int processedOld = processed;
+         byte[] tag = new byte[tagLenBytes];
+         // get the trailing tag bytes from 'in'
+         System.arraycopy(in, inOfs + len - tagLenBytes, tag, 0, tagLenBytes);
+         len -= tagLenBytes;
+
+         if (len > 0) {
+             doLastBlock(in, inOfs, len, out, outOfs, false);
+         }
+
+         byte[] lengthBlock = getLengthBlock(sizeOfAAD*8, processed*8);
+         ghashAllToS.update(lengthBlock);
+
+         byte[] s = ghashAllToS.digest();
+         byte[] sOut = new byte[s.length];
+         GCTR gctrForSToTag = new GCTR(embeddedCipher, this.preCounterBlock);
+         gctrForSToTag.doFinal(s, 0, s.length, sOut, 0);
+         for (int i = 0; i < tagLenBytes; i++) {
+             if (tag[i] != sOut[i]) {
+                 throw new AEADBadTagException("Tag mismatch!");
+             }
+         }
+         return len;
+     }
+
+    // return tag length in bytes
+    int getTagLen() {
+        return this.tagLenBytes;
+    }
+}
--- a/jdk/src/share/classes/com/sun/crypto/provider/HmacMD5KeyGenerator.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/HmacMD5KeyGenerator.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -98,7 +98,7 @@
      */
     protected SecretKey engineGenerateKey() {
         if (this.random == null) {
-            this.random = SunJCE.RANDOM;
+            this.random = SunJCE.getRandom();
         }
 
         byte[] keyBytes = new byte[this.keysize];
--- a/jdk/src/share/classes/com/sun/crypto/provider/HmacPKCS12PBESHA1.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/HmacPKCS12PBESHA1.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -89,7 +89,7 @@
             // generate default for salt and iteration count if necessary
             if (salt == null) {
                 salt = new byte[20];
-                SunJCE.RANDOM.nextBytes(salt);
+                SunJCE.getRandom().nextBytes(salt);
             }
             if (iCount == 0) iCount = 100;
         } else if (!(params instanceof PBEParameterSpec)) {
--- a/jdk/src/share/classes/com/sun/crypto/provider/HmacSHA1KeyGenerator.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/HmacSHA1KeyGenerator.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -98,7 +98,7 @@
      */
     protected SecretKey engineGenerateKey() {
         if (this.random == null) {
-            this.random = SunJCE.RANDOM;
+            this.random = SunJCE.getRandom();
         }
 
         byte[] keyBytes = new byte[this.keysize];
--- a/jdk/src/share/classes/com/sun/crypto/provider/ISO10126Padding.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/ISO10126Padding.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -69,7 +69,7 @@
 
         byte paddingOctet = (byte) (len & 0xff);
         byte[] padding = new byte[len];
-        SunJCE.RANDOM.nextBytes(padding);
+        SunJCE.getRandom().nextBytes(padding);
         padding[len-1] = paddingOctet;
         System.arraycopy(padding, 0, in, off, len);
         return;
--- a/jdk/src/share/classes/com/sun/crypto/provider/KeyGeneratorCore.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/KeyGeneratorCore.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -98,7 +98,7 @@
     // generate the key
     SecretKey implGenerateKey() {
         if (random == null) {
-            random = SunJCE.RANDOM;
+            random = SunJCE.getRandom();
         }
         byte[] b = new byte[(keySize + 7) >> 3];
         random.nextBytes(b);
--- a/jdk/src/share/classes/com/sun/crypto/provider/KeyProtector.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/KeyProtector.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -99,7 +99,7 @@
     {
         // create a random salt (8 bytes)
         byte[] salt = new byte[8];
-        SunJCE.RANDOM.nextBytes(salt);
+        SunJCE.getRandom().nextBytes(salt);
 
         // create PBE parameters from salt and iteration count
         PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);
@@ -284,7 +284,7 @@
     {
         // create a random salt (8 bytes)
         byte[] salt = new byte[8];
-        SunJCE.RANDOM.nextBytes(salt);
+        SunJCE.getRandom().nextBytes(salt);
 
         // create PBE parameters from salt and iteration count
         PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);
--- a/jdk/src/share/classes/com/sun/crypto/provider/PBECipherCore.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/PBECipherCore.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -164,7 +164,7 @@
         AlgorithmParameters params = null;
         if (salt == null) {
             salt = new byte[8];
-            SunJCE.RANDOM.nextBytes(salt);
+            SunJCE.getRandom().nextBytes(salt);
         }
         PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, iCount);
         try {
--- a/jdk/src/share/classes/com/sun/crypto/provider/PBES1Core.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/PBES1Core.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -164,7 +164,7 @@
         AlgorithmParameters params = null;
         if (salt == null) {
             salt = new byte[8];
-            SunJCE.RANDOM.nextBytes(salt);
+            SunJCE.getRandom().nextBytes(salt);
         }
         PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, iCount);
         try {
--- a/jdk/src/share/classes/com/sun/crypto/provider/PBES2Core.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/PBES2Core.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -134,13 +134,13 @@
         if (salt == null) {
             // generate random salt and use default iteration count
             salt = new byte[DEFAULT_SALT_LENGTH];
-            SunJCE.RANDOM.nextBytes(salt);
+            SunJCE.getRandom().nextBytes(salt);
             iCount = DEFAULT_COUNT;
         }
         if (ivSpec == null) {
             // generate random IV
             byte[] ivBytes = new byte[blkSize];
-            SunJCE.RANDOM.nextBytes(ivBytes);
+            SunJCE.getRandom().nextBytes(ivBytes);
             ivSpec = new IvParameterSpec(ivBytes);
         }
         PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, iCount, ivSpec);
--- a/jdk/src/share/classes/com/sun/crypto/provider/PBMAC1Core.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/PBMAC1Core.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -123,7 +123,7 @@
             // generate default for salt and iteration count if necessary
             if (salt == null) {
                 salt = new byte[DEFAULT_SALT_LENGTH];
-                SunJCE.RANDOM.nextBytes(salt);
+                SunJCE.getRandom().nextBytes(salt);
             }
             if (iCount == 0) iCount = DEFAULT_COUNT;
         } else if (!(params instanceof PBEParameterSpec)) {
--- a/jdk/src/share/classes/com/sun/crypto/provider/PKCS12PBECipherCore.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/PKCS12PBECipherCore.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -227,7 +227,7 @@
             // follow the recommendation in PKCS12 v1.0
             // section B.4 to generate salt and iCount.
             salt = new byte[DEFAULT_SALT_LENGTH];
-            SunJCE.RANDOM.nextBytes(salt);
+            SunJCE.getRandom().nextBytes(salt);
             iCount = DEFAULT_COUNT;
         }
         PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, iCount);
@@ -294,7 +294,7 @@
                 if (random != null) {
                     random.nextBytes(salt);
                 } else {
-                    SunJCE.RANDOM.nextBytes(salt);
+                    SunJCE.getRandom().nextBytes(salt);
                 }
             }
             if (iCount == 0) iCount = DEFAULT_COUNT;
--- a/jdk/src/share/classes/com/sun/crypto/provider/SunJCE.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/crypto/provider/SunJCE.java	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -57,6 +57,7 @@
  * - ARCFOUR (RC4 compatible)
  *
  * - Cipher modes ECB, CBC, CFB, OFB, PCBC, CTR, and CTS for all block ciphers
+ *   and mode GCM for AES cipher
  *
  * - Cipher padding ISO10126Padding for non-PKCS#5 block ciphers and
  *   NoPadding and PKCS5Padding for all block ciphers
@@ -90,7 +91,12 @@
     /* Are we debugging? -- for developers */
     static final boolean debug = false;
 
-    static final SecureRandom RANDOM = new SecureRandom();
+    // lazy initialize SecureRandom to avoid potential recursion if Sun
+    // provider has not been installed yet
+    private static class SecureRandomHolder {
+        static final SecureRandom RANDOM = new SecureRandom();
+    }
+    static SecureRandom getRandom() { return SecureRandomHolder.RANDOM; }
 
     public SunJCE() {
         /* We are the "SunJCE" provider */
@@ -100,7 +106,7 @@
             "|CFB8|CFB16|CFB24|CFB32|CFB40|CFB48|CFB56|CFB64" +
             "|OFB8|OFB16|OFB24|OFB32|OFB40|OFB48|OFB56|OFB64";
         final String BLOCK_MODES128 = BLOCK_MODES +
-            "|CFB72|CFB80|CFB88|CFB96|CFB104|CFB112|CFB120|CFB128" +
+            "|GCM|CFB72|CFB80|CFB88|CFB96|CFB104|CFB112|CFB120|CFB128" +
             "|OFB72|OFB80|OFB88|OFB96|OFB104|OFB112|OFB120|OFB128";
         final String BLOCK_PADS = "NOPADDING|PKCS5PADDING|ISO10126PADDING";
 
@@ -258,6 +264,9 @@
                     put("Cipher.AES_128/CFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES128_CFB_NoPadding");
                     put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.4", "AES_128/CFB/NoPadding");
                     put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.4", "AES_128/CFB/NoPadding");
+                    put("Cipher.AES_128/GCM/NoPadding", "com.sun.crypto.provider.AESCipher$AES128_GCM_NoPadding");
+                    put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.6", "AES_128/GCM/NoPadding");
+                    put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.6", "AES_128/GCM/NoPadding");
 
                     put("Cipher.AES_192/ECB/NoPadding", "com.sun.crypto.provider.AESCipher$AES192_ECB_NoPadding");
                     put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.21", "AES_192/ECB/NoPadding");
@@ -271,7 +280,9 @@
                     put("Cipher.AES_192/CFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES192_CFB_NoPadding");
                     put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.24", "AES_192/CFB/NoPadding");
                     put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.24", "AES_192/CFB/NoPadding");
-
+                    put("Cipher.AES_192/GCM/NoPadding", "com.sun.crypto.provider.AESCipher$AES192_GCM_NoPadding");
+                    put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.26", "AES_192/GCM/NoPadding");
+                    put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.26", "AES_192/GCM/NoPadding");
 
                     put("Cipher.AES_256/ECB/NoPadding", "com.sun.crypto.provider.AESCipher$AES256_ECB_NoPadding");
                     put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.41", "AES_256/ECB/NoPadding");
@@ -285,6 +296,9 @@
                     put("Cipher.AES_256/CFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES256_CFB_NoPadding");
                     put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.44", "AES_256/CFB/NoPadding");
                     put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.44", "AES_256/CFB/NoPadding");
+                    put("Cipher.AES_256/GCM/NoPadding", "com.sun.crypto.provider.AESCipher$AES256_GCM_NoPadding");
+                    put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.46", "AES_256/GCM/NoPadding");
+                    put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.46", "AES_256/GCM/NoPadding");
 
                     put("Cipher.AESWrap", "com.sun.crypto.provider.AESWrapCipher$General");
                     put("Cipher.AESWrap SupportedModes", "ECB");
@@ -509,6 +523,8 @@
                     put("AlgorithmParameters.AES",
                         "com.sun.crypto.provider.AESParameters");
                     put("Alg.Alias.AlgorithmParameters.Rijndael", "AES");
+                    put("AlgorithmParameters.GCM",
+                        "com.sun.crypto.provider.GCMParameters");
 
 
                     put("AlgorithmParameters.RC2",
--- a/jdk/src/share/classes/com/sun/jmx/remote/internal/ClientCommunicatorAdmin.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/jmx/remote/internal/ClientCommunicatorAdmin.java	Tue Jan 22 11:54:16 2013 -0800
@@ -115,6 +115,7 @@
                     // restarted is failed by another thread
                     throw ioe;
                 }
+                return;
             } else {
                 state = RE_CONNECTING;
                 lock.notifyAll();
@@ -195,7 +196,7 @@
                     if (e instanceof IOException &&
                         !(e instanceof InterruptedIOException)) {
                         try {
-                            restart((IOException)e);
+                            gotIOException((IOException)e);
                         } catch (Exception ee) {
                             logger.warning("Checker-run",
                                            "Failed to check connection: "+ e);
--- a/jdk/src/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/jmx/remote/internal/ClientNotifForwarder.java	Tue Jan 22 11:54:16 2013 -0800
@@ -51,6 +51,7 @@
 
 import com.sun.jmx.remote.util.ClassLogger;
 import com.sun.jmx.remote.util.EnvHelp;
+import java.rmi.UnmarshalException;
 
 
 public abstract class ClientNotifForwarder {
@@ -594,10 +595,7 @@
                 }
 
                 return nr;
-            } catch (ClassNotFoundException e) {
-                logger.trace("NotifFetcher.fetchNotifs", e);
-                return fetchOneNotif();
-            } catch (NotSerializableException e) {
+            } catch (ClassNotFoundException | NotSerializableException | UnmarshalException e) {
                 logger.trace("NotifFetcher.fetchNotifs", e);
                 return fetchOneNotif();
             } catch (IOException ioe) {
@@ -619,17 +617,18 @@
            timeout.  This allows us to skip sequence numbers for
            notifications that don't match our filters.  Then we ask
            for one notification.  If that produces a
-           ClassNotFoundException or a NotSerializableException, we
-           increase our sequence number and ask again.  Eventually we
-           will either get a successful notification, or a return with
-           0 notifications.  In either case we can return a
+           ClassNotFoundException, NotSerializableException or
+           UnmarshalException, we increase our sequence number and ask again.
+           Eventually we will either get a successful notification, or a
+           return with 0 notifications.  In either case we can return a
            NotificationResult.  This algorithm works (albeit less
            well) even if the server implementation doesn't optimize a
            request for 0 notifications to skip sequence numbers for
            notifications that don't match our filters.
 
-           If we had at least one ClassNotFoundException, then we
-           must emit a JMXConnectionNotification.LOST_NOTIFS.
+           If we had at least one
+           ClassNotFoundException/NotSerializableException/UnmarshalException,
+           then we must emit a JMXConnectionNotification.LOST_NOTIFS.
         */
         private NotificationResult fetchOneNotif() {
             ClientNotifForwarder cnf = ClientNotifForwarder.this;
@@ -668,23 +667,20 @@
                 try {
                     // 1 notif to skip possible missing class
                     result = cnf.fetchNotifs(startSequenceNumber, 1, 0L);
+                } catch (ClassNotFoundException | NotSerializableException | UnmarshalException e) {
+                    logger.warning("NotifFetcher.fetchOneNotif",
+                                   "Failed to deserialize a notification: "+e.toString());
+                    if (logger.traceOn()) {
+                        logger.trace("NotifFetcher.fetchOneNotif",
+                                     "Failed to deserialize a notification.", e);
+                    }
+
+                    notFoundCount++;
+                    startSequenceNumber++;
                 } catch (Exception e) {
-                    if (e instanceof ClassNotFoundException
-                        || e instanceof NotSerializableException) {
-                        logger.warning("NotifFetcher.fetchOneNotif",
-                                     "Failed to deserialize a notification: "+e.toString());
-                        if (logger.traceOn()) {
-                            logger.trace("NotifFetcher.fetchOneNotif",
-                                         "Failed to deserialize a notification.", e);
-                        }
-
-                        notFoundCount++;
-                        startSequenceNumber++;
-                    } else {
-                        if (!shouldStop())
-                            logger.trace("NotifFetcher.fetchOneNotif", e);
-                        return null;
-                    }
+                    if (!shouldStop())
+                        logger.trace("NotifFetcher.fetchOneNotif", e);
+                    return null;
                 }
             }
 
@@ -692,7 +688,7 @@
                 final String msg =
                     "Dropped " + notFoundCount + " notification" +
                     (notFoundCount == 1 ? "" : "s") +
-                    " because classes were missing locally";
+                    " because classes were missing locally or incompatible";
                 lostNotifs(msg, notFoundCount);
                 // Even if result.getEarliestSequenceNumber() is now greater than
                 // it was initially, meaning some notifs have been dropped
--- a/jdk/src/share/classes/com/sun/jmx/remote/internal/IIOPHelper.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/jmx/remote/internal/IIOPHelper.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,13 +26,8 @@
 package com.sun.jmx.remote.internal;
 
 import java.util.Properties;
+import java.io.IOException;
 import java.rmi.Remote;
-import java.rmi.RemoteException;
-import java.rmi.NoSuchObjectException;
-
-import java.util.Properties;
-import java.rmi.Remote;
-import java.rmi.RemoteException;
 import java.rmi.NoSuchObjectException;
 
 import java.security.AccessController;
@@ -115,9 +110,10 @@
      * Connects the Stub to the given ORB.
      */
     public static void connect(Object stub, Object orb)
-        throws RemoteException
+        throws IOException
     {
-        ensureAvailable();
+        if (proxy == null)
+            throw new IOException("Connection to ORB failed, RMI/IIOP not available");
         proxy.connect(stub, orb);
     }
 
@@ -125,15 +121,17 @@
      * Returns true if the given object is an ORB.
      */
     public static boolean isOrb(Object obj) {
-        ensureAvailable();
-        return proxy.isOrb(obj);
+        return (proxy == null) ? false : proxy.isOrb(obj);
     }
 
     /**
      * Creates, and returns, a new ORB instance.
      */
-    public static Object createOrb(String[] args, Properties props) {
-        ensureAvailable();
+    public static Object createOrb(String[] args, Properties props)
+        throws IOException
+    {
+        if (proxy == null)
+            throw new IOException("ORB initialization failed, RMI/IIOP not available");
         return proxy.createOrb(args, props);
     }
 
@@ -166,24 +164,27 @@
     /**
      * Makes a server object ready to receive remote calls
      */
-    public static void exportObject(Remote obj) throws RemoteException {
-        ensureAvailable();
+    public static void exportObject(Remote obj) throws IOException {
+        if (proxy == null)
+            throw new IOException("RMI object cannot be exported, RMI/IIOP not available");
         proxy.exportObject(obj);
     }
 
     /**
      * Deregisters a server object from the runtime.
      */
-    public static void unexportObject(Remote obj) throws NoSuchObjectException {
-        ensureAvailable();
+    public static void unexportObject(Remote obj) throws IOException {
+        if (proxy == null)
+            throw new NoSuchObjectException("Object not exported");
         proxy.unexportObject(obj);
     }
 
     /**
      * Returns a stub for the given server object.
      */
-    public static Remote toStub(Remote obj) throws NoSuchObjectException {
-        ensureAvailable();
+    public static Remote toStub(Remote obj) throws IOException {
+        if (proxy == null)
+            throw new NoSuchObjectException("Object not exported");
         return proxy.toStub(obj);
     }
 }
--- a/jdk/src/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/jmx/remote/internal/ServerNotifForwarder.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,16 +25,15 @@
 
 package com.sun.jmx.remote.internal;
 
-import com.sun.jmx.mbeanserver.Util;
 import com.sun.jmx.remote.security.NotificationAccessController;
 import com.sun.jmx.remote.util.ClassLogger;
 import com.sun.jmx.remote.util.EnvHelp;
 import java.io.IOException;
 import java.security.AccessControlContext;
 import java.security.AccessController;
-import java.security.PrivilegedAction;
 import java.security.PrivilegedActionException;
 import java.security.PrivilegedExceptionAction;
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -291,13 +290,18 @@
     // so that we can know too, and remove the corresponding entry from the listenerMap.
     // See 6957378.
     private void snoopOnUnregister(NotificationResult nr) {
-        Set<IdAndFilter> delegateSet = listenerMap.get(MBeanServerDelegate.DELEGATE_NAME);
-        if (delegateSet == null || delegateSet.isEmpty()) {
-            return;
+        List<IdAndFilter> copy = null;
+        synchronized (listenerMap) {
+            Set<IdAndFilter> delegateSet = listenerMap.get(MBeanServerDelegate.DELEGATE_NAME);
+            if (delegateSet == null || delegateSet.isEmpty()) {
+                return;
+            }
+            copy = new ArrayList<>(delegateSet);
         }
+
         for (TargetedNotification tn : nr.getTargetedNotifications()) {
             Integer id = tn.getListenerID();
-            for (IdAndFilter idaf : delegateSet) {
+            for (IdAndFilter idaf : copy) {
                 if (idaf.id == id) {
                     // This is a notification from the MBeanServerDelegate.
                     Notification n = tn.getNotification();
--- a/jdk/src/share/classes/com/sun/security/auth/login/ConfigFile.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/com/sun/security/auth/login/ConfigFile.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,41 +25,39 @@
 
 package com.sun.security.auth.login;
 
-import javax.security.auth.AuthPermission;
 import javax.security.auth.login.AppConfigurationEntry;
-import java.io.*;
-import java.util.*;
+import javax.security.auth.login.Configuration;
 import java.net.URI;
-import java.net.URL;
-import java.net.MalformedURLException;
-import java.text.MessageFormat;
-import sun.security.util.Debug;
-import sun.security.util.ResourcesMgr;
-import sun.security.util.PropertyExpander;
+
+// NOTE: As of JDK 8, this class instantiates
+// sun.security.provider.ConfigSpiFile and forwards all methods to that
+// implementation. All implementation fixes and enhancements should be made to
+// sun.security.provider.ConfigSpiFile and not this class.
+// See JDK-8005117 for more information.
 
 /**
  * This class represents a default implementation for
- * <code>javax.security.auth.login.Configuration</code>.
+ * {@code javax.security.auth.login.Configuration}.
  *
  * <p> This object stores the runtime login configuration representation,
  * and is the amalgamation of multiple static login
  * configurations that resides in files.
  * The algorithm for locating the login configuration file(s) and reading their
- * information into this <code>Configuration</code> object is:
+ * information into this {@code Configuration} object is:
  *
  * <ol>
  * <li>
  *   Loop through the security properties,
  *   <i>login.config.url.1</i>, <i>login.config.url.2</i>, ...,
  *   <i>login.config.url.X</i>.
- *   Each property value specifies a <code>URL</code> pointing to a
+ *   Each property value specifies a {@code URL} pointing to a
  *   login configuration file to be loaded.  Read in and load
  *   each configuration.
  *
  * <li>
- *   The <code>java.lang.System</code> property
+ *   The {@code java.lang.System} property
  *   <i>java.security.auth.login.config</i>
- *   may also be set to a <code>URL</code> pointing to another
+ *   may also be set to a {@code URL} pointing to another
  *   login configuration file
  *   (which is the case when a user uses the -D switch at runtime).
  *   If this property is defined, and its use is allowed by the
@@ -80,593 +78,63 @@
  *
  * <p> The configuration syntax supported by this implementation
  * is exactly that syntax specified in the
- * <code>javax.security.auth.login.Configuration</code> class.
+ * {@code javax.security.auth.login.Configuration} class.
  *
  * @see javax.security.auth.login.LoginContext
  * @see java.security.Security security properties
  */
-public class ConfigFile extends javax.security.auth.login.Configuration {
+public class ConfigFile extends Configuration {
 
-    private StreamTokenizer st;
-    private int lookahead;
-    private int linenum;
-    private HashMap<String, LinkedList<AppConfigurationEntry>> configuration;
-    private boolean expandProp = true;
-    private URL url;
-
-    private static Debug debugConfig = Debug.getInstance("configfile");
-    private static Debug debugParser = Debug.getInstance("configparser");
+    private sun.security.provider.ConfigSpiFile configFile;
 
     /**
-     * Create a new <code>Configuration</code> object.
+     * Create a new {@code Configuration} object.
+     *
+     * @throws SecurityException if the {@code Configuration} can not be
+     *                           initialized
      */
     public ConfigFile() {
-        try {
-            init(url);
-        } catch (IOException ioe) {
-            throw (SecurityException)
-                new SecurityException(ioe.getMessage()).initCause(ioe);
-        }
-    }
-
-    /**
-     * Create a new <code>Configuration</code> object from the specified URI.
-     *
-     * @param uri Create a new Configuration object from this URI.
-     */
-    public ConfigFile(URI uri) {
-        // only load config from the specified URI
-        try {
-            url = uri.toURL();
-            init(url);
-        } catch (MalformedURLException mue) {
-            throw (SecurityException)
-                new SecurityException(mue.getMessage()).initCause(mue);
-        } catch (IOException ioe) {
-            throw (SecurityException)
-                new SecurityException(ioe.getMessage()).initCause(ioe);
-        }
+        configFile = new sun.security.provider.ConfigSpiFile();
     }
 
     /**
-     * Read and initialize the entire login Configuration.
-     *
-     * <p>
+     * Create a new {@code Configuration} object from the specified {@code URI}.
      *
-     * @exception IOException if the Configuration can not be initialized. <p>
-     * @exception SecurityException if the caller does not have permission
-     *                          to initialize the Configuration.
+     * @param uri the {@code URI}
+     * @throws SecurityException if the {@code Configuration} can not be
+     *                           initialized
+     * @throws NullPointerException if {@code uri} is null
      */
-    private void init(URL url) throws IOException {
-
-        boolean initialized = false;
-        FileReader fr = null;
-        String sep = File.separator;
-
-        if ("false".equals(System.getProperty("policy.expandProperties"))) {
-            expandProp = false;
-        }
-
-        // new configuration
-        HashMap<String, LinkedList<AppConfigurationEntry>> newConfig =
-                new HashMap<>();
-
-        if (url != null) {
-
-            /**
-             * If the caller specified a URI via Configuration.getInstance,
-             * we only read from that URI
-             */
-            if (debugConfig != null) {
-                debugConfig.println("reading " + url);
-            }
-            init(url, newConfig);
-            configuration = newConfig;
-            return;
-        }
-
-        /**
-         * Caller did not specify URI via Configuration.getInstance.
-         * Read from URLs listed in the java.security properties file.
-         */
-
-        String allowSys = java.security.Security.getProperty
-                                                ("policy.allowSystemProperty");
-
-        if ("true".equalsIgnoreCase(allowSys)) {
-            String extra_config = System.getProperty
-                                        ("java.security.auth.login.config");
-            if (extra_config != null) {
-                boolean overrideAll = false;
-                if (extra_config.startsWith("=")) {
-                    overrideAll = true;
-                    extra_config = extra_config.substring(1);
-                }
-                try {
-                    extra_config = PropertyExpander.expand(extra_config);
-                } catch (PropertyExpander.ExpandException peee) {
-                    MessageFormat form = new MessageFormat
-                        (ResourcesMgr.getString
-                                ("Unable.to.properly.expand.config",
-                                "sun.security.util.AuthResources"));
-                    Object[] source = {extra_config};
-                    throw new IOException(form.format(source));
-                }
-
-                URL configURL = null;
-                try {
-                    configURL = new URL(extra_config);
-                } catch (java.net.MalformedURLException mue) {
-                    File configFile = new File(extra_config);
-                    if (configFile.exists()) {
-                        configURL = configFile.toURI().toURL();
-                    } else {
-                        MessageFormat form = new MessageFormat
-                            (ResourcesMgr.getString
-                                ("extra.config.No.such.file.or.directory.",
-                                "sun.security.util.AuthResources"));
-                        Object[] source = {extra_config};
-                        throw new IOException(form.format(source));
-                    }
-                }
-
-                if (debugConfig != null) {
-                    debugConfig.println("reading "+configURL);
-                }
-                init(configURL, newConfig);
-                initialized = true;
-                if (overrideAll) {
-                    if (debugConfig != null) {
-                        debugConfig.println("overriding other policies!");
-                    }
-                    configuration = newConfig;
-                    return;
-                }
-            }
-        }
-
-        int n = 1;
-        String config_url;
-        while ((config_url = java.security.Security.getProperty
-                                        ("login.config.url."+n)) != null) {
-            try {
-                config_url = PropertyExpander.expand
-                        (config_url).replace(File.separatorChar, '/');
-                if (debugConfig != null) {
-                    debugConfig.println("\tReading config: " + config_url);
-                }
-                init(new URL(config_url), newConfig);
-                initialized = true;
-            } catch (PropertyExpander.ExpandException peee) {
-                MessageFormat form = new MessageFormat
-                        (ResourcesMgr.getString
-                                ("Unable.to.properly.expand.config",
-                                "sun.security.util.AuthResources"));
-                Object[] source = {config_url};
-                throw new IOException(form.format(source));
-            }
-            n++;
-        }
-
-        if (initialized == false && n == 1 && config_url == null) {
-
-            // get the config from the user's home directory
-            if (debugConfig != null) {
-                debugConfig.println("\tReading Policy " +
-                                "from ~/.java.login.config");
-            }
-            config_url = System.getProperty("user.home");
-            String userConfigFile = config_url +
-                      File.separatorChar + ".java.login.config";
-
-            // No longer throws an exception when there's no config file
-            // at all. Returns an empty Configuration instead.
-            if (new File(userConfigFile).exists()) {
-                init(new File(userConfigFile).toURI().toURL(),
-                    newConfig);
-            }
-        }
-
-        configuration = newConfig;
-    }
-
-    private void init(URL config,
-        HashMap<String, LinkedList<AppConfigurationEntry>> newConfig)
-        throws IOException {
-
-        InputStreamReader isr = null;
-        try {
-            isr = new InputStreamReader(getInputStream(config), "UTF-8");
-            readConfig(isr, newConfig);
-        } catch (FileNotFoundException fnfe) {
-            if (debugConfig != null) {
-                debugConfig.println(fnfe.toString());
-            }
-            throw new IOException(ResourcesMgr.getString
-                    ("Configuration.Error.No.such.file.or.directory",
-                    "sun.security.util.AuthResources"));
-        } finally {
-            if (isr != null) {
-                isr.close();
-            }
-        }
-    }
-
-    /**
-     * Retrieve an entry from the Configuration using an application name
-     * as an index.
-     *
-     * <p>
-     *
-     * @param applicationName the name used to index the Configuration.
-     * @return an array of AppConfigurationEntries which correspond to
-     *          the stacked configuration of LoginModules for this
-     *          application, or null if this application has no configured
-     *          LoginModules.
-     */
-    public AppConfigurationEntry[] getAppConfigurationEntry
-    (String applicationName) {
-
-        LinkedList<AppConfigurationEntry> list = null;
-        synchronized (configuration) {
-            list = configuration.get(applicationName);
-        }
-
-        if (list == null || list.size() == 0)
-            return null;
-
-        AppConfigurationEntry[] entries =
-                                new AppConfigurationEntry[list.size()];
-        Iterator<AppConfigurationEntry> iterator = list.iterator();
-        for (int i = 0; iterator.hasNext(); i++) {
-            AppConfigurationEntry e = iterator.next();
-            entries[i] = new AppConfigurationEntry(e.getLoginModuleName(),
-                                                e.getControlFlag(),
-                                                e.getOptions());
-        }
-        return entries;
+    public ConfigFile(URI uri) {
+        configFile = new sun.security.provider.ConfigSpiFile(uri);
     }
 
     /**
-     * Refresh and reload the Configuration by re-reading all of the
-     * login configurations.
+     * Retrieve an entry from the {@code Configuration} using an application
+     * name as an index.
      *
-     * <p>
-     *
-     * @exception SecurityException if the caller does not have permission
-     *                          to refresh the Configuration.
+     * @param applicationName the name used to index the {@code Configuration}
+     * @return an array of {@code AppConfigurationEntry} which correspond to
+     *         the stacked configuration of {@code LoginModule}s for this
+     *         application, or null if this application has no configured
+     *         {@code LoginModule}s.
      */
-    public synchronized void refresh() {
-
-        java.lang.SecurityManager sm = System.getSecurityManager();
-        if (sm != null)
-            sm.checkPermission(new AuthPermission("refreshLoginConfiguration"));
-
-        java.security.AccessController.doPrivileged
-            (new java.security.PrivilegedAction<Void>() {
-            public Void run() {
-                try {
-                    init(url);
-                } catch (java.io.IOException ioe) {
-                    throw (SecurityException) new SecurityException
-                                (ioe.getLocalizedMessage()).initCause(ioe);
-                }
-                return null;
-            }
-        });
-    }
-
-    private void readConfig(Reader reader,
-        HashMap<String, LinkedList<AppConfigurationEntry>> newConfig)
-        throws IOException {
-
-        int linenum = 1;
-
-        if (!(reader instanceof BufferedReader))
-            reader = new BufferedReader(reader);
-
-        st = new StreamTokenizer(reader);
-        st.quoteChar('"');
-        st.wordChars('$', '$');
-        st.wordChars('_', '_');
-        st.wordChars('-', '-');
-        st.lowerCaseMode(false);
-        st.slashSlashComments(true);
-        st.slashStarComments(true);
-        st.eolIsSignificant(true);
-
-        lookahead = nextToken();
-        while (lookahead != StreamTokenizer.TT_EOF) {
-            parseLoginEntry(newConfig);
-        }
-    }
-
-    private void parseLoginEntry(
-        HashMap<String, LinkedList<AppConfigurationEntry>> newConfig)
-        throws IOException {
-
-        String appName;
-        String moduleClass;
-        String sflag;
-        AppConfigurationEntry.LoginModuleControlFlag controlFlag;
-        LinkedList<AppConfigurationEntry> configEntries = new LinkedList<>();
-
-        // application name
-        appName = st.sval;
-        lookahead = nextToken();
-
-        if (debugParser != null) {
-            debugParser.println("\tReading next config entry: " + appName);
-        }
-
-        match("{");
+    @Override
+    public AppConfigurationEntry[] getAppConfigurationEntry
+        (String applicationName) {
 
-        // get the modules
-        while (peek("}") == false) {
-            // get the module class name
-            moduleClass = match("module class name");
-
-            // controlFlag (required, optional, etc)
-            sflag = match("controlFlag");
-            if (sflag.equalsIgnoreCase("REQUIRED"))
-                controlFlag =
-                        AppConfigurationEntry.LoginModuleControlFlag.REQUIRED;
-            else if (sflag.equalsIgnoreCase("REQUISITE"))
-                controlFlag =
-                        AppConfigurationEntry.LoginModuleControlFlag.REQUISITE;
-            else if (sflag.equalsIgnoreCase("SUFFICIENT"))
-                controlFlag =
-                        AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT;
-            else if (sflag.equalsIgnoreCase("OPTIONAL"))
-                controlFlag =
-                        AppConfigurationEntry.LoginModuleControlFlag.OPTIONAL;
-            else {
-                MessageFormat form = new MessageFormat(ResourcesMgr.getString
-                        ("Configuration.Error.Invalid.control.flag.flag",
-                        "sun.security.util.AuthResources"));
-                Object[] source = {sflag};
-                throw new IOException(form.format(source));
-            }
-
-            // get the args
-            HashMap<String, String> options = new HashMap<>();
-            String key;
-            String value;
-            while (peek(";") == false) {
-                key = match("option key");
-                match("=");
-                try {
-                    value = expand(match("option value"));
-                } catch (PropertyExpander.ExpandException peee) {
-                    throw new IOException(peee.getLocalizedMessage());
-                }
-                options.put(key, value);
-            }
-
-            lookahead = nextToken();
-
-            // create the new element
-            if (debugParser != null) {
-                debugParser.println("\t\t" + moduleClass + ", " + sflag);
-                java.util.Iterator<String> i = options.keySet().iterator();
-                while (i.hasNext()) {
-                    key = i.next();
-                    debugParser.println("\t\t\t" +
-                                        key +
-                                        "=" +
-                                        options.get(key));
-                }
-            }
-            AppConfigurationEntry entry = new AppConfigurationEntry
-                                                        (moduleClass,
-                                                        controlFlag,
-                                                        options);
-            configEntries.add(entry);
-        }
-
-        match("}");
-        match(";");
-
-        // add this configuration entry
-        if (newConfig.containsKey(appName)) {
-            MessageFormat form = new MessageFormat(ResourcesMgr.getString
-                ("Configuration.Error.Can.not.specify.multiple.entries.for.appName",
-                "sun.security.util.AuthResources"));
-            Object[] source = {appName};
-            throw new IOException(form.format(source));
-        }
-        newConfig.put(appName, configEntries);
+        return configFile.engineGetAppConfigurationEntry(applicationName);
     }
 
-    private String match(String expect) throws IOException {
-
-        String value = null;
-
-        switch(lookahead) {
-        case StreamTokenizer.TT_EOF:
-
-            MessageFormat form1 = new MessageFormat(ResourcesMgr.getString
-                ("Configuration.Error.expected.expect.read.end.of.file.",
-                "sun.security.util.AuthResources"));
-            Object[] source1 = {expect};
-            throw new IOException(form1.format(source1));
-
-        case '"':
-        case StreamTokenizer.TT_WORD:
-
-            if (expect.equalsIgnoreCase("module class name") ||
-                expect.equalsIgnoreCase("controlFlag") ||
-                expect.equalsIgnoreCase("option key") ||
-                expect.equalsIgnoreCase("option value")) {
-                value = st.sval;
-                lookahead = nextToken();
-            } else {
-                MessageFormat form = new MessageFormat(ResourcesMgr.getString
-                        ("Configuration.Error.Line.line.expected.expect.found.value.",
-                        "sun.security.util.AuthResources"));
-                Object[] source = {new Integer(linenum), expect, st.sval};
-                throw new IOException(form.format(source));
-            }
-            break;
-
-        case '{':
-
-            if (expect.equalsIgnoreCase("{")) {
-                lookahead = nextToken();
-            } else {
-                MessageFormat form = new MessageFormat(ResourcesMgr.getString
-                        ("Configuration.Error.Line.line.expected.expect.",
-                        "sun.security.util.AuthResources"));
-                Object[] source = {new Integer(linenum), expect, st.sval};
-                throw new IOException(form.format(source));
-            }
-            break;
-
-        case ';':
-
-            if (expect.equalsIgnoreCase(";")) {
-                lookahead = nextToken();
-            } else {
-                MessageFormat form = new MessageFormat(ResourcesMgr.getString
-                        ("Configuration.Error.Line.line.expected.expect.",
-                        "sun.security.util.AuthResources"));
-                Object[] source = {new Integer(linenum), expect, st.sval};
-                throw new IOException(form.format(source));
-            }
-            break;
-
-        case '}':
-
-            if (expect.equalsIgnoreCase("}")) {
-                lookahead = nextToken();
-            } else {
-                MessageFormat form = new MessageFormat(ResourcesMgr.getString
-                        ("Configuration.Error.Line.line.expected.expect.",
-                        "sun.security.util.AuthResources"));
-                Object[] source = {new Integer(linenum), expect, st.sval};
-                throw new IOException(form.format(source));
-            }
-            break;
-
-        case '=':
-
-            if (expect.equalsIgnoreCase("=")) {
-                lookahead = nextToken();
-            } else {
-                MessageFormat form = new MessageFormat(ResourcesMgr.getString
-                        ("Configuration.Error.Line.line.expected.expect.",
-                        "sun.security.util.AuthResources"));
-                Object[] source = {new Integer(linenum), expect, st.sval};
-                throw new IOException(form.format(source));
-            }
-            break;
-
-        default:
-            MessageFormat form = new MessageFormat(ResourcesMgr.getString
-                        ("Configuration.Error.Line.line.expected.expect.found.value.",
-                        "sun.security.util.AuthResources"));
-            Object[] source = {new Integer(linenum), expect, st.sval};
-            throw new IOException(form.format(source));
-        }
-        return value;
-    }
-
-    private boolean peek(String expect) {
-        boolean found = false;
-
-        switch (lookahead) {
-        case ',':
-            if (expect.equalsIgnoreCase(","))
-                found = true;
-            break;
-        case ';':
-            if (expect.equalsIgnoreCase(";"))
-                found = true;
-            break;
-        case '{':
-            if (expect.equalsIgnoreCase("{"))
-                found = true;
-            break;
-        case '}':
-            if (expect.equalsIgnoreCase("}"))
-                found = true;
-            break;
-        default:
-        }
-        return found;
-    }
-
-    private int nextToken() throws IOException {
-        int tok;
-        while ((tok = st.nextToken()) == StreamTokenizer.TT_EOL) {
-            linenum++;
-        }
-        return tok;
-    }
-
-    /*
-     * Fast path reading from file urls in order to avoid calling
-     * FileURLConnection.connect() which can be quite slow the first time
-     * it is called. We really should clean up FileURLConnection so that
-     * this is not a problem but in the meantime this fix helps reduce
-     * start up time noticeably for the new launcher. -- DAC
+    /**
+     * Refresh and reload the {@code Configuration} by re-reading all of the
+     * login configurations.
+     *
+     * @throws SecurityException if the caller does not have permission
+     *                           to refresh the {@code Configuration}
      */
-    private InputStream getInputStream(URL url) throws IOException {
-        if ("file".equalsIgnoreCase(url.getProtocol())) {
-            // Compatibility notes:
-            //
-            // Code changed from
-            //   String path = url.getFile().replace('/', File.separatorChar);
-            //   return new FileInputStream(path);
-            //
-            // The original implementation would search for "/tmp/a%20b"
-            // when url is "file:///tmp/a%20b". This is incorrect. The
-            // current codes fix this bug and searches for "/tmp/a b".
-            // For compatibility reasons, when the file "/tmp/a b" does
-            // not exist, the file named "/tmp/a%20b" will be tried.
-            //
-            // This also means that if both file exists, the behavior of
-            // this method is changed, and the current codes choose the
-            // correct one.
-            try {
-                return url.openStream();
-            } catch (Exception e) {
-                String file = url.getPath();
-                if (url.getHost().length() > 0) {  // For Windows UNC
-                    file = "//" + url.getHost() + file;
-                }
-                if (debugConfig != null) {
-                    debugConfig.println("cannot read " + url +
-                            ", try " + file);
-                }
-                return new FileInputStream(file);
-            }
-        } else {
-            return url.openStream();
-        }
-    }
-
-    private String expand(String value)
-        throws PropertyExpander.ExpandException, IOException {
-
-        if ("".equals(value)) {
-            return value;
-        }
-
-        if (expandProp) {
-
-            String s = PropertyExpander.expand(value);
-
-            if (s == null || s.length() == 0) {
-                MessageFormat form = new MessageFormat(ResourcesMgr.getString
-                        ("Configuration.Error.Line.line.system.property.value.expanded.to.empty.value",
-                        "sun.security.util.AuthResources"));
-                Object[] source = {new Integer(linenum), value};
-                throw new IOException(form.format(source));
-            }
-            return s;
-        } else {
-            return value;
-        }
+    @Override
+    public synchronized void refresh() {
+        configFile.engineRefresh();
     }
 }
--- a/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/beans/DefaultPersistenceDelegate.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -58,7 +58,8 @@
  */
 
 public class DefaultPersistenceDelegate extends PersistenceDelegate {
-    private String[] constructor;
+    private static final String[] EMPTY = {};
+    private final String[] constructor;
     private Boolean definesEquals;
 
     /**
@@ -67,7 +68,7 @@
      * @see #DefaultPersistenceDelegate(java.lang.String[])
      */
     public DefaultPersistenceDelegate() {
-        this(new String[0]);
+        this.constructor = EMPTY;
     }
 
     /**
@@ -92,7 +93,7 @@
      * @see #instantiate
      */
     public DefaultPersistenceDelegate(String[] constructorPropertyNames) {
-        this.constructor = constructorPropertyNames;
+        this.constructor = (constructorPropertyNames == null) ? EMPTY : constructorPropertyNames.clone();
     }
 
     private static boolean definesEquals(Class<?> type) {
--- a/jdk/src/share/classes/java/beans/EventSetDescriptor.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/beans/EventSetDescriptor.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -277,7 +277,9 @@
                 Method removeListenerMethod)
                 throws IntrospectionException {
         setName(eventSetName);
-        this.listenerMethodDescriptors = listenerMethodDescriptors;
+        this.listenerMethodDescriptors = (listenerMethodDescriptors != null)
+                ? listenerMethodDescriptors.clone()
+                : null;
         setAddListenerMethod(addListenerMethod);
         setRemoveListenerMethod(removeListenerMethod);
         setListenerType(listenerType);
@@ -347,7 +349,9 @@
      * events are fired.
      */
     public synchronized MethodDescriptor[] getListenerMethodDescriptors() {
-        return listenerMethodDescriptors;
+        return (this.listenerMethodDescriptors != null)
+                ? this.listenerMethodDescriptors.clone()
+                : null;
     }
 
     /**
--- a/jdk/src/share/classes/java/beans/MethodDescriptor.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/beans/MethodDescriptor.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -70,7 +70,9 @@
                 ParameterDescriptor parameterDescriptors[]) {
         setName(method.getName());
         setMethod(method);
-        this.parameterDescriptors = parameterDescriptors;
+        this.parameterDescriptors = (parameterDescriptors != null)
+                ? parameterDescriptors.clone()
+                : null;
     }
 
     /**
@@ -161,7 +163,9 @@
      *          a null array if the parameter names aren't known.
      */
     public ParameterDescriptor[] getParameterDescriptors() {
-        return parameterDescriptors;
+        return (this.parameterDescriptors != null)
+                ? this.parameterDescriptors.clone()
+                : null;
     }
 
     /*
--- a/jdk/src/share/classes/java/beans/Statement.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/beans/Statement.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -92,7 +92,7 @@
     public Statement(Object target, String methodName, Object[] arguments) {
         this.target = target;
         this.methodName = methodName;
-        this.arguments = (arguments == null) ? emptyArray : arguments;
+        this.arguments = (arguments == null) ? emptyArray : arguments.clone();
     }
 
     /**
@@ -128,7 +128,7 @@
      * @return the array of arguments
      */
     public Object[] getArguments() {
-        return arguments;
+        return this.arguments.clone();
     }
 
     /**
--- a/jdk/src/share/classes/java/io/FileSystem.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/io/FileSystem.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,6 +25,7 @@
 
 package java.io;
 
+import java.lang.annotation.Native;
 
 /**
  * Package-private abstract class for the local filesystem abstraction.
@@ -98,10 +99,10 @@
     /* -- Attribute accessors -- */
 
     /* Constants for simple boolean attributes */
-    public static final int BA_EXISTS    = 0x01;
-    public static final int BA_REGULAR   = 0x02;
-    public static final int BA_DIRECTORY = 0x04;
-    public static final int BA_HIDDEN    = 0x08;
+    @Native public static final int BA_EXISTS    = 0x01;
+    @Native public static final int BA_REGULAR   = 0x02;
+    @Native public static final int BA_DIRECTORY = 0x04;
+    @Native public static final int BA_HIDDEN    = 0x08;
 
     /**
      * Return the simple boolean attributes for the file or directory denoted
@@ -110,9 +111,9 @@
      */
     public abstract int getBooleanAttributes(File f);
 
-    public static final int ACCESS_READ    = 0x04;
-    public static final int ACCESS_WRITE   = 0x02;
-    public static final int ACCESS_EXECUTE = 0x01;
+    @Native public static final int ACCESS_READ    = 0x04;
+    @Native public static final int ACCESS_WRITE   = 0x02;
+    @Native public static final int ACCESS_EXECUTE = 0x01;
 
     /**
      * Check whether the file or directory denoted by the given abstract
@@ -203,9 +204,9 @@
     public abstract File[] listRoots();
 
     /* -- Disk usage -- */
-    public static final int SPACE_TOTAL  = 0;
-    public static final int SPACE_FREE   = 1;
-    public static final int SPACE_USABLE = 2;
+    @Native public static final int SPACE_TOTAL  = 0;
+    @Native public static final int SPACE_FREE   = 1;
+    @Native public static final int SPACE_USABLE = 2;
 
     public abstract long getSpace(File f, int t);
 
--- a/jdk/src/share/classes/java/lang/AbstractStringBuilder.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/AbstractStringBuilder.java	Tue Jan 22 11:54:16 2013 -0800
@@ -860,9 +860,9 @@
      * @return     the specified subsequence.
      *
      * @throws  IndexOutOfBoundsException
-     *          if <tt>start</tt> or <tt>end</tt> are negative,
-     *          if <tt>end</tt> is greater than <tt>length()</tt>,
-     *          or if <tt>start</tt> is greater than <tt>end</tt>
+     *          if {@code start} or {@code end} are negative,
+     *          if {@code end} is greater than {@code length()},
+     *          or if {@code start} is greater than {@code end}
      * @spec JSR-51
      */
     @Override
@@ -1292,7 +1292,7 @@
     /**
      * Returns the index within this string of the first occurrence of the
      * specified substring, starting at the specified index.  The integer
-     * returned is the smallest value <tt>k</tt> for which:
+     * returned is the smallest value {@code k} for which:
      * <blockquote><pre>
      *     k >= Math.min(fromIndex, str.length()) &&
      *                   this.toString().startsWith(str, k)
@@ -1418,7 +1418,7 @@
     public abstract String toString();
 
     /**
-     * Needed by <tt>String</tt> for the contentEquals method.
+     * Needed by {@code String} for the contentEquals method.
      */
     final char[] getValue() {
         return value;
--- a/jdk/src/share/classes/java/lang/Class.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/Class.java	Tue Jan 22 11:54:16 2013 -0800
@@ -506,6 +506,7 @@
      * returns {@code false} otherwise.
      * @return {@code true} if and only if this class is a synthetic class as
      *         defined by the Java Language Specification.
+     * @jls 13.1 The Form of a Binary
      * @since 1.5
      */
     public boolean isSynthetic() {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/java/lang/FunctionalInterface.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang;
+
+import java.lang.annotation.*;
+
+/**
+ * Indicates that an interface type declaration is intended to be a
+ * <i>functional interface</i> as defined by the Java Language
+ * Specification.
+ *
+ * Conceptually, a functional interface has exactly one abstract
+ * method.  Since {@linkplain java.lang.reflect.Method#isDefault()
+ * default methods} have an implementation, they are not abstract.  If
+ * an interface declares an abstract method overriding one of the
+ * public methods of {@code java.lang.Object}, that also does
+ * <em>not</em> count toward the interface's abstract method count
+ * since any implementation of the interface will have an
+ * implementation from {@code java.lang.Object} or elsewhere.
+ *
+ * <p>Note that instances of functional interfaces can be created with
+ * lambda expressions, method references, or constructor references.
+ *
+ * <p>If a type is annotated with this annotation type, compilers are
+ * required to generate an error message unless:
+ *
+ * <ul>
+ * <li> The type is an interface type and not an annotation type, enum, or class.
+ * <li> The annotated type satisfies the requirements of a functional interface.
+ * </ul>
+ *
+ * @jls 4.3.2. The Class Object
+ * @jls 9.8 Functional Interfaces
+ * @jls 9.4.3 Interface Method Body
+ * @since 1.8
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+public @interface FunctionalInterface {}
--- a/jdk/src/share/classes/java/lang/Integer.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/Integer.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,6 +25,7 @@
 
 package java.lang;
 
+import java.lang.annotation.Native;
 import java.util.Properties;
 
 /**
@@ -54,13 +55,13 @@
      * A constant holding the minimum value an {@code int} can
      * have, -2<sup>31</sup>.
      */
-    public static final int   MIN_VALUE = 0x80000000;
+    @Native public static final int   MIN_VALUE = 0x80000000;
 
     /**
      * A constant holding the maximum value an {@code int} can
      * have, 2<sup>31</sup>-1.
      */
-    public static final int   MAX_VALUE = 0x7fffffff;
+    @Native public static final int   MAX_VALUE = 0x7fffffff;
 
     /**
      * The {@code Class} instance representing the primitive type
@@ -772,7 +773,7 @@
                 int i = parseInt(integerCacheHighPropValue);
                 i = Math.max(i, 127);
                 // Maximum array size is Integer.MAX_VALUE
-                h = Math.min(i, Integer.MAX_VALUE - (-low));
+                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
             }
             high = h;
 
@@ -1295,7 +1296,7 @@
      *
      * @since 1.5
      */
-    public static final int SIZE = 32;
+    @Native public static final int SIZE = 32;
 
     /**
      * The number of bytes used to represent a {@code int} value in two's
@@ -1513,5 +1514,5 @@
     }
 
     /** use serialVersionUID from JDK 1.0.2 for interoperability */
-    private static final long serialVersionUID = 1360826667806852920L;
+    @Native private static final long serialVersionUID = 1360826667806852920L;
 }
--- a/jdk/src/share/classes/java/lang/Long.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/Long.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,6 +25,7 @@
 
 package java.lang;
 
+import java.lang.annotation.Native;
 import java.math.*;
 
 /**
@@ -54,13 +55,13 @@
      * A constant holding the minimum value a {@code long} can
      * have, -2<sup>63</sup>.
      */
-    public static final long MIN_VALUE = 0x8000000000000000L;
+    @Native public static final long MIN_VALUE = 0x8000000000000000L;
 
     /**
      * A constant holding the maximum value a {@code long} can
      * have, 2<sup>63</sup>-1.
      */
-    public static final long MAX_VALUE = 0x7fffffffffffffffL;
+    @Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
 
     /**
      * The {@code Class} instance representing the primitive type
@@ -1317,7 +1318,7 @@
      *
      * @since 1.5
      */
-    public static final int SIZE = 64;
+    @Native public static final int SIZE = 64;
 
     /**
      * The number of bytes used to represent a {@code long} value in two's
@@ -1540,5 +1541,5 @@
     }
 
     /** use serialVersionUID from JDK 1.0.2 for interoperability */
-    private static final long serialVersionUID = 4290774380558885855L;
+    @Native private static final long serialVersionUID = 4290774380558885855L;
 }
--- a/jdk/src/share/classes/java/lang/String.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/String.java	Tue Jan 22 11:54:16 2013 -0800
@@ -615,10 +615,10 @@
     }
 
     /**
-     * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
+     * Returns {@code true} if, and only if, {@link #length()} is {@code 0}.
      *
-     * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
-     * <tt>false</tt>
+     * @return {@code true} if {@link #length()} is {@code 0}, otherwise
+     * {@code false}
      *
      * @since 1.6
      */
@@ -1229,23 +1229,23 @@
     /**
      * Tests if two string regions are equal.
      * <p>
-     * A substring of this <tt>String</tt> object is compared to a substring
+     * A substring of this {@code String} object is compared to a substring
      * of the argument other. The result is true if these substrings
      * represent identical character sequences. The substring of this
-     * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
-     * and has length <tt>len</tt>. The substring of other to be compared
-     * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
-     * result is <tt>false</tt> if and only if at least one of the following
+     * {@code String} object to be compared begins at index {@code toffset}
+     * and has length {@code len}. The substring of other to be compared
+     * begins at index {@code ooffset} and has length {@code len}. The
+     * result is {@code false} if and only if at least one of the following
      * is true:
-     * <ul><li><tt>toffset</tt> is negative.
-     * <li><tt>ooffset</tt> is negative.
-     * <li><tt>toffset+len</tt> is greater than the length of this
-     * <tt>String</tt> object.
-     * <li><tt>ooffset+len</tt> is greater than the length of the other
+     * <ul><li>{@code toffset} is negative.
+     * <li>{@code ooffset} is negative.
+     * <li>{@code toffset+len} is greater than the length of this
+     * {@code String} object.
+     * <li>{@code ooffset+len} is greater than the length of the other
      * argument.
-     * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
+     * <li>There is some nonnegative integer <i>k</i> less than {@code len}
      * such that:
-     * <tt>this.charAt(toffset+<i>k</i>)&nbsp;!=&nbsp;other.charAt(ooffset+<i>k</i>)</tt>
+     * <code>this.charAt(toffset+<i>k</i>)&nbsp;!=&nbsp;other.charAt(ooffset+<i>k</i>)</code>
      * </ul>
      *
      * @param   toffset   the starting offset of the subregion in this string.
@@ -1280,28 +1280,28 @@
     /**
      * Tests if two string regions are equal.
      * <p>
-     * A substring of this <tt>String</tt> object is compared to a substring
-     * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
+     * A substring of this {@code String} object is compared to a substring
+     * of the argument {@code other}. The result is {@code true} if these
      * substrings represent character sequences that are the same, ignoring
-     * case if and only if <tt>ignoreCase</tt> is true. The substring of
-     * this <tt>String</tt> object to be compared begins at index
-     * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
-     * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
-     * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
+     * case if and only if {@code ignoreCase} is true. The substring of
+     * this {@code String} object to be compared begins at index
+     * {@code toffset} and has length {@code len}. The substring of
+     * {@code other} to be compared begins at index {@code ooffset} and
+     * has length {@code len}. The result is {@code false} if and only if
      * at least one of the following is true:
-     * <ul><li><tt>toffset</tt> is negative.
-     * <li><tt>ooffset</tt> is negative.
-     * <li><tt>toffset+len</tt> is greater than the length of this
-     * <tt>String</tt> object.
-     * <li><tt>ooffset+len</tt> is greater than the length of the other
+     * <ul><li>{@code toffset} is negative.
+     * <li>{@code ooffset} is negative.
+     * <li>{@code toffset+len} is greater than the length of this
+     * {@code String} object.
+     * <li>{@code ooffset+len} is greater than the length of the other
      * argument.
-     * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
-     * integer <i>k</i> less than <tt>len</tt> such that:
+     * <li>{@code ignoreCase} is {@code false} and there is some nonnegative
+     * integer <i>k</i> less than {@code len} such that:
      * <blockquote><pre>
      * this.charAt(toffset+k) != other.charAt(ooffset+k)
      * </pre></blockquote>
-     * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
-     * integer <i>k</i> less than <tt>len</tt> such that:
+     * <li>{@code ignoreCase} is {@code true} and there is some nonnegative
+     * integer <i>k</i> less than {@code len} such that:
      * <blockquote><pre>
      * Character.toLowerCase(this.charAt(toffset+k)) !=
      Character.toLowerCase(other.charAt(ooffset+k))
@@ -1500,12 +1500,12 @@
      * of {@code ch} in the range from 0 to 0xFFFF (inclusive),
      * this is the smallest value <i>k</i> such that:
      * <blockquote><pre>
-     * (this.charAt(<i>k</i>) == ch) && (<i>k</i> &gt;= fromIndex)
+     * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &gt;= fromIndex)
      * </pre></blockquote>
      * is true. For other values of {@code ch}, it is the
      * smallest value <i>k</i> such that:
      * <blockquote><pre>
-     * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> &gt;= fromIndex)
+     * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &gt;= fromIndex)
      * </pre></blockquote>
      * is true. In either case, if no such character occurs in this
      * string at or after position {@code fromIndex}, then
@@ -1604,12 +1604,12 @@
      * from 0 to 0xFFFF (inclusive), the index returned is the largest
      * value <i>k</i> such that:
      * <blockquote><pre>
-     * (this.charAt(<i>k</i>) == ch) && (<i>k</i> &lt;= fromIndex)
+     * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &lt;= fromIndex)
      * </pre></blockquote>
      * is true. For other values of {@code ch}, it is the
      * largest value <i>k</i> such that:
      * <blockquote><pre>
-     * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> &lt;= fromIndex)
+     * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &lt;= fromIndex)
      * </pre></blockquote>
      * is true. In either case, if no such character occurs in this
      * string at or before position {@code fromIndex}, then
@@ -1690,7 +1690,7 @@
      *
      * <p>The returned index is the smallest value <i>k</i> for which:
      * <blockquote><pre>
-     * <i>k</i> &gt;= fromIndex && this.startsWith(str, <i>k</i>)
+     * <i>k</i> &gt;= fromIndex {@code &&} this.startsWith(str, <i>k</i>)
      * </pre></blockquote>
      * If no such value of <i>k</i> exists, then {@code -1} is returned.
      *
@@ -1799,7 +1799,7 @@
      *
      * <p>The returned index is the largest value <i>k</i> for which:
      * <blockquote><pre>
-     * <i>k</i> &lt;= fromIndex && this.startsWith(str, <i>k</i>)
+     * <i>k</i> {@code <=} fromIndex {@code &&} this.startsWith(str, <i>k</i>)
      * </pre></blockquote>
      * If no such value of <i>k</i> exists, then {@code -1} is returned.
      *
@@ -2080,17 +2080,18 @@
      * href="../util/regex/Pattern.html#sum">regular expression</a>.
      *
      * <p> An invocation of this method of the form
-     * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
+     * <i>str</i>{@code .matches(}<i>regex</i>{@code )} yields exactly the
      * same result as the expression
      *
-     * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
-     * java.util.regex.Pattern#matches(String,CharSequence)
-     * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
+     * <blockquote>
+     * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#matches(String,CharSequence)
+     * matches(<i>regex</i>, <i>str</i>)}
+     * </blockquote>
      *
      * @param   regex
      *          the regular expression to which this string is to be matched
      *
-     * @return  <tt>true</tt> if, and only if, this string matches the
+     * @return  {@code true} if, and only if, this string matches the
      *          given regular expression
      *
      * @throws  PatternSyntaxException
@@ -2124,18 +2125,20 @@
      * given replacement.
      *
      * <p> An invocation of this method of the form
-     * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
+     * <i>str</i>{@code .replaceFirst(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
      * yields exactly the same result as the expression
      *
-     * <blockquote><tt>
-     * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
-     * compile}(</tt><i>regex</i><tt>).{@link
-     * java.util.regex.Pattern#matcher(java.lang.CharSequence)
-     * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
-     * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
+     * <blockquote>
+     * <code>
+     * {@link java.util.regex.Pattern}.{@link
+     * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
+     * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
+     * java.util.regex.Matcher#replaceFirst replaceFirst}(<i>repl</i>)
+     * </code>
+     * </blockquote>
      *
      *<p>
-     * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
+     * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
      * replacement string may cause the results to be different than if it were
      * being treated as a literal replacement string; see
      * {@link java.util.regex.Matcher#replaceFirst}.
@@ -2147,7 +2150,7 @@
      * @param   replacement
      *          the string to be substituted for the first match
      *
-     * @return  The resulting <tt>String</tt>
+     * @return  The resulting {@code String}
      *
      * @throws  PatternSyntaxException
      *          if the regular expression's syntax is invalid
@@ -2167,18 +2170,20 @@
      * given replacement.
      *
      * <p> An invocation of this method of the form
-     * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
+     * <i>str</i>{@code .replaceAll(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
      * yields exactly the same result as the expression
      *
-     * <blockquote><tt>
-     * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
-     * compile}(</tt><i>regex</i><tt>).{@link
-     * java.util.regex.Pattern#matcher(java.lang.CharSequence)
-     * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
-     * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
+     * <blockquote>
+     * <code>
+     * {@link java.util.regex.Pattern}.{@link
+     * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
+     * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
+     * java.util.regex.Matcher#replaceAll replaceAll}(<i>repl</i>)
+     * </code>
+     * </blockquote>
      *
      *<p>
-     * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
+     * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
      * replacement string may cause the results to be different than if it were
      * being treated as a literal replacement string; see
      * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
@@ -2190,7 +2195,7 @@
      * @param   replacement
      *          the string to be substituted for each match
      *
-     * @return  The resulting <tt>String</tt>
+     * @return  The resulting {@code String}
      *
      * @throws  PatternSyntaxException
      *          if the regular expression's syntax is invalid
@@ -2234,7 +2239,7 @@
      * expression does not match any part of the input then the resulting array
      * has just one element, namely this string.
      *
-     * <p> The <tt>limit</tt> parameter controls the number of times the
+     * <p> The {@code limit} parameter controls the number of times the
      * pattern is applied and therefore affects the length of the resulting
      * array.  If the limit <i>n</i> is greater than zero then the pattern
      * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's
@@ -2245,7 +2250,7 @@
      * the pattern will be applied as many times as possible, the array can
      * have any length, and trailing empty strings will be discarded.
      *
-     * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
+     * <p> The string {@code "boo:and:foo"}, for example, yields the
      * following results with these parameters:
      *
      * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
@@ -2256,33 +2261,34 @@
      * </tr>
      * <tr><td align=center>:</td>
      *     <td align=center>2</td>
-     *     <td><tt>{ "boo", "and:foo" }</tt></td></tr>
+     *     <td>{@code { "boo", "and:foo" }}</td></tr>
      * <tr><td align=center>:</td>
      *     <td align=center>5</td>
-     *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
+     *     <td>{@code { "boo", "and", "foo" }}</td></tr>
      * <tr><td align=center>:</td>
      *     <td align=center>-2</td>
-     *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
+     *     <td>{@code { "boo", "and", "foo" }}</td></tr>
      * <tr><td align=center>o</td>
      *     <td align=center>5</td>
-     *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
+     *     <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
      * <tr><td align=center>o</td>
      *     <td align=center>-2</td>
-     *     <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
+     *     <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
      * <tr><td align=center>o</td>
      *     <td align=center>0</td>
-     *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
+     *     <td>{@code { "b", "", ":and:f" }}</td></tr>
      * </table></blockquote>
      *
      * <p> An invocation of this method of the form
-     * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt>&nbsp;<i>n</i><tt>)</tt>
+     * <i>str.</i>{@code split(}<i>regex</i>{@code ,}&nbsp;<i>n</i>{@code )}
      * yields the same result as the expression
      *
      * <blockquote>
-     * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
-     * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
-     * java.util.regex.Pattern#split(java.lang.CharSequence,int)
-     * split}<tt>(</tt><i>str</i><tt>,</tt>&nbsp;<i>n</i><tt>)</tt>
+     * <code>
+     * {@link java.util.regex.Pattern}.{@link
+     * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
+     * java.util.regex.Pattern#split(java.lang.CharSequence,int) split}(<i>str</i>,&nbsp;<i>n</i>)
+     * </code>
      * </blockquote>
      *
      *
@@ -2364,7 +2370,7 @@
      * argument of zero.  Trailing empty strings are therefore not included in
      * the resulting array.
      *
-     * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
+     * <p> The string {@code "boo:and:foo"}, for example, yields the following
      * results with these expressions:
      *
      * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
@@ -2373,9 +2379,9 @@
      *  <th>Result</th>
      * </tr>
      * <tr><td align=center>:</td>
-     *     <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
+     *     <td>{@code { "boo", "and", "foo" }}</td></tr>
      * <tr><td align=center>o</td>
-     *     <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
+     *     <td>{@code { "b", "", ":and:f" }}</td></tr>
      * </table></blockquote>
      *
      *
@@ -2815,7 +2821,7 @@
      *         limited by the maximum dimension of a Java array as defined by
      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
      *         The behaviour on a
-     *         <tt>null</tt> argument depends on the <a
+     *         {@code null} argument depends on the <a
      *         href="../util/Formatter.html#syntax">conversion</a>.
      *
      * @throws  java.util.IllegalFormatException
@@ -2828,7 +2834,7 @@
      *          formatter class specification.
      *
      * @throws  NullPointerException
-     *          If the <tt>format</tt> is <tt>null</tt>
+     *          If the {@code format} is {@code null}
      *
      * @return  A formatted string
      *
@@ -2845,7 +2851,7 @@
      *
      * @param  l
      *         The {@linkplain java.util.Locale locale} to apply during
-     *         formatting.  If <tt>l</tt> is <tt>null</tt> then no localization
+     *         formatting.  If {@code l} is {@code null} then no localization
      *         is applied.
      *
      * @param  format
@@ -2859,7 +2865,7 @@
      *         limited by the maximum dimension of a Java array as defined by
      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
      *         The behaviour on a
-     *         <tt>null</tt> argument depends on the <a
+     *         {@code null} argument depends on the <a
      *         href="../util/Formatter.html#syntax">conversion</a>.
      *
      * @throws  java.util.IllegalFormatException
@@ -2872,7 +2878,7 @@
      *          formatter class specification
      *
      * @throws  NullPointerException
-     *          If the <tt>format</tt> is <tt>null</tt>
+     *          If the {@code format} is {@code null}
      *
      * @return  A formatted string
      *
@@ -3143,7 +3149,7 @@
     *     programmer should be aware that producing distinct integer results
     *     for unequal objects may improve the performance of hash tables.
     * </ul>
-    * <p/>
+    * </p>
      * The hash value will never be zero.
     *
     * @return  a hash code value for this object.
--- a/jdk/src/share/classes/java/lang/StringBuffer.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/StringBuffer.java	Tue Jan 22 11:54:16 2013 -0800
@@ -57,7 +57,7 @@
  * <p>
  * In general, if sb refers to an instance of a {@code StringBuffer},
  * then {@code sb.append(x)} has the same effect as
- * {@code sb.insert(sb.length(),&nbsp;x)}.
+ * {@code sb.insert(sb.length(), x)}.
  * <p>
  * Whenever an operation occurs involving a source sequence (such as
  * appending or inserting from a source sequence), this class synchronizes
@@ -80,7 +80,7 @@
  *
  * As of  release JDK 5, this class has been supplemented with an equivalent
  * class designed for use by a single thread, {@link StringBuilder}.  The
- * <tt>StringBuilder</tt> class should generally be used in preference to
+ * {@code StringBuilder} class should generally be used in preference to
  * this one, as it supports all of the same operations but it is faster, as
  * it performs no synchronization.
  *
@@ -262,17 +262,17 @@
     }
 
     /**
-     * Appends the specified <tt>StringBuffer</tt> to this sequence.
+     * Appends the specified {@code StringBuffer} to this sequence.
      * <p>
-     * The characters of the <tt>StringBuffer</tt> argument are appended,
-     * in order, to the contents of this <tt>StringBuffer</tt>, increasing the
-     * length of this <tt>StringBuffer</tt> by the length of the argument.
-     * If <tt>sb</tt> is <tt>null</tt>, then the four characters
-     * <tt>"null"</tt> are appended to this <tt>StringBuffer</tt>.
+     * The characters of the {@code StringBuffer} argument are appended,
+     * in order, to the contents of this {@code StringBuffer}, increasing the
+     * length of this {@code StringBuffer} by the length of the argument.
+     * If {@code sb} is {@code null}, then the four characters
+     * {@code "null"} are appended to this {@code StringBuffer}.
      * <p>
      * Let <i>n</i> be the length of the old character sequence, the one
-     * contained in the <tt>StringBuffer</tt> just prior to execution of the
-     * <tt>append</tt> method. Then the character at index <i>k</i> in
+     * contained in the {@code StringBuffer} just prior to execution of the
+     * {@code append} method. Then the character at index <i>k</i> in
      * the new character sequence is equal to the character at index <i>k</i>
      * in the old character sequence, if <i>k</i> is less than <i>n</i>;
      * otherwise, it is equal to the character at index <i>k-n</i> in the
@@ -281,7 +281,7 @@
      * This method synchronizes on {@code this}, the destination
      * object, but does not synchronize on the source ({@code sb}).
      *
-     * @param   sb   the <tt>StringBuffer</tt> to append.
+     * @param   sb   the {@code StringBuffer} to append.
      * @return  a reference to this object.
      * @since 1.4
      */
--- a/jdk/src/share/classes/java/lang/StringBuilder.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/StringBuilder.java	Tue Jan 22 11:54:16 2013 -0800
@@ -28,39 +28,39 @@
 
 /**
  * A mutable sequence of characters.  This class provides an API compatible
- * with <code>StringBuffer</code>, but with no guarantee of synchronization.
+ * with {@code StringBuffer}, but with no guarantee of synchronization.
  * This class is designed for use as a drop-in replacement for
- * <code>StringBuffer</code> in places where the string buffer was being
+ * {@code StringBuffer} in places where the string buffer was being
  * used by a single thread (as is generally the case).   Where possible,
  * it is recommended that this class be used in preference to
- * <code>StringBuffer</code> as it will be faster under most implementations.
+ * {@code StringBuffer} as it will be faster under most implementations.
  *
- * <p>The principal operations on a <code>StringBuilder</code> are the
- * <code>append</code> and <code>insert</code> methods, which are
+ * <p>The principal operations on a {@code StringBuilder} are the
+ * {@code append} and {@code insert} methods, which are
  * overloaded so as to accept data of any type. Each effectively
  * converts a given datum to a string and then appends or inserts the
  * characters of that string to the string builder. The
- * <code>append</code> method always adds these characters at the end
- * of the builder; the <code>insert</code> method adds the characters at
+ * {@code append} method always adds these characters at the end
+ * of the builder; the {@code insert} method adds the characters at
  * a specified point.
  * <p>
- * For example, if <code>z</code> refers to a string builder object
- * whose current contents are "<code>start</code>", then
- * the method call <code>z.append("le")</code> would cause the string
- * builder to contain "<code>startle</code>", whereas
- * <code>z.insert(4, "le")</code> would alter the string builder to
- * contain "<code>starlet</code>".
+ * For example, if {@code z} refers to a string builder object
+ * whose current contents are "{@code start}", then
+ * the method call {@code z.append("le")} would cause the string
+ * builder to contain "{@code startle}", whereas
+ * {@code z.insert(4, "le")} would alter the string builder to
+ * contain "{@code starlet}".
  * <p>
- * In general, if sb refers to an instance of a <code>StringBuilder</code>,
- * then <code>sb.append(x)</code> has the same effect as
- * <code>sb.insert(sb.length(),&nbsp;x)</code>.
- *
+ * In general, if sb refers to an instance of a {@code StringBuilder},
+ * then {@code sb.append(x)} has the same effect as
+ * {@code sb.insert(sb.length(), x)}.
+ * <p>
  * Every string builder has a capacity. As long as the length of the
  * character sequence contained in the string builder does not exceed
  * the capacity, it is not necessary to allocate a new internal
  * buffer. If the internal buffer overflows, it is automatically made larger.
  *
- * <p>Instances of <code>StringBuilder</code> are not safe for
+ * <p>Instances of {@code StringBuilder} are not safe for
  * use by multiple threads. If such synchronization is required then it is
  * recommended that {@link java.lang.StringBuffer} be used.
  *
@@ -87,11 +87,11 @@
 
     /**
      * Constructs a string builder with no characters in it and an
-     * initial capacity specified by the <code>capacity</code> argument.
+     * initial capacity specified by the {@code capacity} argument.
      *
      * @param      capacity  the initial capacity.
-     * @throws     NegativeArraySizeException  if the <code>capacity</code>
-     *               argument is less than <code>0</code>.
+     * @throws     NegativeArraySizeException  if the {@code capacity}
+     *               argument is less than {@code 0}.
      */
     public StringBuilder(int capacity) {
         super(capacity);
@@ -100,10 +100,10 @@
     /**
      * Constructs a string builder initialized to the contents of the
      * specified string. The initial capacity of the string builder is
-     * <code>16</code> plus the length of the string argument.
+     * {@code 16} plus the length of the string argument.
      *
      * @param   str   the initial contents of the buffer.
-     * @throws    NullPointerException if <code>str</code> is <code>null</code>
+     * @throws    NullPointerException if {@code str} is {@code null}
      */
     public StringBuilder(String str) {
         super(str.length() + 16);
@@ -112,12 +112,12 @@
 
     /**
      * Constructs a string builder that contains the same characters
-     * as the specified <code>CharSequence</code>. The initial capacity of
-     * the string builder is <code>16</code> plus the length of the
-     * <code>CharSequence</code> argument.
+     * as the specified {@code CharSequence}. The initial capacity of
+     * the string builder is {@code 16} plus the length of the
+     * {@code CharSequence} argument.
      *
      * @param      seq   the sequence to copy.
-     * @throws    NullPointerException if <code>seq</code> is <code>null</code>
+     * @throws    NullPointerException if {@code seq} is {@code null}
      */
     public StringBuilder(CharSequence seq) {
         this(seq.length() + 16);
@@ -136,22 +136,22 @@
     }
 
     /**
-     * Appends the specified <tt>StringBuffer</tt> to this sequence.
+     * Appends the specified {@code StringBuffer} to this sequence.
      * <p>
-     * The characters of the <tt>StringBuffer</tt> argument are appended,
+     * The characters of the {@code StringBuffer} argument are appended,
      * in order, to this sequence, increasing the
      * length of this sequence by the length of the argument.
-     * If <tt>sb</tt> is <tt>null</tt>, then the four characters
-     * <tt>"null"</tt> are appended to this sequence.
+     * If {@code sb} is {@code null}, then the four characters
+     * {@code "null"} are appended to this sequence.
      * <p>
      * Let <i>n</i> be the length of this character sequence just prior to
-     * execution of the <tt>append</tt> method. Then the character at index
+     * execution of the {@code append} method. Then the character at index
      * <i>k</i> in the new character sequence is equal to the character at
      * index <i>k</i> in the old character sequence, if <i>k</i> is less than
      * <i>n</i>; otherwise, it is equal to the character at index <i>k-n</i>
-     * in the argument <code>sb</code>.
+     * in the argument {@code sb}.
      *
-     * @param   sb   the <tt>StringBuffer</tt> to append.
+     * @param   sb   the {@code StringBuffer} to append.
      * @return  a reference to this object.
      */
     public StringBuilder append(StringBuffer sb) {
@@ -418,13 +418,13 @@
     }
 
     /**
-     * Save the state of the <tt>StringBuilder</tt> instance to a stream
+     * Save the state of the {@code StringBuilder} instance to a stream
      * (that is, serialize it).
      *
      * @serialData the number of characters currently stored in the string
-     *             builder (<tt>int</tt>), followed by the characters in the
-     *             string builder (<tt>char[]</tt>).   The length of the
-     *             <tt>char</tt> array may be greater than the number of
+     *             builder ({@code int}), followed by the characters in the
+     *             string builder ({@code char[]}).   The length of the
+     *             {@code char} array may be greater than the number of
      *             characters currently stored in the string builder, in which
      *             case extra characters are ignored.
      */
--- a/jdk/src/share/classes/java/lang/StringIndexOutOfBoundsException.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/StringIndexOutOfBoundsException.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,7 +26,7 @@
 package java.lang;
 
 /**
- * Thrown by <code>String</code> methods to indicate that an index
+ * Thrown by {@code String} methods to indicate that an index
  * is either negative or greater than the size of the string.  For
  * some methods such as the charAt method, this exception also is
  * thrown when the index is equal to the size of the string.
@@ -40,7 +40,7 @@
     private static final long serialVersionUID = -6762910422159637258L;
 
     /**
-     * Constructs a <code>StringIndexOutOfBoundsException</code> with no
+     * Constructs a {@code StringIndexOutOfBoundsException} with no
      * detail message.
      *
      * @since   JDK1.0.
@@ -50,7 +50,7 @@
     }
 
     /**
-     * Constructs a <code>StringIndexOutOfBoundsException</code> with
+     * Constructs a {@code StringIndexOutOfBoundsException} with
      * the specified detail message.
      *
      * @param   s   the detail message.
@@ -60,7 +60,7 @@
     }
 
     /**
-     * Constructs a new <code>StringIndexOutOfBoundsException</code>
+     * Constructs a new {@code StringIndexOutOfBoundsException}
      * class with an argument indicating the illegal index.
      *
      * @param   index   the illegal index.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/java/lang/annotation/Repeatable.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang.annotation;
+
+/**
+ * The annotation type {@code java.lang.annotation.Repeatable} is
+ * used to indicate that the annotation type whose declaration it
+ * (meta-)annotates is <em>repeatable</em>. The value of
+ * {@code @Repeatable} indicates the <em>containing annotation
+ * type</em> for the repeatable annotation type.
+ *
+ * @since 1.8
+ * @jls 9.6 Annotation Types
+ * @jls 9.7 Annotations
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.ANNOTATION_TYPE)
+public @interface Repeatable {
+    /**
+     * Indicates the <em>containing annotation type</em> for the
+     * repeatable annotation type.
+     */
+    Class<? extends Annotation> value();
+}
--- a/jdk/src/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Tue Jan 22 11:54:16 2013 -0800
@@ -295,9 +295,6 @@
 
         String invokerDesc = invokerType.toMethodDescriptorString();
         mv = cw.visitMethod(Opcodes.ACC_STATIC, invokerName, invokerDesc, null, null);
-
-        // Force inlining of this invoker method.
-        mv.visitAnnotation("Ljava/lang/invoke/ForceInline;", true);
     }
 
     /**
@@ -524,6 +521,9 @@
         // Mark this method as a compiled LambdaForm
         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Compiled;", true);
 
+        // Force inlining of this invoker method.
+        mv.visitAnnotation("Ljava/lang/invoke/ForceInline;", true);
+
         // iterate over the form's names, generating bytecode instructions for each
         // start iterating at the first name following the arguments
         for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) {
@@ -943,6 +943,9 @@
         // Suppress this method in backtraces displayed to the user.
         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true);
 
+        // Don't inline the interpreter entry.
+        mv.visitAnnotation("Ljava/lang/invoke/DontInline;", true);
+
         // create parameter array
         emitIconstInsn(invokerType.parameterCount());
         mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
@@ -1005,6 +1008,9 @@
         // Suppress this method in backtraces displayed to the user.
         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true);
 
+        // Force inlining of this invoker method.
+        mv.visitAnnotation("Ljava/lang/invoke/ForceInline;", true);
+
         // Load receiver
         emitAloadInsn(0);
 
--- a/jdk/src/share/classes/java/lang/invoke/LambdaForm.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/invoke/LambdaForm.java	Tue Jan 22 11:54:16 2013 -0800
@@ -592,6 +592,7 @@
     private int invocationCounter = 0;
 
     @Hidden
+    @DontInline
     /** Interpretively invoke this form on the given arguments. */
     Object interpretWithArguments(Object... argumentValues) throws Throwable {
         if (TRACE_INTERPRETER)
@@ -606,6 +607,7 @@
     }
 
     @Hidden
+    @DontInline
     /** Evaluate a single Name within this form, applying its function to its arguments. */
     Object interpretName(Name name, Object[] values) throws Throwable {
         if (TRACE_INTERPRETER)
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -310,9 +310,9 @@
     }
 
     static class AsVarargsCollector extends MethodHandle {
-        MethodHandle target;
-        final Class<?> arrayType;
-        MethodHandle cache;
+        private final MethodHandle target;
+        private final Class<?> arrayType;
+        private MethodHandle cache;
 
         AsVarargsCollector(MethodHandle target, MethodType type, Class<?> arrayType) {
             super(type, reinvokerForm(type));
--- a/jdk/src/share/classes/java/lang/reflect/Constructor.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/reflect/Constructor.java	Tue Jan 22 11:54:16 2013 -0800
@@ -66,6 +66,8 @@
     private transient ConstructorRepository genericInfo;
     private byte[]              annotations;
     private byte[]              parameterAnnotations;
+    // This is set by the vm at Constructor creation
+    private byte[]              typeAnnotations;
 
     // Generics infrastructure
     // Accessor for factory
@@ -138,6 +140,8 @@
         res.root = this;
         // Might as well eagerly propagate this if already present
         res.constructorAccessor = constructorAccessor;
+
+        res.typeAnnotations = typeAnnotations;
         return res;
     }
 
@@ -407,6 +411,7 @@
 
     /**
      * {@inheritDoc}
+     * @jls 13.1 The Form of a Binary
      * @since 1.5
      */
     @Override
--- a/jdk/src/share/classes/java/lang/reflect/Executable.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/reflect/Executable.java	Tue Jan 22 11:54:16 2013 -0800
@@ -324,6 +324,7 @@
      * @return true if and only if this executable is a synthetic
      * construct as defined by
      * <cite>The Java&trade; Language Specification</cite>.
+     * @jls 13.1 The Form of a Binary
      */
     public boolean isSynthetic() {
         return Modifier.isSynthetic(getModifiers());
--- a/jdk/src/share/classes/java/lang/reflect/Field.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/reflect/Field.java	Tue Jan 22 11:54:16 2013 -0800
@@ -80,6 +80,8 @@
     // currently only two levels deep (i.e., one root Field and
     // potentially many Field objects pointing to it.)
     private Field               root;
+    // This is set by the vm at Field creation
+    private byte[]              typeAnnotations;
 
     // Generics infrastructure
 
@@ -144,6 +146,8 @@
         // Might as well eagerly propagate this if already present
         res.fieldAccessor = fieldAccessor;
         res.overrideFieldAccessor = overrideFieldAccessor;
+
+        res.typeAnnotations = typeAnnotations;
         return res;
     }
 
--- a/jdk/src/share/classes/java/lang/reflect/Member.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/reflect/Member.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -87,6 +87,7 @@
      *
      * @return true if and only if this member was introduced by
      * the compiler.
+     * @jls 13.1 The Form of a Binary
      * @since 1.5
      */
     public boolean isSynthetic();
--- a/jdk/src/share/classes/java/lang/reflect/Method.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/lang/reflect/Method.java	Tue Jan 22 11:54:16 2013 -0800
@@ -79,7 +79,8 @@
     // currently only two levels deep (i.e., one root Method and
     // potentially many Method objects pointing to it.)
     private Method              root;
-
+    // This is set by the vm at Method creation
+    private byte[]              typeAnnotations;
 
     // Generics infrastructure
     private String getGenericSignature() {return signature;}
@@ -150,6 +151,8 @@
         res.root = this;
         // Might as well eagerly propagate this if already present
         res.methodAccessor = methodAccessor;
+
+        res.typeAnnotations = typeAnnotations;
         return res;
     }
 
@@ -497,6 +500,7 @@
 
     /**
      * {@inheritDoc}
+     * @jls 13.1 The Form of a Binary
      * @since 1.5
      */
     @Override
@@ -504,6 +508,22 @@
         return super.isSynthetic();
     }
 
+    /**
+     * Returns {@code true} if this method is a default
+     * method; returns {@code false} otherwise.
+     *
+     * A default method is a non-abstract method, that is, a method
+     * with a body, declared in an interface type.
+     *
+     * @return true if and only if this method is a default
+     * method as defined by the Java Language Specification.
+     * @since 1.8
+     */
+    public boolean isDefault() {
+        return (getModifiers() & Modifier.ABSTRACT) == 0 &&
+            getDeclaringClass().isInterface();
+    }
+
     // NOTE that there is no synchronization used here. It is correct
     // (though not efficient) to generate more than one MethodAccessor
     // for a given Method. However, avoiding synchronization will
--- a/jdk/src/share/classes/java/net/SocketOptions.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/net/SocketOptions.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,6 +25,8 @@
 
 package java.net;
 
+import java.lang.annotation.Native;
+
 /**
  * Interface of methods to get/set socket options.  This interface is
  * implemented by: <B>SocketImpl</B> and  <B>DatagramSocketImpl</B>.
@@ -137,7 +139,7 @@
      * @see Socket#getTcpNoDelay
      */
 
-    public final static int TCP_NODELAY = 0x0001;
+    @Native public final static int TCP_NODELAY = 0x0001;
 
     /**
      * Fetch the local address binding of a socket (this option cannot
@@ -158,7 +160,7 @@
      * @see DatagramSocket#getLocalAddress
      */
 
-    public final static int SO_BINDADDR = 0x000F;
+    @Native public final static int SO_BINDADDR = 0x000F;
 
     /** Sets SO_REUSEADDR for a socket.  This is used only for MulticastSockets
      * in java, and it is set by default for MulticastSockets.
@@ -166,7 +168,7 @@
      * Valid for: DatagramSocketImpl
      */
 
-    public final static int SO_REUSEADDR = 0x04;
+    @Native public final static int SO_REUSEADDR = 0x04;
 
     /**
      * Sets SO_BROADCAST for a socket. This option enables and disables
@@ -177,7 +179,7 @@
      * @since 1.4
      */
 
-    public final static int SO_BROADCAST = 0x0020;
+    @Native public final static int SO_BROADCAST = 0x0020;
 
     /** Set which outgoing interface on which to send multicast packets.
      * Useful on hosts with multiple network interfaces, where applications
@@ -189,7 +191,7 @@
      * @see MulticastSocket#getInterface()
      */
 
-    public final static int IP_MULTICAST_IF = 0x10;
+    @Native public final static int IP_MULTICAST_IF = 0x10;
 
     /** Same as above. This option is introduced so that the behaviour
      *  with IP_MULTICAST_IF will be kept the same as before, while
@@ -201,7 +203,7 @@
      * @see MulticastSocket#getNetworkInterface()
      * @since 1.4
      */
-    public final static int IP_MULTICAST_IF2 = 0x1f;
+    @Native public final static int IP_MULTICAST_IF2 = 0x1f;
 
     /**
      * This option enables or disables local loopback of multicast datagrams.
@@ -209,7 +211,7 @@
      * @since 1.4
      */
 
-    public final static int IP_MULTICAST_LOOP = 0x12;
+    @Native public final static int IP_MULTICAST_LOOP = 0x12;
 
     /**
      * This option sets the type-of-service or traffic class field
@@ -217,7 +219,7 @@
      * @since 1.4
      */
 
-    public final static int IP_TOS = 0x3;
+    @Native public final static int IP_TOS = 0x3;
 
     /**
      * Specify a linger-on-close timeout.  This option disables/enables
@@ -235,7 +237,7 @@
      * @see Socket#setSoLinger
      * @see Socket#getSoLinger
      */
-    public final static int SO_LINGER = 0x0080;
+    @Native public final static int SO_LINGER = 0x0080;
 
     /** Set a timeout on blocking Socket operations:
      * <PRE>
@@ -256,7 +258,7 @@
      * @see ServerSocket#setSoTimeout
      * @see DatagramSocket#setSoTimeout
      */
-    public final static int SO_TIMEOUT = 0x1006;
+    @Native public final static int SO_TIMEOUT = 0x1006;
 
     /**
      * Set a hint the size of the underlying buffers used by the
@@ -273,7 +275,7 @@
      * @see DatagramSocket#setSendBufferSize
      * @see DatagramSocket#getSendBufferSize
      */
-    public final static int SO_SNDBUF = 0x1001;
+    @Native public final static int SO_SNDBUF = 0x1001;
 
     /**
      * Set a hint the size of the underlying buffers used by the
@@ -291,7 +293,7 @@
      * @see DatagramSocket#setReceiveBufferSize
      * @see DatagramSocket#getReceiveBufferSize
      */
-    public final static int SO_RCVBUF = 0x1002;
+    @Native public final static int SO_RCVBUF = 0x1002;
 
     /**
      * When the keepalive option is set for a TCP socket and no data
@@ -314,7 +316,7 @@
      * @see Socket#setKeepAlive
      * @see Socket#getKeepAlive
      */
-    public final static int SO_KEEPALIVE = 0x0008;
+    @Native public final static int SO_KEEPALIVE = 0x0008;
 
     /**
      * When the OOBINLINE option is set, any TCP urgent data received on
@@ -325,5 +327,5 @@
      * @see Socket#setOOBInline
      * @see Socket#getOOBInline
      */
-    public final static int SO_OOBINLINE = 0x1003;
+    @Native public final static int SO_OOBINLINE = 0x1003;
 }
--- a/jdk/src/share/classes/java/net/URLConnection.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/net/URLConnection.java	Tue Jan 22 11:54:16 2013 -0800
@@ -129,15 +129,6 @@
  * <a href="http://www.ietf.org/rfc/rfc2616.txt">http://www.ietf.org/rfc/rfc2616.txt</a>
  * </pre></blockquote>
  *
- * Note about <code>fileNameMap</code>: In versions prior to JDK 1.1.6,
- * field <code>fileNameMap</code> of <code>URLConnection</code> was public.
- * In JDK 1.1.6 and later, <code>fileNameMap</code> is private; accessor
- * and mutator methods {@link #getFileNameMap() getFileNameMap} and
- * {@link #setFileNameMap(java.net.FileNameMap) setFileNameMap} are added
- * to access it.  This change is also described on the <a href=
- * "http://java.sun.com/products/jdk/1.2/compatibility.html">
- * Compatibility</a> page.
- *
  * Invoking the <tt>close()</tt> methods on the <tt>InputStream</tt> or <tt>OutputStream</tt> of an
  * <tt>URLConnection</tt> after a request may free network resources associated with this
  * instance, unless particular protocol specifications specify different behaviours
@@ -305,8 +296,7 @@
      * Loads filename map (a mimetable) from a data file. It will
      * first try to load the user-specific table, defined
      * by &quot;content.types.user.table&quot; property. If that fails,
-     * it tries to load the default built-in table at
-     * lib/content-types.properties under java home.
+     * it tries to load the default built-in table.
      *
      * @return the FileNameMap
      * @since 1.2
--- a/jdk/src/share/classes/java/security/Principal.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/security/Principal.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,8 @@
 
 package java.security;
 
+import javax.security.auth.Subject;
+
 /**
  * This interface represents the abstract notion of a principal, which
  * can be used to represent any entity, such as an individual, a
@@ -45,7 +47,6 @@
      *
      * @return true if the principal passed in is the same as that
      * encapsulated by this principal, and false otherwise.
-
      */
     public boolean equals(Object another);
 
@@ -69,4 +70,24 @@
      * @return the name of this principal.
      */
     public String getName();
+
+    /**
+     * Returns true if the specified subject is implied by this principal.
+     *
+     * <p>The default implementation of this method returns true if
+     * {@code subject} is non-null and contains at least one principal that
+     * is equal to this principal.
+     *
+     * <p>Subclasses may override this with a different implementation, if
+     * necessary.
+     *
+     * @return true if {@code subject} is non-null and is
+     *              implied by this principal, or false otherwise.
+     * @since 1.8
+     */
+    public default boolean implies(Subject subject) {
+        if (subject == null)
+            return false;
+        return subject.getPrincipals().contains(this);
+    }
 }
--- a/jdk/src/share/classes/java/util/Arrays.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/Arrays.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,6 +26,7 @@
 package java.util;
 
 import java.lang.reflect.*;
+import static java.util.ArraysParallelSortHelpers.*;
 
 /**
  * This class contains various methods for manipulating arrays (such as
@@ -54,6 +55,13 @@
  */
 public class Arrays {
 
+    /**
+     * The minimum array length below which the sorting algorithm will not
+     * further partition the sorting task.
+     */
+    // reasonable default so that we don't overcreate tasks
+    private static final int MIN_ARRAY_SORT_GRAN = 256;
+
     // Suppresses default constructor, ensuring non-instantiability.
     private Arrays() {}
 
@@ -787,6 +795,613 @@
         }
     }
 
+    /*
+     * Parallel sorting of primitive type arrays.
+     */
+
+    /**
+     * Sorts the specified array into ascending numerical order.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(byte[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(byte[] a) {
+        parallelSort(a, 0, a.length);
+    }
+
+    /**
+     * Sorts the specified range of the array into ascending order. The range
+     * to be sorted extends from the index {@code fromIndex}, inclusive, to
+     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+     * the range to be sorted is empty.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(byte[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     * @param fromIndex the index of the first element, inclusive, to be sorted
+     * @param toIndex the index of the last element, exclusive, to be sorted
+     *
+     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+     * @throws ArrayIndexOutOfBoundsException
+     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(byte[] a, int fromIndex, int toIndex) {
+        rangeCheck(a.length, fromIndex, toIndex);
+        int nelements = toIndex - fromIndex;
+        int gran = getSplitThreshold(nelements);
+        FJByte.Sorter task = new FJByte.Sorter(a, new byte[a.length], fromIndex,
+                                               nelements, gran);
+        task.invoke();
+    }
+
+    /**
+     * Sorts the specified array into ascending numerical order.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(char[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(char[] a) {
+        parallelSort(a, 0, a.length);
+    }
+
+    /**
+     * Sorts the specified range of the array into ascending order. The range
+     * to be sorted extends from the index {@code fromIndex}, inclusive, to
+     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+     * the range to be sorted is empty.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(char[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     * @param fromIndex the index of the first element, inclusive, to be sorted
+     * @param toIndex the index of the last element, exclusive, to be sorted
+     *
+     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+     * @throws ArrayIndexOutOfBoundsException
+     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(char[] a, int fromIndex, int toIndex) {
+        rangeCheck(a.length, fromIndex, toIndex);
+        int nelements = toIndex - fromIndex;
+        int gran = getSplitThreshold(nelements);
+        FJChar.Sorter task = new FJChar.Sorter(a, new char[a.length], fromIndex,
+                                               nelements, gran);
+        task.invoke();
+    }
+
+    /**
+     * Sorts the specified array into ascending numerical order.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(short[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(short[] a) {
+        parallelSort(a, 0, a.length);
+    }
+
+    /**
+     * Sorts the specified range of the array into ascending order. The range
+     * to be sorted extends from the index {@code fromIndex}, inclusive, to
+     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+     * the range to be sorted is empty.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(short[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     * @param fromIndex the index of the first element, inclusive, to be sorted
+     * @param toIndex the index of the last element, exclusive, to be sorted
+     *
+     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+     * @throws ArrayIndexOutOfBoundsException
+     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(short[] a, int fromIndex, int toIndex) {
+        rangeCheck(a.length, fromIndex, toIndex);
+        int nelements = toIndex - fromIndex;
+        int gran = getSplitThreshold(nelements);
+        FJShort.Sorter task = new FJShort.Sorter(a, new short[a.length], fromIndex,
+                                                 nelements, gran);
+        task.invoke();
+    }
+
+    /**
+     * Sorts the specified array into ascending numerical order.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(int[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(int[] a) {
+        parallelSort(a, 0, a.length);
+    }
+
+    /**
+     * Sorts the specified range of the array into ascending order. The range
+     * to be sorted extends from the index {@code fromIndex}, inclusive, to
+     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+     * the range to be sorted is empty.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(int[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     * @param fromIndex the index of the first element, inclusive, to be sorted
+     * @param toIndex the index of the last element, exclusive, to be sorted
+     *
+     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+     * @throws ArrayIndexOutOfBoundsException
+     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(int[] a, int fromIndex, int toIndex) {
+        rangeCheck(a.length, fromIndex, toIndex);
+        int nelements = toIndex - fromIndex;
+        int gran = getSplitThreshold(nelements);
+        FJInt.Sorter task = new FJInt.Sorter(a, new int[a.length], fromIndex,
+                                             nelements, gran);
+        task.invoke();
+    }
+
+    /**
+     * Sorts the specified array into ascending numerical order.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(long[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(long[] a) {
+        parallelSort(a, 0, a.length);
+    }
+
+    /**
+     * Sorts the specified range of the array into ascending order. The range
+     * to be sorted extends from the index {@code fromIndex}, inclusive, to
+     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+     * the range to be sorted is empty.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(long[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     * @param fromIndex the index of the first element, inclusive, to be sorted
+     * @param toIndex the index of the last element, exclusive, to be sorted
+     *
+     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+     * @throws ArrayIndexOutOfBoundsException
+     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(long[] a, int fromIndex, int toIndex) {
+        rangeCheck(a.length, fromIndex, toIndex);
+        int nelements = toIndex - fromIndex;
+        int gran = getSplitThreshold(nelements);
+        FJLong.Sorter task = new FJLong.Sorter(a, new long[a.length], fromIndex,
+                                               nelements, gran);
+        task.invoke();
+    }
+
+    /**
+     * Sorts the specified array into ascending numerical order.
+     *
+     * <p>The {@code <} relation does not provide a total order on all float
+     * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
+     * value compares neither less than, greater than, nor equal to any value,
+     * even itself. This method uses the total order imposed by the method
+     * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
+     * {@code 0.0f} and {@code Float.NaN} is considered greater than any
+     * other value and all {@code Float.NaN} values are considered equal.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(float[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(float[] a) {
+        parallelSort(a, 0, a.length);
+    }
+
+    /**
+     * Sorts the specified range of the array into ascending order. The range
+     * to be sorted extends from the index {@code fromIndex}, inclusive, to
+     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+     * the range to be sorted is empty.
+     *
+     * <p>The {@code <} relation does not provide a total order on all float
+     * values: {@code -0.0f == 0.0f} is {@code true} and a {@code Float.NaN}
+     * value compares neither less than, greater than, nor equal to any value,
+     * even itself. This method uses the total order imposed by the method
+     * {@link Float#compareTo}: {@code -0.0f} is treated as less than value
+     * {@code 0.0f} and {@code Float.NaN} is considered greater than any
+     * other value and all {@code Float.NaN} values are considered equal.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(float[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     * @param fromIndex the index of the first element, inclusive, to be sorted
+     * @param toIndex the index of the last element, exclusive, to be sorted
+     *
+     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+     * @throws ArrayIndexOutOfBoundsException
+     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(float[] a, int fromIndex, int toIndex) {
+        rangeCheck(a.length, fromIndex, toIndex);
+        int nelements = toIndex - fromIndex;
+        int gran = getSplitThreshold(nelements);
+        FJFloat.Sorter task = new FJFloat.Sorter(a, new float[a.length], fromIndex,
+                                                 nelements, gran);
+        task.invoke();
+    }
+
+    /**
+     * Sorts the specified array into ascending numerical order.
+     *
+     * <p>The {@code <} relation does not provide a total order on all double
+     * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
+     * value compares neither less than, greater than, nor equal to any value,
+     * even itself. This method uses the total order imposed by the method
+     * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
+     * {@code 0.0d} and {@code Double.NaN} is considered greater than any
+     * other value and all {@code Double.NaN} values are considered equal.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(double[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(double[] a) {
+        parallelSort(a, 0, a.length);
+    }
+
+    /**
+     * Sorts the specified range of the array into ascending order. The range
+     * to be sorted extends from the index {@code fromIndex}, inclusive, to
+     * the index {@code toIndex}, exclusive. If {@code fromIndex == toIndex},
+     * the range to be sorted is empty.
+     *
+     * <p>The {@code <} relation does not provide a total order on all double
+     * values: {@code -0.0d == 0.0d} is {@code true} and a {@code Double.NaN}
+     * value compares neither less than, greater than, nor equal to any value,
+     * even itself. This method uses the total order imposed by the method
+     * {@link Double#compareTo}: {@code -0.0d} is treated as less than value
+     * {@code 0.0d} and {@code Double.NaN} is considered greater than any
+     * other value and all {@code Double.NaN} values are considered equal.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(double[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     * @param fromIndex the index of the first element, inclusive, to be sorted
+     * @param toIndex the index of the last element, exclusive, to be sorted
+     *
+     * @throws IllegalArgumentException if {@code fromIndex > toIndex}
+     * @throws ArrayIndexOutOfBoundsException
+     *     if {@code fromIndex < 0} or {@code toIndex > a.length}
+     *
+     * @since 1.8
+     */
+    public static void parallelSort(double[] a, int fromIndex, int toIndex) {
+        rangeCheck(a.length, fromIndex, toIndex);
+        int nelements = toIndex - fromIndex;
+        int gran = getSplitThreshold(nelements);
+        FJDouble.Sorter task = new FJDouble.Sorter(a, new double[a.length],
+                                                   fromIndex, nelements, gran);
+        task.invoke();
+    }
+
+    /*
+     * Parallel sorting of complex type arrays.
+     */
+
+    /**
+     * Sorts the specified array of objects into ascending order, according
+     * to the {@linkplain Comparable natural ordering} of its elements.
+     * All elements in the array must implement the {@link Comparable}
+     * interface.  Furthermore, all elements in the array must be
+     * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} must
+     * not throw a {@code ClassCastException} for any elements {@code e1}
+     * and {@code e2} in the array).
+     *
+     * <p>This sort is not guaranteed to be <i>stable</i>:  equal elements
+     * may be reordered as a result of the sort.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(Object[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     *
+     * @throws ClassCastException if the array contains elements that are not
+     *         <i>mutually comparable</i> (for example, strings and integers)
+     * @throws IllegalArgumentException (optional) if the natural
+     *         ordering of the array elements is found to violate the
+     *         {@link Comparable} contract
+     *
+     * @since 1.8
+     */
+    public static <T extends Comparable<? super T>> void parallelSort(T[] a) {
+        parallelSort(a, 0, a.length);
+    }
+
+    /**
+     * Sorts the specified range of the specified array of objects into
+     * ascending order, according to the
+     * {@linkplain Comparable natural ordering} of its
+     * elements.  The range to be sorted extends from index
+     * {@code fromIndex}, inclusive, to index {@code toIndex}, exclusive.
+     * (If {@code fromIndex==toIndex}, the range to be sorted is empty.)  All
+     * elements in this range must implement the {@link Comparable}
+     * interface.  Furthermore, all elements in this range must be <i>mutually
+     * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
+     * {@code ClassCastException} for any elements {@code e1} and
+     * {@code e2} in the array).
+     *
+     * <p>This sort is not guaranteed to be <i>stable</i>:  equal elements
+     * may be reordered as a result of the sort.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(Object[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     * @param fromIndex the index of the first element (inclusive) to be
+     *        sorted
+     * @param toIndex the index of the last element (exclusive) to be sorted
+     * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
+     *         (optional) if the natural ordering of the array elements is
+     *         found to violate the {@link Comparable} contract
+     * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
+     *         {@code toIndex > a.length}
+     * @throws ClassCastException if the array contains elements that are
+     *         not <i>mutually comparable</i> (for example, strings and
+     *         integers).
+     *
+     * @since 1.8
+     */
+    public static <T extends Comparable<? super T>>
+            void parallelSort(T[] a, int fromIndex, int toIndex) {
+        rangeCheck(a.length, fromIndex, toIndex);
+        int nelements = toIndex - fromIndex;
+        Class<?> tc = a.getClass().getComponentType();
+        @SuppressWarnings("unchecked")
+        T[] workspace = (T[])Array.newInstance(tc, a.length);
+        int gran = getSplitThreshold(nelements);
+        FJComparable.Sorter<T> task = new FJComparable.Sorter<>(a, workspace,
+                                                                fromIndex,
+                                                                nelements, gran);
+        task.invoke();
+    }
+
+    /**
+     * Sorts the specified array of objects according to the order induced by
+     * the specified comparator.  All elements in the array must be
+     * <i>mutually comparable</i> by the specified comparator (that is,
+     * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
+     * for any elements {@code e1} and {@code e2} in the array).
+     *
+     * <p>This sort is not guaranteed to be <i>stable</i>:  equal elements
+     * may be reordered as a result of the sort.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(Object[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     * @param c the comparator to determine the order of the array.  A
+     *        {@code null} value indicates that the elements'
+     *        {@linkplain Comparable natural ordering} should be used.
+     * @throws ClassCastException if the array contains elements that are
+     *         not <i>mutually comparable</i> using the specified comparator
+     * @throws IllegalArgumentException (optional) if the comparator is
+     *         found to violate the {@link java.util.Comparator} contract
+     *
+     * @since 1.8
+     */
+    public static <T> void parallelSort(T[] a, Comparator<? super T> c) {
+        parallelSort(a, 0, a.length, c);
+    }
+
+    /**
+     * Sorts the specified range of the specified array of objects according
+     * to the order induced by the specified comparator.  The range to be
+     * sorted extends from index {@code fromIndex}, inclusive, to index
+     * {@code toIndex}, exclusive.  (If {@code fromIndex==toIndex}, the
+     * range to be sorted is empty.)  All elements in the range must be
+     * <i>mutually comparable</i> by the specified comparator (that is,
+     * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
+     * for any elements {@code e1} and {@code e2} in the range).
+     *
+     * <p>This sort is not guaranteed to be <i>stable</i>:  equal elements
+     * may be reordered as a result of the sort.
+     *
+     * <p>Implementation note: The sorting algorithm is a parallel sort-merge
+     * that breaks the array into sub-arrays that are themselves sorted and then
+     * merged. When the sub-array length reaches a minimum granularity, the
+     * sub-array is sorted using the appropriate {@link Arrays#sort(Object[])
+     * Arrays.sort} method. The algorithm requires a working space equal to the
+     * size of the original array. The {@link
+     * java.util.concurrent.ForkJoinPool#commonPool() ForkJoin common pool} is
+     * used to execute any parallel tasks.
+     *
+     * @param a the array to be sorted
+     * @param fromIndex the index of the first element (inclusive) to be
+     *        sorted
+     * @param toIndex the index of the last element (exclusive) to be sorted
+     * @param c the comparator to determine the order of the array.  A
+     *        {@code null} value indicates that the elements'
+     *        {@linkplain Comparable natural ordering} should be used.
+     * @throws IllegalArgumentException if {@code fromIndex > toIndex} or
+     *         (optional) if the natural ordering of the array elements is
+     *         found to violate the {@link Comparable} contract
+     * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
+     *         {@code toIndex > a.length}
+     * @throws ClassCastException if the array contains elements that are
+     *         not <i>mutually comparable</i> (for example, strings and
+     *         integers).
+     *
+     * @since 1.8
+     */
+    public static <T> void parallelSort(T[] a, int fromIndex, int toIndex,
+                                        Comparator<? super T> c) {
+        rangeCheck(a.length, fromIndex, toIndex);
+        int nelements = toIndex - fromIndex;
+        Class<?> tc = a.getClass().getComponentType();
+        @SuppressWarnings("unchecked")
+        T[] workspace = (T[])Array.newInstance(tc, a.length);
+        int gran = getSplitThreshold(nelements);
+        FJComparator.Sorter<T> task = new FJComparator.Sorter<>(a, workspace,
+                                                                fromIndex,
+                                                                nelements, gran, c);
+        task.invoke();
+    }
+
+    /**
+     * Returns the size threshold for splitting into subtasks.
+     * By default, uses about 8 times as many tasks as threads
+     *
+     * @param n number of elements in the array to be processed
+     */
+    private static int getSplitThreshold(int n) {
+        int p = java.util.concurrent.ForkJoinPool.getCommonPoolParallelism();
+        int t = (p > 1) ? (1 + n / (p << 3)) : n;
+        return t < MIN_ARRAY_SORT_GRAN ? MIN_ARRAY_SORT_GRAN : t;
+    }
+
     /**
      * Checks that {@code fromIndex} and {@code toIndex} are in
      * the range and throws an appropriate exception, if they aren't.
@@ -1480,9 +2095,9 @@
         while (low <= high) {
             int mid = (low + high) >>> 1;
             @SuppressWarnings("rawtypes")
-                Comparable midVal = (Comparable)a[mid];
+            Comparable midVal = (Comparable)a[mid];
             @SuppressWarnings("unchecked")
-                int cmp = midVal.compareTo(key);
+            int cmp = midVal.compareTo(key);
 
             if (cmp < 0)
                 low = mid + 1;
@@ -2847,19 +3462,20 @@
         private final E[] a;
 
         ArrayList(E[] array) {
-            if (array==null)
-                throw new NullPointerException();
-            a = array;
+            a = Objects.requireNonNull(array);
         }
 
+        @Override
         public int size() {
             return a.length;
         }
 
+        @Override
         public Object[] toArray() {
             return a.clone();
         }
 
+        @Override
         @SuppressWarnings("unchecked")
         public <T> T[] toArray(T[] a) {
             int size = size();
@@ -2872,16 +3488,19 @@
             return a;
         }
 
+        @Override
         public E get(int index) {
             return a[index];
         }
 
+        @Override
         public E set(int index, E element) {
             E oldValue = a[index];
             a[index] = element;
             return oldValue;
         }
 
+        @Override
         public int indexOf(Object o) {
             if (o==null) {
                 for (int i=0; i<a.length; i++)
@@ -2895,6 +3514,7 @@
             return -1;
         }
 
+        @Override
         public boolean contains(Object o) {
             return indexOf(o) != -1;
         }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/java/util/ArraysParallelSortHelpers.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,1223 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package java.util;
+
+import java.util.concurrent.RecursiveAction;
+
+/**
+ * Helper utilities for the parallel sort methods in Arrays.parallelSort.
+ *
+ * For each primitive type, plus Object, we define a static class to
+ * contain the Sorter and Merger implementations for that type:
+ *
+ * Sorter classes based mainly on CilkSort
+ * <A href="http://supertech.lcs.mit.edu/cilk/"> Cilk</A>:
+ * Basic algorithm:
+ * if array size is small, just use a sequential quicksort (via Arrays.sort)
+ *         Otherwise:
+ *         1. Break array in half.
+ *         2. For each half,
+ *             a. break the half in half (i.e., quarters),
+ *             b. sort the quarters
+ *             c. merge them together
+ *         3. merge together the two halves.
+ *
+ * One reason for splitting in quarters is that this guarantees
+ * that the final sort is in the main array, not the workspace
+ * array.  (workspace and main swap roles on each subsort step.)
+ * Leaf-level sorts use a Sequential quicksort, that in turn uses
+ * insertion sort if under threshold.  Otherwise it uses median of
+ * three to pick pivot, and loops rather than recurses along left
+ * path.
+ *
+ *
+ * Merger classes perform merging for Sorter. If big enough, splits Left
+ * partition in half; finds the greatest point in Right partition
+ * less than the beginning of the second half of Left via binary
+ * search; and then, in parallel, merges left half of Left with
+ * elements of Right up to split point, and merges right half of
+ * Left with elements of R past split point. At leaf, it just
+ * sequentially merges. This is all messy to code; sadly we need
+ * distinct versions for each type.
+ *
+ */
+/*package*/ class ArraysParallelSortHelpers {
+
+    // RFE: we should only need a working array as large as the subarray
+    //      to be sorted, but the logic assumes that indices in the two
+    //      arrays always line-up
+
+    /** byte support class */
+    static final class FJByte {
+        static final class Sorter extends RecursiveAction {
+            static final long serialVersionUID = 749471161188027634L;
+            final byte[] a;     // array to be sorted.
+            final byte[] w;     // workspace for merge
+            final int origin;   // origin of the part of array we deal with
+            final int n;        // Number of elements in (sub)arrays.
+            final int gran;     // split control
+
+            Sorter(byte[] a, byte[] w, int origin, int n, int gran) {
+                this.a = a;
+                this.w = w;
+                this.origin = origin;
+                this.n = n;
+                this.gran = gran;
+            }
+
+            public void compute() {
+                final int l = origin;
+                final int g = gran;
+                final int n = this.n;
+                final byte[] a = this.a;
+                final byte[] w = this.w;
+                if (n > g) {
+                    int h = n >>> 1; // half
+                    int q = n >>> 2; // lower quarter index
+                    int u = h + q;   // upper quarter
+                    FJSubSorter ls = new FJSubSorter(new Sorter(a, w, l, q,  g),
+                                                     new Sorter(a, w, l+q, h-q, g),
+                                                     new Merger(a, w, l,   q,
+                                                                l+q, h-q, l, g, null));
+                    FJSubSorter rs = new FJSubSorter(new Sorter(a, w, l+h, q,   g),
+                                                     new Sorter(a, w, l+u, n-u, g),
+                                                     new Merger(a, w, l+h, q,
+                                                                l+u, n-u, l+h, g, null));
+                    rs.fork();
+                    ls.compute();
+                    if (rs.tryUnfork()) rs.compute(); else rs.join();
+                    new Merger(w, a, l, h,
+                               l+h, n-h, l, g, null).compute();
+                } else {
+                    DualPivotQuicksort.sort(a, l, l+n-1);   //skip rangeCheck
+                }
+            }
+        }
+
+        static final class Merger extends RecursiveAction {
+            static final long serialVersionUID = -9090258248781844470L;
+            final byte[] a;
+            final byte[] w;
+            final int lo;
+            final int ln;
+            final int ro;
+            final int rn;
+            final int wo;
+            final int gran;
+            final Merger next;
+
+            Merger(byte[] a, byte[] w, int lo, int ln, int ro, int rn, int wo,
+                   int gran, Merger next) {
+                this.a = a;
+                this.w = w;
+                this.lo = lo;
+                this.ln = ln;
+                this.ro = ro;
+                this.rn = rn;
+                this.wo = wo;
+                this.gran = gran;
+                this.next = next;
+            }
+
+            public void compute() {
+                final byte[] a = this.a;
+                final byte[] w = this.w;
+                Merger rights = null;
+                int nleft = ln;
+                int nright = rn;
+                while (nleft > gran) {
+                    int lh = nleft >>> 1;
+                    int splitIndex = lo + lh;
+                    byte split = a[splitIndex];
+                    int rl = 0;
+                    int rh = nright;
+                    while (rl < rh) {
+                        int mid = (rl + rh) >>> 1;
+                        if (split <= a[ro + mid])
+                            rh = mid;
+                        else
+                            rl = mid + 1;
+                    }
+                    (rights = new Merger(a, w, splitIndex, nleft-lh, ro+rh,
+                                         nright-rh, wo+lh+rh, gran, rights)).fork();
+                    nleft = lh;
+                    nright = rh;
+                }
+
+                int l = lo;
+                int lFence = l + nleft;
+                int r = ro;
+                int rFence = r + nright;
+                int k = wo;
+                while (l < lFence && r < rFence) {
+                    byte al = a[l];
+                    byte ar = a[r];
+                    byte t;
+                    if (al <= ar) {++l; t=al;} else {++r; t = ar;}
+                    w[k++] = t;
+                }
+                while (l < lFence)
+                    w[k++] = a[l++];
+                while (r < rFence)
+                    w[k++] = a[r++];
+                while (rights != null) {
+                    if (rights.tryUnfork())
+                        rights.compute();
+                    else
+                        rights.join();
+                    rights = rights.next;
+                }
+            }
+        }
+    } // FJByte
+
+    /** char support class */
+    static final class FJChar {
+        static final class Sorter extends RecursiveAction {
+            static final long serialVersionUID = 8723376019074596641L;
+            final char[] a;     // array to be sorted.
+            final char[] w;     // workspace for merge
+            final int origin;   // origin of the part of array we deal with
+            final int n;        // Number of elements in (sub)arrays.
+            final int gran;     // split control
+
+            Sorter(char[] a, char[] w, int origin, int n, int gran) {
+                this.a = a;
+                this.w = w;
+                this.origin = origin;
+                this.n = n;
+                this.gran = gran;
+            }
+
+            public void compute() {
+                final int l = origin;
+                final int g = gran;
+                final int n = this.n;
+                final char[] a = this.a;
+                final char[] w = this.w;
+                if (n > g) {
+                    int h = n >>> 1; // half
+                    int q = n >>> 2; // lower quarter index
+                    int u = h + q;   // upper quarter
+                    FJSubSorter ls = new FJSubSorter(new Sorter(a, w, l, q,   g),
+                                                     new Sorter(a, w, l+q, h-q, g),
+                                                     new Merger(a, w, l,   q,
+                                                                l+q, h-q, l, g, null));
+                    FJSubSorter rs = new FJSubSorter(new Sorter(a, w, l + h, q,   g),
+                                                     new Sorter(a, w, l+u, n-u, g),
+                                                     new Merger(a, w, l+h, q,
+                                                                l+u, n-u, l+h, g, null));
+                    rs.fork();
+                    ls.compute();
+                    if (rs.tryUnfork()) rs.compute(); else rs.join();
+                    new Merger(w, a, l, h, l + h, n - h, l, g, null).compute();
+                } else {
+                    DualPivotQuicksort.sort(a, l, l+n-1);   // skip rangeCheck
+                }
+            }
+        }
+
+        static final class Merger extends RecursiveAction {
+            static final long serialVersionUID = -1383975444621698926L;
+            final char[] a;
+            final char[] w;
+            final int lo;
+            final int ln;
+            final int ro;
+            final int rn;
+            final int wo;
+            final int gran;
+            final Merger next;
+
+            Merger(char[] a, char[] w, int lo, int ln, int ro, int rn, int wo,
+                   int gran, Merger next) {
+                this.a = a;
+                this.w = w;
+                this.lo = lo;
+                this.ln = ln;
+                this.ro = ro;
+                this.rn = rn;
+                this.wo = wo;
+                this.gran = gran;
+                this.next = next;
+            }
+
+            public void compute() {
+                final char[] a = this.a;
+                final char[] w = this.w;
+                Merger rights = null;
+                int nleft = ln;
+                int nright = rn;
+                while (nleft > gran) {
+                    int lh = nleft >>> 1;
+                    int splitIndex = lo + lh;
+                    char split = a[splitIndex];
+                    int rl = 0;
+                    int rh = nright;
+                    while (rl < rh) {
+                        int mid = (rl + rh) >>> 1;
+                        if (split <= a[ro + mid])
+                            rh = mid;
+                        else
+                            rl = mid + 1;
+                    }
+                    (rights = new Merger(a, w, splitIndex, nleft-lh, ro+rh,
+                                         nright-rh, wo+lh+rh, gran, rights)).fork();
+                    nleft = lh;
+                    nright = rh;
+                }
+
+                int l = lo;
+                int lFence = l + nleft;
+                int r = ro;
+                int rFence = r + nright;
+                int k = wo;
+                while (l < lFence && r < rFence) {
+                    char al = a[l];
+                    char ar = a[r];
+                    char t;
+                    if (al <= ar) {++l; t=al;} else {++r; t = ar;}
+                    w[k++] = t;
+                }
+                while (l < lFence)
+                    w[k++] = a[l++];
+                while (r < rFence)
+                    w[k++] = a[r++];
+                while (rights != null) {
+                    if (rights.tryUnfork())
+                        rights.compute();
+                    else
+                        rights.join();
+                    rights = rights.next;
+                }
+            }
+        }
+    } // FJChar
+
+    /** short support class */
+    static final class FJShort {
+        static final class Sorter extends RecursiveAction {
+            static final long serialVersionUID = -7886754793730583084L;
+            final short[] a;    // array to be sorted.
+            final short[] w;    // workspace for merge
+            final int origin;   // origin of the part of array we deal with
+            final int n;        // Number of elements in (sub)arrays.
+            final int gran;     // split control
+
+            Sorter(short[] a, short[] w, int origin, int n, int gran) {
+                this.a = a;
+                this.w = w;
+                this.origin = origin;
+                this.n = n;
+                this.gran = gran;
+            }
+
+            public void compute() {
+                final int l = origin;
+                final int g = gran;
+                final int n = this.n;
+                final short[] a = this.a;
+                final short[] w = this.w;
+                if (n > g) {
+                    int h = n >>> 1; // half
+                    int q = n >>> 2; // lower quarter index
+                    int u = h + q;   // upper quarter
+                    FJSubSorter ls = new FJSubSorter(new Sorter(a, w, l, q,   g),
+                                                     new Sorter(a, w, l+q, h-q, g),
+                                                     new Merger(a, w, l,   q,
+                                                                l+q, h-q, l, g, null));
+                    FJSubSorter rs = new FJSubSorter(new Sorter(a, w, l + h, q,   g),
+                                                     new Sorter(a, w, l+u, n-u, g),
+                                                     new Merger(a, w, l+h, q,
+                                                                l+u, n-u, l+h, g, null));
+                    rs.fork();
+                    ls.compute();
+                    if (rs.tryUnfork()) rs.compute(); else rs.join();
+                    new Merger(w, a, l, h, l + h, n - h, l, g, null).compute();
+                } else {
+                    DualPivotQuicksort.sort(a, l, l+n-1);   // skip rangeCheck
+                }
+            }
+        }
+
+        static final class Merger extends RecursiveAction {
+            static final long serialVersionUID = 3895749408536700048L;
+            final short[] a;
+            final short[] w;
+            final int lo;
+            final int ln;
+            final int ro;
+            final int rn;
+            final int wo;
+            final int gran;
+            final Merger next;
+
+            Merger(short[] a, short[] w, int lo, int ln, int ro, int rn, int wo,
+                   int gran, Merger next) {
+                this.a = a;
+                this.w = w;
+                this.lo = lo;
+                this.ln = ln;
+                this.ro = ro;
+                this.rn = rn;
+                this.wo = wo;
+                this.gran = gran;
+                this.next = next;
+            }
+
+            public void compute() {
+                final short[] a = this.a;
+                final short[] w = this.w;
+                Merger rights = null;
+                int nleft = ln;
+                int nright = rn;
+                while (nleft > gran) {
+                    int lh = nleft >>> 1;
+                    int splitIndex = lo + lh;
+                    short split = a[splitIndex];
+                    int rl = 0;
+                    int rh = nright;
+                    while (rl < rh) {
+                        int mid = (rl + rh) >>> 1;
+                        if (split <= a[ro + mid])
+                            rh = mid;
+                        else
+                            rl = mid + 1;
+                    }
+                    (rights = new Merger(a, w, splitIndex, nleft-lh, ro+rh,
+                                         nright-rh, wo+lh+rh, gran, rights)).fork();
+                    nleft = lh;
+                    nright = rh;
+                }
+
+                int l = lo;
+                int lFence = l + nleft;
+                int r = ro;
+                int rFence = r + nright;
+                int k = wo;
+                while (l < lFence && r < rFence) {
+                    short al = a[l];
+                    short ar = a[r];
+                    short t;
+                    if (al <= ar) {++l; t=al;} else {++r; t = ar;}
+                    w[k++] = t;
+                }
+                while (l < lFence)
+                    w[k++] = a[l++];
+                while (r < rFence)
+                    w[k++] = a[r++];
+                while (rights != null) {
+                    if (rights.tryUnfork())
+                        rights.compute();
+                    else
+                        rights.join();
+                    rights = rights.next;
+                }
+            }
+        }
+    } // FJShort
+
+    /** int support class */
+    static final class FJInt {
+        static final class Sorter extends RecursiveAction {
+            static final long serialVersionUID = 4263311808957292729L;
+            final int[] a;     // array to be sorted.
+            final int[] w;     // workspace for merge
+            final int origin;  // origin of the part of array we deal with
+            final int n;       // Number of elements in (sub)arrays.
+            final int gran;    // split control
+
+            Sorter(int[] a, int[] w, int origin, int n, int gran) {
+                this.a = a;
+                this.w = w;
+                this.origin = origin;
+                this.n = n;
+                this.gran = gran;
+            }
+
+            public void compute() {
+                final int l = origin;
+                final int g = gran;
+                final int n = this.n;
+                final int[] a = this.a;
+                final int[] w = this.w;
+                if (n > g) {
+                    int h = n >>> 1; // half
+                    int q = n >>> 2; // lower quarter index
+                    int u = h + q;   // upper quarter
+                    FJSubSorter ls = new FJSubSorter(new Sorter(a, w, l, q,   g),
+                                                     new Sorter(a, w, l+q, h-q, g),
+                                                     new Merger(a, w, l,   q,
+                                                                l+q, h-q, l, g, null));
+                    FJSubSorter rs = new FJSubSorter(new Sorter(a, w, l + h, q,   g),
+                                                     new Sorter(a, w, l+u, n-u, g),
+                                                     new Merger(a, w, l+h, q,
+                                                                l+u, n-u, l+h, g, null));
+                    rs.fork();
+                    ls.compute();
+                    if (rs.tryUnfork()) rs.compute(); else rs.join();
+                    new Merger(w, a, l, h, l + h, n - h, l, g, null).compute();
+                } else {
+                    DualPivotQuicksort.sort(a, l, l+n-1);   // skip rangeCheck
+                }
+            }
+        }
+
+        static final class Merger extends RecursiveAction {
+            static final long serialVersionUID = -8727507284219982792L;
+            final int[] a;
+            final int[] w;
+            final int lo;
+            final int ln;
+            final int ro;
+            final int rn;
+            final int wo;
+            final int gran;
+            final Merger next;
+
+            Merger(int[] a, int[] w, int lo, int ln, int ro, int rn, int wo,
+                   int gran, Merger next) {
+                this.a = a;
+                this.w = w;
+                this.lo = lo;
+                this.ln = ln;
+                this.ro = ro;
+                this.rn = rn;
+                this.wo = wo;
+                this.gran = gran;
+                this.next = next;
+            }
+
+            public void compute() {
+                final int[] a = this.a;
+                final int[] w = this.w;
+                Merger rights = null;
+                int nleft = ln;
+                int nright = rn;
+                while (nleft > gran) {
+                    int lh = nleft >>> 1;
+                    int splitIndex = lo + lh;
+                    int split = a[splitIndex];
+                    int rl = 0;
+                    int rh = nright;
+                    while (rl < rh) {
+                        int mid = (rl + rh) >>> 1;
+                        if (split <= a[ro + mid])
+                            rh = mid;
+                        else
+                            rl = mid + 1;
+                    }
+                    (rights = new Merger(a, w, splitIndex, nleft-lh, ro+rh,
+                                         nright-rh, wo+lh+rh, gran, rights)).fork();
+                    nleft = lh;
+                    nright = rh;
+                }
+
+                int l = lo;
+                int lFence = l + nleft;
+                int r = ro;
+                int rFence = r + nright;
+                int k = wo;
+                while (l < lFence && r < rFence) {
+                    int al = a[l];
+                    int ar = a[r];
+                    int t;
+                    if (al <= ar) {++l; t=al;} else {++r; t = ar;}
+                    w[k++] = t;
+                }
+                while (l < lFence)
+                    w[k++] = a[l++];
+                while (r < rFence)
+                    w[k++] = a[r++];
+                while (rights != null) {
+                    if (rights.tryUnfork())
+                        rights.compute();
+                    else
+                        rights.join();
+                    rights = rights.next;
+                }
+            }
+        }
+    } // FJInt
+
+    /** long support class */
+    static final class FJLong {
+        static final class Sorter extends RecursiveAction {
+            static final long serialVersionUID = 6553695007444392455L;
+            final long[] a;     // array to be sorted.
+            final long[] w;     // workspace for merge
+            final int origin;   // origin of the part of array we deal with
+            final int n;        // Number of elements in (sub)arrays.
+            final int gran;     // split control
+
+            Sorter(long[] a, long[] w, int origin, int n, int gran) {
+                this.a = a;
+                this.w = w;
+                this.origin = origin;
+                this.n = n;
+                this.gran = gran;
+            }
+
+            public void compute() {
+                final int l = origin;
+                final int g = gran;
+                final int n = this.n;
+                final long[] a = this.a;
+                final long[] w = this.w;
+                if (n > g) {
+                    int h = n >>> 1; // half
+                    int q = n >>> 2; // lower quarter index
+                    int u = h + q;   // upper quarter
+                    FJSubSorter ls = new FJSubSorter(new Sorter(a, w, l, q,   g),
+                                                     new Sorter(a, w, l+q, h-q, g),
+                                                     new Merger(a, w, l,   q,
+                                                                l+q, h-q, l, g, null));
+                    FJSubSorter rs = new FJSubSorter(new Sorter(a, w, l + h, q,   g),
+                                                     new Sorter(a, w, l+u, n-u, g),
+                                                     new Merger(a, w, l+h, q,
+                                                                l+u, n-u, l+h, g, null));
+                    rs.fork();
+                    ls.compute();
+                    if (rs.tryUnfork()) rs.compute(); else rs.join();
+                    new Merger(w, a, l, h, l + h, n - h, l, g, null).compute();
+                } else {
+                    DualPivotQuicksort.sort(a, l, l+n-1);   // skip rangeCheck
+                }
+            }
+        }
+
+        static final class Merger extends RecursiveAction {
+            static final long serialVersionUID = 8843567516333283861L;
+            final long[] a;
+            final long[] w;
+            final int lo;
+            final int ln;
+            final int ro;
+            final int rn;
+            final int wo;
+            final int gran;
+            final Merger next;
+
+            Merger(long[] a, long[] w, int lo, int ln, int ro, int rn, int wo,
+                   int gran, Merger next) {
+                this.a = a;
+                this.w = w;
+                this.lo = lo;
+                this.ln = ln;
+                this.ro = ro;
+                this.rn = rn;
+                this.wo = wo;
+                this.gran = gran;
+                this.next = next;
+            }
+
+            public void compute() {
+                final long[] a = this.a;
+                final long[] w = this.w;
+                Merger rights = null;
+                int nleft = ln;
+                int nright = rn;
+                while (nleft > gran) {
+                    int lh = nleft >>> 1;
+                    int splitIndex = lo + lh;
+                    long split = a[splitIndex];
+                    int rl = 0;
+                    int rh = nright;
+                    while (rl < rh) {
+                        int mid = (rl + rh) >>> 1;
+                        if (split <= a[ro + mid])
+                            rh = mid;
+                        else
+                            rl = mid + 1;
+                    }
+                    (rights = new Merger(a, w, splitIndex, nleft-lh, ro+rh,
+                      nright-rh, wo+lh+rh, gran, rights)).fork();
+                    nleft = lh;
+                    nright = rh;
+                }
+
+                int l = lo;
+                int lFence = l + nleft;
+                int r = ro;
+                int rFence = r + nright;
+                int k = wo;
+                while (l < lFence && r < rFence) {
+                    long al = a[l];
+                    long ar = a[r];
+                    long t;
+                    if (al <= ar) {++l; t=al;} else {++r; t = ar;}
+                    w[k++] = t;
+                }
+                while (l < lFence)
+                    w[k++] = a[l++];
+                while (r < rFence)
+                    w[k++] = a[r++];
+                while (rights != null) {
+                    if (rights.tryUnfork())
+                        rights.compute();
+                    else
+                        rights.join();
+                    rights = rights.next;
+                }
+            }
+        }
+    } // FJLong
+
+    /** float support class */
+    static final class FJFloat {
+        static final class Sorter extends RecursiveAction {
+            static final long serialVersionUID = 1602600178202763377L;
+            final float[] a;    // array to be sorted.
+            final float[] w;    // workspace for merge
+            final int origin;   // origin of the part of array we deal with
+            final int n;        // Number of elements in (sub)arrays.
+            final int gran;     // split control
+
+            Sorter(float[] a, float[] w, int origin, int n, int gran) {
+                this.a = a;
+                this.w = w;
+                this.origin = origin;
+                this.n = n;
+                this.gran = gran;
+            }
+
+            public void compute() {
+                final int l = origin;
+                final int g = gran;
+                final int n = this.n;
+                final float[] a = this.a;
+                final float[] w = this.w;
+                if (n > g) {
+                    int h = n >>> 1; // half
+                    int q = n >>> 2; // lower quarter index
+                    int u = h + q;   // upper quarter
+                    FJSubSorter ls = new FJSubSorter(new Sorter(a, w, l, q,   g),
+                                                     new Sorter(a, w, l+q, h-q, g),
+                                                     new Merger(a, w, l,   q,
+                                                                l+q, h-q, l, g, null));
+                    FJSubSorter rs = new FJSubSorter(new Sorter(a, w, l + h, q,   g),
+                                                     new Sorter(a, w, l+u, n-u, g),
+                                                     new Merger(a, w, l+h, q,
+                                                                l+u, n-u, l+h, g, null));
+                    rs.fork();
+                    ls.compute();
+                    if (rs.tryUnfork()) rs.compute(); else rs.join();
+                    new Merger(w, a, l, h, l + h, n - h, l, g, null).compute();
+                } else {
+                    DualPivotQuicksort.sort(a, l, l+n-1);   // skip rangeCheck
+                }
+            }
+        }
+
+        static final class Merger extends RecursiveAction {
+            static final long serialVersionUID = 1518176433845397426L;
+            final float[] a;
+            final float[] w;
+            final int lo;
+            final int ln;
+            final int ro;
+            final int rn;
+            final int wo;
+            final int gran;
+            final Merger next;
+
+            Merger(float[] a, float[] w, int lo, int ln, int ro, int rn, int wo,
+                   int gran, Merger next) {
+                this.a = a;
+                this.w = w;
+                this.lo = lo;
+                this.ln = ln;
+                this.ro = ro;
+                this.rn = rn;
+                this.wo = wo;
+                this.gran = gran;
+                this.next = next;
+            }
+
+            public void compute() {
+                final float[] a = this.a;
+                final float[] w = this.w;
+                Merger rights = null;
+                int nleft = ln;
+                int nright = rn;
+                while (nleft > gran) {
+                    int lh = nleft >>> 1;
+                    int splitIndex = lo + lh;
+                    float split = a[splitIndex];
+                    int rl = 0;
+                    int rh = nright;
+                    while (rl < rh) {
+                        int mid = (rl + rh) >>> 1;
+                        if (Float.compare(split, a[ro+mid]) <= 0)
+                            rh = mid;
+                        else
+                            rl = mid + 1;
+                    }
+                    (rights = new Merger(a, w, splitIndex, nleft-lh, ro+rh,
+                                         nright-rh, wo+lh+rh, gran, rights)).fork();
+                    nleft = lh;
+                    nright = rh;
+                }
+
+                int l = lo;
+                int lFence = l + nleft;
+                int r = ro;
+                int rFence = r + nright;
+                int k = wo;
+                while (l < lFence && r < rFence) {
+                    float al = a[l];
+                    float ar = a[r];
+                    float t;
+                    if (Float.compare(al, ar) <= 0) {
+                        ++l;
+                        t = al;
+                    } else {
+                        ++r;
+                        t = ar;
+                    }
+                    w[k++] = t;
+                }
+                while (l < lFence)
+                    w[k++] = a[l++];
+                while (r < rFence)
+                    w[k++] = a[r++];
+                while (rights != null) {
+                    if (rights.tryUnfork())
+                        rights.compute();
+                    else
+                        rights.join();
+                    rights = rights.next;
+                }
+            }
+        }
+    } // FJFloat
+
+    /** double support class */
+    static final class FJDouble {
+        static final class Sorter extends RecursiveAction {
+            static final long serialVersionUID = 2446542900576103244L;
+            final double[] a;    // array to be sorted.
+            final double[] w;    // workspace for merge
+            final int origin;    // origin of the part of array we deal with
+            final int n;         // Number of elements in (sub)arrays.
+            final int gran;      // split control
+
+            Sorter(double[] a, double[] w, int origin, int n, int gran) {
+                this.a = a;
+                this.w = w;
+                this.origin = origin;
+                this.n = n;
+                this.gran = gran;
+            }
+
+            public void compute() {
+                final int l = origin;
+                final int g = gran;
+                final int n = this.n;
+                final double[] a = this.a;
+                final double[] w = this.w;
+                if (n > g) {
+                    int h = n >>> 1; // half
+                    int q = n >>> 2; // lower quarter index
+                    int u = h + q;   // upper quarter
+                    FJSubSorter ls = new FJSubSorter(new Sorter(a, w, l, q,   g),
+                                                     new Sorter(a, w, l+q, h-q, g),
+                                                     new Merger(a, w, l,   q,
+                                                                l+q, h-q, l, g, null));
+                    FJSubSorter rs = new FJSubSorter(new Sorter(a, w, l + h, q,   g),
+                                                     new Sorter(a, w, l+u, n-u, g),
+                                                     new Merger(a, w, l+h, q,
+                                                                l+u, n-u, l+h, g, null));
+                    rs.fork();
+                    ls.compute();
+                    if (rs.tryUnfork()) rs.compute(); else rs.join();
+                    new Merger(w, a, l, h, l + h, n - h, l, g, null).compute();
+                } else {
+                    DualPivotQuicksort.sort(a, l, l+n-1);   // skip rangeCheck
+                }
+            }
+        }
+
+        static final class Merger extends RecursiveAction {
+            static final long serialVersionUID = 8076242187166127592L;
+            final double[] a;
+            final double[] w;
+            final int lo;
+            final int ln;
+            final int ro;
+            final int rn;
+            final int wo;
+            final int gran;
+            final Merger next;
+
+            Merger(double[] a, double[] w, int lo, int ln, int ro, int rn, int wo,
+                   int gran, Merger next) {
+                this.a = a;
+                this.w = w;
+                this.lo = lo;
+                this.ln = ln;
+                this.ro = ro;
+                this.rn = rn;
+                this.wo = wo;
+                this.gran = gran;
+                this.next = next;
+            }
+
+            public void compute() {
+                final double[] a = this.a;
+                final double[] w = this.w;
+                Merger rights = null;
+                int nleft = ln;
+                int nright = rn;
+                while (nleft > gran) {
+                    int lh = nleft >>> 1;
+                    int splitIndex = lo + lh;
+                    double split = a[splitIndex];
+                    int rl = 0;
+                    int rh = nright;
+                    while (rl < rh) {
+                        int mid = (rl + rh) >>> 1;
+                        if (Double.compare(split, a[ro+mid]) <= 0)
+                            rh = mid;
+                        else
+                            rl = mid + 1;
+                    }
+                    (rights = new Merger(a, w, splitIndex, nleft-lh, ro+rh,
+                                         nright-rh, wo+lh+rh, gran, rights)).fork();
+                    nleft = lh;
+                    nright = rh;
+                }
+
+                int l = lo;
+                int lFence = l + nleft;
+                int r = ro;
+                int rFence = r + nright;
+                int k = wo;
+                while (l < lFence && r < rFence) {
+                    double al = a[l];
+                    double ar = a[r];
+                    double t;
+                    if (Double.compare(al, ar) <= 0) {
+                        ++l;
+                        t = al;
+                    } else {
+                        ++r;
+                        t = ar;
+                    }
+                    w[k++] = t;
+                }
+                while (l < lFence)
+                    w[k++] = a[l++];
+                while (r < rFence)
+                    w[k++] = a[r++];
+                while (rights != null) {
+                    if (rights.tryUnfork())
+                        rights.compute();
+                    else
+                        rights.join();
+                    rights = rights.next;
+                }
+            }
+        }
+    } // FJDouble
+
+    /** Comparable support class */
+    static final class FJComparable {
+        static final class Sorter<T extends Comparable<? super T>> extends RecursiveAction {
+            static final long serialVersionUID = -1024003289463302522L;
+            final T[] a;
+            final T[] w;
+            final int origin;
+            final int n;
+            final int gran;
+
+            Sorter(T[] a, T[] w, int origin, int n, int gran) {
+                this.a = a;
+                this.w = w;
+                this.origin = origin;
+                this.n = n;
+                this.gran = gran;
+            }
+
+            public void compute() {
+                final int l = origin;
+                final int g = gran;
+                final int n = this.n;
+                final T[] a = this.a;
+                final T[] w = this.w;
+                if (n > g) {
+                    int h = n >>> 1;
+                    int q = n >>> 2;
+                    int u = h + q;
+                    FJSubSorter ls = new FJSubSorter(new Sorter<>(a, w, l, q,   g),
+                                                     new Sorter<>(a, w, l+q, h-q, g),
+                                                     new Merger<>(a, w, l,   q,
+                                                                  l+q, h-q, l, g, null));
+                    FJSubSorter rs = new FJSubSorter(new Sorter<>(a, w, l+h, q,   g),
+                                                     new Sorter<>(a, w, l+u, n-u, g),
+                                                     new Merger<>(a, w, l+h, q,
+                                                                  l+u, n-u, l+h, g, null));
+                    rs.fork();
+                    ls.compute();
+                    if (rs.tryUnfork()) rs.compute(); else rs.join();
+                    new Merger<>(w, a, l, h, l + h, n - h, l, g, null).compute();
+                } else {
+                    Arrays.sort(a, l, l+n);
+                }
+            }
+        }
+
+        static final class Merger<T extends Comparable<? super T>> extends RecursiveAction {
+            static final long serialVersionUID = -3989771675258379302L;
+            final T[] a;
+            final T[] w;
+            final int lo;
+            final int ln;
+            final int ro;
+            final int rn;
+            final int wo;
+            final int gran;
+            final Merger<T> next;
+
+            Merger(T[] a, T[] w, int lo, int ln, int ro, int rn, int wo,
+                   int gran, Merger<T> next) {
+                this.a = a;
+                this.w = w;
+                this.lo = lo;
+                this.ln = ln;
+                this.ro = ro;
+                this.rn = rn;
+                this.wo = wo;
+                this.gran = gran;
+                this.next = next;
+            }
+
+            public void compute() {
+                final T[] a = this.a;
+                final T[] w = this.w;
+                Merger<T> rights = null;
+                int nleft = ln;
+                int nright = rn;
+                while (nleft > gran) {
+                    int lh = nleft >>> 1;
+                    int splitIndex = lo + lh;
+                    T split = a[splitIndex];
+                    int rl = 0;
+                    int rh = nright;
+                    while (rl < rh) {
+                        int mid = (rl + rh) >>> 1;
+                        if (split.compareTo(a[ro + mid]) <= 0)
+                            rh = mid;
+                        else
+                            rl = mid + 1;
+                    }
+                    (rights = new Merger<>(a, w, splitIndex, nleft-lh, ro+rh,
+                                           nright-rh, wo+lh+rh, gran, rights)).fork();
+                    nleft = lh;
+                    nright = rh;
+                }
+
+                int l = lo;
+                int lFence = l + nleft;
+                int r = ro;
+                int rFence = r + nright;
+                int k = wo;
+                while (l < lFence && r < rFence) {
+                    T al = a[l];
+                    T ar = a[r];
+                    T t;
+                    if (al.compareTo(ar) <= 0) {++l; t=al;} else {++r; t=ar; }
+                    w[k++] = t;
+                }
+                while (l < lFence)
+                    w[k++] = a[l++];
+                while (r < rFence)
+                    w[k++] = a[r++];
+                while (rights != null) {
+                    if (rights.tryUnfork())
+                        rights.compute();
+                    else
+                        rights.join();
+                    rights = rights.next;
+                }
+            }
+        }
+    } // FJComparable
+
+    /** Object + Comparator support class */
+    static final class FJComparator {
+        static final class Sorter<T> extends RecursiveAction {
+            static final long serialVersionUID = 9191600840025808581L;
+            final T[] a;       // array to be sorted.
+            final T[] w;       // workspace for merge
+            final int origin;  // origin of the part of array we deal with
+            final int n;       // Number of elements in (sub)arrays.
+            final int gran;    // split control
+            final Comparator<? super T> cmp; // Comparator to use
+
+            Sorter(T[] a, T[] w, int origin, int n, int gran, Comparator<? super T> cmp) {
+                this.a = a;
+                this.w = w;
+                this.origin = origin;
+                this.n = n;
+                this.cmp = cmp;
+                this.gran = gran;
+            }
+
+            public void compute() {
+                final int l = origin;
+                final int g = gran;
+                final int n = this.n;
+                final T[] a = this.a;
+                final T[] w = this.w;
+                if (n > g) {
+                    int h = n >>> 1; // half
+                    int q = n >>> 2; // lower quarter index
+                    int u = h + q;   // upper quarter
+                    FJSubSorter ls = new FJSubSorter(new Sorter<>(a, w, l, q,   g, cmp),
+                                                     new Sorter<>(a, w, l+q, h-q, g, cmp),
+                                                     new Merger<>(a, w, l,   q,
+                                                                  l+q, h-q, l, g, null, cmp));
+                    FJSubSorter rs = new FJSubSorter(new Sorter<>(a, w, l + h, q,   g, cmp),
+                                                     new Sorter<>(a, w, l+u, n-u, g, cmp),
+                                                     new Merger<>(a, w, l+h, q,
+                                                                  l+u, n-u, l+h, g, null, cmp));
+                    rs.fork();
+                    ls.compute();
+                    if (rs.tryUnfork()) rs.compute(); else rs.join();
+                    new Merger<>(w, a, l, h, l + h, n - h, l, g, null, cmp).compute();
+                } else {
+                    Arrays.sort(a, l, l+n, cmp);
+                }
+            }
+        }
+
+        static final class Merger<T> extends RecursiveAction {
+            static final long serialVersionUID = -2679539040379156203L;
+            final T[] a;
+            final T[] w;
+            final int lo;
+            final int ln;
+            final int ro;
+            final int rn;
+            final int wo;
+            final int gran;
+            final Merger<T> next;
+            final Comparator<? super T> cmp;
+
+            Merger(T[] a, T[] w, int lo, int ln, int ro, int rn, int wo,
+                   int gran, Merger<T> next, Comparator<? super T> cmp) {
+                this.a = a;
+                this.w = w;
+                this.lo = lo;
+                this.ln = ln;
+                this.ro = ro;
+                this.rn = rn;
+                this.wo = wo;
+                this.gran = gran;
+                this.next = next;
+                this.cmp = cmp;
+            }
+
+            public void compute() {
+                final T[] a = this.a;
+                final T[] w = this.w;
+                Merger<T> rights = null;
+                int nleft = ln;
+                int nright = rn;
+                while (nleft > gran) {
+                    int lh = nleft >>> 1;
+                    int splitIndex = lo + lh;
+                    T split = a[splitIndex];
+                    int rl = 0;
+                    int rh = nright;
+                    while (rl < rh) {
+                        int mid = (rl + rh) >>> 1;
+                        if (cmp.compare(split, a[ro+mid]) <= 0)
+                            rh = mid;
+                        else
+                            rl = mid + 1;
+                    }
+                    (rights = new Merger<>(a, w, splitIndex, nleft-lh, ro+rh,
+                                           nright-rh, wo+lh+rh, gran, rights, cmp)).fork();
+                    nleft = lh;
+                    nright = rh;
+                }
+
+                int l = lo;
+                int lFence = l + nleft;
+                int r = ro;
+                int rFence = r + nright;
+                int k = wo;
+                while (l < lFence && r < rFence) {
+                    T al = a[l];
+                    T ar = a[r];
+                    T t;
+                    if (cmp.compare(al, ar) <= 0) {
+                        ++l;
+                        t = al;
+                    } else {
+                        ++r;
+                        t = ar;
+                    }
+                    w[k++] = t;
+                }
+                while (l < lFence)
+                    w[k++] = a[l++];
+                while (r < rFence)
+                    w[k++] = a[r++];
+                while (rights != null) {
+                    if (rights.tryUnfork())
+                        rights.compute();
+                    else
+                        rights.join();
+                    rights = rights.next;
+                }
+            }
+        }
+    } // FJComparator
+
+    /** Utility class to sort half a partitioned array */
+    private static final class FJSubSorter extends RecursiveAction {
+        static final long serialVersionUID = 9159249695527935512L;
+        final RecursiveAction left;
+        final RecursiveAction right;
+        final RecursiveAction merger;
+
+        FJSubSorter(RecursiveAction left, RecursiveAction right,
+                    RecursiveAction merger) {
+            this.left = left;
+            this.right = right;
+            this.merger = merger;
+        }
+
+        public void compute() {
+            right.fork();
+            left.invoke();
+            right.join();
+            merger.invoke();
+        }
+    }
+}
--- a/jdk/src/share/classes/java/util/Calendar.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/Calendar.java	Tue Jan 22 11:54:16 2013 -0800
@@ -749,7 +749,7 @@
      *
      * @see #NARROW_STANDALONE
      * @see #SHORT_FORMAT
-     * @see #LONG_FOTMAT
+     * @see #LONG_FORMAT
      * @since 1.8
      */
     public static final int NARROW_FORMAT = 4;
--- a/jdk/src/share/classes/java/util/CurrencyData.properties	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/CurrencyData.properties	Tue Jan 22 11:54:16 2013 -0800
@@ -28,7 +28,7 @@
 # Version of the currency code information in this class.
 # It is a serial number that accompanies with each amendment.
 
-dataVersion=153
+dataVersion=154
 
 # List of all valid ISO 4217 currency codes.
 # To ensure compatibility, do not remove codes.
@@ -52,7 +52,8 @@
     TPE626-TRL792-TRY949-TTD780-TWD901-TZS834-UAH980-UGX800-USD840-USN997-USS998-\
     UYU858-UZS860-VEB862-VEF937-VND704-VUV548-WST882-XAF950-XAG961-XAU959-XBA955-\
     XBB956-XBC957-XBD958-XCD951-XDR960-XFO000-XFU000-XOF952-XPD964-XPF953-\
-    XPT962-XSU994-XTS963-XUA965-XXX999-YER886-YUM891-ZAR710-ZMK894-ZWD716-ZWL932-ZWN942-ZWR935
+    XPT962-XSU994-XTS963-XUA965-XXX999-YER886-YUM891-ZAR710-ZMK894-ZMW967-ZWD716-ZWL932-\
+    ZWN942-ZWR935
 
 
 # Mappings from ISO 3166 country codes to ISO 4217 currency codes.
@@ -573,7 +574,7 @@
 # YEMEN
 YE=YER
 # ZAMBIA
-ZM=ZMK
+ZM=ZMW
 # ZIMBABWE
 ZW=ZWL
 
--- a/jdk/src/share/classes/java/util/LocaleISOData.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/LocaleISOData.java	Tue Jan 22 11:54:16 2013 -0800
@@ -473,7 +473,7 @@
         + "YE" + "YEM"  // Yemen
         + "YT" + "MYT"  // Mayotte
         + "ZA" + "ZAF"  // South Africa, Republic of
-        + "ZM" + "ZMB"  // Zambia, Republic of
+        + "ZM" + "ZMW"  // Zambia, Republic of
         + "ZW" + "ZWE"  // Zimbabwe
         ;
 
--- a/jdk/src/share/classes/java/util/Properties.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/Properties.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1188,7 +1188,7 @@
                         provider = loadProviderAsService(cl);
                         if (provider != null)
                             return provider;
-                        throw new InternalError("No fallback");
+                        return new jdk.internal.util.xml.BasicXmlPropertiesProvider();
                 }});
         }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/java/util/concurrent/CountedCompleter.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,743 @@
+/*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * This file is available under and governed by the GNU General Public
+ * License version 2 only, as published by the Free Software Foundation.
+ * However, the following notice accompanied the original version of this
+ * file:
+ *
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+package java.util.concurrent;
+
+/**
+ * A {@link ForkJoinTask} with a completion action performed when
+ * triggered and there are no remaining pending
+ * actions. CountedCompleters are in general more robust in the
+ * presence of subtask stalls and blockage than are other forms of
+ * ForkJoinTasks, but are less intuitive to program.  Uses of
+ * CountedCompleter are similar to those of other completion based
+ * components (such as {@link java.nio.channels.CompletionHandler})
+ * except that multiple <em>pending</em> completions may be necessary
+ * to trigger the completion action {@link #onCompletion}, not just one.
+ * Unless initialized otherwise, the {@linkplain #getPendingCount pending
+ * count} starts at zero, but may be (atomically) changed using
+ * methods {@link #setPendingCount}, {@link #addToPendingCount}, and
+ * {@link #compareAndSetPendingCount}. Upon invocation of {@link
+ * #tryComplete}, if the pending action count is nonzero, it is
+ * decremented; otherwise, the completion action is performed, and if
+ * this completer itself has a completer, the process is continued
+ * with its completer.  As is the case with related synchronization
+ * components such as {@link java.util.concurrent.Phaser Phaser} and
+ * {@link java.util.concurrent.Semaphore Semaphore}, these methods
+ * affect only internal counts; they do not establish any further
+ * internal bookkeeping. In particular, the identities of pending
+ * tasks are not maintained. As illustrated below, you can create
+ * subclasses that do record some or all pending tasks or their
+ * results when needed.  As illustrated below, utility methods
+ * supporting customization of completion traversals are also
+ * provided. However, because CountedCompleters provide only basic
+ * synchronization mechanisms, it may be useful to create further
+ * abstract subclasses that maintain linkages, fields, and additional
+ * support methods appropriate for a set of related usages.
+ *
+ * <p>A concrete CountedCompleter class must define method {@link
+ * #compute}, that should in most cases (as illustrated below), invoke
+ * {@code tryComplete()} once before returning. The class may also
+ * optionally override method {@link #onCompletion} to perform an
+ * action upon normal completion, and method {@link
+ * #onExceptionalCompletion} to perform an action upon any exception.
+ *
+ * <p>CountedCompleters most often do not bear results, in which case
+ * they are normally declared as {@code CountedCompleter<Void>}, and
+ * will always return {@code null} as a result value.  In other cases,
+ * you should override method {@link #getRawResult} to provide a
+ * result from {@code join(), invoke()}, and related methods.  In
+ * general, this method should return the value of a field (or a
+ * function of one or more fields) of the CountedCompleter object that
+ * holds the result upon completion. Method {@link #setRawResult} by
+ * default plays no role in CountedCompleters.  It is possible, but
+ * rarely applicable, to override this method to maintain other
+ * objects or fields holding result data.
+ *
+ * <p>A CountedCompleter that does not itself have a completer (i.e.,
+ * one for which {@link #getCompleter} returns {@code null}) can be
+ * used as a regular ForkJoinTask with this added functionality.
+ * However, any completer that in turn has another completer serves
+ * only as an internal helper for other computations, so its own task
+ * status (as reported in methods such as {@link ForkJoinTask#isDone})
+ * is arbitrary; this status changes only upon explicit invocations of
+ * {@link #complete}, {@link ForkJoinTask#cancel}, {@link
+ * ForkJoinTask#completeExceptionally} or upon exceptional completion
+ * of method {@code compute}. Upon any exceptional completion, the
+ * exception may be relayed to a task's completer (and its completer,
+ * and so on), if one exists and it has not otherwise already
+ * completed. Similarly, cancelling an internal CountedCompleter has
+ * only a local effect on that completer, so is not often useful.
+ *
+ * <p><b>Sample Usages.</b>
+ *
+ * <p><b>Parallel recursive decomposition.</b> CountedCompleters may
+ * be arranged in trees similar to those often used with {@link
+ * RecursiveAction}s, although the constructions involved in setting
+ * them up typically vary. Here, the completer of each task is its
+ * parent in the computation tree. Even though they entail a bit more
+ * bookkeeping, CountedCompleters may be better choices when applying
+ * a possibly time-consuming operation (that cannot be further
+ * subdivided) to each element of an array or collection; especially
+ * when the operation takes a significantly different amount of time
+ * to complete for some elements than others, either because of
+ * intrinsic variation (for example I/O) or auxiliary effects such as
+ * garbage collection.  Because CountedCompleters provide their own
+ * continuations, other threads need not block waiting to perform
+ * them.
+ *
+ * <p>For example, here is an initial version of a class that uses
+ * divide-by-two recursive decomposition to divide work into single
+ * pieces (leaf tasks). Even when work is split into individual calls,
+ * tree-based techniques are usually preferable to directly forking
+ * leaf tasks, because they reduce inter-thread communication and
+ * improve load balancing. In the recursive case, the second of each
+ * pair of subtasks to finish triggers completion of its parent
+ * (because no result combination is performed, the default no-op
+ * implementation of method {@code onCompletion} is not overridden). A
+ * static utility method sets up the base task and invokes it
+ * (here, implicitly using the {@link ForkJoinPool#commonPool()}).
+ *
+ * <pre> {@code
+ * class MyOperation<E> { void apply(E e) { ... }  }
+ *
+ * class ForEach<E> extends CountedCompleter<Void> {
+ *
+ *   public static <E> void forEach(E[] array, MyOperation<E> op) {
+ *     new ForEach<E>(null, array, op, 0, array.length).invoke();
+ *   }
+ *
+ *   final E[] array; final MyOperation<E> op; final int lo, hi;
+ *   ForEach(CountedCompleter<?> p, E[] array, MyOperation<E> op, int lo, int hi) {
+ *     super(p);
+ *     this.array = array; this.op = op; this.lo = lo; this.hi = hi;
+ *   }
+ *
+ *   public void compute() { // version 1
+ *     if (hi - lo >= 2) {
+ *       int mid = (lo + hi) >>> 1;
+ *       setPendingCount(2); // must set pending count before fork
+ *       new ForEach(this, array, op, mid, hi).fork(); // right child
+ *       new ForEach(this, array, op, lo, mid).fork(); // left child
+ *     }
+ *     else if (hi > lo)
+ *       op.apply(array[lo]);
+ *     tryComplete();
+ *   }
+ * }}</pre>
+ *
+ * This design can be improved by noticing that in the recursive case,
+ * the task has nothing to do after forking its right task, so can
+ * directly invoke its left task before returning. (This is an analog
+ * of tail recursion removal.)  Also, because the task returns upon
+ * executing its left task (rather than falling through to invoke
+ * {@code tryComplete}) the pending count is set to one:
+ *
+ * <pre> {@code
+ * class ForEach<E> ...
+ *   public void compute() { // version 2
+ *     if (hi - lo >= 2) {
+ *       int mid = (lo + hi) >>> 1;
+ *       setPendingCount(1); // only one pending
+ *       new ForEach(this, array, op, mid, hi).fork(); // right child
+ *       new ForEach(this, array, op, lo, mid).compute(); // direct invoke
+ *     }
+ *     else {
+ *       if (hi > lo)
+ *         op.apply(array[lo]);
+ *       tryComplete();
+ *     }
+ *   }
+ * }</pre>
+ *
+ * As a further improvement, notice that the left task need not even
+ * exist.  Instead of creating a new one, we can iterate using the
+ * original task, and add a pending count for each fork. Additionally,
+ * because no task in this tree implements an {@link #onCompletion}
+ * method, {@code tryComplete()} can be replaced with {@link
+ * #propagateCompletion}.
+ *
+ * <pre> {@code
+ * class ForEach<E> ...
+ *   public void compute() { // version 3
+ *     int l = lo,  h = hi;
+ *     while (h - l >= 2) {
+ *       int mid = (l + h) >>> 1;
+ *       addToPendingCount(1);
+ *       new ForEach(this, array, op, mid, h).fork(); // right child
+ *       h = mid;
+ *     }
+ *     if (h > l)
+ *       op.apply(array[l]);
+ *     propagateCompletion();
+ *   }
+ * }</pre>
+ *
+ * Additional improvements of such classes might entail precomputing
+ * pending counts so that they can be established in constructors,
+ * specializing classes for leaf steps, subdividing by say, four,
+ * instead of two per iteration, and using an adaptive threshold
+ * instead of always subdividing down to single elements.
+ *
+ * <p><b>Searching.</b> A tree of CountedCompleters can search for a
+ * value or property in different parts of a data structure, and
+ * report a result in an {@link
+ * java.util.concurrent.atomic.AtomicReference AtomicReference} as
+ * soon as one is found. The others can poll the result to avoid
+ * unnecessary work. (You could additionally {@linkplain #cancel
+ * cancel} other tasks, but it is usually simpler and more efficient
+ * to just let them notice that the result is set and if so skip
+ * further processing.)  Illustrating again with an array using full
+ * partitioning (again, in practice, leaf tasks will almost always
+ * process more than one element):
+ *
+ * <pre> {@code
+ * class Searcher<E> extends CountedCompleter<E> {
+ *   final E[] array; final AtomicReference<E> result; final int lo, hi;
+ *   Searcher(CountedCompleter<?> p, E[] array, AtomicReference<E> result, int lo, int hi) {
+ *     super(p);
+ *     this.array = array; this.result = result; this.lo = lo; this.hi = hi;
+ *   }
+ *   public E getRawResult() { return result.get(); }
+ *   public void compute() { // similar to ForEach version 3
+ *     int l = lo,  h = hi;
+ *     while (result.get() == null && h >= l) {
+ *       if (h - l >= 2) {
+ *         int mid = (l + h) >>> 1;
+ *         addToPendingCount(1);
+ *         new Searcher(this, array, result, mid, h).fork();
+ *         h = mid;
+ *       }
+ *       else {
+ *         E x = array[l];
+ *         if (matches(x) && result.compareAndSet(null, x))
+ *           quietlyCompleteRoot(); // root task is now joinable
+ *         break;
+ *       }
+ *     }
+ *     tryComplete(); // normally complete whether or not found
+ *   }
+ *   boolean matches(E e) { ... } // return true if found
+ *
+ *   public static <E> E search(E[] array) {
+ *       return new Searcher<E>(null, array, new AtomicReference<E>(), 0, array.length).invoke();
+ *   }
+ *}}</pre>
+ *
+ * In this example, as well as others in which tasks have no other
+ * effects except to compareAndSet a common result, the trailing
+ * unconditional invocation of {@code tryComplete} could be made
+ * conditional ({@code if (result.get() == null) tryComplete();})
+ * because no further bookkeeping is required to manage completions
+ * once the root task completes.
+ *
+ * <p><b>Recording subtasks.</b> CountedCompleter tasks that combine
+ * results of multiple subtasks usually need to access these results
+ * in method {@link #onCompletion}. As illustrated in the following
+ * class (that performs a simplified form of map-reduce where mappings
+ * and reductions are all of type {@code E}), one way to do this in
+ * divide and conquer designs is to have each subtask record its
+ * sibling, so that it can be accessed in method {@code onCompletion}.
+ * This technique applies to reductions in which the order of
+ * combining left and right results does not matter; ordered
+ * reductions require explicit left/right designations.  Variants of
+ * other streamlinings seen in the above examples may also apply.
+ *
+ * <pre> {@code
+ * class MyMapper<E> { E apply(E v) {  ...  } }
+ * class MyReducer<E> { E apply(E x, E y) {  ...  } }
+ * class MapReducer<E> extends CountedCompleter<E> {
+ *   final E[] array; final MyMapper<E> mapper;
+ *   final MyReducer<E> reducer; final int lo, hi;
+ *   MapReducer<E> sibling;
+ *   E result;
+ *   MapReducer(CountedCompleter<?> p, E[] array, MyMapper<E> mapper,
+ *              MyReducer<E> reducer, int lo, int hi) {
+ *     super(p);
+ *     this.array = array; this.mapper = mapper;
+ *     this.reducer = reducer; this.lo = lo; this.hi = hi;
+ *   }
+ *   public void compute() {
+ *     if (hi - lo >= 2) {
+ *       int mid = (lo + hi) >>> 1;
+ *       MapReducer<E> left = new MapReducer(this, array, mapper, reducer, lo, mid);
+ *       MapReducer<E> right = new MapReducer(this, array, mapper, reducer, mid, hi);
+ *       left.sibling = right;
+ *       right.sibling = left;
+ *       setPendingCount(1); // only right is pending
+ *       right.fork();
+ *       left.compute();     // directly execute left
+ *     }
+ *     else {
+ *       if (hi > lo)
+ *           result = mapper.apply(array[lo]);
+ *       tryComplete();
+ *     }
+ *   }
+ *   public void onCompletion(CountedCompleter<?> caller) {
+ *     if (caller != this) {
+ *       MapReducer<E> child = (MapReducer<E>)caller;
+ *       MapReducer<E> sib = child.sibling;
+ *       if (sib == null || sib.result == null)
+ *         result = child.result;
+ *       else
+ *         result = reducer.apply(child.result, sib.result);
+ *     }
+ *   }
+ *   public E getRawResult() { return result; }
+ *
+ *   public static <E> E mapReduce(E[] array, MyMapper<E> mapper, MyReducer<E> reducer) {
+ *     return new MapReducer<E>(null, array, mapper, reducer,
+ *                              0, array.length).invoke();
+ *   }
+ * }}</pre>
+ *
+ * Here, method {@code onCompletion} takes a form common to many
+ * completion designs that combine results. This callback-style method
+ * is triggered once per task, in either of the two different contexts
+ * in which the pending count is, or becomes, zero: (1) by a task
+ * itself, if its pending count is zero upon invocation of {@code
+ * tryComplete}, or (2) by any of its subtasks when they complete and
+ * decrement the pending count to zero. The {@code caller} argument
+ * distinguishes cases.  Most often, when the caller is {@code this},
+ * no action is necessary. Otherwise the caller argument can be used
+ * (usually via a cast) to supply a value (and/or links to other
+ * values) to be combined.  Assuming proper use of pending counts, the
+ * actions inside {@code onCompletion} occur (once) upon completion of
+ * a task and its subtasks. No additional synchronization is required
+ * within this method to ensure thread safety of accesses to fields of
+ * this task or other completed tasks.
+ *
+ * <p><b>Completion Traversals</b>. If using {@code onCompletion} to
+ * process completions is inapplicable or inconvenient, you can use
+ * methods {@link #firstComplete} and {@link #nextComplete} to create
+ * custom traversals.  For example, to define a MapReducer that only
+ * splits out right-hand tasks in the form of the third ForEach
+ * example, the completions must cooperatively reduce along
+ * unexhausted subtask links, which can be done as follows:
+ *
+ * <pre> {@code
+ * class MapReducer<E> extends CountedCompleter<E> { // version 2
+ *   final E[] array; final MyMapper<E> mapper;
+ *   final MyReducer<E> reducer; final int lo, hi;
+ *   MapReducer<E> forks, next; // record subtask forks in list
+ *   E result;
+ *   MapReducer(CountedCompleter<?> p, E[] array, MyMapper<E> mapper,
+ *              MyReducer<E> reducer, int lo, int hi, MapReducer<E> next) {
+ *     super(p);
+ *     this.array = array; this.mapper = mapper;
+ *     this.reducer = reducer; this.lo = lo; this.hi = hi;
+ *     this.next = next;
+ *   }
+ *   public void compute() {
+ *     int l = lo,  h = hi;
+ *     while (h - l >= 2) {
+ *       int mid = (l + h) >>> 1;
+ *       addToPendingCount(1);
+ *       (forks = new MapReducer(this, array, mapper, reducer, mid, h, forks)).fork;
+ *       h = mid;
+ *     }
+ *     if (h > l)
+ *       result = mapper.apply(array[l]);
+ *     // process completions by reducing along and advancing subtask links
+ *     for (CountedCompleter<?> c = firstComplete(); c != null; c = c.nextComplete()) {
+ *       for (MapReducer t = (MapReducer)c, s = t.forks;  s != null; s = t.forks = s.next)
+ *         t.result = reducer.apply(t.result, s.result);
+ *     }
+ *   }
+ *   public E getRawResult() { return result; }
+ *
+ *   public static <E> E mapReduce(E[] array, MyMapper<E> mapper, MyReducer<E> reducer) {
+ *     return new MapReducer<E>(null, array, mapper, reducer,
+ *                              0, array.length, null).invoke();
+ *   }
+ * }}</pre>
+ *
+ * <p><b>Triggers.</b> Some CountedCompleters are themselves never
+ * forked, but instead serve as bits of plumbing in other designs;
+ * including those in which the completion of one of more async tasks
+ * triggers another async task. For example:
+ *
+ * <pre> {@code
+ * class HeaderBuilder extends CountedCompleter<...> { ... }
+ * class BodyBuilder extends CountedCompleter<...> { ... }
+ * class PacketSender extends CountedCompleter<...> {
+ *   PacketSender(...) { super(null, 1); ... } // trigger on second completion
+ *   public void compute() { } // never called
+ *   public void onCompletion(CountedCompleter<?> caller) { sendPacket(); }
+ * }
+ * // sample use:
+ * PacketSender p = new PacketSender();
+ * new HeaderBuilder(p, ...).fork();
+ * new BodyBuilder(p, ...).fork();
+ * }</pre>
+ *
+ * @since 1.8
+ * @author Doug Lea
+ */
+public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
+    private static final long serialVersionUID = 5232453752276485070L;
+
+    /** This task's completer, or null if none */
+    final CountedCompleter<?> completer;
+    /** The number of pending tasks until completion */
+    volatile int pending;
+
+    /**
+     * Creates a new CountedCompleter with the given completer
+     * and initial pending count.
+     *
+     * @param completer this task's completer, or {@code null} if none
+     * @param initialPendingCount the initial pending count
+     */
+    protected CountedCompleter(CountedCompleter<?> completer,
+                               int initialPendingCount) {
+        this.completer = completer;
+        this.pending = initialPendingCount;
+    }
+
+    /**
+     * Creates a new CountedCompleter with the given completer
+     * and an initial pending count of zero.
+     *
+     * @param completer this task's completer, or {@code null} if none
+     */
+    protected CountedCompleter(CountedCompleter<?> completer) {
+        this.completer = completer;
+    }
+
+    /**
+     * Creates a new CountedCompleter with no completer
+     * and an initial pending count of zero.
+     */
+    protected CountedCompleter() {
+        this.completer = null;
+    }
+
+    /**
+     * The main computation performed by this task.
+     */
+    public abstract void compute();
+
+    /**
+     * Performs an action when method {@link #tryComplete} is invoked
+     * and the pending count is zero, or when the unconditional
+     * method {@link #complete} is invoked.  By default, this method
+     * does nothing. You can distinguish cases by checking the
+     * identity of the given caller argument. If not equal to {@code
+     * this}, then it is typically a subtask that may contain results
+     * (and/or links to other results) to combine.
+     *
+     * @param caller the task invoking this method (which may
+     * be this task itself).
+     */
+    public void onCompletion(CountedCompleter<?> caller) {
+    }
+
+    /**
+     * Performs an action when method {@link #completeExceptionally}
+     * is invoked or method {@link #compute} throws an exception, and
+     * this task has not otherwise already completed normally. On
+     * entry to this method, this task {@link
+     * ForkJoinTask#isCompletedAbnormally}.  The return value of this
+     * method controls further propagation: If {@code true} and this
+     * task has a completer, then this completer is also completed
+     * exceptionally.  The default implementation of this method does
+     * nothing except return {@code true}.
+     *
+     * @param ex the exception
+     * @param caller the task invoking this method (which may
+     * be this task itself).
+     * @return true if this exception should be propagated to this
+     * task's completer, if one exists.
+     */
+    public boolean onExceptionalCompletion(Throwable ex, CountedCompleter<?> caller) {
+        return true;
+    }
+
+    /**
+     * Returns the completer established in this task's constructor,
+     * or {@code null} if none.
+     *
+     * @return the completer
+     */
+    public final CountedCompleter<?> getCompleter() {
+        return completer;
+    }
+
+    /**
+     * Returns the current pending count.
+     *
+     * @return the current pending count
+     */
+    public final int getPendingCount() {
+        return pending;
+    }
+
+    /**
+     * Sets the pending count to the given value.
+     *
+     * @param count the count
+     */
+    public final void setPendingCount(int count) {
+        pending = count;
+    }
+
+    /**
+     * Adds (atomically) the given value to the pending count.
+     *
+     * @param delta the value to add
+     */
+    public final void addToPendingCount(int delta) {
+        int c; // note: can replace with intrinsic in jdk8
+        do {} while (!U.compareAndSwapInt(this, PENDING, c = pending, c+delta));
+    }
+
+    /**
+     * Sets (atomically) the pending count to the given count only if
+     * it currently holds the given expected value.
+     *
+     * @param expected the expected value
+     * @param count the new value
+     * @return true if successful
+     */
+    public final boolean compareAndSetPendingCount(int expected, int count) {
+        return U.compareAndSwapInt(this, PENDING, expected, count);
+    }
+
+    /**
+     * If the pending count is nonzero, (atomically) decrements it.
+     *
+     * @return the initial (undecremented) pending count holding on entry
+     * to this method
+     */
+    public final int decrementPendingCountUnlessZero() {
+        int c;
+        do {} while ((c = pending) != 0 &&
+                     !U.compareAndSwapInt(this, PENDING, c, c - 1));
+        return c;
+    }
+
+    /**
+     * Returns the root of the current computation; i.e., this
+     * task if it has no completer, else its completer's root.
+     *
+     * @return the root of the current computation
+     */
+    public final CountedCompleter<?> getRoot() {
+        CountedCompleter<?> a = this, p;
+        while ((p = a.completer) != null)
+            a = p;
+        return a;
+    }
+
+    /**
+     * If the pending count is nonzero, decrements the count;
+     * otherwise invokes {@link #onCompletion} and then similarly
+     * tries to complete this task's completer, if one exists,
+     * else marks this task as complete.
+     */
+    public final void tryComplete() {
+        CountedCompleter<?> a = this, s = a;
+        for (int c;;) {
+            if ((c = a.pending) == 0) {
+                a.onCompletion(s);
+                if ((a = (s = a).completer) == null) {
+                    s.quietlyComplete();
+                    return;
+                }
+            }
+            else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
+                return;
+        }
+    }
+
+    /**
+     * Equivalent to {@link #tryComplete} but does not invoke {@link
+     * #onCompletion} along the completion path: If the pending count
+     * is nonzero, decrements the count; otherwise, similarly tries to
+     * complete this task's completer, if one exists, else marks this
+     * task as complete. This method may be useful in cases where
+     * {@code onCompletion} should not, or need not, be invoked for
+     * each completer in a computation.
+     */
+    public final void propagateCompletion() {
+        CountedCompleter<?> a = this, s = a;
+        for (int c;;) {
+            if ((c = a.pending) == 0) {
+                if ((a = (s = a).completer) == null) {
+                    s.quietlyComplete();
+                    return;
+                }
+            }
+            else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
+                return;
+        }
+    }
+
+    /**
+     * Regardless of pending count, invokes {@link #onCompletion},
+     * marks this task as complete and further triggers {@link
+     * #tryComplete} on this task's completer, if one exists.  The
+     * given rawResult is used as an argument to {@link #setRawResult}
+     * before invoking {@link #onCompletion} or marking this task as
+     * complete; its value is meaningful only for classes overriding
+     * {@code setRawResult}.
+     *
+     * <p>This method may be useful when forcing completion as soon as
+     * any one (versus all) of several subtask results are obtained.
+     * However, in the common (and recommended) case in which {@code
+     * setRawResult} is not overridden, this effect can be obtained
+     * more simply using {@code quietlyCompleteRoot();}.
+     *
+     * @param rawResult the raw result
+     */
+    public void complete(T rawResult) {
+        CountedCompleter<?> p;
+        setRawResult(rawResult);
+        onCompletion(this);
+        quietlyComplete();
+        if ((p = completer) != null)
+            p.tryComplete();
+    }
+
+
+    /**
+     * If this task's pending count is zero, returns this task;
+     * otherwise decrements its pending count and returns {@code
+     * null}. This method is designed to be used with {@link
+     * #nextComplete} in completion traversal loops.
+     *
+     * @return this task, if pending count was zero, else {@code null}
+     */
+    public final CountedCompleter<?> firstComplete() {
+        for (int c;;) {
+            if ((c = pending) == 0)
+                return this;
+            else if (U.compareAndSwapInt(this, PENDING, c, c - 1))
+                return null;
+        }
+    }
+
+    /**
+     * If this task does not have a completer, invokes {@link
+     * ForkJoinTask#quietlyComplete} and returns {@code null}.  Or, if
+     * this task's pending count is non-zero, decrements its pending
+     * count and returns {@code null}.  Otherwise, returns the
+     * completer.  This method can be used as part of a completion
+     * traversal loop for homogeneous task hierarchies:
+     *
+     * <pre> {@code
+     * for (CountedCompleter<?> c = firstComplete();
+     *      c != null;
+     *      c = c.nextComplete()) {
+     *   // ... process c ...
+     * }}</pre>
+     *
+     * @return the completer, or {@code null} if none
+     */
+    public final CountedCompleter<?> nextComplete() {
+        CountedCompleter<?> p;
+        if ((p = completer) != null)
+            return p.firstComplete();
+        else {
+            quietlyComplete();
+            return null;
+        }
+    }
+
+    /**
+     * Equivalent to {@code getRoot().quietlyComplete()}.
+     */
+    public final void quietlyCompleteRoot() {
+        for (CountedCompleter<?> a = this, p;;) {
+            if ((p = a.completer) == null) {
+                a.quietlyComplete();
+                return;
+            }
+            a = p;
+        }
+    }
+
+    /**
+     * Supports ForkJoinTask exception propagation.
+     */
+    void internalPropagateException(Throwable ex) {
+        CountedCompleter<?> a = this, s = a;
+        while (a.onExceptionalCompletion(ex, s) &&
+               (a = (s = a).completer) != null && a.status >= 0)
+            a.recordExceptionalCompletion(ex);
+    }
+
+    /**
+     * Implements execution conventions for CountedCompleters.
+     */
+    protected final boolean exec() {
+        compute();
+        return false;
+    }
+
+    /**
+     * Returns the result of the computation. By default
+     * returns {@code null}, which is appropriate for {@code Void}
+     * actions, but in other cases should be overridden, almost
+     * always to return a field or function of a field that
+     * holds the result upon completion.
+     *
+     * @return the result of the computation
+     */
+    public T getRawResult() { return null; }
+
+    /**
+     * A method that result-bearing CountedCompleters may optionally
+     * use to help maintain result data.  By default, does nothing.
+     * Overrides are not recommended. However, if this method is
+     * overridden to update existing objects or fields, then it must
+     * in general be defined to be thread-safe.
+     */
+    protected void setRawResult(T t) { }
+
+    // Unsafe mechanics
+    private static final sun.misc.Unsafe U;
+    private static final long PENDING;
+    static {
+        try {
+            U = sun.misc.Unsafe.getUnsafe();
+            PENDING = U.objectFieldOffset
+                (CountedCompleter.class.getDeclaredField("pending"));
+        } catch (Exception e) {
+            throw new Error(e);
+        }
+    }
+}
--- a/jdk/src/share/classes/java/util/concurrent/ForkJoinPool.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/concurrent/ForkJoinPool.java	Tue Jan 22 11:54:16 2013 -0800
@@ -40,7 +40,6 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
-import java.util.Random;
 import java.util.concurrent.AbstractExecutorService;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutorService;
@@ -48,11 +47,6 @@
 import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.RunnableFuture;
 import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.locks.LockSupport;
-import java.util.concurrent.locks.ReentrantLock;
-import java.util.concurrent.locks.Condition;
 
 /**
  * An {@link ExecutorService} for running {@link ForkJoinTask}s.
@@ -63,21 +57,31 @@
  * <p>A {@code ForkJoinPool} differs from other kinds of {@link
  * ExecutorService} mainly by virtue of employing
  * <em>work-stealing</em>: all threads in the pool attempt to find and
- * execute subtasks created by other active tasks (eventually blocking
- * waiting for work if none exist). This enables efficient processing
- * when most tasks spawn other subtasks (as do most {@code
- * ForkJoinTask}s). When setting <em>asyncMode</em> to true in
- * constructors, {@code ForkJoinPool}s may also be appropriate for use
- * with event-style tasks that are never joined.
+ * execute tasks submitted to the pool and/or created by other active
+ * tasks (eventually blocking waiting for work if none exist). This
+ * enables efficient processing when most tasks spawn other subtasks
+ * (as do most {@code ForkJoinTask}s), as well as when many small
+ * tasks are submitted to the pool from external clients.  Especially
+ * when setting <em>asyncMode</em> to true in constructors, {@code
+ * ForkJoinPool}s may also be appropriate for use with event-style
+ * tasks that are never joined.
  *
- * <p>A {@code ForkJoinPool} is constructed with a given target
- * parallelism level; by default, equal to the number of available
- * processors. The pool attempts to maintain enough active (or
- * available) threads by dynamically adding, suspending, or resuming
- * internal worker threads, even if some tasks are stalled waiting to
- * join others. However, no such adjustments are guaranteed in the
- * face of blocked IO or other unmanaged synchronization. The nested
- * {@link ManagedBlocker} interface enables extension of the kinds of
+ * <p>A static {@link #commonPool()} is available and appropriate for
+ * most applications. The common pool is used by any ForkJoinTask that
+ * is not explicitly submitted to a specified pool. Using the common
+ * pool normally reduces resource usage (its threads are slowly
+ * reclaimed during periods of non-use, and reinstated upon subsequent
+ * use).
+ *
+ * <p>For applications that require separate or custom pools, a {@code
+ * ForkJoinPool} may be constructed with a given target parallelism
+ * level; by default, equal to the number of available processors. The
+ * pool attempts to maintain enough active (or available) threads by
+ * dynamically adding, suspending, or resuming internal worker
+ * threads, even if some tasks are stalled waiting to join
+ * others. However, no such adjustments are guaranteed in the face of
+ * blocked I/O or other unmanaged synchronization. The nested {@link
+ * ManagedBlocker} interface enables extension of the kinds of
  * synchronization accommodated.
  *
  * <p>In addition to execution and lifecycle control methods, this
@@ -87,16 +91,17 @@
  * {@link #toString} returns indications of pool state in a
  * convenient form for informal monitoring.
  *
- * <p> As is the case with other ExecutorServices, there are three
- * main task execution methods summarized in the following
- * table. These are designed to be used by clients not already engaged
- * in fork/join computations in the current pool.  The main forms of
- * these methods accept instances of {@code ForkJoinTask}, but
- * overloaded forms also allow mixed execution of plain {@code
+ * <p>As is the case with other ExecutorServices, there are three
+ * main task execution methods summarized in the following table.
+ * These are designed to be used primarily by clients not already
+ * engaged in fork/join computations in the current pool.  The main
+ * forms of these methods accept instances of {@code ForkJoinTask},
+ * but overloaded forms also allow mixed execution of plain {@code
  * Runnable}- or {@code Callable}- based activities as well.  However,
- * tasks that are already executing in a pool should normally
- * <em>NOT</em> use these pool execution methods, but instead use the
- * within-computation forms listed in the table.
+ * tasks that are already executing in a pool should normally instead
+ * use the within-computation forms listed in the table unless using
+ * async event-style tasks that are not usually joined, in which case
+ * there is little difference among choice of methods.
  *
  * <table BORDER CELLPADDING=3 CELLSPACING=1>
  *  <tr>
@@ -121,23 +126,16 @@
  *  </tr>
  * </table>
  *
- * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
- * used for all parallel task execution in a program or subsystem.
- * Otherwise, use would not usually outweigh the construction and
- * bookkeeping overhead of creating a large set of threads. For
- * example, a common pool could be used for the {@code SortTasks}
- * illustrated in {@link RecursiveAction}. Because {@code
- * ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon
- * daemon} mode, there is typically no need to explicitly {@link
- * #shutdown} such a pool upon program exit.
- *
- * <pre>
- * static final ForkJoinPool mainPool = new ForkJoinPool();
- * ...
- * public void sort(long[] array) {
- *   mainPool.invoke(new SortTask(array, 0, array.length));
- * }
- * </pre>
+ * <p>The common pool is by default constructed with default
+ * parameters, but these may be controlled by setting three {@link
+ * System#getProperty system properties} with prefix {@code
+ * java.util.concurrent.ForkJoinPool.common}: {@code parallelism} --
+ * an integer greater than zero, {@code threadFactory} -- the class
+ * name of a {@link ForkJoinWorkerThreadFactory}, and {@code
+ * exceptionHandler} -- the class name of a {@link
+ * java.lang.Thread.UncaughtExceptionHandler
+ * Thread.UncaughtExceptionHandler}. Upon any error in establishing
+ * these settings, default parameters are used.
  *
  * <p><b>Implementation notes</b>: This implementation restricts the
  * maximum number of running threads to 32767. Attempts to create
@@ -156,214 +154,388 @@
     /*
      * Implementation Overview
      *
-     * This class provides the central bookkeeping and control for a
-     * set of worker threads: Submissions from non-FJ threads enter
-     * into a submission queue. Workers take these tasks and typically
-     * split them into subtasks that may be stolen by other workers.
-     * Preference rules give first priority to processing tasks from
-     * their own queues (LIFO or FIFO, depending on mode), then to
-     * randomized FIFO steals of tasks in other worker queues, and
-     * lastly to new submissions.
+     * This class and its nested classes provide the main
+     * functionality and control for a set of worker threads:
+     * Submissions from non-FJ threads enter into submission queues.
+     * Workers take these tasks and typically split them into subtasks
+     * that may be stolen by other workers.  Preference rules give
+     * first priority to processing tasks from their own queues (LIFO
+     * or FIFO, depending on mode), then to randomized FIFO steals of
+     * tasks in other queues.
+     *
+     * WorkQueues
+     * ==========
+     *
+     * Most operations occur within work-stealing queues (in nested
+     * class WorkQueue).  These are special forms of Deques that
+     * support only three of the four possible end-operations -- push,
+     * pop, and poll (aka steal), under the further constraints that
+     * push and pop are called only from the owning thread (or, as
+     * extended here, under a lock), while poll may be called from
+     * other threads.  (If you are unfamiliar with them, you probably
+     * want to read Herlihy and Shavit's book "The Art of
+     * Multiprocessor programming", chapter 16 describing these in
+     * more detail before proceeding.)  The main work-stealing queue
+     * design is roughly similar to those in the papers "Dynamic
+     * Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005
+     * (http://research.sun.com/scalable/pubs/index.html) and
+     * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
+     * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
+     * The main differences ultimately stem from GC requirements that
+     * we null out taken slots as soon as we can, to maintain as small
+     * a footprint as possible even in programs generating huge
+     * numbers of tasks. To accomplish this, we shift the CAS
+     * arbitrating pop vs poll (steal) from being on the indices
+     * ("base" and "top") to the slots themselves.  So, both a
+     * successful pop and poll mainly entail a CAS of a slot from
+     * non-null to null.  Because we rely on CASes of references, we
+     * do not need tag bits on base or top.  They are simple ints as
+     * used in any circular array-based queue (see for example
+     * ArrayDeque).  Updates to the indices must still be ordered in a
+     * way that guarantees that top == base means the queue is empty,
+     * but otherwise may err on the side of possibly making the queue
+     * appear nonempty when a push, pop, or poll have not fully
+     * committed. Note that this means that the poll operation,
+     * considered individually, is not wait-free. One thief cannot
+     * successfully continue until another in-progress one (or, if
+     * previously empty, a push) completes.  However, in the
+     * aggregate, we ensure at least probabilistic non-blockingness.
+     * If an attempted steal fails, a thief always chooses a different
+     * random victim target to try next. So, in order for one thief to
+     * progress, it suffices for any in-progress poll or new push on
+     * any empty queue to complete. (This is why we normally use
+     * method pollAt and its variants that try once at the apparent
+     * base index, else consider alternative actions, rather than
+     * method poll.)
+     *
+     * This approach also enables support of a user mode in which local
+     * task processing is in FIFO, not LIFO order, simply by using
+     * poll rather than pop.  This can be useful in message-passing
+     * frameworks in which tasks are never joined.  However neither
+     * mode considers affinities, loads, cache localities, etc, so
+     * rarely provide the best possible performance on a given
+     * machine, but portably provide good throughput by averaging over
+     * these factors.  (Further, even if we did try to use such
+     * information, we do not usually have a basis for exploiting it.
+     * For example, some sets of tasks profit from cache affinities,
+     * but others are harmed by cache pollution effects.)
+     *
+     * WorkQueues are also used in a similar way for tasks submitted
+     * to the pool. We cannot mix these tasks in the same queues used
+     * for work-stealing (this would contaminate lifo/fifo
+     * processing). Instead, we randomly associate submission queues
+     * with submitting threads, using a form of hashing.  The
+     * ThreadLocal Submitter class contains a value initially used as
+     * a hash code for choosing existing queues, but may be randomly
+     * repositioned upon contention with other submitters.  In
+     * essence, submitters act like workers except that they are
+     * restricted to executing local tasks that they submitted (or in
+     * the case of CountedCompleters, others with the same root task).
+     * However, because most shared/external queue operations are more
+     * expensive than internal, and because, at steady state, external
+     * submitters will compete for CPU with workers, ForkJoinTask.join
+     * and related methods disable them from repeatedly helping to
+     * process tasks if all workers are active.  Insertion of tasks in
+     * shared mode requires a lock (mainly to protect in the case of
+     * resizing) but we use only a simple spinlock (using bits in
+     * field qlock), because submitters encountering a busy queue move
+     * on to try or create other queues -- they block only when
+     * creating and registering new queues.
+     *
+     * Management
+     * ==========
      *
      * The main throughput advantages of work-stealing stem from
      * decentralized control -- workers mostly take tasks from
      * themselves or each other. We cannot negate this in the
      * implementation of other management responsibilities. The main
      * tactic for avoiding bottlenecks is packing nearly all
-     * essentially atomic control state into a single 64bit volatile
-     * variable ("ctl"). This variable is read on the order of 10-100
-     * times as often as it is modified (always via CAS). (There is
-     * some additional control state, for example variable "shutdown"
-     * for which we can cope with uncoordinated updates.)  This
-     * streamlines synchronization and control at the expense of messy
-     * constructions needed to repack status bits upon updates.
-     * Updates tend not to contend with each other except during
-     * bursts while submitted tasks begin or end.  In some cases when
-     * they do contend, threads can instead do something else
-     * (usually, scan for tasks) until contention subsides.
+     * essentially atomic control state into two volatile variables
+     * that are by far most often read (not written) as status and
+     * consistency checks.
      *
-     * To enable packing, we restrict maximum parallelism to (1<<15)-1
-     * (which is far in excess of normal operating range) to allow
-     * ids, counts, and their negations (used for thresholding) to fit
-     * into 16bit fields.
+     * Field "ctl" contains 64 bits holding all the information needed
+     * to atomically decide to add, inactivate, enqueue (on an event
+     * queue), dequeue, and/or re-activate workers.  To enable this
+     * packing, we restrict maximum parallelism to (1<<15)-1 (which is
+     * far in excess of normal operating range) to allow ids, counts,
+     * and their negations (used for thresholding) to fit into 16bit
+     * fields.
+     *
+     * Field "plock" is a form of sequence lock with a saturating
+     * shutdown bit (similarly for per-queue "qlocks"), mainly
+     * protecting updates to the workQueues array, as well as to
+     * enable shutdown.  When used as a lock, it is normally only very
+     * briefly held, so is nearly always available after at most a
+     * brief spin, but we use a monitor-based backup strategy to
+     * block when needed.
      *
-     * Recording Workers.  Workers are recorded in the "workers" array
-     * that is created upon pool construction and expanded if (rarely)
-     * necessary.  This is an array as opposed to some other data
-     * structure to support index-based random steals by workers.
-     * Updates to the array recording new workers and unrecording
-     * terminated ones are protected from each other by a seqLock
-     * (scanGuard) but the array is otherwise concurrently readable,
-     * and accessed directly by workers. To simplify index-based
-     * operations, the array size is always a power of two, and all
-     * readers must tolerate null slots. To avoid flailing during
-     * start-up, the array is presized to hold twice #parallelism
-     * workers (which is unlikely to need further resizing during
-     * execution). But to avoid dealing with so many null slots,
-     * variable scanGuard includes a mask for the nearest power of two
-     * that contains all current workers.  All worker thread creation
-     * is on-demand, triggered by task submissions, replacement of
-     * terminated workers, and/or compensation for blocked
-     * workers. However, all other support code is set up to work with
-     * other policies.  To ensure that we do not hold on to worker
-     * references that would prevent GC, ALL accesses to workers are
-     * via indices into the workers array (which is one source of some
-     * of the messy code constructions here). In essence, the workers
-     * array serves as a weak reference mechanism. Thus for example
-     * the wait queue field of ctl stores worker indices, not worker
-     * references.  Access to the workers in associated methods (for
-     * example signalWork) must both index-check and null-check the
-     * IDs. All such accesses ignore bad IDs by returning out early
-     * from what they are doing, since this can only be associated
-     * with termination, in which case it is OK to give up.
+     * Recording WorkQueues.  WorkQueues are recorded in the
+     * "workQueues" array that is created upon first use and expanded
+     * if necessary.  Updates to the array while recording new workers
+     * and unrecording terminated ones are protected from each other
+     * by a lock but the array is otherwise concurrently readable, and
+     * accessed directly.  To simplify index-based operations, the
+     * array size is always a power of two, and all readers must
+     * tolerate null slots. Worker queues are at odd indices. Shared
+     * (submission) queues are at even indices, up to a maximum of 64
+     * slots, to limit growth even if array needs to expand to add
+     * more workers. Grouping them together in this way simplifies and
+     * speeds up task scanning.
      *
-     * All uses of the workers array, as well as queue arrays, check
-     * that the array is non-null (even if previously non-null). This
-     * allows nulling during termination, which is currently not
-     * necessary, but remains an option for resource-revocation-based
-     * shutdown schemes.
+     * All worker thread creation is on-demand, triggered by task
+     * submissions, replacement of terminated workers, and/or
+     * compensation for blocked workers. However, all other support
+     * code is set up to work with other policies.  To ensure that we
+     * do not hold on to worker references that would prevent GC, ALL
+     * accesses to workQueues are via indices into the workQueues
+     * array (which is one source of some of the messy code
+     * constructions here). In essence, the workQueues array serves as
+     * a weak reference mechanism. Thus for example the wait queue
+     * field of ctl stores indices, not references.  Access to the
+     * workQueues in associated methods (for example signalWork) must
+     * both index-check and null-check the IDs. All such accesses
+     * ignore bad IDs by returning out early from what they are doing,
+     * since this can only be associated with termination, in which
+     * case it is OK to give up.  All uses of the workQueues array
+     * also check that it is non-null (even if previously
+     * non-null). This allows nulling during termination, which is
+     * currently not necessary, but remains an option for
+     * resource-revocation-based shutdown schemes. It also helps
+     * reduce JIT issuance of uncommon-trap code, which tends to
+     * unnecessarily complicate control flow in some methods.
      *
-     * Wait Queuing. Unlike HPC work-stealing frameworks, we cannot
+     * Event Queuing. Unlike HPC work-stealing frameworks, we cannot
      * let workers spin indefinitely scanning for tasks when none can
      * be found immediately, and we cannot start/resume workers unless
      * there appear to be tasks available.  On the other hand, we must
      * quickly prod them into action when new tasks are submitted or
-     * generated.  We park/unpark workers after placing in an event
-     * wait queue when they cannot find work. This "queue" is actually
-     * a simple Treiber stack, headed by the "id" field of ctl, plus a
-     * 15bit counter value to both wake up waiters (by advancing their
-     * count) and avoid ABA effects. Successors are held in worker
-     * field "nextWait".  Queuing deals with several intrinsic races,
-     * mainly that a task-producing thread can miss seeing (and
+     * generated. In many usages, ramp-up time to activate workers is
+     * the main limiting factor in overall performance (this is
+     * compounded at program start-up by JIT compilation and
+     * allocation). So we try to streamline this as much as possible.
+     * We park/unpark workers after placing in an event wait queue
+     * when they cannot find work. This "queue" is actually a simple
+     * Treiber stack, headed by the "id" field of ctl, plus a 15bit
+     * counter value (that reflects the number of times a worker has
+     * been inactivated) to avoid ABA effects (we need only as many
+     * version numbers as worker threads). Successors are held in
+     * field WorkQueue.nextWait.  Queuing deals with several intrinsic
+     * races, mainly that a task-producing thread can miss seeing (and
      * signalling) another thread that gave up looking for work but
      * has not yet entered the wait queue. We solve this by requiring
-     * a full sweep of all workers both before (in scan()) and after
-     * (in tryAwaitWork()) a newly waiting worker is added to the wait
-     * queue. During a rescan, the worker might release some other
-     * queued worker rather than itself, which has the same net
-     * effect. Because enqueued workers may actually be rescanning
-     * rather than waiting, we set and clear the "parked" field of
-     * ForkJoinWorkerThread to reduce unnecessary calls to unpark.
-     * (Use of the parked field requires a secondary recheck to avoid
-     * missed signals.)
+     * a full sweep of all workers (via repeated calls to method
+     * scan()) both before and after a newly waiting worker is added
+     * to the wait queue. During a rescan, the worker might release
+     * some other queued worker rather than itself, which has the same
+     * net effect. Because enqueued workers may actually be rescanning
+     * rather than waiting, we set and clear the "parker" field of
+     * WorkQueues to reduce unnecessary calls to unpark.  (This
+     * requires a secondary recheck to avoid missed signals.)  Note
+     * the unusual conventions about Thread.interrupts surrounding
+     * parking and other blocking: Because interrupts are used solely
+     * to alert threads to check termination, which is checked anyway
+     * upon blocking, we clear status (using Thread.interrupted)
+     * before any call to park, so that park does not immediately
+     * return due to status being set via some other unrelated call to
+     * interrupt in user code.
      *
      * Signalling.  We create or wake up workers only when there
      * appears to be at least one task they might be able to find and
-     * execute.  When a submission is added or another worker adds a
-     * task to a queue that previously had two or fewer tasks, they
-     * signal waiting workers (or trigger creation of new ones if
-     * fewer than the given parallelism level -- see signalWork).
-     * These primary signals are buttressed by signals during rescans
-     * as well as those performed when a worker steals a task and
-     * notices that there are more tasks too; together these cover the
-     * signals needed in cases when more than two tasks are pushed
-     * but untaken.
+     * execute. However, many other threads may notice the same task
+     * and each signal to wake up a thread that might take it. So in
+     * general, pools will be over-signalled.  When a submission is
+     * added or another worker adds a task to a queue that has fewer
+     * than two tasks, they signal waiting workers (or trigger
+     * creation of new ones if fewer than the given parallelism level
+     * -- signalWork), and may leave a hint to the unparked worker to
+     * help signal others upon wakeup).  These primary signals are
+     * buttressed by others (see method helpSignal) whenever other
+     * threads scan for work or do not have a task to process.  On
+     * most platforms, signalling (unpark) overhead time is noticeably
+     * long, and the time between signalling a thread and it actually
+     * making progress can be very noticeably long, so it is worth
+     * offloading these delays from critical paths as much as
+     * possible.
      *
      * Trimming workers. To release resources after periods of lack of
      * use, a worker starting to wait when the pool is quiescent will
-     * time out and terminate if the pool has remained quiescent for
-     * SHRINK_RATE nanosecs. This will slowly propagate, eventually
-     * terminating all workers after long periods of non-use.
-     *
-     * Submissions. External submissions are maintained in an
-     * array-based queue that is structured identically to
-     * ForkJoinWorkerThread queues except for the use of
-     * submissionLock in method addSubmission. Unlike the case for
-     * worker queues, multiple external threads can add new
-     * submissions, so adding requires a lock.
+     * time out and terminate if the pool has remained quiescent for a
+     * given period -- a short period if there are more threads than
+     * parallelism, longer as the number of threads decreases. This
+     * will slowly propagate, eventually terminating all workers after
+     * periods of non-use.
      *
-     * Compensation. Beyond work-stealing support and lifecycle
-     * control, the main responsibility of this framework is to take
-     * actions when one worker is waiting to join a task stolen (or
-     * always held by) another.  Because we are multiplexing many
-     * tasks on to a pool of workers, we can't just let them block (as
-     * in Thread.join).  We also cannot just reassign the joiner's
-     * run-time stack with another and replace it later, which would
-     * be a form of "continuation", that even if possible is not
-     * necessarily a good idea since we sometimes need both an
-     * unblocked task and its continuation to progress. Instead we
-     * combine two tactics:
+     * Shutdown and Termination. A call to shutdownNow atomically sets
+     * a plock bit and then (non-atomically) sets each worker's
+     * qlock status, cancels all unprocessed tasks, and wakes up
+     * all waiting workers.  Detecting whether termination should
+     * commence after a non-abrupt shutdown() call requires more work
+     * and bookkeeping. We need consensus about quiescence (i.e., that
+     * there is no more work). The active count provides a primary
+     * indication but non-abrupt shutdown still requires a rechecking
+     * scan for any workers that are inactive but not queued.
+     *
+     * Joining Tasks
+     * =============
+     *
+     * Any of several actions may be taken when one worker is waiting
+     * to join a task stolen (or always held) by another.  Because we
+     * are multiplexing many tasks on to a pool of workers, we can't
+     * just let them block (as in Thread.join).  We also cannot just
+     * reassign the joiner's run-time stack with another and replace
+     * it later, which would be a form of "continuation", that even if
+     * possible is not necessarily a good idea since we sometimes need
+     * both an unblocked task and its continuation to progress.
+     * Instead we combine two tactics:
      *
      *   Helping: Arranging for the joiner to execute some task that it
-     *      would be running if the steal had not occurred.  Method
-     *      ForkJoinWorkerThread.joinTask tracks joining->stealing
-     *      links to try to find such a task.
+     *      would be running if the steal had not occurred.
      *
      *   Compensating: Unless there are already enough live threads,
-     *      method tryPreBlock() may create or re-activate a spare
-     *      thread to compensate for blocked joiners until they
-     *      unblock.
+     *      method tryCompensate() may create or re-activate a spare
+     *      thread to compensate for blocked joiners until they unblock.
+     *
+     * A third form (implemented in tryRemoveAndExec) amounts to
+     * helping a hypothetical compensator: If we can readily tell that
+     * a possible action of a compensator is to steal and execute the
+     * task being joined, the joining thread can do so directly,
+     * without the need for a compensation thread (although at the
+     * expense of larger run-time stacks, but the tradeoff is
+     * typically worthwhile).
      *
      * The ManagedBlocker extension API can't use helping so relies
      * only on compensation in method awaitBlocker.
      *
+     * The algorithm in tryHelpStealer entails a form of "linear"
+     * helping: Each worker records (in field currentSteal) the most
+     * recent task it stole from some other worker. Plus, it records
+     * (in field currentJoin) the task it is currently actively
+     * joining. Method tryHelpStealer uses these markers to try to
+     * find a worker to help (i.e., steal back a task from and execute
+     * it) that could hasten completion of the actively joined task.
+     * In essence, the joiner executes a task that would be on its own
+     * local deque had the to-be-joined task not been stolen. This may
+     * be seen as a conservative variant of the approach in Wagner &
+     * Calder "Leapfrogging: a portable technique for implementing
+     * efficient futures" SIGPLAN Notices, 1993
+     * (http://portal.acm.org/citation.cfm?id=155354). It differs in
+     * that: (1) We only maintain dependency links across workers upon
+     * steals, rather than use per-task bookkeeping.  This sometimes
+     * requires a linear scan of workQueues array to locate stealers,
+     * but often doesn't because stealers leave hints (that may become
+     * stale/wrong) of where to locate them.  It is only a hint
+     * because a worker might have had multiple steals and the hint
+     * records only one of them (usually the most current).  Hinting
+     * isolates cost to when it is needed, rather than adding to
+     * per-task overhead.  (2) It is "shallow", ignoring nesting and
+     * potentially cyclic mutual steals.  (3) It is intentionally
+     * racy: field currentJoin is updated only while actively joining,
+     * which means that we miss links in the chain during long-lived
+     * tasks, GC stalls etc (which is OK since blocking in such cases
+     * is usually a good idea).  (4) We bound the number of attempts
+     * to find work (see MAX_HELP) and fall back to suspending the
+     * worker and if necessary replacing it with another.
+     *
+     * Helping actions for CountedCompleters are much simpler: Method
+     * helpComplete can take and execute any task with the same root
+     * as the task being waited on. However, this still entails some
+     * traversal of completer chains, so is less efficient than using
+     * CountedCompleters without explicit joins.
+     *
      * It is impossible to keep exactly the target parallelism number
      * of threads running at any given time.  Determining the
      * existence of conservatively safe helping targets, the
      * availability of already-created spares, and the apparent need
-     * to create new spares are all racy and require heuristic
-     * guidance, so we rely on multiple retries of each.  Currently,
-     * in keeping with on-demand signalling policy, we compensate only
-     * if blocking would leave less than one active (non-waiting,
-     * non-blocked) worker. Additionally, to avoid some false alarms
-     * due to GC, lagging counters, system activity, etc, compensated
-     * blocking for joins is only attempted after rechecks stabilize
-     * (retries are interspersed with Thread.yield, for good
-     * citizenship).  The variable blockedCount, incremented before
-     * blocking and decremented after, is sometimes needed to
-     * distinguish cases of waiting for work vs blocking on joins or
-     * other managed sync. Both cases are equivalent for most pool
-     * control, so we can update non-atomically. (Additionally,
-     * contention on blockedCount alleviates some contention on ctl).
+     * to create new spares are all racy, so we rely on multiple
+     * retries of each.  Compensation in the apparent absence of
+     * helping opportunities is challenging to control on JVMs, where
+     * GC and other activities can stall progress of tasks that in
+     * turn stall out many other dependent tasks, without us being
+     * able to determine whether they will ever require compensation.
+     * Even though work-stealing otherwise encounters little
+     * degradation in the presence of more threads than cores,
+     * aggressively adding new threads in such cases entails risk of
+     * unwanted positive feedback control loops in which more threads
+     * cause more dependent stalls (as well as delayed progress of
+     * unblocked threads to the point that we know they are available)
+     * leading to more situations requiring more threads, and so
+     * on. This aspect of control can be seen as an (analytically
+     * intractable) game with an opponent that may choose the worst
+     * (for us) active thread to stall at any time.  We take several
+     * precautions to bound losses (and thus bound gains), mainly in
+     * methods tryCompensate and awaitJoin.
+     *
+     * Common Pool
+     * ===========
      *
-     * Shutdown and Termination. A call to shutdownNow atomically sets
-     * the ctl stop bit and then (non-atomically) sets each workers
-     * "terminate" status, cancels all unprocessed tasks, and wakes up
-     * all waiting workers.  Detecting whether termination should
-     * commence after a non-abrupt shutdown() call requires more work
-     * and bookkeeping. We need consensus about quiesence (i.e., that
-     * there is no more work) which is reflected in active counts so
-     * long as there are no current blockers, as well as possible
-     * re-evaluations during independent changes in blocking or
-     * quiescing workers.
+     * The static commonPool always exists after static
+     * initialization.  Since it (or any other created pool) need
+     * never be used, we minimize initial construction overhead and
+     * footprint to the setup of about a dozen fields, with no nested
+     * allocation. Most bootstrapping occurs within method
+     * fullExternalPush during the first submission to the pool.
      *
-     * Style notes: There is a lot of representation-level coupling
-     * among classes ForkJoinPool, ForkJoinWorkerThread, and
-     * ForkJoinTask.  Most fields of ForkJoinWorkerThread maintain
-     * data structures managed by ForkJoinPool, so are directly
-     * accessed.  Conversely we allow access to "workers" array by
-     * workers, and direct access to ForkJoinTask.status by both
-     * ForkJoinPool and ForkJoinWorkerThread.  There is little point
+     * When external threads submit to the common pool, they can
+     * perform some subtask processing (see externalHelpJoin and
+     * related methods).  We do not need to record whether these
+     * submissions are to the common pool -- if not, externalHelpJoin
+     * returns quickly (at the most helping to signal some common pool
+     * workers). These submitters would otherwise be blocked waiting
+     * for completion, so the extra effort (with liberally sprinkled
+     * task status checks) in inapplicable cases amounts to an odd
+     * form of limited spin-wait before blocking in ForkJoinTask.join.
+     *
+     * Style notes
+     * ===========
+     *
+     * There is a lot of representation-level coupling among classes
+     * ForkJoinPool, ForkJoinWorkerThread, and ForkJoinTask.  The
+     * fields of WorkQueue maintain data structures managed by
+     * ForkJoinPool, so are directly accessed.  There is little point
      * trying to reduce this, since any associated future changes in
      * representations will need to be accompanied by algorithmic
-     * changes anyway. All together, these low-level implementation
-     * choices produce as much as a factor of 4 performance
-     * improvement compared to naive implementations, and enable the
-     * processing of billions of tasks per second, at the expense of
-     * some ugliness.
+     * changes anyway. Several methods intrinsically sprawl because
+     * they must accumulate sets of consistent reads of volatiles held
+     * in local variables.  Methods signalWork() and scan() are the
+     * main bottlenecks, so are especially heavily
+     * micro-optimized/mangled.  There are lots of inline assignments
+     * (of form "while ((local = field) != 0)") which are usually the
+     * simplest way to ensure the required read orderings (which are
+     * sometimes critical). This leads to a "C"-like style of listing
+     * declarations of these locals at the heads of methods or blocks.
+     * There are several occurrences of the unusual "do {} while
+     * (!cas...)"  which is the simplest way to force an update of a
+     * CAS'ed variable. There are also other coding oddities (including
+     * several unnecessary-looking hoisted null checks) that help
+     * some methods perform reasonably even when interpreted (not
+     * compiled).
      *
-     * Methods signalWork() and scan() are the main bottlenecks so are
-     * especially heavily micro-optimized/mangled.  There are lots of
-     * inline assignments (of form "while ((local = field) != 0)")
-     * which are usually the simplest way to ensure the required read
-     * orderings (which are sometimes critical). This leads to a
-     * "C"-like style of listing declarations of these locals at the
-     * heads of methods or blocks.  There are several occurrences of
-     * the unusual "do {} while (!cas...)"  which is the simplest way
-     * to force an update of a CAS'ed variable. There are also other
-     * coding oddities that help some methods perform reasonably even
-     * when interpreted (not compiled).
-     *
-     * The order of declarations in this file is: (1) declarations of
-     * statics (2) fields (along with constants used when unpacking
-     * some of them), listed in an order that tends to reduce
-     * contention among them a bit under most JVMs.  (3) internal
-     * control methods (4) callbacks and other support for
-     * ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
-     * methods (plus a few little helpers). (6) static block
-     * initializing all statics in a minimally dependent order.
+     * The order of declarations in this file is:
+     * (1) Static utility functions
+     * (2) Nested (static) classes
+     * (3) Static fields
+     * (4) Fields, along with constants used when unpacking some of them
+     * (5) Internal control methods
+     * (6) Callbacks and other support for ForkJoinTask methods
+     * (7) Exported methods
+     * (8) Static block initializing statics in minimally dependent order
      */
 
+    // Static utilities
+
+    /**
+     * If there is a security manager, makes sure caller has
+     * permission to modify threads.
+     */
+    private static void checkPermission() {
+        SecurityManager security = System.getSecurityManager();
+        if (security != null)
+            security.checkPermission(modifyThreadPermission);
+    }
+
+    // Nested classes
+
     /**
      * Factory for creating new {@link ForkJoinWorkerThread}s.
      * A {@code ForkJoinWorkerThreadFactory} must be defined and used
@@ -384,14 +556,526 @@
      * Default ForkJoinWorkerThreadFactory implementation; creates a
      * new ForkJoinWorkerThread.
      */
-    static class DefaultForkJoinWorkerThreadFactory
+    static final class DefaultForkJoinWorkerThreadFactory
         implements ForkJoinWorkerThreadFactory {
-        public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
+        public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
             return new ForkJoinWorkerThread(pool);
         }
     }
 
     /**
+     * Per-thread records for threads that submit to pools. Currently
+     * holds only pseudo-random seed / index that is used to choose
+     * submission queues in method externalPush. In the future, this may
+     * also incorporate a means to implement different task rejection
+     * and resubmission policies.
+     *
+     * Seeds for submitters and workers/workQueues work in basically
+     * the same way but are initialized and updated using slightly
+     * different mechanics. Both are initialized using the same
+     * approach as in class ThreadLocal, where successive values are
+     * unlikely to collide with previous values. Seeds are then
+     * randomly modified upon collisions using xorshifts, which
+     * requires a non-zero seed.
+     */
+    static final class Submitter {
+        int seed;
+        Submitter(int s) { seed = s; }
+    }
+
+    /**
+     * Class for artificial tasks that are used to replace the target
+     * of local joins if they are removed from an interior queue slot
+     * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
+     * actually do anything beyond having a unique identity.
+     */
+    static final class EmptyTask extends ForkJoinTask<Void> {
+        private static final long serialVersionUID = -7721805057305804111L;
+        EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
+        public final Void getRawResult() { return null; }
+        public final void setRawResult(Void x) {}
+        public final boolean exec() { return true; }
+    }
+
+    /**
+     * Queues supporting work-stealing as well as external task
+     * submission. See above for main rationale and algorithms.
+     * Implementation relies heavily on "Unsafe" intrinsics
+     * and selective use of "volatile":
+     *
+     * Field "base" is the index (mod array.length) of the least valid
+     * queue slot, which is always the next position to steal (poll)
+     * from if nonempty. Reads and writes require volatile orderings
+     * but not CAS, because updates are only performed after slot
+     * CASes.
+     *
+     * Field "top" is the index (mod array.length) of the next queue
+     * slot to push to or pop from. It is written only by owner thread
+     * for push, or under lock for external/shared push, and accessed
+     * by other threads only after reading (volatile) base.  Both top
+     * and base are allowed to wrap around on overflow, but (top -
+     * base) (or more commonly -(base - top) to force volatile read of
+     * base before top) still estimates size. The lock ("qlock") is
+     * forced to -1 on termination, causing all further lock attempts
+     * to fail. (Note: we don't need CAS for termination state because
+     * upon pool shutdown, all shared-queues will stop being used
+     * anyway.)  Nearly all lock bodies are set up so that exceptions
+     * within lock bodies are "impossible" (modulo JVM errors that
+     * would cause failure anyway.)
+     *
+     * The array slots are read and written using the emulation of
+     * volatiles/atomics provided by Unsafe. Insertions must in
+     * general use putOrderedObject as a form of releasing store to
+     * ensure that all writes to the task object are ordered before
+     * its publication in the queue.  All removals entail a CAS to
+     * null.  The array is always a power of two. To ensure safety of
+     * Unsafe array operations, all accesses perform explicit null
+     * checks and implicit bounds checks via power-of-two masking.
+     *
+     * In addition to basic queuing support, this class contains
+     * fields described elsewhere to control execution. It turns out
+     * to work better memory-layout-wise to include them in this class
+     * rather than a separate class.
+     *
+     * Performance on most platforms is very sensitive to placement of
+     * instances of both WorkQueues and their arrays -- we absolutely
+     * do not want multiple WorkQueue instances or multiple queue
+     * arrays sharing cache lines. (It would be best for queue objects
+     * and their arrays to share, but there is nothing available to
+     * help arrange that).  Unfortunately, because they are recorded
+     * in a common array, WorkQueue instances are often moved to be
+     * adjacent by garbage collectors. To reduce impact, we use field
+     * padding that works OK on common platforms; this effectively
+     * trades off slightly slower average field access for the sake of
+     * avoiding really bad worst-case access. (Until better JVM
+     * support is in place, this padding is dependent on transient
+     * properties of JVM field layout rules.) We also take care in
+     * allocating, sizing and resizing the array. Non-shared queue
+     * arrays are initialized by workers before use. Others are
+     * allocated on first use.
+     */
+    static final class WorkQueue {
+        /**
+         * Capacity of work-stealing queue array upon initialization.
+         * Must be a power of two; at least 4, but should be larger to
+         * reduce or eliminate cacheline sharing among queues.
+         * Currently, it is much larger, as a partial workaround for
+         * the fact that JVMs often place arrays in locations that
+         * share GC bookkeeping (especially cardmarks) such that
+         * per-write accesses encounter serious memory contention.
+         */
+        static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
+
+        /**
+         * Maximum size for queue arrays. Must be a power of two less
+         * than or equal to 1 << (31 - width of array entry) to ensure
+         * lack of wraparound of index calculations, but defined to a
+         * value a bit less than this to help users trap runaway
+         * programs before saturating systems.
+         */
+        static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M
+
+        // Heuristic padding to ameliorate unfortunate memory placements
+        volatile long pad00, pad01, pad02, pad03, pad04, pad05, pad06;
+
+        int seed;                  // for random scanning; initialize nonzero
+        volatile int eventCount;   // encoded inactivation count; < 0 if inactive
+        int nextWait;              // encoded record of next event waiter
+        int hint;                  // steal or signal hint (index)
+        int poolIndex;             // index of this queue in pool (or 0)
+        final int mode;            // 0: lifo, > 0: fifo, < 0: shared
+        int nsteals;               // number of steals
+        volatile int qlock;        // 1: locked, -1: terminate; else 0
+        volatile int base;         // index of next slot for poll
+        int top;                   // index of next slot for push
+        ForkJoinTask<?>[] array;   // the elements (initially unallocated)
+        final ForkJoinPool pool;   // the containing pool (may be null)
+        final ForkJoinWorkerThread owner; // owning thread or null if shared
+        volatile Thread parker;    // == owner during call to park; else null
+        volatile ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
+        ForkJoinTask<?> currentSteal; // current non-local task being executed
+
+        volatile Object pad10, pad11, pad12, pad13, pad14, pad15, pad16, pad17;
+        volatile Object pad18, pad19, pad1a, pad1b, pad1c, pad1d;
+
+        WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode,
+                  int seed) {
+            this.pool = pool;
+            this.owner = owner;
+            this.mode = mode;
+            this.seed = seed;
+            // Place indices in the center of array (that is not yet allocated)
+            base = top = INITIAL_QUEUE_CAPACITY >>> 1;
+        }
+
+        /**
+         * Returns the approximate number of tasks in the queue.
+         */
+        final int queueSize() {
+            int n = base - top;       // non-owner callers must read base first
+            return (n >= 0) ? 0 : -n; // ignore transient negative
+        }
+
+       /**
+         * Provides a more accurate estimate of whether this queue has
+         * any tasks than does queueSize, by checking whether a
+         * near-empty queue has at least one unclaimed task.
+         */
+        final boolean isEmpty() {
+            ForkJoinTask<?>[] a; int m, s;
+            int n = base - (s = top);
+            return (n >= 0 ||
+                    (n == -1 &&
+                     ((a = array) == null ||
+                      (m = a.length - 1) < 0 ||
+                      U.getObject
+                      (a, (long)((m & (s - 1)) << ASHIFT) + ABASE) == null)));
+        }
+
+        /**
+         * Pushes a task. Call only by owner in unshared queues.  (The
+         * shared-queue version is embedded in method externalPush.)
+         *
+         * @param task the task. Caller must ensure non-null.
+         * @throw RejectedExecutionException if array cannot be resized
+         */
+        final void push(ForkJoinTask<?> task) {
+            ForkJoinTask<?>[] a; ForkJoinPool p;
+            int s = top, m, n;
+            if ((a = array) != null) {    // ignore if queue removed
+                int j = (((m = a.length - 1) & s) << ASHIFT) + ABASE;
+                U.putOrderedObject(a, j, task);
+                if ((n = (top = s + 1) - base) <= 2) {
+                    if ((p = pool) != null)
+                        p.signalWork(this);
+                }
+                else if (n >= m)
+                    growArray();
+            }
+        }
+
+       /**
+         * Initializes or doubles the capacity of array. Call either
+         * by owner or with lock held -- it is OK for base, but not
+         * top, to move while resizings are in progress.
+         */
+        final ForkJoinTask<?>[] growArray() {
+            ForkJoinTask<?>[] oldA = array;
+            int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
+            if (size > MAXIMUM_QUEUE_CAPACITY)
+                throw new RejectedExecutionException("Queue capacity exceeded");
+            int oldMask, t, b;
+            ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
+            if (oldA != null && (oldMask = oldA.length - 1) >= 0 &&
+                (t = top) - (b = base) > 0) {
+                int mask = size - 1;
+                do {
+                    ForkJoinTask<?> x;
+                    int oldj = ((b & oldMask) << ASHIFT) + ABASE;
+                    int j    = ((b &    mask) << ASHIFT) + ABASE;
+                    x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj);
+                    if (x != null &&
+                        U.compareAndSwapObject(oldA, oldj, x, null))
+                        U.putObjectVolatile(a, j, x);
+                } while (++b != t);
+            }
+            return a;
+        }
+
+        /**
+         * Takes next task, if one exists, in LIFO order.  Call only
+         * by owner in unshared queues.
+         */
+        final ForkJoinTask<?> pop() {
+            ForkJoinTask<?>[] a; ForkJoinTask<?> t; int m;
+            if ((a = array) != null && (m = a.length - 1) >= 0) {
+                for (int s; (s = top - 1) - base >= 0;) {
+                    long j = ((m & s) << ASHIFT) + ABASE;
+                    if ((t = (ForkJoinTask<?>)U.getObject(a, j)) == null)
+                        break;
+                    if (U.compareAndSwapObject(a, j, t, null)) {
+                        top = s;
+                        return t;
+                    }
+                }
+            }
+            return null;
+        }
+
+        /**
+         * Takes a task in FIFO order if b is base of queue and a task
+         * can be claimed without contention. Specialized versions
+         * appear in ForkJoinPool methods scan and tryHelpStealer.
+         */
+        final ForkJoinTask<?> pollAt(int b) {
+            ForkJoinTask<?> t; ForkJoinTask<?>[] a;
+            if ((a = array) != null) {
+                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
+                if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null &&
+                    base == b &&
+                    U.compareAndSwapObject(a, j, t, null)) {
+                    base = b + 1;
+                    return t;
+                }
+            }
+            return null;
+        }
+
+        /**
+         * Takes next task, if one exists, in FIFO order.
+         */
+        final ForkJoinTask<?> poll() {
+            ForkJoinTask<?>[] a; int b; ForkJoinTask<?> t;
+            while ((b = base) - top < 0 && (a = array) != null) {
+                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
+                t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
+                if (t != null) {
+                    if (base == b &&
+                        U.compareAndSwapObject(a, j, t, null)) {
+                        base = b + 1;
+                        return t;
+                    }
+                }
+                else if (base == b) {
+                    if (b + 1 == top)
+                        break;
+                    Thread.yield(); // wait for lagging update (very rare)
+                }
+            }
+            return null;
+        }
+
+        /**
+         * Takes next task, if one exists, in order specified by mode.
+         */
+        final ForkJoinTask<?> nextLocalTask() {
+            return mode == 0 ? pop() : poll();
+        }
+
+        /**
+         * Returns next task, if one exists, in order specified by mode.
+         */
+        final ForkJoinTask<?> peek() {
+            ForkJoinTask<?>[] a = array; int m;
+            if (a == null || (m = a.length - 1) < 0)
+                return null;
+            int i = mode == 0 ? top - 1 : base;
+            int j = ((i & m) << ASHIFT) + ABASE;
+            return (ForkJoinTask<?>)U.getObjectVolatile(a, j);
+        }
+
+        /**
+         * Pops the given task only if it is at the current top.
+         * (A shared version is available only via FJP.tryExternalUnpush)
+         */
+        final boolean tryUnpush(ForkJoinTask<?> t) {
+            ForkJoinTask<?>[] a; int s;
+            if ((a = array) != null && (s = top) != base &&
+                U.compareAndSwapObject
+                (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
+                top = s;
+                return true;
+            }
+            return false;
+        }
+
+        /**
+         * Removes and cancels all known tasks, ignoring any exceptions.
+         */
+        final void cancelAll() {
+            ForkJoinTask.cancelIgnoringExceptions(currentJoin);
+            ForkJoinTask.cancelIgnoringExceptions(currentSteal);
+            for (ForkJoinTask<?> t; (t = poll()) != null; )
+                ForkJoinTask.cancelIgnoringExceptions(t);
+        }
+
+        /**
+         * Computes next value for random probes.  Scans don't require
+         * a very high quality generator, but also not a crummy one.
+         * Marsaglia xor-shift is cheap and works well enough.  Note:
+         * This is manually inlined in its usages in ForkJoinPool to
+         * avoid writes inside busy scan loops.
+         */
+        final int nextSeed() {
+            int r = seed;
+            r ^= r << 13;
+            r ^= r >>> 17;
+            return seed = r ^= r << 5;
+        }
+
+        // Specialized execution methods
+
+        /**
+         * Pops and runs tasks until empty.
+         */
+        private void popAndExecAll() {
+            // A bit faster than repeated pop calls
+            ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t;
+            while ((a = array) != null && (m = a.length - 1) >= 0 &&
+                   (s = top - 1) - base >= 0 &&
+                   (t = ((ForkJoinTask<?>)
+                         U.getObject(a, j = ((m & s) << ASHIFT) + ABASE)))
+                   != null) {
+                if (U.compareAndSwapObject(a, j, t, null)) {
+                    top = s;
+                    t.doExec();
+                }
+            }
+        }
+
+        /**
+         * Polls and runs tasks until empty.
+         */
+        private void pollAndExecAll() {
+            for (ForkJoinTask<?> t; (t = poll()) != null;)
+                t.doExec();
+        }
+
+        /**
+         * If present, removes from queue and executes the given task,
+         * or any other cancelled task. Returns (true) on any CAS
+         * or consistency check failure so caller can retry.
+         *
+         * @return false if no progress can be made, else true;
+         */
+        final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
+            boolean stat = true, removed = false, empty = true;
+            ForkJoinTask<?>[] a; int m, s, b, n;
+            if ((a = array) != null && (m = a.length - 1) >= 0 &&
+                (n = (s = top) - (b = base)) > 0) {
+                for (ForkJoinTask<?> t;;) {           // traverse from s to b
+                    int j = ((--s & m) << ASHIFT) + ABASE;
+                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
+                    if (t == null)                    // inconsistent length
+                        break;
+                    else if (t == task) {
+                        if (s + 1 == top) {           // pop
+                            if (!U.compareAndSwapObject(a, j, task, null))
+                                break;
+                            top = s;
+                            removed = true;
+                        }
+                        else if (base == b)           // replace with proxy
+                            removed = U.compareAndSwapObject(a, j, task,
+                                                             new EmptyTask());
+                        break;
+                    }
+                    else if (t.status >= 0)
+                        empty = false;
+                    else if (s + 1 == top) {          // pop and throw away
+                        if (U.compareAndSwapObject(a, j, t, null))
+                            top = s;
+                        break;
+                    }
+                    if (--n == 0) {
+                        if (!empty && base == b)
+                            stat = false;
+                        break;
+                    }
+                }
+            }
+            if (removed)
+                task.doExec();
+            return stat;
+        }
+
+        /**
+         * Polls for and executes the given task or any other task in
+         * its CountedCompleter computation
+         */
+        final boolean pollAndExecCC(ForkJoinTask<?> root) {
+            ForkJoinTask<?>[] a; int b; Object o;
+            outer: while ((b = base) - top < 0 && (a = array) != null) {
+                long j = (((a.length - 1) & b) << ASHIFT) + ABASE;
+                if ((o = U.getObject(a, j)) == null ||
+                    !(o instanceof CountedCompleter))
+                    break;
+                for (CountedCompleter<?> t = (CountedCompleter<?>)o, r = t;;) {
+                    if (r == root) {
+                        if (base == b &&
+                            U.compareAndSwapObject(a, j, t, null)) {
+                            base = b + 1;
+                            t.doExec();
+                            return true;
+                        }
+                        else
+                            break; // restart
+                    }
+                    if ((r = r.completer) == null)
+                        break outer; // not part of root computation
+                }
+            }
+            return false;
+        }
+
+        /**
+         * Executes a top-level task and any local tasks remaining
+         * after execution.
+         */
+        final void runTask(ForkJoinTask<?> t) {
+            if (t != null) {
+                (currentSteal = t).doExec();
+                currentSteal = null;
+                ++nsteals;
+                if (base - top < 0) {       // process remaining local tasks
+                    if (mode == 0)
+                        popAndExecAll();
+                    else
+                        pollAndExecAll();
+                }
+            }
+        }
+
+        /**
+         * Executes a non-top-level (stolen) task.
+         */
+        final void runSubtask(ForkJoinTask<?> t) {
+            if (t != null) {
+                ForkJoinTask<?> ps = currentSteal;
+                (currentSteal = t).doExec();
+                currentSteal = ps;
+            }
+        }
+
+        /**
+         * Returns true if owned and not known to be blocked.
+         */
+        final boolean isApparentlyUnblocked() {
+            Thread wt; Thread.State s;
+            return (eventCount >= 0 &&
+                    (wt = owner) != null &&
+                    (s = wt.getState()) != Thread.State.BLOCKED &&
+                    s != Thread.State.WAITING &&
+                    s != Thread.State.TIMED_WAITING);
+        }
+
+        // Unsafe mechanics
+        private static final sun.misc.Unsafe U;
+        private static final long QLOCK;
+        private static final int ABASE;
+        private static final int ASHIFT;
+        static {
+            int s;
+            try {
+                U = sun.misc.Unsafe.getUnsafe();
+                Class<?> k = WorkQueue.class;
+                Class<?> ak = ForkJoinTask[].class;
+                QLOCK = U.objectFieldOffset
+                    (k.getDeclaredField("qlock"));
+                ABASE = U.arrayBaseOffset(ak);
+                s = U.arrayIndexScale(ak);
+            } catch (Exception e) {
+                throw new Error(e);
+            }
+            if ((s & (s-1)) != 0)
+                throw new Error("data type scale not a power of two");
+            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
+        }
+    }
+
+    // static fields (initialized in static initializer below)
+
+    /**
      * Creates a new ForkJoinWorkerThread. This factory is used unless
      * overridden in ForkJoinPool constructors.
      */
@@ -399,107 +1083,93 @@
         defaultForkJoinWorkerThreadFactory;
 
     /**
+     * Per-thread submission bookkeeping. Shared across all pools
+     * to reduce ThreadLocal pollution and because random motion
+     * to avoid contention in one pool is likely to hold for others.
+     * Lazily initialized on first submission (but null-checked
+     * in other contexts to avoid unnecessary initialization).
+     */
+    static final ThreadLocal<Submitter> submitters;
+
+    /**
      * Permission required for callers of methods that may start or
      * kill threads.
      */
     private static final RuntimePermission modifyThreadPermission;
 
     /**
-     * If there is a security manager, makes sure caller has
-     * permission to modify threads.
+     * Common (static) pool. Non-null for public use unless a static
+     * construction exception, but internal usages null-check on use
+     * to paranoically avoid potential initialization circularities
+     * as well as to simplify generated code.
      */
-    private static void checkPermission() {
-        SecurityManager security = System.getSecurityManager();
-        if (security != null)
-            security.checkPermission(modifyThreadPermission);
-    }
+    static final ForkJoinPool commonPool;
 
     /**
-     * Generator for assigning sequence numbers as pool names.
+     * Common pool parallelism. Must equal commonPool.parallelism.
      */
-    private static final AtomicInteger poolNumberGenerator;
+    static final int commonPoolParallelism;
 
     /**
-     * Generator for initial random seeds for worker victim
-     * selection. This is used only to create initial seeds. Random
-     * steals use a cheaper xorshift generator per steal attempt. We
-     * don't expect much contention on seedGenerator, so just use a
-     * plain Random.
+     * Sequence number for creating workerNamePrefix.
      */
-    static final Random workerSeedGenerator;
+    private static int poolNumberSequence;
 
     /**
-     * Array holding all worker threads in the pool.  Initialized upon
-     * construction. Array size must be a power of two.  Updates and
-     * replacements are protected by scanGuard, but the array is
-     * always kept in a consistent enough state to be randomly
-     * accessed without locking by workers performing work-stealing,
-     * as well as other traversal-based methods in this class, so long
-     * as reads memory-acquire by first reading ctl. All readers must
-     * tolerate that some array slots may be null.
+     * Return the next sequence number. We don't expect this to
+     * ever contend so use simple builtin sync.
      */
-    ForkJoinWorkerThread[] workers;
+    private static final synchronized int nextPoolId() {
+        return ++poolNumberSequence;
+    }
 
-    /**
-     * Initial size for submission queue array. Must be a power of
-     * two.  In many applications, these always stay small so we use a
-     * small initial cap.
-     */
-    private static final int INITIAL_QUEUE_CAPACITY = 8;
+    // static constants
 
     /**
-     * Maximum size for submission queue array. Must be a power of two
-     * less than or equal to 1 << (31 - width of array entry) to
-     * ensure lack of index wraparound, but is capped at a lower
-     * value to help users trap runaway computations.
+     * Initial timeout value (in nanoseconds) for the thread
+     * triggering quiescence to park waiting for new work. On timeout,
+     * the thread will instead try to shrink the number of
+     * workers. The value should be large enough to avoid overly
+     * aggressive shrinkage during most transient stalls (long GCs
+     * etc).
      */
-    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 24; // 16M
+    private static final long IDLE_TIMEOUT      = 2000L * 1000L * 1000L; // 2sec
 
     /**
-     * Array serving as submission queue. Initialized upon construction.
+     * Timeout value when there are more threads than parallelism level
      */
-    private ForkJoinTask<?>[] submissionQueue;
+    private static final long FAST_IDLE_TIMEOUT =  200L * 1000L * 1000L;
 
     /**
-     * Lock protecting submissions array for addSubmission
+     * Tolerance for idle timeouts, to cope with timer undershoots
      */
-    private final ReentrantLock submissionLock;
-
-    /**
-     * Condition for awaitTermination, using submissionLock for
-     * convenience.
-     */
-    private final Condition termination;
+    private static final long TIMEOUT_SLOP = 2000000L;
 
     /**
-     * Creation factory for worker threads.
+     * The maximum stolen->joining link depth allowed in method
+     * tryHelpStealer.  Must be a power of two.  Depths for legitimate
+     * chains are unbounded, but we use a fixed constant to avoid
+     * (otherwise unchecked) cycles and to bound staleness of
+     * traversal parameters at the expense of sometimes blocking when
+     * we could be helping.
      */
-    private final ForkJoinWorkerThreadFactory factory;
-
-    /**
-     * The uncaught exception handler used when any worker abruptly
-     * terminates.
-     */
-    final Thread.UncaughtExceptionHandler ueh;
+    private static final int MAX_HELP = 64;
 
     /**
-     * Prefix for assigning names to worker threads
+     * Increment for seed generators. See class ThreadLocal for
+     * explanation.
      */
-    private final String workerNamePrefix;
+    private static final int SEED_INCREMENT = 0x61c88647;
 
     /**
-     * Sum of per-thread steal counts, updated only when threads are
-     * idle or terminating.
-     */
-    private volatile long stealCount;
-
-    /**
-     * Main pool control -- a long packed with:
+     * Bits and masks for control variables
+     *
+     * Field ctl is a long packed with:
      * AC: Number of active running workers minus target parallelism (16 bits)
-     * TC: Number of total workers minus target parallelism (16bits)
+     * TC: Number of total workers minus target parallelism (16 bits)
      * ST: true if pool is terminating (1 bit)
      * EC: the wait count of top waiting thread (15 bits)
-     * ID: ~poolIndex of top of Treiber stack of waiting threads (16 bits)
+     * ID: poolIndex of top of Treiber stack of waiters (16 bits)
      *
      * When convenient, we can extract the upper 32 bits of counts and
      * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
@@ -508,13 +1178,26 @@
      * parallelism and the positionings of fields makes it possible to
      * perform the most common checks via sign tests of fields: When
      * ac is negative, there are not enough active workers, when tc is
-     * negative, there are not enough total workers, when id is
-     * negative, there is at least one waiting worker, and when e is
+     * negative, there are not enough total workers, and when e is
      * negative, the pool is terminating.  To deal with these possibly
      * negative fields, we use casts in and out of "short" and/or
      * signed shifts to maintain signedness.
+     *
+     * When a thread is queued (inactivated), its eventCount field is
+     * set negative, which is the only way to tell if a worker is
+     * prevented from executing tasks, even though it must continue to
+     * scan for them to avoid queuing races. Note however that
+     * eventCount updates lag releases so usage requires care.
+     *
+     * Field plock is an int packed with:
+     * SHUTDOWN: true if shutdown is enabled (1 bit)
+     * SEQ:  a sequence lock, with PL_LOCK bit set if locked (30 bits)
+     * SIGNAL: set when threads may be waiting on the lock (1 bit)
+     *
+     * The sequence number enables simple consistency checks:
+     * Staleness of read-only operations on the workQueues array can
+     * be checked by comparing plock before vs after the reads.
      */
-    volatile long ctl;
 
     // bit positions/shifts for fields
     private static final int  AC_SHIFT   = 48;
@@ -523,8 +1206,10 @@
     private static final int  EC_SHIFT   = 16;
 
     // bounds
-    private static final int  MAX_ID     = 0x7fff;  // max poolIndex
-    private static final int  SMASK      = 0xffff;  // mask short bits
+    private static final int  SMASK      = 0xffff;  // short bits
+    private static final int  MAX_CAP    = 0x7fff;  // max #workers - 1
+    private static final int  EVENMASK   = 0xfffe;  // even short bits
+    private static final int  SQMASK     = 0x007e;  // max 64 (even) slots
     private static final int  SHORT_SIGN = 1 << 15;
     private static final int  INT_SIGN   = 1 << 31;
 
@@ -546,649 +1231,648 @@
     private static final int  UTC_UNIT   = 1 << UTC_SHIFT;
 
     // masks and units for dealing with e = (int)ctl
-    private static final int  E_MASK     = 0x7fffffff; // no STOP_BIT
-    private static final int  EC_UNIT    = 1 << EC_SHIFT;
-
-    /**
-     * The target parallelism level.
-     */
-    final int parallelism;
+    private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
+    private static final int E_SEQ       = 1 << EC_SHIFT;
 
-    /**
-     * Index (mod submission queue length) of next element to take
-     * from submission queue. Usage is identical to that for
-     * per-worker queues -- see ForkJoinWorkerThread internal
-     * documentation.
-     */
-    volatile int queueBase;
-
-    /**
-     * Index (mod submission queue length) of next element to add
-     * in submission queue. Usage is identical to that for
-     * per-worker queues -- see ForkJoinWorkerThread internal
-     * documentation.
-     */
-    int queueTop;
+    // plock bits
+    private static final int SHUTDOWN    = 1 << 31;
+    private static final int PL_LOCK     = 2;
+    private static final int PL_SIGNAL   = 1;
+    private static final int PL_SPINS    = 1 << 8;
 
-    /**
-     * True when shutdown() has been called.
-     */
-    volatile boolean shutdown;
-
-    /**
-     * True if use local fifo, not default lifo, for local polling
-     * Read by, and replicated by ForkJoinWorkerThreads
-     */
-    final boolean locallyFifo;
+    // access mode for WorkQueue
+    static final int LIFO_QUEUE          =  0;
+    static final int FIFO_QUEUE          =  1;
+    static final int SHARED_QUEUE        = -1;
 
-    /**
-     * The number of threads in ForkJoinWorkerThreads.helpQuiescePool.
-     * When non-zero, suppresses automatic shutdown when active
-     * counts become zero.
-     */
-    volatile int quiescerCount;
+    // bounds for #steps in scan loop -- must be power 2 minus 1
+    private static final int MIN_SCAN    = 0x1ff;   // cover estimation slop
+    private static final int MAX_SCAN    = 0x1ffff; // 4 * max workers
+
+    // Instance fields
 
-    /**
-     * The number of threads blocked in join.
-     */
-    volatile int blockedCount;
-
-    /**
-     * Counter for worker Thread names (unrelated to their poolIndex)
+    /*
+     * Field layout of this class tends to matter more than one would
+     * like. Runtime layout order is only loosely related to
+     * declaration order and may differ across JVMs, but the following
+     * empirically works OK on current JVMs.
      */
-    private volatile int nextWorkerNumber;
 
-    /**
-     * The index for the next created worker. Accessed under scanGuard.
-     */
-    private int nextWorkerIndex;
+    // Heuristic padding to ameliorate unfortunate memory placements
+    volatile long pad00, pad01, pad02, pad03, pad04, pad05, pad06;
 
-    /**
-     * SeqLock and index masking for updates to workers array.  Locked
-     * when SG_UNIT is set. Unlocking clears bit by adding
-     * SG_UNIT. Staleness of read-only operations can be checked by
-     * comparing scanGuard to value before the reads. The low 16 bits
-     * (i.e, anding with SMASK) hold (the smallest power of two
-     * covering all worker indices, minus one, and is used to avoid
-     * dealing with large numbers of null slots when the workers array
-     * is overallocated.
-     */
-    volatile int scanGuard;
+    volatile long stealCount;                  // collects worker counts
+    volatile long ctl;                         // main pool control
+    volatile int plock;                        // shutdown status and seqLock
+    volatile int indexSeed;                    // worker/submitter index seed
+    final int config;                          // mode and parallelism level
+    WorkQueue[] workQueues;                    // main registry
+    final ForkJoinWorkerThreadFactory factory;
+    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
+    final String workerNamePrefix;             // to create worker name string
 
-    private static final int SG_UNIT = 1 << 16;
+    volatile Object pad10, pad11, pad12, pad13, pad14, pad15, pad16, pad17;
+    volatile Object pad18, pad19, pad1a, pad1b;
 
-    /**
-     * The wakeup interval (in nanoseconds) for a worker waiting for a
-     * task when the pool is quiescent to instead try to shrink the
-     * number of workers.  The exact value does not matter too
-     * much. It must be short enough to release resources during
-     * sustained periods of idleness, but not so short that threads
-     * are continually re-created.
+    /*
+     * Acquires the plock lock to protect worker array and related
+     * updates. This method is called only if an initial CAS on plock
+     * fails. This acts as a spinLock for normal cases, but falls back
+     * to builtin monitor to block when (rarely) needed. This would be
+     * a terrible idea for a highly contended lock, but works fine as
+     * a more conservative alternative to a pure spinlock.
      */
-    private static final long SHRINK_RATE =
-        4L * 1000L * 1000L * 1000L; // 4 seconds
-
-    /**
-     * Top-level loop for worker threads: On each step: if the
-     * previous step swept through all queues and found no tasks, or
-     * there are excess threads, then possibly blocks. Otherwise,
-     * scans for and, if found, executes a task. Returns when pool
-     * and/or worker terminate.
-     *
-     * @param w the worker
-     */
-    final void work(ForkJoinWorkerThread w) {
-        boolean swept = false;                // true on empty scans
-        long c;
-        while (!w.terminate && (int)(c = ctl) >= 0) {
-            int a;                            // active count
-            if (!swept && (a = (int)(c >> AC_SHIFT)) <= 0)
-                swept = scan(w, a);
-            else if (tryAwaitWork(w, c))
-                swept = false;
+    private int acquirePlock() {
+        int spins = PL_SPINS, r = 0, ps, nps;
+        for (;;) {
+            if (((ps = plock) & PL_LOCK) == 0 &&
+                U.compareAndSwapInt(this, PLOCK, ps, nps = ps + PL_LOCK))
+                return nps;
+            else if (r == 0) { // randomize spins if possible
+                Thread t = Thread.currentThread(); WorkQueue w; Submitter z;
+                if ((t instanceof ForkJoinWorkerThread) &&
+                    (w = ((ForkJoinWorkerThread)t).workQueue) != null)
+                    r = w.seed;
+                else if ((z = submitters.get()) != null)
+                    r = z.seed;
+                else
+                    r = 1;
+            }
+            else if (spins >= 0) {
+                r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
+                if (r >= 0)
+                    --spins;
+            }
+            else if (U.compareAndSwapInt(this, PLOCK, ps, ps | PL_SIGNAL)) {
+                synchronized (this) {
+                    if ((plock & PL_SIGNAL) != 0) {
+                        try {
+                            wait();
+                        } catch (InterruptedException ie) {
+                            try {
+                                Thread.currentThread().interrupt();
+                            } catch (SecurityException ignore) {
+                            }
+                        }
+                    }
+                    else
+                        notifyAll();
+                }
+            }
         }
     }
 
-    // Signalling
+    /**
+     * Unlocks and signals any thread waiting for plock. Called only
+     * when CAS of seq value for unlock fails.
+     */
+    private void releasePlock(int ps) {
+        plock = ps;
+        synchronized (this) { notifyAll(); }
+    }
 
     /**
-     * Wakes up or creates a worker.
+     * Performs secondary initialization, called when plock is zero.
+     * Creates workQueue array and sets plock to a valid value.  The
+     * lock body must be exception-free (so no try/finally) so we
+     * optimistically allocate new array outside the lock and throw
+     * away if (very rarely) not needed. (A similar tactic is used in
+     * fullExternalPush.)  Because the plock seq value can eventually
+     * wrap around zero, this method harmlessly fails to reinitialize
+     * if workQueues exists, while still advancing plock.
+     *
+     * Additionally tries to create the first worker.
      */
-    final void signalWork() {
-        /*
-         * The while condition is true if: (there is are too few total
-         * workers OR there is at least one waiter) AND (there are too
-         * few active workers OR the pool is terminating).  The value
-         * of e distinguishes the remaining cases: zero (no waiters)
-         * for create, negative if terminating (in which case do
-         * nothing), else release a waiter. The secondary checks for
-         * release (non-null array etc) can fail if the pool begins
-         * terminating after the test, and don't impose any added cost
-         * because JVMs must perform null and bounds checks anyway.
-         */
-        long c; int e, u;
-        while ((((e = (int)(c = ctl)) | (u = (int)(c >>> 32))) &
-                (INT_SIGN|SHORT_SIGN)) == (INT_SIGN|SHORT_SIGN) && e >= 0) {
-            if (e > 0) {                         // release a waiting worker
-                int i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws;
-                if ((ws = workers) == null ||
-                    (i = ~e & SMASK) >= ws.length ||
-                    (w = ws[i]) == null)
-                    break;
-                long nc = (((long)(w.nextWait & E_MASK)) |
-                           ((long)(u + UAC_UNIT) << 32));
-                if (w.eventCount == e &&
-                    UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
-                    w.eventCount = (e + EC_UNIT) & E_MASK;
-                    if (w.parked)
-                        UNSAFE.unpark(w);
-                    break;
+    private void initWorkers() {
+        WorkQueue[] ws, nws; int ps;
+        int p = config & SMASK;        // find power of two table size
+        int n = (p > 1) ? p - 1 : 1;   // ensure at least 2 slots
+        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
+        n = (n + 1) << 1;
+        if ((ws = workQueues) == null || ws.length == 0)
+            nws = new WorkQueue[n];
+        else
+            nws = null;
+        if (((ps = plock) & PL_LOCK) != 0 ||
+            !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
+            ps = acquirePlock();
+        if (((ws = workQueues) == null || ws.length == 0) && nws != null)
+            workQueues = nws;
+        int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
+        if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
+            releasePlock(nps);
+        tryAddWorker();
+    }
+
+    /**
+     * Tries to create and start one worker if fewer than target
+     * parallelism level exist. Adjusts counts etc on failure.
+     */
+    private void tryAddWorker() {
+        long c; int u;
+        while ((u = (int)((c = ctl) >>> 32)) < 0 &&
+               (u & SHORT_SIGN) != 0 && (int)c == 0) {
+            long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
+                             ((u + UAC_UNIT) & UAC_MASK)) << 32;
+            if (U.compareAndSwapLong(this, CTL, c, nc)) {
+                ForkJoinWorkerThreadFactory fac;
+                Throwable ex = null;
+                ForkJoinWorkerThread wt = null;
+                try {
+                    if ((fac = factory) != null &&
+                        (wt = fac.newThread(this)) != null) {
+                        wt.start();
+                        break;
+                    }
+                } catch (Throwable e) {
+                    ex = e;
                 }
-            }
-            else if (UNSAFE.compareAndSwapLong
-                     (this, ctlOffset, c,
-                      (long)(((u + UTC_UNIT) & UTC_MASK) |
-                             ((u + UAC_UNIT) & UAC_MASK)) << 32)) {
-                addWorker();
+                deregisterWorker(wt, ex);
                 break;
             }
         }
     }
 
+    //  Registering and deregistering workers
+
     /**
-     * Variant of signalWork to help release waiters on rescans.
-     * Tries once to release a waiter if active count < 0.
+     * Callback from ForkJoinWorkerThread to establish and record its
+     * WorkQueue. To avoid scanning bias due to packing entries in
+     * front of the workQueues array, we treat the array as a simple
+     * power-of-two hash table using per-thread seed as hash,
+     * expanding as needed.
+     *
+     * @param wt the worker thread
+     * @return the worker's queue
+     */
+    final WorkQueue registerWorker(ForkJoinWorkerThread wt) {
+        Thread.UncaughtExceptionHandler handler; WorkQueue[] ws; int s, ps;
+        wt.setDaemon(true);
+        if ((handler = ueh) != null)
+            wt.setUncaughtExceptionHandler(handler);
+        do {} while (!U.compareAndSwapInt(this, INDEXSEED, s = indexSeed,
+                                          s += SEED_INCREMENT) ||
+                     s == 0); // skip 0
+        WorkQueue w = new WorkQueue(this, wt, config >>> 16, s);
+        if (((ps = plock) & PL_LOCK) != 0 ||
+            !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
+            ps = acquirePlock();
+        int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
+        try {
+            if ((ws = workQueues) != null) {    // skip if shutting down
+                int n = ws.length, m = n - 1;
+                int r = (s << 1) | 1;           // use odd-numbered indices
+                if (ws[r &= m] != null) {       // collision
+                    int probes = 0;             // step by approx half size
+                    int step = (n <= 4) ? 2 : ((n >>> 1) & EVENMASK) + 2;
+                    while (ws[r = (r + step) & m] != null) {
+                        if (++probes >= n) {
+                            workQueues = ws = Arrays.copyOf(ws, n <<= 1);
+                            m = n - 1;
+                            probes = 0;
+                        }
+                    }
+                }
+                w.eventCount = w.poolIndex = r; // volatile write orders
+                ws[r] = w;
+            }
+        } finally {
+            if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
+                releasePlock(nps);
+        }
+        wt.setName(workerNamePrefix.concat(Integer.toString(w.poolIndex)));
+        return w;
+    }
+
+    /**
+     * Final callback from terminating worker, as well as upon failure
+     * to construct or start a worker.  Removes record of worker from
+     * array, and adjusts counts. If pool is shutting down, tries to
+     * complete termination.
      *
-     * @return false if failed due to contention, else true
+     * @param wt the worker thread or null if construction failed
+     * @param ex the exception causing failure, or null if none
+     */
+    final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
+        WorkQueue w = null;
+        if (wt != null && (w = wt.workQueue) != null) {
+            int ps;
+            w.qlock = -1;                // ensure set
+            long ns = w.nsteals, sc;     // collect steal count
+            do {} while (!U.compareAndSwapLong(this, STEALCOUNT,
+                                               sc = stealCount, sc + ns));
+            if (((ps = plock) & PL_LOCK) != 0 ||
+                !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
+                ps = acquirePlock();
+            int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
+            try {
+                int idx = w.poolIndex;
+                WorkQueue[] ws = workQueues;
+                if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
+                    ws[idx] = null;
+            } finally {
+                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
+                    releasePlock(nps);
+            }
+        }
+
+        long c;                          // adjust ctl counts
+        do {} while (!U.compareAndSwapLong
+                     (this, CTL, c = ctl, (((c - AC_UNIT) & AC_MASK) |
+                                           ((c - TC_UNIT) & TC_MASK) |
+                                           (c & ~(AC_MASK|TC_MASK)))));
+
+        if (!tryTerminate(false, false) && w != null && w.array != null) {
+            w.cancelAll();               // cancel remaining tasks
+            WorkQueue[] ws; WorkQueue v; Thread p; int u, i, e;
+            while ((u = (int)((c = ctl) >>> 32)) < 0 && (e = (int)c) >= 0) {
+                if (e > 0) {             // activate or create replacement
+                    if ((ws = workQueues) == null ||
+                        (i = e & SMASK) >= ws.length ||
+                        (v = ws[i]) != null)
+                        break;
+                    long nc = (((long)(v.nextWait & E_MASK)) |
+                               ((long)(u + UAC_UNIT) << 32));
+                    if (v.eventCount != (e | INT_SIGN))
+                        break;
+                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
+                        v.eventCount = (e + E_SEQ) & E_MASK;
+                        if ((p = v.parker) != null)
+                            U.unpark(p);
+                        break;
+                    }
+                }
+                else {
+                    if ((short)u < 0)
+                        tryAddWorker();
+                    break;
+                }
+            }
+        }
+        if (ex == null)                     // help clean refs on way out
+            ForkJoinTask.helpExpungeStaleExceptions();
+        else                                // rethrow
+            ForkJoinTask.rethrow(ex);
+    }
+
+    // Submissions
+
+    /**
+     * Unless shutting down, adds the given task to a submission queue
+     * at submitter's current queue index (modulo submission
+     * range). Only the most common path is directly handled in this
+     * method. All others are relayed to fullExternalPush.
+     *
+     * @param task the task. Caller must ensure non-null.
      */
-    private boolean tryReleaseWaiter() {
-        long c; int e, i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws;
-        if ((e = (int)(c = ctl)) > 0 &&
-            (int)(c >> AC_SHIFT) < 0 &&
-            (ws = workers) != null &&
-            (i = ~e & SMASK) < ws.length &&
-            (w = ws[i]) != null) {
-            long nc = ((long)(w.nextWait & E_MASK) |
-                       ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
-            if (w.eventCount != e ||
-                !UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc))
-                return false;
-            w.eventCount = (e + EC_UNIT) & E_MASK;
-            if (w.parked)
-                UNSAFE.unpark(w);
+    final void externalPush(ForkJoinTask<?> task) {
+        WorkQueue[] ws; WorkQueue q; Submitter z; int m; ForkJoinTask<?>[] a;
+        if ((z = submitters.get()) != null && plock > 0 &&
+            (ws = workQueues) != null && (m = (ws.length - 1)) >= 0 &&
+            (q = ws[m & z.seed & SQMASK]) != null &&
+            U.compareAndSwapInt(q, QLOCK, 0, 1)) { // lock
+            int b = q.base, s = q.top, n, an;
+            if ((a = q.array) != null && (an = a.length) > (n = s + 1 - b)) {
+                int j = (((an - 1) & s) << ASHIFT) + ABASE;
+                U.putOrderedObject(a, j, task);
+                q.top = s + 1;                     // push on to deque
+                q.qlock = 0;
+                if (n <= 2)
+                    signalWork(q);
+                return;
+            }
+            q.qlock = 0;
         }
-        return true;
+        fullExternalPush(task);
+    }
+
+    /**
+     * Full version of externalPush. This method is called, among
+     * other times, upon the first submission of the first task to the
+     * pool, so must perform secondary initialization (via
+     * initWorkers). It also detects first submission by an external
+     * thread by looking up its ThreadLocal, and creates a new shared
+     * queue if the one at index if empty or contended. The plock lock
+     * body must be exception-free (so no try/finally) so we
+     * optimistically allocate new queues outside the lock and throw
+     * them away if (very rarely) not needed.
+     */
+    private void fullExternalPush(ForkJoinTask<?> task) {
+        int r = 0; // random index seed
+        for (Submitter z = submitters.get();;) {
+            WorkQueue[] ws; WorkQueue q; int ps, m, k;
+            if (z == null) {
+                if (U.compareAndSwapInt(this, INDEXSEED, r = indexSeed,
+                                        r += SEED_INCREMENT) && r != 0)
+                    submitters.set(z = new Submitter(r));
+            }
+            else if (r == 0) {               // move to a different index
+                r = z.seed;
+                r ^= r << 13;                // same xorshift as WorkQueues
+                r ^= r >>> 17;
+                z.seed = r ^ (r << 5);
+            }
+            else if ((ps = plock) < 0)
+                throw new RejectedExecutionException();
+            else if (ps == 0 || (ws = workQueues) == null ||
+                     (m = ws.length - 1) < 0)
+                initWorkers();
+            else if ((q = ws[k = r & m & SQMASK]) != null) {
+                if (q.qlock == 0 && U.compareAndSwapInt(q, QLOCK, 0, 1)) {
+                    ForkJoinTask<?>[] a = q.array;
+                    int s = q.top;
+                    boolean submitted = false;
+                    try {                      // locked version of push
+                        if ((a != null && a.length > s + 1 - q.base) ||
+                            (a = q.growArray()) != null) {   // must presize
+                            int j = (((a.length - 1) & s) << ASHIFT) + ABASE;
+                            U.putOrderedObject(a, j, task);
+                            q.top = s + 1;
+                            submitted = true;
+                        }
+                    } finally {
+                        q.qlock = 0;  // unlock
+                    }
+                    if (submitted) {
+                        signalWork(q);
+                        return;
+                    }
+                }
+                r = 0; // move on failure
+            }
+            else if (((ps = plock) & PL_LOCK) == 0) { // create new queue
+                q = new WorkQueue(this, null, SHARED_QUEUE, r);
+                if (((ps = plock) & PL_LOCK) != 0 ||
+                    !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
+                    ps = acquirePlock();
+                if ((ws = workQueues) != null && k < ws.length && ws[k] == null)
+                    ws[k] = q;
+                int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
+                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
+                    releasePlock(nps);
+            }
+            else
+                r = 0; // try elsewhere while lock held
+        }
+    }
+
+    // Maintaining ctl counts
+
+    /**
+     * Increments active count; mainly called upon return from blocking.
+     */
+    final void incrementActiveCount() {
+        long c;
+        do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT));
+    }
+
+    /**
+     * Tries to create or activate a worker if too few are active.
+     *
+     * @param q the (non-null) queue holding tasks to be signalled
+     */
+    final void signalWork(WorkQueue q) {
+        int hint = q.poolIndex;
+        long c; int e, u, i, n; WorkQueue[] ws; WorkQueue w; Thread p;
+        while ((u = (int)((c = ctl) >>> 32)) < 0) {
+            if ((e = (int)c) > 0) {
+                if ((ws = workQueues) != null && ws.length > (i = e & SMASK) &&
+                    (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
+                    long nc = (((long)(w.nextWait & E_MASK)) |
+                               ((long)(u + UAC_UNIT) << 32));
+                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
+                        w.hint = hint;
+                        w.eventCount = (e + E_SEQ) & E_MASK;
+                        if ((p = w.parker) != null)
+                            U.unpark(p);
+                        break;
+                    }
+                    if (q.top - q.base <= 0)
+                        break;
+                }
+                else
+                    break;
+            }
+            else {
+                if ((short)u < 0)
+                    tryAddWorker();
+                break;
+            }
+        }
     }
 
     // Scanning for tasks
 
     /**
-     * Scans for and, if found, executes one task. Scans start at a
-     * random index of workers array, and randomly select the first
-     * (2*#workers)-1 probes, and then, if all empty, resort to 2
-     * circular sweeps, which is necessary to check quiescence. and
-     * taking a submission only if no stealable tasks were found.  The
-     * steal code inside the loop is a specialized form of
-     * ForkJoinWorkerThread.deqTask, followed bookkeeping to support
-     * helpJoinTask and signal propagation. The code for submission
-     * queues is almost identical. On each steal, the worker completes
-     * not only the task, but also all local tasks that this task may
-     * have generated. On detecting staleness or contention when
-     * trying to take a task, this method returns without finishing
-     * sweep, which allows global state rechecks before retry.
-     *
-     * @param w the worker
-     * @param a the number of active workers
-     * @return true if swept all queues without finding a task
+     * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
      */
-    private boolean scan(ForkJoinWorkerThread w, int a) {
-        int g = scanGuard; // mask 0 avoids useless scans if only one active
-        int m = (parallelism == 1 - a && blockedCount == 0) ? 0 : g & SMASK;
-        ForkJoinWorkerThread[] ws = workers;
-        if (ws == null || ws.length <= m)         // staleness check
-            return false;
-        for (int r = w.seed, k = r, j = -(m + m); j <= m + m; ++j) {
-            ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
-            ForkJoinWorkerThread v = ws[k & m];
-            if (v != null && (b = v.queueBase) != v.queueTop &&
-                (q = v.queue) != null && (i = (q.length - 1) & b) >= 0) {
-                long u = (i << ASHIFT) + ABASE;
-                if ((t = q[i]) != null && v.queueBase == b &&
-                    UNSAFE.compareAndSwapObject(q, u, t, null)) {
-                    int d = (v.queueBase = b + 1) - v.queueTop;
-                    v.stealHint = w.poolIndex;
-                    if (d != 0)
-                        signalWork();             // propagate if nonempty
-                    w.execTask(t);
-                }
-                r ^= r << 13; r ^= r >>> 17; w.seed = r ^ (r << 5);
-                return false;                     // store next seed
-            }
-            else if (j < 0) {                     // xorshift
-                r ^= r << 13; r ^= r >>> 17; k = r ^= r << 5;
-            }
-            else
-                ++k;
-        }
-        if (scanGuard != g)                       // staleness check
-            return false;
-        else {                                    // try to take submission
-            ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
-            if ((b = queueBase) != queueTop &&
-                (q = submissionQueue) != null &&
-                (i = (q.length - 1) & b) >= 0) {
-                long u = (i << ASHIFT) + ABASE;
-                if ((t = q[i]) != null && queueBase == b &&
-                    UNSAFE.compareAndSwapObject(q, u, t, null)) {
-                    queueBase = b + 1;
-                    w.execTask(t);
-                }
-                return false;
-            }
-            return true;                         // all queues empty
-        }
+    final void runWorker(WorkQueue w) {
+        w.growArray(); // allocate queue
+        do { w.runTask(scan(w)); } while (w.qlock >= 0);
     }
 
     /**
-     * Tries to enqueue worker w in wait queue and await change in
-     * worker's eventCount.  If the pool is quiescent and there is
-     * more than one worker, possibly terminates worker upon exit.
-     * Otherwise, before blocking, rescans queues to avoid missed
-     * signals.  Upon finding work, releases at least one worker
-     * (which may be the current worker). Rescans restart upon
-     * detected staleness or failure to release due to
-     * contention. Note the unusual conventions about Thread.interrupt
-     * here and elsewhere: Because interrupts are used solely to alert
-     * threads to check termination, which is checked here anyway, we
-     * clear status (using Thread.interrupted) before any call to
-     * park, so that park does not immediately return due to status
-     * being set via some other unrelated call to interrupt in user
-     * code.
+     * Scans for and, if found, returns one task, else possibly
+     * inactivates the worker. This method operates on single reads of
+     * volatile state and is designed to be re-invoked continuously,
+     * in part because it returns upon detecting inconsistencies,
+     * contention, or state changes that indicate possible success on
+     * re-invocation.
      *
-     * @param w the calling worker
-     * @param c the ctl value on entry
-     * @return true if waited or another thread was released upon enq
+     * The scan searches for tasks across queues (starting at a random
+     * index, and relying on registerWorker to irregularly scatter
+     * them within array to avoid bias), checking each at least twice.
+     * The scan terminates upon either finding a non-empty queue, or
+     * completing the sweep. If the worker is not inactivated, it
+     * takes and returns a task from this queue. Otherwise, if not
+     * activated, it signals workers (that may include itself) and
+     * returns so caller can retry. Also returns for true if the
+     * worker array may have changed during an empty scan.  On failure
+     * to find a task, we take one of the following actions, after
+     * which the caller will retry calling this method unless
+     * terminated.
+     *
+     * * If pool is terminating, terminate the worker.
+     *
+     * * If not already enqueued, try to inactivate and enqueue the
+     * worker on wait queue. Or, if inactivating has caused the pool
+     * to be quiescent, relay to idleAwaitWork to possibly shrink
+     * pool.
+     *
+     * * If already enqueued and none of the above apply, possibly
+     * park awaiting signal, else lingering to help scan and signal.
+     *
+     * * If a non-empty queue discovered or left as a hint,
+     * help wake up other workers before return
+     *
+     * @param w the worker (via its WorkQueue)
+     * @return a task or null if none found
      */
-    private boolean tryAwaitWork(ForkJoinWorkerThread w, long c) {
-        int v = w.eventCount;
-        w.nextWait = (int)c;                      // w's successor record
-        long nc = (long)(v & E_MASK) | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
-        if (ctl != c || !UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
-            long d = ctl; // return true if lost to a deq, to force scan
-            return (int)d != (int)c && ((d - c) & AC_MASK) >= 0L;
-        }
-        for (int sc = w.stealCount; sc != 0;) {   // accumulate stealCount
-            long s = stealCount;
-            if (UNSAFE.compareAndSwapLong(this, stealCountOffset, s, s + sc))
-                sc = w.stealCount = 0;
-            else if (w.eventCount != v)
-                return true;                      // update next time
-        }
-        if ((!shutdown || !tryTerminate(false)) &&
-            (int)c != 0 && parallelism + (int)(nc >> AC_SHIFT) == 0 &&
-            blockedCount == 0 && quiescerCount == 0)
-            idleAwaitWork(w, nc, c, v);           // quiescent
-        for (boolean rescanned = false;;) {
-            if (w.eventCount != v)
-                return true;
-            if (!rescanned) {
-                int g = scanGuard, m = g & SMASK;
-                ForkJoinWorkerThread[] ws = workers;
-                if (ws != null && m < ws.length) {
-                    rescanned = true;
-                    for (int i = 0; i <= m; ++i) {
-                        ForkJoinWorkerThread u = ws[i];
-                        if (u != null) {
-                            if (u.queueBase != u.queueTop &&
-                                !tryReleaseWaiter())
-                                rescanned = false; // contended
-                            if (w.eventCount != v)
-                                return true;
-                        }
+    private final ForkJoinTask<?> scan(WorkQueue w) {
+        WorkQueue[] ws; int m;
+        int ps = plock;                          // read plock before ws
+        if (w != null && (ws = workQueues) != null && (m = ws.length - 1) >= 0) {
+            int ec = w.eventCount;               // ec is negative if inactive
+            int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
+            w.hint = -1;                         // update seed and clear hint
+            int j = ((m + m + 1) | MIN_SCAN) & MAX_SCAN;
+            do {
+                WorkQueue q; ForkJoinTask<?>[] a; int b;
+                if ((q = ws[(r + j) & m]) != null && (b = q.base) - q.top < 0 &&
+                    (a = q.array) != null) {     // probably nonempty
+                    int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
+                    ForkJoinTask<?> t = (ForkJoinTask<?>)
+                        U.getObjectVolatile(a, i);
+                    if (q.base == b && ec >= 0 && t != null &&
+                        U.compareAndSwapObject(a, i, t, null)) {
+                        if ((q.base = b + 1) - q.top < 0)
+                            signalWork(q);
+                        return t;                // taken
+                    }
+                    else if ((ec < 0 || j < m) && (int)(ctl >> AC_SHIFT) <= 0) {
+                        w.hint = (r + j) & m;    // help signal below
+                        break;                   // cannot take
                     }
                 }
-                if (scanGuard != g ||              // stale
-                    (queueBase != queueTop && !tryReleaseWaiter()))
-                    rescanned = false;
-                if (!rescanned)
-                    Thread.yield();                // reduce contention
-                else
-                    Thread.interrupted();          // clear before park
+            } while (--j >= 0);
+
+            int h, e, ns; long c, sc; WorkQueue q;
+            if ((ns = w.nsteals) != 0) {
+                if (U.compareAndSwapLong(this, STEALCOUNT,
+                                         sc = stealCount, sc + ns))
+                    w.nsteals = 0;               // collect steals and rescan
             }
+            else if (plock != ps)                // consistency check
+                ;                                // skip
+            else if ((e = (int)(c = ctl)) < 0)
+                w.qlock = -1;                    // pool is terminating
             else {
-                w.parked = true;                   // must recheck
-                if (w.eventCount != v) {
-                    w.parked = false;
-                    return true;
+                if ((h = w.hint) < 0) {
+                    if (ec >= 0) {               // try to enqueue/inactivate
+                        long nc = (((long)ec |
+                                    ((c - AC_UNIT) & (AC_MASK|TC_MASK))));
+                        w.nextWait = e;          // link and mark inactive
+                        w.eventCount = ec | INT_SIGN;
+                        if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
+                            w.eventCount = ec;   // unmark on CAS failure
+                        else if ((int)(c >> AC_SHIFT) == 1 - (config & SMASK))
+                            idleAwaitWork(w, nc, c);
+                    }
+                    else if (w.eventCount < 0 && !tryTerminate(false, false) &&
+                             ctl == c) {         // block
+                        Thread wt = Thread.currentThread();
+                        Thread.interrupted();    // clear status
+                        U.putObject(wt, PARKBLOCKER, this);
+                        w.parker = wt;           // emulate LockSupport.park
+                        if (w.eventCount < 0)    // recheck
+                            U.park(false, 0L);
+                        w.parker = null;
+                        U.putObject(wt, PARKBLOCKER, null);
+                    }
                 }
-                LockSupport.park(this);
-                rescanned = w.parked = false;
+                if ((h >= 0 || (h = w.hint) >= 0) &&
+                    (ws = workQueues) != null && h < ws.length &&
+                    (q = ws[h]) != null) {      // signal others before retry
+                    WorkQueue v; Thread p; int u, i, s;
+                    for (int n = (config & SMASK) >>> 1;;) {
+                        int idleCount = (w.eventCount < 0) ? 0 : -1;
+                        if (((s = idleCount - q.base + q.top) <= n &&
+                             (n = s) <= 0) ||
+                            (u = (int)((c = ctl) >>> 32)) >= 0 ||
+                            (e = (int)c) <= 0 || m < (i = e & SMASK) ||
+                            (v = ws[i]) == null)
+                            break;
+                        long nc = (((long)(v.nextWait & E_MASK)) |
+                                   ((long)(u + UAC_UNIT) << 32));
+                        if (v.eventCount != (e | INT_SIGN) ||
+                            !U.compareAndSwapLong(this, CTL, c, nc))
+                            break;
+                        v.hint = h;
+                        v.eventCount = (e + E_SEQ) & E_MASK;
+                        if ((p = v.parker) != null)
+                            U.unpark(p);
+                        if (--n <= 0)
+                            break;
+                    }
+                }
             }
         }
+        return null;
     }
 
     /**
-     * If inactivating worker w has caused pool to become
-     * quiescent, check for pool termination, and wait for event
-     * for up to SHRINK_RATE nanosecs (rescans are unnecessary in
-     * this case because quiescence reflects consensus about lack
-     * of work). On timeout, if ctl has not changed, terminate the
-     * worker. Upon its termination (see deregisterWorker), it may
-     * wake up another worker to possibly repeat this process.
+     * If inactivating worker w has caused the pool to become
+     * quiescent, checks for pool termination, and, so long as this is
+     * not the only worker, waits for event for up to a given
+     * duration.  On timeout, if ctl has not changed, terminates the
+     * worker, which will in turn wake up another worker to possibly
+     * repeat this process.
      *
      * @param w the calling worker
-     * @param currentCtl the ctl value after enqueuing w
-     * @param prevCtl the ctl value if w terminated
-     * @param v the eventCount w awaits change
+     * @param currentCtl the ctl value triggering possible quiescence
+     * @param prevCtl the ctl value to restore if thread is terminated
      */
-    private void idleAwaitWork(ForkJoinWorkerThread w, long currentCtl,
-                               long prevCtl, int v) {
-        if (w.eventCount == v) {
-            if (shutdown)
-                tryTerminate(false);
-            ForkJoinTask.helpExpungeStaleExceptions(); // help clean weak refs
+    private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
+        if (w != null && w.eventCount < 0 &&
+            !tryTerminate(false, false) && (int)prevCtl != 0) {
+            int dc = -(short)(currentCtl >>> TC_SHIFT);
+            long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT;
+            long deadline = System.nanoTime() + parkTime - TIMEOUT_SLOP;
+            Thread wt = Thread.currentThread();
             while (ctl == currentCtl) {
-                long startTime = System.nanoTime();
-                w.parked = true;
-                if (w.eventCount == v)             // must recheck
-                    LockSupport.parkNanos(this, SHRINK_RATE);
-                w.parked = false;
-                if (w.eventCount != v)
+                Thread.interrupted();  // timed variant of version in scan()
+                U.putObject(wt, PARKBLOCKER, this);
+                w.parker = wt;
+                if (ctl == currentCtl)
+                    U.park(false, parkTime);
+                w.parker = null;
+                U.putObject(wt, PARKBLOCKER, null);
+                if (ctl != currentCtl)
                     break;
-                else if (System.nanoTime() - startTime <
-                         SHRINK_RATE - (SHRINK_RATE / 10)) // timing slop
-                    Thread.interrupted();          // spurious wakeup
-                else if (UNSAFE.compareAndSwapLong(this, ctlOffset,
-                                                   currentCtl, prevCtl)) {
-                    w.terminate = true;            // restore previous
-                    w.eventCount = ((int)currentCtl + EC_UNIT) & E_MASK;
+                if (deadline - System.nanoTime() <= 0L &&
+                    U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
+                    w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
+                    w.qlock = -1;   // shrink
                     break;
                 }
             }
         }
     }
 
-    // Submissions
-
     /**
-     * Enqueues the given task in the submissionQueue.  Same idea as
-     * ForkJoinWorkerThread.pushTask except for use of submissionLock.
-     *
-     * @param t the task
-     */
-    private void addSubmission(ForkJoinTask<?> t) {
-        final ReentrantLock lock = this.submissionLock;
-        lock.lock();
-        try {
-            ForkJoinTask<?>[] q; int s, m;
-            if ((q = submissionQueue) != null) {    // ignore if queue removed
-                long u = (((s = queueTop) & (m = q.length-1)) << ASHIFT)+ABASE;
-                UNSAFE.putOrderedObject(q, u, t);
-                queueTop = s + 1;
-                if (s - queueBase == m)
-                    growSubmissionQueue();
-            }
-        } finally {
-            lock.unlock();
-        }
-        signalWork();
-    }
-
-    //  (pollSubmission is defined below with exported methods)
-
-    /**
-     * Creates or doubles submissionQueue array.
-     * Basically identical to ForkJoinWorkerThread version.
-     */
-    private void growSubmissionQueue() {
-        ForkJoinTask<?>[] oldQ = submissionQueue;
-        int size = oldQ != null ? oldQ.length << 1 : INITIAL_QUEUE_CAPACITY;
-        if (size > MAXIMUM_QUEUE_CAPACITY)
-            throw new RejectedExecutionException("Queue capacity exceeded");
-        if (size < INITIAL_QUEUE_CAPACITY)
-            size = INITIAL_QUEUE_CAPACITY;
-        ForkJoinTask<?>[] q = submissionQueue = new ForkJoinTask<?>[size];
-        int mask = size - 1;
-        int top = queueTop;
-        int oldMask;
-        if (oldQ != null && (oldMask = oldQ.length - 1) >= 0) {
-            for (int b = queueBase; b != top; ++b) {
-                long u = ((b & oldMask) << ASHIFT) + ABASE;
-                Object x = UNSAFE.getObjectVolatile(oldQ, u);
-                if (x != null && UNSAFE.compareAndSwapObject(oldQ, u, x, null))
-                    UNSAFE.putObjectVolatile
-                        (q, ((b & mask) << ASHIFT) + ABASE, x);
-            }
-        }
-    }
-
-    // Blocking support
-
-    /**
-     * Tries to increment blockedCount, decrement active count
-     * (sometimes implicitly) and possibly release or create a
-     * compensating worker in preparation for blocking. Fails
-     * on contention or termination.
+     * Scans through queues looking for work while joining a task; if
+     * any present, signals. May return early if more signalling is
+     * detectably unneeded.
      *
-     * @return true if the caller can block, else should recheck and retry
-     */
-    private boolean tryPreBlock() {
-        int b = blockedCount;
-        if (UNSAFE.compareAndSwapInt(this, blockedCountOffset, b, b + 1)) {
-            int pc = parallelism;
-            do {
-                ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w;
-                int e, ac, tc, rc, i;
-                long c = ctl;
-                int u = (int)(c >>> 32);
-                if ((e = (int)c) < 0) {
-                                                 // skip -- terminating
-                }
-                else if ((ac = (u >> UAC_SHIFT)) <= 0 && e != 0 &&
-                         (ws = workers) != null &&
-                         (i = ~e & SMASK) < ws.length &&
-                         (w = ws[i]) != null) {
-                    long nc = ((long)(w.nextWait & E_MASK) |
-                               (c & (AC_MASK|TC_MASK)));
-                    if (w.eventCount == e &&
-                        UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
-                        w.eventCount = (e + EC_UNIT) & E_MASK;
-                        if (w.parked)
-                            UNSAFE.unpark(w);
-                        return true;             // release an idle worker
-                    }
-                }
-                else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) {
-                    long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
-                    if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc))
-                        return true;             // no compensation needed
-                }
-                else if (tc + pc < MAX_ID) {
-                    long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
-                    if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
-                        addWorker();
-                        return true;            // create a replacement
-                    }
-                }
-                // try to back out on any failure and let caller retry
-            } while (!UNSAFE.compareAndSwapInt(this, blockedCountOffset,
-                                               b = blockedCount, b - 1));
-        }
-        return false;
-    }
-
-    /**
-     * Decrements blockedCount and increments active count
-     */
-    private void postBlock() {
-        long c;
-        do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset,  // no mask
-                                                c = ctl, c + AC_UNIT));
-        int b;
-        do {} while (!UNSAFE.compareAndSwapInt(this, blockedCountOffset,
-                                               b = blockedCount, b - 1));
-    }
-
-    /**
-     * Possibly blocks waiting for the given task to complete, or
-     * cancels the task if terminating.  Fails to wait if contended.
-     *
-     * @param joinMe the task
+     * @param task return early if done
+     * @param origin an index to start scan
      */
-    final void tryAwaitJoin(ForkJoinTask<?> joinMe) {
-        int s;
-        Thread.interrupted(); // clear interrupts before checking termination
-        if (joinMe.status >= 0) {
-            if (tryPreBlock()) {
-                joinMe.tryAwaitDone(0L);
-                postBlock();
-            }
-            else if ((ctl & STOP_BIT) != 0L)
-                joinMe.cancelIgnoringExceptions();
-        }
-    }
-
-    /**
-     * Possibly blocks the given worker waiting for joinMe to
-     * complete or timeout
-     *
-     * @param joinMe the task
-     * @param millis the wait time for underlying Object.wait
-     */
-    final void timedAwaitJoin(ForkJoinTask<?> joinMe, long nanos) {
-        while (joinMe.status >= 0) {
-            Thread.interrupted();
-            if ((ctl & STOP_BIT) != 0L) {
-                joinMe.cancelIgnoringExceptions();
-                break;
-            }
-            if (tryPreBlock()) {
-                long last = System.nanoTime();
-                while (joinMe.status >= 0) {
-                    long millis = TimeUnit.NANOSECONDS.toMillis(nanos);
-                    if (millis <= 0)
-                        break;
-                    joinMe.tryAwaitDone(millis);
-                    if (joinMe.status < 0)
-                        break;
-                    if ((ctl & STOP_BIT) != 0L) {
-                        joinMe.cancelIgnoringExceptions();
+    private void helpSignal(ForkJoinTask<?> task, int origin) {
+        WorkQueue[] ws; WorkQueue w; Thread p; long c; int m, u, e, i, s;
+        if (task != null && task.status >= 0 &&
+            (u = (int)(ctl >>> 32)) < 0 && (u >> UAC_SHIFT) < 0 &&
+            (ws = workQueues) != null && (m = ws.length - 1) >= 0) {
+            outer: for (int k = origin, j = m; j >= 0; --j) {
+                WorkQueue q = ws[k++ & m];
+                for (int n = m;;) { // limit to at most m signals
+                    if (task.status < 0)
+                        break outer;
+                    if (q == null ||
+                        ((s = -q.base + q.top) <= n && (n = s) <= 0))
                         break;
-                    }
-                    long now = System.nanoTime();
-                    nanos -= now - last;
-                    last = now;
-                }
-                postBlock();
-                break;
-            }
-        }
-    }
-
-    /**
-     * If necessary, compensates for blocker, and blocks
-     */
-    private void awaitBlocker(ManagedBlocker blocker)
-        throws InterruptedException {
-        while (!blocker.isReleasable()) {
-            if (tryPreBlock()) {
-                try {
-                    do {} while (!blocker.isReleasable() && !blocker.block());
-                } finally {
-                    postBlock();
-                }
-                break;
-            }
-        }
-    }
-
-    // Creating, registering and deregistring workers
-
-    /**
-     * Tries to create and start a worker; minimally rolls back counts
-     * on failure.
-     */
-    private void addWorker() {
-        Throwable ex = null;
-        ForkJoinWorkerThread t = null;
-        try {
-            t = factory.newThread(this);
-        } catch (Throwable e) {
-            ex = e;
-        }
-        if (t == null) {  // null or exceptional factory return
-            long c;       // adjust counts
-            do {} while (!UNSAFE.compareAndSwapLong
-                         (this, ctlOffset, c = ctl,
-                          (((c - AC_UNIT) & AC_MASK) |
-                           ((c - TC_UNIT) & TC_MASK) |
-                           (c & ~(AC_MASK|TC_MASK)))));
-            // Propagate exception if originating from an external caller
-            if (!tryTerminate(false) && ex != null &&
-                !(Thread.currentThread() instanceof ForkJoinWorkerThread))
-                UNSAFE.throwException(ex);
-        }
-        else
-            t.start();
-    }
-
-    /**
-     * Callback from ForkJoinWorkerThread constructor to assign a
-     * public name
-     */
-    final String nextWorkerName() {
-        for (int n;;) {
-            if (UNSAFE.compareAndSwapInt(this, nextWorkerNumberOffset,
-                                         n = nextWorkerNumber, ++n))
-                return workerNamePrefix + n;
-        }
-    }
-
-    /**
-     * Callback from ForkJoinWorkerThread constructor to
-     * determine its poolIndex and record in workers array.
-     *
-     * @param w the worker
-     * @return the worker's pool index
-     */
-    final int registerWorker(ForkJoinWorkerThread w) {
-        /*
-         * In the typical case, a new worker acquires the lock, uses
-         * next available index and returns quickly.  Since we should
-         * not block callers (ultimately from signalWork or
-         * tryPreBlock) waiting for the lock needed to do this, we
-         * instead help release other workers while waiting for the
-         * lock.
-         */
-        for (int g;;) {
-            ForkJoinWorkerThread[] ws;
-            if (((g = scanGuard) & SG_UNIT) == 0 &&
-                UNSAFE.compareAndSwapInt(this, scanGuardOffset,
-                                         g, g | SG_UNIT)) {
-                int k = nextWorkerIndex;
-                try {
-                    if ((ws = workers) != null) { // ignore on shutdown
-                        int n = ws.length;
-                        if (k < 0 || k >= n || ws[k] != null) {
-                            for (k = 0; k < n && ws[k] != null; ++k)
-                                ;
-                            if (k == n)
-                                ws = workers = Arrays.copyOf(ws, n << 1);
-                        }
-                        ws[k] = w;
-                        nextWorkerIndex = k + 1;
-                        int m = g & SMASK;
-                        g = (k > m) ? ((m << 1) + 1) & SMASK : g + (SG_UNIT<<1);
-                    }
-                } finally {
-                    scanGuard = g;
-                }
-                return k;
-            }
-            else if ((ws = workers) != null) { // help release others
-                for (ForkJoinWorkerThread u : ws) {
-                    if (u != null && u.queueBase != u.queueTop) {
-                        if (tryReleaseWaiter())
+                    if ((u = (int)((c = ctl) >>> 32)) >= 0 ||
+                        (e = (int)c) <= 0 || m < (i = e & SMASK) ||
+                        (w = ws[i]) == null)
+                        break outer;
+                    long nc = (((long)(w.nextWait & E_MASK)) |
+                               ((long)(u + UAC_UNIT) << 32));
+                    if (w.eventCount != (e | INT_SIGN))
+                        break outer;
+                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
+                        w.eventCount = (e + E_SEQ) & E_MASK;
+                        if ((p = w.parker) != null)
+                            U.unpark(p);
+                        if (--n <= 0)
                             break;
                     }
                 }
@@ -1197,202 +1881,631 @@
     }
 
     /**
-     * Final callback from terminating worker.  Removes record of
-     * worker from array, and adjusts counts. If pool is shutting
-     * down, tries to complete termination.
-     *
-     * @param w the worker
-     */
-    final void deregisterWorker(ForkJoinWorkerThread w, Throwable ex) {
-        int idx = w.poolIndex;
-        int sc = w.stealCount;
-        int steps = 0;
-        // Remove from array, adjust worker counts and collect steal count.
-        // We can intermix failed removes or adjusts with steal updates
-        do {
-            long s, c;
-            int g;
-            if (steps == 0 && ((g = scanGuard) & SG_UNIT) == 0 &&
-                UNSAFE.compareAndSwapInt(this, scanGuardOffset,
-                                         g, g |= SG_UNIT)) {
-                ForkJoinWorkerThread[] ws = workers;
-                if (ws != null && idx >= 0 &&
-                    idx < ws.length && ws[idx] == w)
-                    ws[idx] = null;    // verify
-                nextWorkerIndex = idx;
-                scanGuard = g + SG_UNIT;
-                steps = 1;
-            }
-            if (steps == 1 &&
-                UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl,
-                                          (((c - AC_UNIT) & AC_MASK) |
-                                           ((c - TC_UNIT) & TC_MASK) |
-                                           (c & ~(AC_MASK|TC_MASK)))))
-                steps = 2;
-            if (sc != 0 &&
-                UNSAFE.compareAndSwapLong(this, stealCountOffset,
-                                          s = stealCount, s + sc))
-                sc = 0;
-        } while (steps != 2 || sc != 0);
-        if (!tryTerminate(false)) {
-            if (ex != null)   // possibly replace if died abnormally
-                signalWork();
-            else
-                tryReleaseWaiter();
-        }
-    }
-
-    // Shutdown and termination
-
-    /**
-     * Possibly initiates and/or completes termination.
+     * Tries to locate and execute tasks for a stealer of the given
+     * task, or in turn one of its stealers, Traces currentSteal ->
+     * currentJoin links looking for a thread working on a descendant
+     * of the given task and with a non-empty queue to steal back and
+     * execute tasks from. The first call to this method upon a
+     * waiting join will often entail scanning/search, (which is OK
+     * because the joiner has nothing better to do), but this method
+     * leaves hints in workers to speed up subsequent calls. The
+     * implementation is very branchy to cope with potential
+     * inconsistencies or loops encountering chains that are stale,
+     * unknown, or so long that they are likely cyclic.
      *
-     * @param now if true, unconditionally terminate, else only
-     * if shutdown and empty queue and no active workers
-     * @return true if now terminating or terminated
+     * @param joiner the joining worker
+     * @param task the task to join
+     * @return 0 if no progress can be made, negative if task
+     * known complete, else positive
      */
-    private boolean tryTerminate(boolean now) {
-        long c;
-        while (((c = ctl) & STOP_BIT) == 0) {
-            if (!now) {
-                if ((int)(c >> AC_SHIFT) != -parallelism)
-                    return false;
-                if (!shutdown || blockedCount != 0 || quiescerCount != 0 ||
-                    queueBase != queueTop) {
-                    if (ctl == c) // staleness check
-                        return false;
-                    continue;
-                }
-            }
-            if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, c | STOP_BIT))
-                startTerminating();
-        }
-        if ((short)(c >>> TC_SHIFT) == -parallelism) { // signal when 0 workers
-            final ReentrantLock lock = this.submissionLock;
-            lock.lock();
-            try {
-                termination.signalAll();
-            } finally {
-                lock.unlock();
-            }
-        }
-        return true;
-    }
-
-    /**
-     * Runs up to three passes through workers: (0) Setting
-     * termination status for each worker, followed by wakeups up to
-     * queued workers; (1) helping cancel tasks; (2) interrupting
-     * lagging threads (likely in external tasks, but possibly also
-     * blocked in joins).  Each pass repeats previous steps because of
-     * potential lagging thread creation.
-     */
-    private void startTerminating() {
-        cancelSubmissions();
-        for (int pass = 0; pass < 3; ++pass) {
-            ForkJoinWorkerThread[] ws = workers;
-            if (ws != null) {
-                for (ForkJoinWorkerThread w : ws) {
-                    if (w != null) {
-                        w.terminate = true;
-                        if (pass > 0) {
-                            w.cancelTasks();
-                            if (pass > 1 && !w.isInterrupted()) {
-                                try {
-                                    w.interrupt();
-                                } catch (SecurityException ignore) {
-                                }
+    private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
+        int stat = 0, steps = 0;                    // bound to avoid cycles
+        if (joiner != null && task != null) {       // hoist null checks
+            restart: for (;;) {
+                ForkJoinTask<?> subtask = task;     // current target
+                for (WorkQueue j = joiner, v;;) {   // v is stealer of subtask
+                    WorkQueue[] ws; int m, s, h;
+                    if ((s = task.status) < 0) {
+                        stat = s;
+                        break restart;
+                    }
+                    if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
+                        break restart;              // shutting down
+                    if ((v = ws[h = (j.hint | 1) & m]) == null ||
+                        v.currentSteal != subtask) {
+                        for (int origin = h;;) {    // find stealer
+                            if (((h = (h + 2) & m) & 15) == 1 &&
+                                (subtask.status < 0 || j.currentJoin != subtask))
+                                continue restart;   // occasional staleness check
+                            if ((v = ws[h]) != null &&
+                                v.currentSteal == subtask) {
+                                j.hint = h;        // save hint
+                                break;
+                            }
+                            if (h == origin)
+                                break restart;      // cannot find stealer
+                        }
+                    }
+                    for (;;) { // help stealer or descend to its stealer
+                        ForkJoinTask[] a;  int b;
+                        if (subtask.status < 0)     // surround probes with
+                            continue restart;       //   consistency checks
+                        if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
+                            int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
+                            ForkJoinTask<?> t =
+                                (ForkJoinTask<?>)U.getObjectVolatile(a, i);
+                            if (subtask.status < 0 || j.currentJoin != subtask ||
+                                v.currentSteal != subtask)
+                                continue restart;   // stale
+                            stat = 1;               // apparent progress
+                            if (t != null && v.base == b &&
+                                U.compareAndSwapObject(a, i, t, null)) {
+                                v.base = b + 1;     // help stealer
+                                joiner.runSubtask(t);
+                            }
+                            else if (v.base == b && ++steps == MAX_HELP)
+                                break restart;      // v apparently stalled
+                        }
+                        else {                      // empty -- try to descend
+                            ForkJoinTask<?> next = v.currentJoin;
+                            if (subtask.status < 0 || j.currentJoin != subtask ||
+                                v.currentSteal != subtask)
+                                continue restart;   // stale
+                            else if (next == null || ++steps == MAX_HELP)
+                                break restart;      // dead-end or maybe cyclic
+                            else {
+                                subtask = next;
+                                j = v;
+                                break;
                             }
                         }
                     }
                 }
-                terminateWaiters();
+            }
+        }
+        return stat;
+    }
+
+    /**
+     * Analog of tryHelpStealer for CountedCompleters. Tries to steal
+     * and run tasks within the target's computation.
+     *
+     * @param task the task to join
+     * @param mode if shared, exit upon completing any task
+     * if all workers are active
+     *
+     */
+    private int helpComplete(ForkJoinTask<?> task, int mode) {
+        WorkQueue[] ws; WorkQueue q; int m, n, s, u;
+        if (task != null && (ws = workQueues) != null &&
+            (m = ws.length - 1) >= 0) {
+            for (int j = 1, origin = j;;) {
+                if ((s = task.status) < 0)
+                    return s;
+                if ((q = ws[j & m]) != null && q.pollAndExecCC(task)) {
+                    origin = j;
+                    if (mode == SHARED_QUEUE &&
+                        ((u = (int)(ctl >>> 32)) >= 0 || (u >> UAC_SHIFT) >= 0))
+                        break;
+                }
+                else if ((j = (j + 2) & m) == origin)
+                    break;
+            }
+        }
+        return 0;
+    }
+
+    /**
+     * Tries to decrement active count (sometimes implicitly) and
+     * possibly release or create a compensating worker in preparation
+     * for blocking. Fails on contention or termination. Otherwise,
+     * adds a new thread if no idle workers are available and pool
+     * may become starved.
+     */
+    final boolean tryCompensate() {
+        int pc = config & SMASK, e, i, tc; long c;
+        WorkQueue[] ws; WorkQueue w; Thread p;
+        if ((ws = workQueues) != null && (e = (int)(c = ctl)) >= 0) {
+            if (e != 0 && (i = e & SMASK) < ws.length &&
+                (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
+                long nc = ((long)(w.nextWait & E_MASK) |
+                           (c & (AC_MASK|TC_MASK)));
+                if (U.compareAndSwapLong(this, CTL, c, nc)) {
+                    w.eventCount = (e + E_SEQ) & E_MASK;
+                    if ((p = w.parker) != null)
+                        U.unpark(p);
+                    return true;   // replace with idle worker
+                }
+            }
+            else if ((tc = (short)(c >>> TC_SHIFT)) >= 0 &&
+                     (int)(c >> AC_SHIFT) + pc > 1) {
+                long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
+                if (U.compareAndSwapLong(this, CTL, c, nc))
+                    return true;   // no compensation
+            }
+            else if (tc + pc < MAX_CAP) {
+                long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
+                if (U.compareAndSwapLong(this, CTL, c, nc)) {
+                    ForkJoinWorkerThreadFactory fac;
+                    Throwable ex = null;
+                    ForkJoinWorkerThread wt = null;
+                    try {
+                        if ((fac = factory) != null &&
+                            (wt = fac.newThread(this)) != null) {
+                            wt.start();
+                            return true;
+                        }
+                    } catch (Throwable rex) {
+                        ex = rex;
+                    }
+                    deregisterWorker(wt, ex); // clean up and return false
+                }
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Helps and/or blocks until the given task is done.
+     *
+     * @param joiner the joining worker
+     * @param task the task
+     * @return task status on exit
+     */
+    final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
+        int s = 0;
+        if (joiner != null && task != null && (s = task.status) >= 0) {
+            ForkJoinTask<?> prevJoin = joiner.currentJoin;
+            joiner.currentJoin = task;
+            do {} while ((s = task.status) >= 0 && !joiner.isEmpty() &&
+                         joiner.tryRemoveAndExec(task)); // process local tasks
+            if (s >= 0 && (s = task.status) >= 0) {
+                helpSignal(task, joiner.poolIndex);
+                if ((s = task.status) >= 0 &&
+                    (task instanceof CountedCompleter))
+                    s = helpComplete(task, LIFO_QUEUE);
+            }
+            while (s >= 0 && (s = task.status) >= 0) {
+                if ((!joiner.isEmpty() ||           // try helping
+                     (s = tryHelpStealer(joiner, task)) == 0) &&
+                    (s = task.status) >= 0) {
+                    helpSignal(task, joiner.poolIndex);
+                    if ((s = task.status) >= 0 && tryCompensate()) {
+                        if (task.trySetSignal() && (s = task.status) >= 0) {
+                            synchronized (task) {
+                                if (task.status >= 0) {
+                                    try {                // see ForkJoinTask
+                                        task.wait();     //  for explanation
+                                    } catch (InterruptedException ie) {
+                                    }
+                                }
+                                else
+                                    task.notifyAll();
+                            }
+                        }
+                        long c;                          // re-activate
+                        do {} while (!U.compareAndSwapLong
+                                     (this, CTL, c = ctl, c + AC_UNIT));
+                    }
+                }
+            }
+            joiner.currentJoin = prevJoin;
+        }
+        return s;
+    }
+
+    /**
+     * Stripped-down variant of awaitJoin used by timed joins. Tries
+     * to help join only while there is continuous progress. (Caller
+     * will then enter a timed wait.)
+     *
+     * @param joiner the joining worker
+     * @param task the task
+     */
+    final void helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
+        int s;
+        if (joiner != null && task != null && (s = task.status) >= 0) {
+            ForkJoinTask<?> prevJoin = joiner.currentJoin;
+            joiner.currentJoin = task;
+            do {} while ((s = task.status) >= 0 && !joiner.isEmpty() &&
+                         joiner.tryRemoveAndExec(task));
+            if (s >= 0 && (s = task.status) >= 0) {
+                helpSignal(task, joiner.poolIndex);
+                if ((s = task.status) >= 0 &&
+                    (task instanceof CountedCompleter))
+                    s = helpComplete(task, LIFO_QUEUE);
+            }
+            if (s >= 0 && joiner.isEmpty()) {
+                do {} while (task.status >= 0 &&
+                             tryHelpStealer(joiner, task) > 0);
+            }
+            joiner.currentJoin = prevJoin;
+        }
+    }
+
+    /**
+     * Returns a (probably) non-empty steal queue, if one is found
+     * during a random, then cyclic scan, else null.  This method must
+     * be retried by caller if, by the time it tries to use the queue,
+     * it is empty.
+     * @param r a (random) seed for scanning
+     */
+    private WorkQueue findNonEmptyStealQueue(int r) {
+        for (WorkQueue[] ws;;) {
+            int ps = plock, m, n;
+            if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
+                return null;
+            for (int j = (m + 1) << 2; ;) {
+                WorkQueue q = ws[(((r + j) << 1) | 1) & m];
+                if (q != null && (n = q.base - q.top) < 0) {
+                    if (n < -1)
+                        signalWork(q);
+                    return q;
+                }
+                else if (--j < 0) {
+                    if (plock == ps)
+                        return null;
+                    break;
+                }
             }
         }
     }
 
     /**
-     * Polls and cancels all submissions. Called only during termination.
+     * Runs tasks until {@code isQuiescent()}. We piggyback on
+     * active count ctl maintenance, but rather than blocking
+     * when tasks cannot be found, we rescan until all others cannot
+     * find tasks either.
      */
-    private void cancelSubmissions() {
-        while (queueBase != queueTop) {
-            ForkJoinTask<?> task = pollSubmission();
-            if (task != null) {
-                try {
-                    task.cancel(false);
-                } catch (Throwable ignore) {
+    final void helpQuiescePool(WorkQueue w) {
+        for (boolean active = true;;) {
+            ForkJoinTask<?> localTask; // exhaust local queue
+            while ((localTask = w.nextLocalTask()) != null)
+                localTask.doExec();
+            // Similar to loop in scan(), but ignoring submissions
+            WorkQueue q = findNonEmptyStealQueue(w.nextSeed());
+            if (q != null) {
+                ForkJoinTask<?> t; int b;
+                if (!active) {      // re-establish active count
+                    long c;
+                    active = true;
+                    do {} while (!U.compareAndSwapLong
+                                 (this, CTL, c = ctl, c + AC_UNIT));
+                }
+                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
+                    w.runSubtask(t);
+            }
+            else {
+                long c;
+                if (active) {       // decrement active count without queuing
+                    active = false;
+                    do {} while (!U.compareAndSwapLong
+                                 (this, CTL, c = ctl, c -= AC_UNIT));
+                }
+                else
+                    c = ctl;        // re-increment on exit
+                if ((int)(c >> AC_SHIFT) + (config & SMASK) == 0) {
+                    do {} while (!U.compareAndSwapLong
+                                 (this, CTL, c = ctl, c + AC_UNIT));
+                    break;
                 }
             }
         }
     }
 
     /**
-     * Tries to set the termination status of waiting workers, and
-     * then wakes them up (after which they will terminate).
+     * Gets and removes a local or stolen task for the given worker.
+     *
+     * @return a task, if available
+     */
+    final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
+        for (ForkJoinTask<?> t;;) {
+            WorkQueue q; int b;
+            if ((t = w.nextLocalTask()) != null)
+                return t;
+            if ((q = findNonEmptyStealQueue(w.nextSeed())) == null)
+                return null;
+            if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
+                return t;
+        }
+    }
+
+    /**
+     * Returns a cheap heuristic guide for task partitioning when
+     * programmers, frameworks, tools, or languages have little or no
+     * idea about task granularity.  In essence by offering this
+     * method, we ask users only about tradeoffs in overhead vs
+     * expected throughput and its variance, rather than how finely to
+     * partition tasks.
+     *
+     * In a steady state strict (tree-structured) computation, each
+     * thread makes available for stealing enough tasks for other
+     * threads to remain active. Inductively, if all threads play by
+     * the same rules, each thread should make available only a
+     * constant number of tasks.
+     *
+     * The minimum useful constant is just 1. But using a value of 1
+     * would require immediate replenishment upon each steal to
+     * maintain enough tasks, which is infeasible.  Further,
+     * partitionings/granularities of offered tasks should minimize
+     * steal rates, which in general means that threads nearer the top
+     * of computation tree should generate more than those nearer the
+     * bottom. In perfect steady state, each thread is at
+     * approximately the same level of computation tree. However,
+     * producing extra tasks amortizes the uncertainty of progress and
+     * diffusion assumptions.
+     *
+     * So, users will want to use values larger, but not much larger
+     * than 1 to both smooth over transient shortages and hedge
+     * against uneven progress; as traded off against the cost of
+     * extra task overhead. We leave the user to pick a threshold
+     * value to compare with the results of this call to guide
+     * decisions, but recommend values such as 3.
+     *
+     * When all threads are active, it is on average OK to estimate
+     * surplus strictly locally. In steady-state, if one thread is
+     * maintaining say 2 surplus tasks, then so are others. So we can
+     * just use estimated queue length.  However, this strategy alone
+     * leads to serious mis-estimates in some non-steady-state
+     * conditions (ramp-up, ramp-down, other stalls). We can detect
+     * many of these by further considering the number of "idle"
+     * threads, that are known to have zero queued tasks, so
+     * compensate by a factor of (#idle/#active) threads.
+     *
+     * Note: The approximation of #busy workers as #active workers is
+     * not very good under current signalling scheme, and should be
+     * improved.
      */
-    private void terminateWaiters() {
-        ForkJoinWorkerThread[] ws = workers;
-        if (ws != null) {
-            ForkJoinWorkerThread w; long c; int i, e;
-            int n = ws.length;
-            while ((i = ~(e = (int)(c = ctl)) & SMASK) < n &&
-                   (w = ws[i]) != null && w.eventCount == (e & E_MASK)) {
-                if (UNSAFE.compareAndSwapLong(this, ctlOffset, c,
-                                              (long)(w.nextWait & E_MASK) |
-                                              ((c + AC_UNIT) & AC_MASK) |
-                                              (c & (TC_MASK|STOP_BIT)))) {
-                    w.terminate = true;
-                    w.eventCount = e + EC_UNIT;
-                    if (w.parked)
-                        UNSAFE.unpark(w);
+    static int getSurplusQueuedTaskCount() {
+        Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
+        if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) {
+            int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).config & SMASK;
+            int n = (q = wt.workQueue).top - q.base;
+            int a = (int)(pool.ctl >> AC_SHIFT) + p;
+            return n - (a > (p >>>= 1) ? 0 :
+                        a > (p >>>= 1) ? 1 :
+                        a > (p >>>= 1) ? 2 :
+                        a > (p >>>= 1) ? 4 :
+                        8);
+        }
+        return 0;
+    }
+
+    //  Termination
+
+    /**
+     * Possibly initiates and/or completes termination.  The caller
+     * triggering termination runs three passes through workQueues:
+     * (0) Setting termination status, followed by wakeups of queued
+     * workers; (1) cancelling all tasks; (2) interrupting lagging
+     * threads (likely in external tasks, but possibly also blocked in
+     * joins).  Each pass repeats previous steps because of potential
+     * lagging thread creation.
+     *
+     * @param now if true, unconditionally terminate, else only
+     * if no work and no active workers
+     * @param enable if true, enable shutdown when next possible
+     * @return true if now terminating or terminated
+     */
+    private boolean tryTerminate(boolean now, boolean enable) {
+        if (this == commonPool)                     // cannot shut down
+            return false;
+        for (long c;;) {
+            if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
+                if ((short)(c >>> TC_SHIFT) == -(config & SMASK)) {
+                    synchronized (this) {
+                        notifyAll();                // signal when 0 workers
+                    }
+                }
+                return true;
+            }
+            if (plock >= 0) {                       // not yet enabled
+                int ps;
+                if (!enable)
+                    return false;
+                if (((ps = plock) & PL_LOCK) != 0 ||
+                    !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
+                    ps = acquirePlock();
+                if (!U.compareAndSwapInt(this, PLOCK, ps, SHUTDOWN))
+                    releasePlock(SHUTDOWN);
+            }
+            if (!now) {                             // check if idle & no tasks
+                if ((int)(c >> AC_SHIFT) != -(config & SMASK) ||
+                    hasQueuedSubmissions())
+                    return false;
+                // Check for unqueued inactive workers. One pass suffices.
+                WorkQueue[] ws = workQueues; WorkQueue w;
+                if (ws != null) {
+                    for (int i = 1; i < ws.length; i += 2) {
+                        if ((w = ws[i]) != null && w.eventCount >= 0)
+                            return false;
+                    }
+                }
+            }
+            if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) {
+                for (int pass = 0; pass < 3; ++pass) {
+                    WorkQueue[] ws = workQueues;
+                    if (ws != null) {
+                        WorkQueue w; Thread wt;
+                        int n = ws.length;
+                        for (int i = 0; i < n; ++i) {
+                            if ((w = ws[i]) != null) {
+                                w.qlock = -1;
+                                if (pass > 0) {
+                                    w.cancelAll();
+                                    if (pass > 1 && (wt = w.owner) != null) {
+                                        if (!wt.isInterrupted()) {
+                                            try {
+                                                wt.interrupt();
+                                            } catch (SecurityException ignore) {
+                                            }
+                                        }
+                                        U.unpark(wt);
+                                    }
+                                }
+                            }
+                        }
+                        // Wake up workers parked on event queue
+                        int i, e; long cc; Thread p;
+                        while ((e = (int)(cc = ctl) & E_MASK) != 0 &&
+                               (i = e & SMASK) < n &&
+                               (w = ws[i]) != null) {
+                            long nc = ((long)(w.nextWait & E_MASK) |
+                                       ((cc + AC_UNIT) & AC_MASK) |
+                                       (cc & (TC_MASK|STOP_BIT)));
+                            if (w.eventCount == (e | INT_SIGN) &&
+                                U.compareAndSwapLong(this, CTL, cc, nc)) {
+                                w.eventCount = (e + E_SEQ) & E_MASK;
+                                w.qlock = -1;
+                                if ((p = w.parker) != null)
+                                    U.unpark(p);
+                            }
+                        }
+                    }
                 }
             }
         }
     }
 
-    // misc ForkJoinWorkerThread support
+    // external operations on common pool
+
+    /**
+     * Returns common pool queue for a thread that has submitted at
+     * least one task.
+     */
+    static WorkQueue commonSubmitterQueue() {
+        ForkJoinPool p; WorkQueue[] ws; int m; Submitter z;
+        return ((z = submitters.get()) != null &&
+                (p = commonPool) != null &&
+                (ws = p.workQueues) != null &&
+                (m = ws.length - 1) >= 0) ?
+            ws[m & z.seed & SQMASK] : null;
+    }
 
     /**
-     * Increment or decrement quiescerCount. Needed only to prevent
-     * triggering shutdown if a worker is transiently inactive while
-     * checking quiescence.
-     *
-     * @param delta 1 for increment, -1 for decrement
+     * Tries to pop the given task from submitter's queue in common pool.
      */
-    final void addQuiescerCount(int delta) {
-        int c;
-        do {} while (!UNSAFE.compareAndSwapInt(this, quiescerCountOffset,
-                                               c = quiescerCount, c + delta));
+    static boolean tryExternalUnpush(ForkJoinTask<?> t) {
+        ForkJoinPool p; WorkQueue[] ws; WorkQueue q; Submitter z;
+        ForkJoinTask<?>[] a;  int m, s;
+        if (t != null &&
+            (z = submitters.get()) != null &&
+            (p = commonPool) != null &&
+            (ws = p.workQueues) != null &&
+            (m = ws.length - 1) >= 0 &&
+            (q = ws[m & z.seed & SQMASK]) != null &&
+            (s = q.top) != q.base &&
+            (a = q.array) != null) {
+            long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
+            if (U.getObject(a, j) == t &&
+                U.compareAndSwapInt(q, QLOCK, 0, 1)) {
+                if (q.array == a && q.top == s && // recheck
+                    U.compareAndSwapObject(a, j, t, null)) {
+                    q.top = s - 1;
+                    q.qlock = 0;
+                    return true;
+                }
+                q.qlock = 0;
+            }
+        }
+        return false;
     }
 
     /**
-     * Directly increment or decrement active count without
-     * queuing. This method is used to transiently assert inactivation
-     * while checking quiescence.
-     *
-     * @param delta 1 for increment, -1 for decrement
+     * Tries to pop and run local tasks within the same computation
+     * as the given root. On failure, tries to help complete from
+     * other queues via helpComplete.
      */
-    final void addActiveCount(int delta) {
-        long d = delta < 0 ? -AC_UNIT : AC_UNIT;
-        long c;
-        do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl,
-                                                ((c + d) & AC_MASK) |
-                                                (c & ~AC_MASK)));
+    private void externalHelpComplete(WorkQueue q, ForkJoinTask<?> root) {
+        ForkJoinTask<?>[] a; int m;
+        if (q != null && (a = q.array) != null && (m = (a.length - 1)) >= 0 &&
+            root != null && root.status >= 0) {
+            for (;;) {
+                int s, u; Object o; CountedCompleter<?> task = null;
+                if ((s = q.top) - q.base > 0) {
+                    long j = ((m & (s - 1)) << ASHIFT) + ABASE;
+                    if ((o = U.getObject(a, j)) != null &&
+                        (o instanceof CountedCompleter)) {
+                        CountedCompleter<?> t = (CountedCompleter<?>)o, r = t;
+                        do {
+                            if (r == root) {
+                                if (U.compareAndSwapInt(q, QLOCK, 0, 1)) {
+                                    if (q.array == a && q.top == s &&
+                                        U.compareAndSwapObject(a, j, t, null)) {
+                                        q.top = s - 1;
+                                        task = t;
+                                    }
+                                    q.qlock = 0;
+                                }
+                                break;
+                            }
+                        } while ((r = r.completer) != null);
+                    }
+                }
+                if (task != null)
+                    task.doExec();
+                if (root.status < 0 ||
+                    (u = (int)(ctl >>> 32)) >= 0 || (u >> UAC_SHIFT) >= 0)
+                    break;
+                if (task == null) {
+                    helpSignal(root, q.poolIndex);
+                    if (root.status >= 0)
+                        helpComplete(root, SHARED_QUEUE);
+                    break;
+                }
+            }
+        }
     }
 
     /**
-     * Returns the approximate (non-atomic) number of idle threads per
-     * active thread.
+     * Tries to help execute or signal availability of the given task
+     * from submitter's queue in common pool.
      */
-    final int idlePerActive() {
-        // Approximate at powers of two for small values, saturate past 4
-        int p = parallelism;
-        int a = p + (int)(ctl >> AC_SHIFT);
-        return (a > (p >>>= 1) ? 0 :
-                a > (p >>>= 1) ? 1 :
-                a > (p >>>= 1) ? 2 :
-                a > (p >>>= 1) ? 4 :
-                8);
+    static void externalHelpJoin(ForkJoinTask<?> t) {
+        // Some hard-to-avoid overlap with tryExternalUnpush
+        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, w; Submitter z;
+        ForkJoinTask<?>[] a;  int m, s, n;
+        if (t != null &&
+            (z = submitters.get()) != null &&
+            (p = commonPool) != null &&
+            (ws = p.workQueues) != null &&
+            (m = ws.length - 1) >= 0 &&
+            (q = ws[m & z.seed & SQMASK]) != null &&
+            (a = q.array) != null) {
+            int am = a.length - 1;
+            if ((s = q.top) != q.base) {
+                long j = ((am & (s - 1)) << ASHIFT) + ABASE;
+                if (U.getObject(a, j) == t &&
+                    U.compareAndSwapInt(q, QLOCK, 0, 1)) {
+                    if (q.array == a && q.top == s &&
+                        U.compareAndSwapObject(a, j, t, null)) {
+                        q.top = s - 1;
+                        q.qlock = 0;
+                        t.doExec();
+                    }
+                    else
+                        q.qlock = 0;
+                }
+            }
+            if (t.status >= 0) {
+                if (t instanceof CountedCompleter)
+                    p.externalHelpComplete(q, t);
+                else
+                    p.helpSignal(t, q.poolIndex);
+            }
+        }
+    }
+
+    /**
+     * Restricted version of helpQuiescePool for external callers
+     */
+    static void externalHelpQuiescePool() {
+        ForkJoinPool p; ForkJoinTask<?> t; WorkQueue q; int b;
+        if ((p = commonPool) != null &&
+            (q = p.findNonEmptyStealQueue(1)) != null &&
+            (b = q.base) - q.top < 0 &&
+            (t = q.pollAt(b)) != null)
+            t.doExec();
     }
 
     // Exported methods
@@ -1464,31 +2577,47 @@
         checkPermission();
         if (factory == null)
             throw new NullPointerException();
-        if (parallelism <= 0 || parallelism > MAX_ID)
+        if (parallelism <= 0 || parallelism > MAX_CAP)
             throw new IllegalArgumentException();
-        this.parallelism = parallelism;
         this.factory = factory;
         this.ueh = handler;
-        this.locallyFifo = asyncMode;
+        this.config = parallelism | (asyncMode ? (FIFO_QUEUE << 16) : 0);
         long np = (long)(-parallelism); // offset ctl counts
         this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
-        this.submissionQueue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
-        // initialize workers array with room for 2*parallelism if possible
-        int n = parallelism << 1;
-        if (n >= MAX_ID)
-            n = MAX_ID;
-        else { // See Hackers Delight, sec 3.2, where n < (1 << 16)
-            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8;
-        }
-        workers = new ForkJoinWorkerThread[n + 1];
-        this.submissionLock = new ReentrantLock();
-        this.termination = submissionLock.newCondition();
+        int pn = nextPoolId();
         StringBuilder sb = new StringBuilder("ForkJoinPool-");
-        sb.append(poolNumberGenerator.incrementAndGet());
+        sb.append(Integer.toString(pn));
         sb.append("-worker-");
         this.workerNamePrefix = sb.toString();
     }
 
+    /**
+     * Constructor for common pool, suitable only for static initialization.
+     * Basically the same as above, but uses smallest possible initial footprint.
+     */
+    ForkJoinPool(int parallelism, long ctl,
+                 ForkJoinWorkerThreadFactory factory,
+                 Thread.UncaughtExceptionHandler handler) {
+        this.config = parallelism;
+        this.ctl = ctl;
+        this.factory = factory;
+        this.ueh = handler;
+        this.workerNamePrefix = "ForkJoinPool.commonPool-worker-";
+    }
+
+    /**
+     * Returns the common pool instance. This pool is statically
+     * constructed; its run state is unaffected by attempts to
+     * {@link #shutdown} or {@link #shutdownNow}.
+     *
+     * @return the common pool instance
+     * @since 1.8
+     */
+    public static ForkJoinPool commonPool() {
+        // assert commonPool != null : "static init error";
+        return commonPool;
+    }
+
     // Execution methods
 
     /**
@@ -1508,34 +2637,10 @@
      *         scheduled for execution
      */
     public <T> T invoke(ForkJoinTask<T> task) {
-        Thread t = Thread.currentThread();
         if (task == null)
             throw new NullPointerException();
-        if (shutdown)
-            throw new RejectedExecutionException();
-        if ((t instanceof ForkJoinWorkerThread) &&
-            ((ForkJoinWorkerThread)t).pool == this)
-            return task.invoke();  // bypass submit if in same pool
-        else {
-            addSubmission(task);
-            return task.join();
-        }
-    }
-
-    /**
-     * Unless terminating, forks task if within an ongoing FJ
-     * computation in the current pool, else submits as external task.
-     */
-    private <T> void forkOrSubmit(ForkJoinTask<T> task) {
-        ForkJoinWorkerThread w;
-        Thread t = Thread.currentThread();
-        if (shutdown)
-            throw new RejectedExecutionException();
-        if ((t instanceof ForkJoinWorkerThread) &&
-            (w = (ForkJoinWorkerThread)t).pool == this)
-            w.pushTask(task);
-        else
-            addSubmission(task);
+        externalPush(task);
+        return task.join();
     }
 
     /**
@@ -1549,7 +2654,7 @@
     public void execute(ForkJoinTask<?> task) {
         if (task == null)
             throw new NullPointerException();
-        forkOrSubmit(task);
+        externalPush(task);
     }
 
     // AbstractExecutorService methods
@@ -1566,8 +2671,8 @@
         if (task instanceof ForkJoinTask<?>) // avoid re-wrap
             job = (ForkJoinTask<?>) task;
         else
-            job = ForkJoinTask.adapt(task, null);
-        forkOrSubmit(job);
+            job = new ForkJoinTask.AdaptedRunnableAction(task);
+        externalPush(job);
     }
 
     /**
@@ -1582,7 +2687,7 @@
     public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
         if (task == null)
             throw new NullPointerException();
-        forkOrSubmit(task);
+        externalPush(task);
         return task;
     }
 
@@ -1592,10 +2697,8 @@
      *         scheduled for execution
      */
     public <T> ForkJoinTask<T> submit(Callable<T> task) {
-        if (task == null)
-            throw new NullPointerException();
-        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
-        forkOrSubmit(job);
+        ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
+        externalPush(job);
         return job;
     }
 
@@ -1605,10 +2708,8 @@
      *         scheduled for execution
      */
     public <T> ForkJoinTask<T> submit(Runnable task, T result) {
-        if (task == null)
-            throw new NullPointerException();
-        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
-        forkOrSubmit(job);
+        ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
+        externalPush(job);
         return job;
     }
 
@@ -1624,8 +2725,8 @@
         if (task instanceof ForkJoinTask<?>) // avoid re-wrap
             job = (ForkJoinTask<?>) task;
         else
-            job = ForkJoinTask.adapt(task, null);
-        forkOrSubmit(job);
+            job = new ForkJoinTask.AdaptedRunnableAction(task);
+        externalPush(job);
         return job;
     }
 
@@ -1634,25 +2735,31 @@
      * @throws RejectedExecutionException {@inheritDoc}
      */
     public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
-        ArrayList<ForkJoinTask<T>> forkJoinTasks =
-            new ArrayList<ForkJoinTask<T>>(tasks.size());
-        for (Callable<T> task : tasks)
-            forkJoinTasks.add(ForkJoinTask.adapt(task));
-        invoke(new InvokeAll<T>(forkJoinTasks));
-
+        // In previous versions of this class, this method constructed
+        // a task to run ForkJoinTask.invokeAll, but now external
+        // invocation of multiple tasks is at least as efficient.
+        List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size());
+        // Workaround needed because method wasn't declared with
+        // wildcards in return type but should have been.
         @SuppressWarnings({"unchecked", "rawtypes"})
-            List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
-        return futures;
-    }
+            List<Future<T>> futures = (List<Future<T>>) (List) fs;
 
-    static final class InvokeAll<T> extends RecursiveAction {
-        final ArrayList<ForkJoinTask<T>> tasks;
-        InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
-        public void compute() {
-            try { invokeAll(tasks); }
-            catch (Exception ignore) {}
+        boolean done = false;
+        try {
+            for (Callable<T> t : tasks) {
+                ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
+                externalPush(f);
+                fs.add(f);
+            }
+            for (ForkJoinTask<T> f : fs)
+                f.quietlyJoin();
+            done = true;
+            return futures;
+        } finally {
+            if (!done)
+                for (ForkJoinTask<T> f : fs)
+                    f.cancel(false);
         }
-        private static final long serialVersionUID = -7914297376763021607L;
     }
 
     /**
@@ -1680,7 +2787,17 @@
      * @return the targeted parallelism level of this pool
      */
     public int getParallelism() {
-        return parallelism;
+        return config & SMASK;
+    }
+
+    /**
+     * Returns the targeted parallelism level of the common pool.
+     *
+     * @return the targeted parallelism level of the common pool
+     * @since 1.8
+     */
+    public static int getCommonPoolParallelism() {
+        return commonPoolParallelism;
     }
 
     /**
@@ -1692,7 +2809,7 @@
      * @return the number of worker threads
      */
     public int getPoolSize() {
-        return parallelism + (short)(ctl >>> TC_SHIFT);
+        return (config & SMASK) + (short)(ctl >>> TC_SHIFT);
     }
 
     /**
@@ -1702,7 +2819,7 @@
      * @return {@code true} if this pool uses async mode
      */
     public boolean getAsyncMode() {
-        return locallyFifo;
+        return (config >>> 16) == FIFO_QUEUE;
     }
 
     /**
@@ -1714,8 +2831,15 @@
      * @return the number of worker threads
      */
     public int getRunningThreadCount() {
-        int r = parallelism + (int)(ctl >> AC_SHIFT);
-        return (r <= 0) ? 0 : r; // suppress momentarily negative values
+        int rc = 0;
+        WorkQueue[] ws; WorkQueue w;
+        if ((ws = workQueues) != null) {
+            for (int i = 1; i < ws.length; i += 2) {
+                if ((w = ws[i]) != null && w.isApparentlyUnblocked())
+                    ++rc;
+            }
+        }
+        return rc;
     }
 
     /**
@@ -1726,7 +2850,7 @@
      * @return the number of active threads
      */
     public int getActiveThreadCount() {
-        int r = parallelism + (int)(ctl >> AC_SHIFT) + blockedCount;
+        int r = (config & SMASK) + (int)(ctl >> AC_SHIFT);
         return (r <= 0) ? 0 : r; // suppress momentarily negative values
     }
 
@@ -1742,7 +2866,7 @@
      * @return {@code true} if all threads are currently idle
      */
     public boolean isQuiescent() {
-        return parallelism + (int)(ctl >> AC_SHIFT) + blockedCount == 0;
+        return (int)(ctl >> AC_SHIFT) + (config & SMASK) == 0;
     }
 
     /**
@@ -1757,7 +2881,15 @@
      * @return the number of steals
      */
     public long getStealCount() {
-        return stealCount;
+        long count = stealCount;
+        WorkQueue[] ws; WorkQueue w;
+        if ((ws = workQueues) != null) {
+            for (int i = 1; i < ws.length; i += 2) {
+                if ((w = ws[i]) != null)
+                    count += w.nsteals;
+            }
+        }
+        return count;
     }
 
     /**
@@ -1772,12 +2904,12 @@
      */
     public long getQueuedTaskCount() {
         long count = 0;
-        ForkJoinWorkerThread[] ws;
-        if ((short)(ctl >>> TC_SHIFT) > -parallelism &&
-            (ws = workers) != null) {
-            for (ForkJoinWorkerThread w : ws)
-                if (w != null)
-                    count -= w.queueBase - w.queueTop; // must read base first
+        WorkQueue[] ws; WorkQueue w;
+        if ((ws = workQueues) != null) {
+            for (int i = 1; i < ws.length; i += 2) {
+                if ((w = ws[i]) != null)
+                    count += w.queueSize();
+            }
         }
         return count;
     }
@@ -1790,7 +2922,15 @@
      * @return the number of queued submissions
      */
     public int getQueuedSubmissionCount() {
-        return -queueBase + queueTop;
+        int count = 0;
+        WorkQueue[] ws; WorkQueue w;
+        if ((ws = workQueues) != null) {
+            for (int i = 0; i < ws.length; i += 2) {
+                if ((w = ws[i]) != null)
+                    count += w.queueSize();
+            }
+        }
+        return count;
     }
 
     /**
@@ -1800,7 +2940,14 @@
      * @return {@code true} if there are any queued submissions
      */
     public boolean hasQueuedSubmissions() {
-        return queueBase != queueTop;
+        WorkQueue[] ws; WorkQueue w;
+        if ((ws = workQueues) != null) {
+            for (int i = 0; i < ws.length; i += 2) {
+                if ((w = ws[i]) != null && !w.isEmpty())
+                    return true;
+            }
+        }
+        return false;
     }
 
     /**
@@ -1811,16 +2958,11 @@
      * @return the next submission, or {@code null} if none
      */
     protected ForkJoinTask<?> pollSubmission() {
-        ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
-        while ((b = queueBase) != queueTop &&
-               (q = submissionQueue) != null &&
-               (i = (q.length - 1) & b) >= 0) {
-            long u = (i << ASHIFT) + ABASE;
-            if ((t = q[i]) != null &&
-                queueBase == b &&
-                UNSAFE.compareAndSwapObject(q, u, t, null)) {
-                queueBase = b + 1;
-                return t;
+        WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
+        if ((ws = workQueues) != null) {
+            for (int i = 0; i < ws.length; i += 2) {
+                if ((w = ws[i]) != null && (t = w.poll()) != null)
+                    return t;
             }
         }
         return null;
@@ -1845,20 +2987,17 @@
      */
     protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
         int count = 0;
-        while (queueBase != queueTop) {
-            ForkJoinTask<?> t = pollSubmission();
-            if (t != null) {
-                c.add(t);
-                ++count;
+        WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
+        if ((ws = workQueues) != null) {
+            for (int i = 0; i < ws.length; ++i) {
+                if ((w = ws[i]) != null) {
+                    while ((t = w.poll()) != null) {
+                        c.add(t);
+                        ++count;
+                    }
+                }
             }
         }
-        ForkJoinWorkerThread[] ws;
-        if ((short)(ctl >>> TC_SHIFT) > -parallelism &&
-            (ws = workers) != null) {
-            for (ForkJoinWorkerThread w : ws)
-                if (w != null)
-                    count += w.drainTasksTo(c);
-        }
         return count;
     }
 
@@ -1870,21 +3009,36 @@
      * @return a string identifying this pool, as well as its state
      */
     public String toString() {
-        long st = getStealCount();
-        long qt = getQueuedTaskCount();
-        long qs = getQueuedSubmissionCount();
-        int pc = parallelism;
+        // Use a single pass through workQueues to collect counts
+        long qt = 0L, qs = 0L; int rc = 0;
+        long st = stealCount;
         long c = ctl;
+        WorkQueue[] ws; WorkQueue w;
+        if ((ws = workQueues) != null) {
+            for (int i = 0; i < ws.length; ++i) {
+                if ((w = ws[i]) != null) {
+                    int size = w.queueSize();
+                    if ((i & 1) == 0)
+                        qs += size;
+                    else {
+                        qt += size;
+                        st += w.nsteals;
+                        if (w.isApparentlyUnblocked())
+                            ++rc;
+                    }
+                }
+            }
+        }
+        int pc = (config & SMASK);
         int tc = pc + (short)(c >>> TC_SHIFT);
-        int rc = pc + (int)(c >> AC_SHIFT);
-        if (rc < 0) // ignore transient negative
-            rc = 0;
-        int ac = rc + blockedCount;
+        int ac = pc + (int)(c >> AC_SHIFT);
+        if (ac < 0) // ignore transient negative
+            ac = 0;
         String level;
         if ((c & STOP_BIT) != 0)
             level = (tc == 0) ? "Terminated" : "Terminating";
         else
-            level = shutdown ? "Shutting down" : "Running";
+            level = plock < 0 ? "Shutting down" : "Running";
         return super.toString() +
             "[" + level +
             ", parallelism = " + pc +
@@ -1898,11 +3052,13 @@
     }
 
     /**
-     * Initiates an orderly shutdown in which previously submitted
-     * tasks are executed, but no new tasks will be accepted.
-     * Invocation has no additional effect if already shut down.
-     * Tasks that are in the process of being submitted concurrently
-     * during the course of this method may or may not be rejected.
+     * Possibly initiates an orderly shutdown in which previously
+     * submitted tasks are executed, but no new tasks will be
+     * accepted. Invocation has no effect on execution state if this
+     * is the {@link #commonPool}, and no additional effect if
+     * already shut down.  Tasks that are in the process of being
+     * submitted concurrently during the course of this method may or
+     * may not be rejected.
      *
      * @throws SecurityException if a security manager exists and
      *         the caller is not permitted to modify threads
@@ -1911,19 +3067,20 @@
      */
     public void shutdown() {
         checkPermission();
-        shutdown = true;
-        tryTerminate(false);
+        tryTerminate(false, true);
     }
 
     /**
-     * Attempts to cancel and/or stop all tasks, and reject all
-     * subsequently submitted tasks.  Tasks that are in the process of
-     * being submitted or executed concurrently during the course of
-     * this method may or may not be rejected. This method cancels
-     * both existing and unexecuted tasks, in order to permit
-     * termination in the presence of task dependencies. So the method
-     * always returns an empty list (unlike the case for some other
-     * Executors).
+     * Possibly attempts to cancel and/or stop all tasks, and reject
+     * all subsequently submitted tasks.  Invocation has no effect on
+     * execution state if this is the {@link #commonPool}, and no
+     * additional effect if already shut down. Otherwise, tasks that
+     * are in the process of being submitted or executed concurrently
+     * during the course of this method may or may not be
+     * rejected. This method cancels both existing and unexecuted
+     * tasks, in order to permit termination in the presence of task
+     * dependencies. So the method always returns an empty list
+     * (unlike the case for some other Executors).
      *
      * @return an empty list
      * @throws SecurityException if a security manager exists and
@@ -1933,8 +3090,7 @@
      */
     public List<Runnable> shutdownNow() {
         checkPermission();
-        shutdown = true;
-        tryTerminate(true);
+        tryTerminate(true, true);
         return Collections.emptyList();
     }
 
@@ -1946,7 +3102,7 @@
     public boolean isTerminated() {
         long c = ctl;
         return ((c & STOP_BIT) != 0L &&
-                (short)(c >>> TC_SHIFT) == -parallelism);
+                (short)(c >>> TC_SHIFT) == -(config & SMASK));
     }
 
     /**
@@ -1954,7 +3110,7 @@
      * commenced but not yet completed.  This method may be useful for
      * debugging. A return of {@code true} reported a sufficient
      * period after shutdown may indicate that submitted tasks have
-     * ignored or suppressed interruption, or are waiting for IO,
+     * ignored or suppressed interruption, or are waiting for I/O,
      * causing this executor not to properly terminate. (See the
      * advisory notes for class {@link ForkJoinTask} stating that
      * tasks should not normally entail blocking operations.  But if
@@ -1965,14 +3121,7 @@
     public boolean isTerminating() {
         long c = ctl;
         return ((c & STOP_BIT) != 0L &&
-                (short)(c >>> TC_SHIFT) != -parallelism);
-    }
-
-    /**
-     * Returns true if terminating or terminated. Used by ForkJoinWorkerThread.
-     */
-    final boolean isAtLeastTerminating() {
-        return (ctl & STOP_BIT) != 0L;
+                (short)(c >>> TC_SHIFT) != -(config & SMASK));
     }
 
     /**
@@ -1981,13 +3130,15 @@
      * @return {@code true} if this pool has been shut down
      */
     public boolean isShutdown() {
-        return shutdown;
+        return plock < 0;
     }
 
     /**
-     * Blocks until all tasks have completed execution after a shutdown
-     * request, or the timeout occurs, or the current thread is
-     * interrupted, whichever happens first.
+     * Blocks until all tasks have completed execution after a
+     * shutdown request, or the timeout occurs, or the current thread
+     * is interrupted, whichever happens first. Note that the {@link
+     * #commonPool()} never terminates until program shutdown so
+     * this method will always time out.
      *
      * @param timeout the maximum time to wait
      * @param unit the time unit of the timeout argument
@@ -1998,19 +3149,21 @@
     public boolean awaitTermination(long timeout, TimeUnit unit)
         throws InterruptedException {
         long nanos = unit.toNanos(timeout);
-        final ReentrantLock lock = this.submissionLock;
-        lock.lock();
-        try {
-            for (;;) {
-                if (isTerminated())
-                    return true;
-                if (nanos <= 0)
-                    return false;
-                nanos = termination.awaitNanos(nanos);
+        if (isTerminated())
+            return true;
+        long startTime = System.nanoTime();
+        boolean terminated = false;
+        synchronized (this) {
+            for (long waitTime = nanos, millis = 0L;;) {
+                if (terminated = isTerminated() ||
+                    waitTime <= 0L ||
+                    (millis = unit.toMillis(waitTime)) <= 0L)
+                    break;
+                wait(millis);
+                waitTime = nanos - (System.nanoTime() - startTime);
             }
-        } finally {
-            lock.unlock();
         }
+        return terminated;
     }
 
     /**
@@ -2110,11 +3263,35 @@
         throws InterruptedException {
         Thread t = Thread.currentThread();
         if (t instanceof ForkJoinWorkerThread) {
-            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
-            w.pool.awaitBlocker(blocker);
+            ForkJoinPool p = ((ForkJoinWorkerThread)t).pool;
+            while (!blocker.isReleasable()) { // variant of helpSignal
+                WorkQueue[] ws; WorkQueue q; int m, u;
+                if ((ws = p.workQueues) != null && (m = ws.length - 1) >= 0) {
+                    for (int i = 0; i <= m; ++i) {
+                        if (blocker.isReleasable())
+                            return;
+                        if ((q = ws[i]) != null && q.base - q.top < 0) {
+                            p.signalWork(q);
+                            if ((u = (int)(p.ctl >>> 32)) >= 0 ||
+                                (u >> UAC_SHIFT) >= 0)
+                                break;
+                        }
+                    }
+                }
+                if (p.tryCompensate()) {
+                    try {
+                        do {} while (!blocker.isReleasable() &&
+                                     !blocker.block());
+                    } finally {
+                        p.incrementActiveCount();
+                    }
+                    break;
+                }
+            }
         }
         else {
-            do {} while (!blocker.isReleasable() && !blocker.block());
+            do {} while (!blocker.isReleasable() &&
+                         !blocker.block());
         }
     }
 
@@ -2123,55 +3300,93 @@
     // implement RunnableFuture.
 
     protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
-        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
+        return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
     }
 
     protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
-        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
+        return new ForkJoinTask.AdaptedCallable<T>(callable);
     }
 
     // Unsafe mechanics
-    private static final sun.misc.Unsafe UNSAFE;
-    private static final long ctlOffset;
-    private static final long stealCountOffset;
-    private static final long blockedCountOffset;
-    private static final long quiescerCountOffset;
-    private static final long scanGuardOffset;
-    private static final long nextWorkerNumberOffset;
-    private static final long ABASE;
+    private static final sun.misc.Unsafe U;
+    private static final long CTL;
+    private static final long PARKBLOCKER;
+    private static final int ABASE;
     private static final int ASHIFT;
+    private static final long STEALCOUNT;
+    private static final long PLOCK;
+    private static final long INDEXSEED;
+    private static final long QLOCK;
 
     static {
-        poolNumberGenerator = new AtomicInteger();
-        workerSeedGenerator = new Random();
-        modifyThreadPermission = new RuntimePermission("modifyThread");
-        defaultForkJoinWorkerThreadFactory =
-            new DefaultForkJoinWorkerThreadFactory();
-        int s;
+        int s; // initialize field offsets for CAS etc
         try {
-            UNSAFE = sun.misc.Unsafe.getUnsafe();
+            U = sun.misc.Unsafe.getUnsafe();
             Class<?> k = ForkJoinPool.class;
-            ctlOffset = UNSAFE.objectFieldOffset
+            CTL = U.objectFieldOffset
                 (k.getDeclaredField("ctl"));
-            stealCountOffset = UNSAFE.objectFieldOffset
+            STEALCOUNT = U.objectFieldOffset
                 (k.getDeclaredField("stealCount"));
-            blockedCountOffset = UNSAFE.objectFieldOffset
-                (k.getDeclaredField("blockedCount"));
-            quiescerCountOffset = UNSAFE.objectFieldOffset
-                (k.getDeclaredField("quiescerCount"));
-            scanGuardOffset = UNSAFE.objectFieldOffset
-                (k.getDeclaredField("scanGuard"));
-            nextWorkerNumberOffset = UNSAFE.objectFieldOffset
-                (k.getDeclaredField("nextWorkerNumber"));
-            Class<?> a = ForkJoinTask[].class;
-            ABASE = UNSAFE.arrayBaseOffset(a);
-            s = UNSAFE.arrayIndexScale(a);
+            PLOCK = U.objectFieldOffset
+                (k.getDeclaredField("plock"));
+            INDEXSEED = U.objectFieldOffset
+                (k.getDeclaredField("indexSeed"));
+            Class<?> tk = Thread.class;
+            PARKBLOCKER = U.objectFieldOffset
+                (tk.getDeclaredField("parkBlocker"));
+            Class<?> wk = WorkQueue.class;
+            QLOCK = U.objectFieldOffset
+                (wk.getDeclaredField("qlock"));
+            Class<?> ak = ForkJoinTask[].class;
+            ABASE = U.arrayBaseOffset(ak);
+            s = U.arrayIndexScale(ak);
+            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
         } catch (Exception e) {
             throw new Error(e);
         }
         if ((s & (s-1)) != 0)
             throw new Error("data type scale not a power of two");
-        ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
+
+        submitters = new ThreadLocal<Submitter>();
+        ForkJoinWorkerThreadFactory fac = defaultForkJoinWorkerThreadFactory =
+            new DefaultForkJoinWorkerThreadFactory();
+        modifyThreadPermission = new RuntimePermission("modifyThread");
+
+        /*
+         * Establish common pool parameters.  For extra caution,
+         * computations to set up common pool state are here; the
+         * constructor just assigns these values to fields.
+         */
+
+        int par = 0;
+        Thread.UncaughtExceptionHandler handler = null;
+        try {  // TBD: limit or report ignored exceptions?
+            String pp = System.getProperty
+                ("java.util.concurrent.ForkJoinPool.common.parallelism");
+            String hp = System.getProperty
+                ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
+            String fp = System.getProperty
+                ("java.util.concurrent.ForkJoinPool.common.threadFactory");
+            if (fp != null)
+                fac = ((ForkJoinWorkerThreadFactory)ClassLoader.
+                       getSystemClassLoader().loadClass(fp).newInstance());
+            if (hp != null)
+                handler = ((Thread.UncaughtExceptionHandler)ClassLoader.
+                           getSystemClassLoader().loadClass(hp).newInstance());
+            if (pp != null)
+                par = Integer.parseInt(pp);
+        } catch (Exception ignore) {
+        }
+
+        if (par <= 0)
+            par = Runtime.getRuntime().availableProcessors();
+        if (par > MAX_CAP)
+            par = MAX_CAP;
+        commonPoolParallelism = par;
+        long np = (long)(-par); // precompute initial ctl value
+        long ct = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
+
+        commonPool = new ForkJoinPool(par, ct, fac, handler);
     }
 
 }
--- a/jdk/src/share/classes/java/util/concurrent/ForkJoinTask.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/concurrent/ForkJoinTask.java	Tue Jan 22 11:54:16 2013 -0800
@@ -37,17 +37,13 @@
 
 import java.io.Serializable;
 import java.util.Collection;
-import java.util.Collections;
 import java.util.List;
 import java.util.RandomAccess;
-import java.util.Map;
 import java.lang.ref.WeakReference;
 import java.lang.ref.ReferenceQueue;
 import java.util.concurrent.Callable;
 import java.util.concurrent.CancellationException;
 import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Executor;
-import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Future;
 import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.RunnableFuture;
@@ -63,46 +59,59 @@
  * subtasks may be hosted by a small number of actual threads in a
  * ForkJoinPool, at the price of some usage limitations.
  *
- * <p>A "main" {@code ForkJoinTask} begins execution when submitted
- * to a {@link ForkJoinPool}.  Once started, it will usually in turn
- * start other subtasks.  As indicated by the name of this class,
- * many programs using {@code ForkJoinTask} employ only methods
- * {@link #fork} and {@link #join}, or derivatives such as {@link
+ * <p>A "main" {@code ForkJoinTask} begins execution when it is
+ * explicitly submitted to a {@link ForkJoinPool}, or, if not already
+ * engaged in a ForkJoin computation, commenced in the {@link
+ * ForkJoinPool#commonPool()} via {@link #fork}, {@link #invoke}, or
+ * related methods.  Once started, it will usually in turn start other
+ * subtasks.  As indicated by the name of this class, many programs
+ * using {@code ForkJoinTask} employ only methods {@link #fork} and
+ * {@link #join}, or derivatives such as {@link
  * #invokeAll(ForkJoinTask...) invokeAll}.  However, this class also
  * provides a number of other methods that can come into play in
- * advanced usages, as well as extension mechanics that allow
- * support of new forms of fork/join processing.
+ * advanced usages, as well as extension mechanics that allow support
+ * of new forms of fork/join processing.
  *
  * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
  * The efficiency of {@code ForkJoinTask}s stems from a set of
  * restrictions (that are only partially statically enforceable)
- * reflecting their intended use as computational tasks calculating
- * pure functions or operating on purely isolated objects.  The
- * primary coordination mechanisms are {@link #fork}, that arranges
+ * reflecting their main use as computational tasks calculating pure
+ * functions or operating on purely isolated objects.  The primary
+ * coordination mechanisms are {@link #fork}, that arranges
  * asynchronous execution, and {@link #join}, that doesn't proceed
  * until the task's result has been computed.  Computations should
- * avoid {@code synchronized} methods or blocks, and should minimize
- * other blocking synchronization apart from joining other tasks or
- * using synchronizers such as Phasers that are advertised to
- * cooperate with fork/join scheduling. Tasks should also not perform
- * blocking IO, and should ideally access variables that are
- * completely independent of those accessed by other running
- * tasks. Minor breaches of these restrictions, for example using
- * shared output streams, may be tolerable in practice, but frequent
- * use may result in poor performance, and the potential to
- * indefinitely stall if the number of threads not waiting for IO or
- * other external synchronization becomes exhausted. This usage
- * restriction is in part enforced by not permitting checked
- * exceptions such as {@code IOExceptions} to be thrown. However,
- * computations may still encounter unchecked exceptions, that are
- * rethrown to callers attempting to join them. These exceptions may
- * additionally include {@link RejectedExecutionException} stemming
- * from internal resource exhaustion, such as failure to allocate
- * internal task queues. Rethrown exceptions behave in the same way as
- * regular exceptions, but, when possible, contain stack traces (as
- * displayed for example using {@code ex.printStackTrace()}) of both
- * the thread that initiated the computation as well as the thread
- * actually encountering the exception; minimally only the latter.
+ * ideally avoid {@code synchronized} methods or blocks, and should
+ * minimize other blocking synchronization apart from joining other
+ * tasks or using synchronizers such as Phasers that are advertised to
+ * cooperate with fork/join scheduling. Subdividable tasks should also
+ * not perform blocking I/O, and should ideally access variables that
+ * are completely independent of those accessed by other running
+ * tasks. These guidelines are loosely enforced by not permitting
+ * checked exceptions such as {@code IOExceptions} to be
+ * thrown. However, computations may still encounter unchecked
+ * exceptions, that are rethrown to callers attempting to join
+ * them. These exceptions may additionally include {@link
+ * RejectedExecutionException} stemming from internal resource
+ * exhaustion, such as failure to allocate internal task
+ * queues. Rethrown exceptions behave in the same way as regular
+ * exceptions, but, when possible, contain stack traces (as displayed
+ * for example using {@code ex.printStackTrace()}) of both the thread
+ * that initiated the computation as well as the thread actually
+ * encountering the exception; minimally only the latter.
+ *
+ * <p>It is possible to define and use ForkJoinTasks that may block,
+ * but doing do requires three further considerations: (1) Completion
+ * of few if any <em>other</em> tasks should be dependent on a task
+ * that blocks on external synchronization or I/O. Event-style async
+ * tasks that are never joined (for example, those subclassing {@link
+ * CountedCompleter}) often fall into this category.  (2) To minimize
+ * resource impact, tasks should be small; ideally performing only the
+ * (possibly) blocking action. (3) Unless the {@link
+ * ForkJoinPool.ManagedBlocker} API is used, or the number of possibly
+ * blocked tasks is known to be less than the pool's {@link
+ * ForkJoinPool#getParallelism} level, the pool cannot guarantee that
+ * enough threads will be available to ensure progress or good
+ * performance.
  *
  * <p>The primary method for awaiting completion and extracting
  * results of a task is {@link #join}, but there are several variants:
@@ -118,6 +127,13 @@
  * performs the most common form of parallel invocation: forking a set
  * of tasks and joining them all.
  *
+ * <p>In the most typical usages, a fork-join pair act like a call
+ * (fork) and return (join) from a parallel recursive function. As is
+ * the case with other forms of recursive calls, returns (joins)
+ * should be performed innermost-first. For example, {@code a.fork();
+ * b.fork(); b.join(); a.join();} is likely to be substantially more
+ * efficient than joining {@code a} before {@code b}.
+ *
  * <p>The execution status of tasks may be queried at several levels
  * of detail: {@link #isDone} is true if a task completed in any way
  * (including the case where a task was cancelled without executing);
@@ -133,18 +149,13 @@
  * <p>The ForkJoinTask class is not usually directly subclassed.
  * Instead, you subclass one of the abstract classes that support a
  * particular style of fork/join processing, typically {@link
- * RecursiveAction} for computations that do not return results, or
- * {@link RecursiveTask} for those that do.  Normally, a concrete
- * ForkJoinTask subclass declares fields comprising its parameters,
- * established in a constructor, and then defines a {@code compute}
- * method that somehow uses the control methods supplied by this base
- * class. While these methods have {@code public} access (to allow
- * instances of different task subclasses to call each other's
- * methods), some of them may only be called from within other
- * ForkJoinTasks (as may be determined using method {@link
- * #inForkJoinPool}).  Attempts to invoke them in other contexts
- * result in exceptions or errors, possibly including
- * {@code ClassCastException}.
+ * RecursiveAction} for most computations that do not return results,
+ * {@link RecursiveTask} for those that do, and {@link
+ * CountedCompleter} for those in which completed actions trigger
+ * other actions.  Normally, a concrete ForkJoinTask subclass declares
+ * fields comprising its parameters, established in a constructor, and
+ * then defines a {@code compute} method that somehow uses the control
+ * methods supplied by this base class.
  *
  * <p>Method {@link #join} and its variants are appropriate for use
  * only when completion dependencies are acyclic; that is, the
@@ -154,7 +165,17 @@
  * supports other methods and techniques (for example the use of
  * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
  * may be of use in constructing custom subclasses for problems that
- * are not statically structured as DAGs.
+ * are not statically structured as DAGs. To support such usages a
+ * ForkJoinTask may be atomically <em>tagged</em> with a {@code short}
+ * value using {@link #setForkJoinTaskTag} or {@link
+ * #compareAndSetForkJoinTaskTag} and checked using {@link
+ * #getForkJoinTaskTag}. The ForkJoinTask implementation does not use
+ * these {@code protected} methods or tags for any purpose, but they
+ * may be of use in the construction of specialized subclasses.  For
+ * example, parallel graph traversals can use the supplied methods to
+ * avoid revisiting nodes/tasks that have already been processed.
+ * (Method names for tagging are bulky in part to encourage definition
+ * of methods that reflect their usage patterns.)
  *
  * <p>Most base support methods are {@code final}, to prevent
  * overriding of implementations that are intrinsically tied to the
@@ -194,41 +215,50 @@
      * See the internal documentation of class ForkJoinPool for a
      * general implementation overview.  ForkJoinTasks are mainly
      * responsible for maintaining their "status" field amidst relays
-     * to methods in ForkJoinWorkerThread and ForkJoinPool. The
-     * methods of this class are more-or-less layered into (1) basic
-     * status maintenance (2) execution and awaiting completion (3)
-     * user-level methods that additionally report results. This is
-     * sometimes hard to see because this file orders exported methods
-     * in a way that flows well in javadocs.
+     * to methods in ForkJoinWorkerThread and ForkJoinPool.
+     *
+     * The methods of this class are more-or-less layered into
+     * (1) basic status maintenance
+     * (2) execution and awaiting completion
+     * (3) user-level methods that additionally report results.
+     * This is sometimes hard to see because this file orders exported
+     * methods in a way that flows well in javadocs.
      */
 
     /*
      * The status field holds run control status bits packed into a
      * single int to minimize footprint and to ensure atomicity (via
      * CAS).  Status is initially zero, and takes on nonnegative
-     * values until completed, upon which status holds value
-     * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
-     * waits by other threads have the SIGNAL bit set.  Completion of
-     * a stolen task with SIGNAL set awakens any waiters via
-     * notifyAll. Even though suboptimal for some purposes, we use
-     * basic builtin wait/notify to take advantage of "monitor
-     * inflation" in JVMs that we would otherwise need to emulate to
-     * avoid adding further per-task bookkeeping overhead.  We want
-     * these monitors to be "fat", i.e., not use biasing or thin-lock
-     * techniques, so use some odd coding idioms that tend to avoid
-     * them.
+     * values until completed, upon which status (anded with
+     * DONE_MASK) holds value NORMAL, CANCELLED, or EXCEPTIONAL. Tasks
+     * undergoing blocking waits by other threads have the SIGNAL bit
+     * set.  Completion of a stolen task with SIGNAL set awakens any
+     * waiters via notifyAll. Even though suboptimal for some
+     * purposes, we use basic builtin wait/notify to take advantage of
+     * "monitor inflation" in JVMs that we would otherwise need to
+     * emulate to avoid adding further per-task bookkeeping overhead.
+     * We want these monitors to be "fat", i.e., not use biasing or
+     * thin-lock techniques, so use some odd coding idioms that tend
+     * to avoid them, mainly by arranging that every synchronized
+     * block performs a wait, notifyAll or both.
+     *
+     * These control bits occupy only (some of) the upper half (16
+     * bits) of status field. The lower bits are used for user-defined
+     * tags.
      */
 
     /** The run status of this task */
     volatile int status; // accessed directly by pool and workers
-    private static final int NORMAL      = -1;
-    private static final int CANCELLED   = -2;
-    private static final int EXCEPTIONAL = -3;
-    private static final int SIGNAL      =  1;
+    static final int DONE_MASK   = 0xf0000000;  // mask out non-completion bits
+    static final int NORMAL      = 0xf0000000;  // must be negative
+    static final int CANCELLED   = 0xc0000000;  // must be < NORMAL
+    static final int EXCEPTIONAL = 0x80000000;  // must be < CANCELLED
+    static final int SIGNAL      = 0x00010000;  // must be >= 1 << 16
+    static final int SMASK       = 0x0000ffff;  // short bits for tags
 
     /**
-     * Marks completion and wakes up threads waiting to join this task,
-     * also clearing signal request bits.
+     * Marks completion and wakes up threads waiting to join this
+     * task.
      *
      * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
      * @return completion status on exit
@@ -237,8 +267,8 @@
         for (int s;;) {
             if ((s = status) < 0)
                 return s;
-            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
-                if (s != 0)
+            if (U.compareAndSwapInt(this, STATUS, s, s | completion)) {
+                if ((s >>> 16) != 0)
                     synchronized (this) { notifyAll(); }
                 return completion;
             }
@@ -246,27 +276,36 @@
     }
 
     /**
-     * Tries to block a worker thread until completed or timed out.
-     * Uses Object.wait time argument conventions.
-     * May fail on contention or interrupt.
+     * Primary execution method for stolen tasks. Unless done, calls
+     * exec and records status if completed, but doesn't wait for
+     * completion otherwise.
      *
-     * @param millis if > 0, wait time.
+     * @return status on exit from this method
      */
-    final void tryAwaitDone(long millis) {
-        int s;
-        try {
-            if (((s = status) > 0 ||
-                 (s == 0 &&
-                  UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL))) &&
-                status > 0) {
-                synchronized (this) {
-                    if (status > 0)
-                        wait(millis);
-                }
+    final int doExec() {
+        int s; boolean completed;
+        if ((s = status) >= 0) {
+            try {
+                completed = exec();
+            } catch (Throwable rex) {
+                return setExceptionalCompletion(rex);
             }
-        } catch (InterruptedException ie) {
-            // caller must check termination
+            if (completed)
+                s = setCompletion(NORMAL);
         }
+        return s;
+    }
+
+    /**
+     * Tries to set SIGNAL status unless already completed. Used by
+     * ForkJoinPool. Other variants are directly incorporated into
+     * externalAwaitDone etc.
+     *
+     * @return true if successful
+     */
+    final boolean trySetSignal() {
+        int s = status;
+        return s >= 0 && U.compareAndSwapInt(this, STATUS, s, s | SIGNAL);
     }
 
     /**
@@ -275,113 +314,78 @@
      */
     private int externalAwaitDone() {
         int s;
-        if ((s = status) >= 0) {
-            boolean interrupted = false;
-            synchronized (this) {
-                while ((s = status) >= 0) {
-                    if (s == 0)
-                        UNSAFE.compareAndSwapInt(this, statusOffset,
-                                                 0, SIGNAL);
-                    else {
+        ForkJoinPool.externalHelpJoin(this);
+        boolean interrupted = false;
+        while ((s = status) >= 0) {
+            if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
+                synchronized (this) {
+                    if (status >= 0) {
                         try {
                             wait();
                         } catch (InterruptedException ie) {
                             interrupted = true;
                         }
                     }
+                    else
+                        notifyAll();
                 }
             }
-            if (interrupted)
-                Thread.currentThread().interrupt();
         }
+        if (interrupted)
+            Thread.currentThread().interrupt();
         return s;
     }
 
     /**
-     * Blocks a non-worker-thread until completion or interruption or timeout.
+     * Blocks a non-worker-thread until completion or interruption.
      */
-    private int externalInterruptibleAwaitDone(long millis)
-        throws InterruptedException {
+    private int externalInterruptibleAwaitDone() throws InterruptedException {
         int s;
         if (Thread.interrupted())
             throw new InterruptedException();
-        if ((s = status) >= 0) {
-            synchronized (this) {
-                while ((s = status) >= 0) {
-                    if (s == 0)
-                        UNSAFE.compareAndSwapInt(this, statusOffset,
-                                                 0, SIGNAL);
-                    else {
-                        wait(millis);
-                        if (millis > 0L)
-                            break;
-                    }
+        ForkJoinPool.externalHelpJoin(this);
+        while ((s = status) >= 0) {
+            if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
+                synchronized (this) {
+                    if (status >= 0)
+                        wait();
+                    else
+                        notifyAll();
                 }
             }
         }
         return s;
     }
 
-    /**
-     * Primary execution method for stolen tasks. Unless done, calls
-     * exec and records status if completed, but doesn't wait for
-     * completion otherwise.
-     */
-    final void doExec() {
-        if (status >= 0) {
-            boolean completed;
-            try {
-                completed = exec();
-            } catch (Throwable rex) {
-                setExceptionalCompletion(rex);
-                return;
-            }
-            if (completed)
-                setCompletion(NORMAL); // must be outside try block
-        }
-    }
 
     /**
-     * Primary mechanics for join, get, quietlyJoin.
+     * Implementation for join, get, quietlyJoin. Directly handles
+     * only cases of already-completed, external wait, and
+     * unfork+exec.  Others are relayed to ForkJoinPool.awaitJoin.
+     *
      * @return status upon completion
      */
     private int doJoin() {
-        Thread t; ForkJoinWorkerThread w; int s; boolean completed;
-        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
-            if ((s = status) < 0)
-                return s;
-            if ((w = (ForkJoinWorkerThread)t).unpushTask(this)) {
-                try {
-                    completed = exec();
-                } catch (Throwable rex) {
-                    return setExceptionalCompletion(rex);
-                }
-                if (completed)
-                    return setCompletion(NORMAL);
-            }
-            return w.joinTask(this);
-        }
-        else
-            return externalAwaitDone();
+        int s; Thread t; ForkJoinWorkerThread wt; ForkJoinPool.WorkQueue w;
+        return (s = status) < 0 ? s :
+            ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
+            (w = (wt = (ForkJoinWorkerThread)t).workQueue).
+            tryUnpush(this) && (s = doExec()) < 0 ? s :
+            wt.pool.awaitJoin(w, this) :
+            externalAwaitDone();
     }
 
     /**
-     * Primary mechanics for invoke, quietlyInvoke.
+     * Implementation for invoke, quietlyInvoke.
+     *
      * @return status upon completion
      */
     private int doInvoke() {
-        int s; boolean completed;
-        if ((s = status) < 0)
-            return s;
-        try {
-            completed = exec();
-        } catch (Throwable rex) {
-            return setExceptionalCompletion(rex);
-        }
-        if (completed)
-            return setCompletion(NORMAL);
-        else
-            return doJoin();
+        int s; Thread t; ForkJoinWorkerThread wt;
+        return (s = doExec()) < 0 ? s :
+            ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
+            (wt = (ForkJoinWorkerThread)t).pool.awaitJoin(wt.workQueue, this) :
+            externalAwaitDone();
     }
 
     // Exception table support
@@ -416,7 +420,7 @@
      * any ForkJoinPool will call helpExpungeStaleExceptions when its
      * pool becomes isQuiescent.
      */
-    static final class ExceptionNode extends WeakReference<ForkJoinTask<?>>{
+    static final class ExceptionNode extends WeakReference<ForkJoinTask<?>> {
         final Throwable ex;
         ExceptionNode next;
         final long thrower;  // use id not ref to avoid weak cycles
@@ -429,30 +433,67 @@
     }
 
     /**
-     * Records exception and sets exceptional completion.
+     * Records exception and sets status.
+     *
+     * @return status on exit
+     */
+    final int recordExceptionalCompletion(Throwable ex) {
+        int s;
+        if ((s = status) >= 0) {
+            int h = System.identityHashCode(this);
+            final ReentrantLock lock = exceptionTableLock;
+            lock.lock();
+            try {
+                expungeStaleExceptions();
+                ExceptionNode[] t = exceptionTable;
+                int i = h & (t.length - 1);
+                for (ExceptionNode e = t[i]; ; e = e.next) {
+                    if (e == null) {
+                        t[i] = new ExceptionNode(this, ex, t[i]);
+                        break;
+                    }
+                    if (e.get() == this) // already present
+                        break;
+                }
+            } finally {
+                lock.unlock();
+            }
+            s = setCompletion(EXCEPTIONAL);
+        }
+        return s;
+    }
+
+    /**
+     * Records exception and possibly propagates
      *
      * @return status on exit
      */
     private int setExceptionalCompletion(Throwable ex) {
-        int h = System.identityHashCode(this);
-        final ReentrantLock lock = exceptionTableLock;
-        lock.lock();
-        try {
-            expungeStaleExceptions();
-            ExceptionNode[] t = exceptionTable;
-            int i = h & (t.length - 1);
-            for (ExceptionNode e = t[i]; ; e = e.next) {
-                if (e == null) {
-                    t[i] = new ExceptionNode(this, ex, t[i]);
-                    break;
-                }
-                if (e.get() == this) // already present
-                    break;
+        int s = recordExceptionalCompletion(ex);
+        if ((s & DONE_MASK) == EXCEPTIONAL)
+            internalPropagateException(ex);
+        return s;
+    }
+
+    /**
+     * Hook for exception propagation support for tasks with completers.
+     */
+    void internalPropagateException(Throwable ex) {
+    }
+
+    /**
+     * Cancels, ignoring any exceptions thrown by cancel. Used during
+     * worker and pool shutdown. Cancel is spec'ed not to throw any
+     * exceptions, but if it does anyway, we have no recourse during
+     * shutdown, so guard against this case.
+     */
+    static final void cancelIgnoringExceptions(ForkJoinTask<?> t) {
+        if (t != null && t.status >= 0) {
+            try {
+                t.cancel(false);
+            } catch (Throwable ignore) {
             }
-        } finally {
-            lock.unlock();
         }
-        return setCompletion(EXCEPTIONAL);
     }
 
     /**
@@ -501,7 +542,7 @@
      * @return the exception, or null if none
      */
     private Throwable getThrowableException() {
-        if (status != EXCEPTIONAL)
+        if ((status & DONE_MASK) != EXCEPTIONAL)
             return null;
         int h = System.identityHashCode(this);
         ExceptionNode e;
@@ -519,7 +560,7 @@
         Throwable ex;
         if (e == null || (ex = e.ex) == null)
             return null;
-        if (e.thrower != Thread.currentThread().getId()) {
+        if (false && e.thrower != Thread.currentThread().getId()) {
             Class<? extends Throwable> ec = ex.getClass();
             try {
                 Constructor<?> noArgCtor = null;
@@ -586,41 +627,61 @@
     }
 
     /**
-     * Report the result of invoke or join; called only upon
-     * non-normal return of internal versions.
+     * A version of "sneaky throw" to relay exceptions
      */
-    private V reportResult() {
-        int s; Throwable ex;
-        if ((s = status) == CANCELLED)
+    static void rethrow(final Throwable ex) {
+        if (ex != null) {
+            if (ex instanceof Error)
+                throw (Error)ex;
+            if (ex instanceof RuntimeException)
+                throw (RuntimeException)ex;
+            throw uncheckedThrowable(ex, RuntimeException.class);
+        }
+    }
+
+    /**
+     * The sneaky part of sneaky throw, relying on generics
+     * limitations to evade compiler complaints about rethrowing
+     * unchecked exceptions
+     */
+    @SuppressWarnings("unchecked") static <T extends Throwable>
+        T uncheckedThrowable(final Throwable t, final Class<T> c) {
+        return (T)t; // rely on vacuous cast
+    }
+
+    /**
+     * Throws exception, if any, associated with the given status.
+     */
+    private void reportException(int s) {
+        if (s == CANCELLED)
             throw new CancellationException();
-        if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
-            UNSAFE.throwException(ex);
-        return getRawResult();
+        if (s == EXCEPTIONAL)
+            rethrow(getThrowableException());
     }
 
     // public methods
 
     /**
-     * Arranges to asynchronously execute this task.  While it is not
-     * necessarily enforced, it is a usage error to fork a task more
-     * than once unless it has completed and been reinitialized.
-     * Subsequent modifications to the state of this task or any data
-     * it operates on are not necessarily consistently observable by
-     * any thread other than the one executing it unless preceded by a
-     * call to {@link #join} or related methods, or a call to {@link
-     * #isDone} returning {@code true}.
-     *
-     * <p>This method may be invoked only from within {@code
-     * ForkJoinPool} computations (as may be determined using method
-     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
-     * result in exceptions or errors, possibly including {@code
-     * ClassCastException}.
+     * Arranges to asynchronously execute this task in the pool the
+     * current task is running in, if applicable, or using the {@link
+     * ForkJoinPool#commonPool()} if not {@link #inForkJoinPool}.  While
+     * it is not necessarily enforced, it is a usage error to fork a
+     * task more than once unless it has completed and been
+     * reinitialized.  Subsequent modifications to the state of this
+     * task or any data it operates on are not necessarily
+     * consistently observable by any thread other than the one
+     * executing it unless preceded by a call to {@link #join} or
+     * related methods, or a call to {@link #isDone} returning {@code
+     * true}.
      *
      * @return {@code this}, to simplify usage
      */
     public final ForkJoinTask<V> fork() {
-        ((ForkJoinWorkerThread) Thread.currentThread())
-            .pushTask(this);
+        Thread t;
+        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
+            ((ForkJoinWorkerThread)t).workQueue.push(this);
+        else
+            ForkJoinPool.commonPool.externalPush(this);
         return this;
     }
 
@@ -636,10 +697,10 @@
      * @return the computed result
      */
     public final V join() {
-        if (doJoin() != NORMAL)
-            return reportResult();
-        else
-            return getRawResult();
+        int s;
+        if ((s = doJoin() & DONE_MASK) != NORMAL)
+            reportException(s);
+        return getRawResult();
     }
 
     /**
@@ -651,10 +712,10 @@
      * @return the computed result
      */
     public final V invoke() {
-        if (doInvoke() != NORMAL)
-            return reportResult();
-        else
-            return getRawResult();
+        int s;
+        if ((s = doInvoke() & DONE_MASK) != NORMAL)
+            reportException(s);
+        return getRawResult();
     }
 
     /**
@@ -670,20 +731,17 @@
      * cancelled, completed normally or exceptionally, or left
      * unprocessed.
      *
-     * <p>This method may be invoked only from within {@code
-     * ForkJoinPool} computations (as may be determined using method
-     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
-     * result in exceptions or errors, possibly including {@code
-     * ClassCastException}.
-     *
      * @param t1 the first task
      * @param t2 the second task
      * @throws NullPointerException if any task is null
      */
     public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
+        int s1, s2;
         t2.fork();
-        t1.invoke();
-        t2.join();
+        if ((s1 = t1.doInvoke() & DONE_MASK) != NORMAL)
+            t1.reportException(s1);
+        if ((s2 = t2.doJoin() & DONE_MASK) != NORMAL)
+            t2.reportException(s2);
     }
 
     /**
@@ -698,12 +756,6 @@
      * related methods to check if they have been cancelled, completed
      * normally or exceptionally, or left unprocessed.
      *
-     * <p>This method may be invoked only from within {@code
-     * ForkJoinPool} computations (as may be determined using method
-     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
-     * result in exceptions or errors, possibly including {@code
-     * ClassCastException}.
-     *
      * @param tasks the tasks
      * @throws NullPointerException if any task is null
      */
@@ -726,12 +778,12 @@
             if (t != null) {
                 if (ex != null)
                     t.cancel(false);
-                else if (t.doJoin() < NORMAL && ex == null)
+                else if (t.doJoin() < NORMAL)
                     ex = t.getException();
             }
         }
         if (ex != null)
-            UNSAFE.throwException(ex);
+            rethrow(ex);
     }
 
     /**
@@ -747,12 +799,6 @@
      * cancelled, completed normally or exceptionally, or left
      * unprocessed.
      *
-     * <p>This method may be invoked only from within {@code
-     * ForkJoinPool} computations (as may be determined using method
-     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
-     * result in exceptions or errors, possibly including {@code
-     * ClassCastException}.
-     *
      * @param tasks the collection of tasks
      * @return the tasks argument, to simplify usage
      * @throws NullPointerException if tasks or any element are null
@@ -783,12 +829,12 @@
             if (t != null) {
                 if (ex != null)
                     t.cancel(false);
-                else if (t.doJoin() < NORMAL && ex == null)
+                else if (t.doJoin() < NORMAL)
                     ex = t.getException();
             }
         }
         if (ex != null)
-            UNSAFE.throwException(ex);
+            rethrow(ex);
         return tasks;
     }
 
@@ -820,20 +866,7 @@
      * @return {@code true} if this task is now cancelled
      */
     public boolean cancel(boolean mayInterruptIfRunning) {
-        return setCompletion(CANCELLED) == CANCELLED;
-    }
-
-    /**
-     * Cancels, ignoring any exceptions thrown by cancel. Used during
-     * worker and pool shutdown. Cancel is spec'ed not to throw any
-     * exceptions, but if it does anyway, we have no recourse during
-     * shutdown, so guard against this case.
-     */
-    final void cancelIgnoringExceptions() {
-        try {
-            cancel(false);
-        } catch (Throwable ignore) {
-        }
+        return (setCompletion(CANCELLED) & DONE_MASK) == CANCELLED;
     }
 
     public final boolean isDone() {
@@ -841,7 +874,7 @@
     }
 
     public final boolean isCancelled() {
-        return status == CANCELLED;
+        return (status & DONE_MASK) == CANCELLED;
     }
 
     /**
@@ -861,7 +894,7 @@
      * exception and was not cancelled
      */
     public final boolean isCompletedNormally() {
-        return status == NORMAL;
+        return (status & DONE_MASK) == NORMAL;
     }
 
     /**
@@ -872,7 +905,7 @@
      * @return the exception, or {@code null} if none
      */
     public final Throwable getException() {
-        int s = status;
+        int s = status & DONE_MASK;
         return ((s >= NORMAL)    ? null :
                 (s == CANCELLED) ? new CancellationException() :
                 getThrowableException());
@@ -922,6 +955,18 @@
     }
 
     /**
+     * Completes this task normally without setting a value. The most
+     * recent value established by {@link #setRawResult} (or {@code
+     * null} by default) will be returned as the result of subsequent
+     * invocations of {@code join} and related operations.
+     *
+     * @since 1.8
+     */
+    public final void quietlyComplete() {
+        setCompletion(NORMAL);
+    }
+
+    /**
      * Waits if necessary for the computation to complete, and then
      * retrieves its result.
      *
@@ -934,9 +979,9 @@
      */
     public final V get() throws InterruptedException, ExecutionException {
         int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
-            doJoin() : externalInterruptibleAwaitDone(0L);
+            doJoin() : externalInterruptibleAwaitDone();
         Throwable ex;
-        if (s == CANCELLED)
+        if ((s &= DONE_MASK) == CANCELLED)
             throw new CancellationException();
         if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
             throw new ExecutionException(ex);
@@ -959,32 +1004,62 @@
      */
     public final V get(long timeout, TimeUnit unit)
         throws InterruptedException, ExecutionException, TimeoutException {
-        Thread t = Thread.currentThread();
-        if (t instanceof ForkJoinWorkerThread) {
-            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
-            long nanos = unit.toNanos(timeout);
-            if (status >= 0) {
-                boolean completed = false;
-                if (w.unpushTask(this)) {
-                    try {
-                        completed = exec();
-                    } catch (Throwable rex) {
-                        setExceptionalCompletion(rex);
+        if (Thread.interrupted())
+            throw new InterruptedException();
+        // Messy in part because we measure in nanosecs, but wait in millisecs
+        int s; long ns, ms;
+        if ((s = status) >= 0 && (ns = unit.toNanos(timeout)) > 0L) {
+            long deadline = System.nanoTime() + ns;
+            ForkJoinPool p = null;
+            ForkJoinPool.WorkQueue w = null;
+            Thread t = Thread.currentThread();
+            if (t instanceof ForkJoinWorkerThread) {
+                ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
+                p = wt.pool;
+                w = wt.workQueue;
+                p.helpJoinOnce(w, this); // no retries on failure
+            }
+            else
+                ForkJoinPool.externalHelpJoin(this);
+            boolean canBlock = false;
+            boolean interrupted = false;
+            try {
+                while ((s = status) >= 0) {
+                    if (w != null && w.qlock < 0)
+                        cancelIgnoringExceptions(this);
+                    else if (!canBlock) {
+                        if (p == null || p.tryCompensate())
+                            canBlock = true;
+                    }
+                    else {
+                        if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) > 0L &&
+                            U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
+                            synchronized (this) {
+                                if (status >= 0) {
+                                    try {
+                                        wait(ms);
+                                    } catch (InterruptedException ie) {
+                                        if (p == null)
+                                            interrupted = true;
+                                    }
+                                }
+                                else
+                                    notifyAll();
+                            }
+                        }
+                        if ((s = status) < 0 || interrupted ||
+                            (ns = deadline - System.nanoTime()) <= 0L)
+                            break;
                     }
                 }
-                if (completed)
-                    setCompletion(NORMAL);
-                else if (status >= 0 && nanos > 0)
-                    w.pool.timedAwaitJoin(this, nanos);
+            } finally {
+                if (p != null && canBlock)
+                    p.incrementActiveCount();
             }
+            if (interrupted)
+                throw new InterruptedException();
         }
-        else {
-            long millis = unit.toMillis(timeout);
-            if (millis > 0)
-                externalInterruptibleAwaitDone(millis);
-        }
-        int s = status;
-        if (s != NORMAL) {
+        if ((s &= DONE_MASK) != NORMAL) {
             Throwable ex;
             if (s == CANCELLED)
                 throw new CancellationException();
@@ -1021,16 +1096,15 @@
      * be of use in designs in which many tasks are forked, but none
      * are explicitly joined, instead executing them until all are
      * processed.
-     *
-     * <p>This method may be invoked only from within {@code
-     * ForkJoinPool} computations (as may be determined using method
-     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
-     * result in exceptions or errors, possibly including {@code
-     * ClassCastException}.
      */
     public static void helpQuiesce() {
-        ((ForkJoinWorkerThread) Thread.currentThread())
-            .helpQuiescePool();
+        Thread t;
+        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
+            ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
+            wt.pool.helpQuiescePool(wt.workQueue);
+        }
+        else
+            ForkJoinPool.externalHelpQuiescePool();
     }
 
     /**
@@ -1050,7 +1124,7 @@
      * setRawResult(null)}.
      */
     public void reinitialize() {
-        if (status == EXCEPTIONAL)
+        if ((status & DONE_MASK) == EXCEPTIONAL)
             clearExceptionalCompletion();
         else
             status = 0;
@@ -1083,23 +1157,19 @@
 
     /**
      * Tries to unschedule this task for execution. This method will
-     * typically succeed if this task is the most recently forked task
-     * by the current thread, and has not commenced executing in
-     * another thread.  This method may be useful when arranging
-     * alternative local processing of tasks that could have been, but
-     * were not, stolen.
-     *
-     * <p>This method may be invoked only from within {@code
-     * ForkJoinPool} computations (as may be determined using method
-     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
-     * result in exceptions or errors, possibly including {@code
-     * ClassCastException}.
+     * typically (but is not guaranteed to) succeed if this task is
+     * the most recently forked task by the current thread, and has
+     * not commenced executing in another thread.  This method may be
+     * useful when arranging alternative local processing of tasks
+     * that could have been, but were not, stolen.
      *
      * @return {@code true} if unforked
      */
     public boolean tryUnfork() {
-        return ((ForkJoinWorkerThread) Thread.currentThread())
-            .unpushTask(this);
+        Thread t;
+        return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
+                ((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) :
+                ForkJoinPool.tryExternalUnpush(this));
     }
 
     /**
@@ -1108,40 +1178,32 @@
      * value may be useful for heuristic decisions about whether to
      * fork other tasks.
      *
-     * <p>This method may be invoked only from within {@code
-     * ForkJoinPool} computations (as may be determined using method
-     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
-     * result in exceptions or errors, possibly including {@code
-     * ClassCastException}.
-     *
      * @return the number of tasks
      */
     public static int getQueuedTaskCount() {
-        return ((ForkJoinWorkerThread) Thread.currentThread())
-            .getQueueSize();
+        Thread t; ForkJoinPool.WorkQueue q;
+        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
+            q = ((ForkJoinWorkerThread)t).workQueue;
+        else
+            q = ForkJoinPool.commonSubmitterQueue();
+        return (q == null) ? 0 : q.queueSize();
     }
 
     /**
      * Returns an estimate of how many more locally queued tasks are
      * held by the current worker thread than there are other worker
-     * threads that might steal them.  This value may be useful for
+     * threads that might steal them, or zero if this thread is not
+     * operating in a ForkJoinPool. This value may be useful for
      * heuristic decisions about whether to fork other tasks. In many
      * usages of ForkJoinTasks, at steady state, each worker should
      * aim to maintain a small constant surplus (for example, 3) of
      * tasks, and to process computations locally if this threshold is
      * exceeded.
      *
-     * <p>This method may be invoked only from within {@code
-     * ForkJoinPool} computations (as may be determined using method
-     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
-     * result in exceptions or errors, possibly including {@code
-     * ClassCastException}.
-     *
      * @return the surplus number of tasks, which may be negative
      */
     public static int getSurplusQueuedTaskCount() {
-        return ((ForkJoinWorkerThread) Thread.currentThread())
-            .getEstimatedSurplusTaskCount();
+        return ForkJoinPool.getSurplusQueuedTaskCount();
     }
 
     // Extension methods
@@ -1167,15 +1229,18 @@
     protected abstract void setRawResult(V value);
 
     /**
-     * Immediately performs the base action of this task.  This method
-     * is designed to support extensions, and should not in general be
-     * called otherwise. The return value controls whether this task
-     * is considered to be done normally. It may return false in
+     * Immediately performs the base action of this task and returns
+     * true if, upon return from this method, this task is guaranteed
+     * to have completed normally. This method may return false
+     * otherwise, to indicate that this task is not necessarily
+     * complete (or is not known to be complete), for example in
      * asynchronous actions that require explicit invocations of
-     * {@link #complete} to become joinable. It may also throw an
-     * (unchecked) exception to indicate abnormal exit.
+     * completion methods. This method may also throw an (unchecked)
+     * exception to indicate abnormal exit. This method is designed to
+     * support extensions, and should not in general be called
+     * otherwise.
      *
-     * @return {@code true} if completed normally
+     * @return {@code true} if this task is known to have completed normally
      */
     protected abstract boolean exec();
 
@@ -1189,59 +1254,102 @@
      * primarily to support extensions, and is unlikely to be useful
      * otherwise.
      *
-     * <p>This method may be invoked only from within {@code
-     * ForkJoinPool} computations (as may be determined using method
-     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
-     * result in exceptions or errors, possibly including {@code
-     * ClassCastException}.
-     *
      * @return the next task, or {@code null} if none are available
      */
     protected static ForkJoinTask<?> peekNextLocalTask() {
-        return ((ForkJoinWorkerThread) Thread.currentThread())
-            .peekTask();
+        Thread t; ForkJoinPool.WorkQueue q;
+        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
+            q = ((ForkJoinWorkerThread)t).workQueue;
+        else
+            q = ForkJoinPool.commonSubmitterQueue();
+        return (q == null) ? null : q.peek();
     }
 
     /**
      * Unschedules and returns, without executing, the next task
-     * queued by the current thread but not yet executed.  This method
-     * is designed primarily to support extensions, and is unlikely to
-     * be useful otherwise.
-     *
-     * <p>This method may be invoked only from within {@code
-     * ForkJoinPool} computations (as may be determined using method
-     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
-     * result in exceptions or errors, possibly including {@code
-     * ClassCastException}.
+     * queued by the current thread but not yet executed, if the
+     * current thread is operating in a ForkJoinPool.  This method is
+     * designed primarily to support extensions, and is unlikely to be
+     * useful otherwise.
      *
      * @return the next task, or {@code null} if none are available
      */
     protected static ForkJoinTask<?> pollNextLocalTask() {
-        return ((ForkJoinWorkerThread) Thread.currentThread())
-            .pollLocalTask();
+        Thread t;
+        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
+            ((ForkJoinWorkerThread)t).workQueue.nextLocalTask() :
+            null;
     }
 
     /**
-     * Unschedules and returns, without executing, the next task
+     * If the current thread is operating in a ForkJoinPool,
+     * unschedules and returns, without executing, the next task
      * queued by the current thread but not yet executed, if one is
      * available, or if not available, a task that was forked by some
      * other thread, if available. Availability may be transient, so a
-     * {@code null} result does not necessarily imply quiescence
-     * of the pool this task is operating in.  This method is designed
+     * {@code null} result does not necessarily imply quiescence of
+     * the pool this task is operating in.  This method is designed
      * primarily to support extensions, and is unlikely to be useful
      * otherwise.
      *
-     * <p>This method may be invoked only from within {@code
-     * ForkJoinPool} computations (as may be determined using method
-     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
-     * result in exceptions or errors, possibly including {@code
-     * ClassCastException}.
-     *
      * @return a task, or {@code null} if none are available
      */
     protected static ForkJoinTask<?> pollTask() {
-        return ((ForkJoinWorkerThread) Thread.currentThread())
-            .pollTask();
+        Thread t; ForkJoinWorkerThread wt;
+        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
+            (wt = (ForkJoinWorkerThread)t).pool.nextTaskFor(wt.workQueue) :
+            null;
+    }
+
+    // tag operations
+
+    /**
+     * Returns the tag for this task.
+     *
+     * @return the tag for this task
+     * @since 1.8
+     */
+    public final short getForkJoinTaskTag() {
+        return (short)status;
+    }
+
+    /**
+     * Atomically sets the tag value for this task.
+     *
+     * @param tag the tag value
+     * @return the previous value of the tag
+     * @since 1.8
+     */
+    public final short setForkJoinTaskTag(short tag) {
+        for (int s;;) {
+            if (U.compareAndSwapInt(this, STATUS, s = status,
+                                    (s & ~SMASK) | (tag & SMASK)))
+                return (short)s;
+        }
+    }
+
+    /**
+     * Atomically conditionally sets the tag value for this task.
+     * Among other applications, tags can be used as visit markers
+     * in tasks operating on graphs, as in methods that check: {@code
+     * if (task.compareAndSetForkJoinTaskTag((short)0, (short)1))}
+     * before processing, otherwise exiting because the node has
+     * already been visited.
+     *
+     * @param e the expected tag value
+     * @param tag the new tag value
+     * @return true if successful; i.e., the current value was
+     * equal to e and is now tag.
+     * @since 1.8
+     */
+    public final boolean compareAndSetForkJoinTaskTag(short e, short tag) {
+        for (int s;;) {
+            if ((short)(s = status) != e)
+                return false;
+            if (U.compareAndSwapInt(this, STATUS, s,
+                                    (s & ~SMASK) | (tag & SMASK)))
+                return true;
+        }
     }
 
     /**
@@ -1252,21 +1360,33 @@
     static final class AdaptedRunnable<T> extends ForkJoinTask<T>
         implements RunnableFuture<T> {
         final Runnable runnable;
-        final T resultOnCompletion;
         T result;
         AdaptedRunnable(Runnable runnable, T result) {
             if (runnable == null) throw new NullPointerException();
             this.runnable = runnable;
-            this.resultOnCompletion = result;
+            this.result = result; // OK to set this even before completion
         }
-        public T getRawResult() { return result; }
-        public void setRawResult(T v) { result = v; }
-        public boolean exec() {
-            runnable.run();
-            result = resultOnCompletion;
-            return true;
+        public final T getRawResult() { return result; }
+        public final void setRawResult(T v) { result = v; }
+        public final boolean exec() { runnable.run(); return true; }
+        public final void run() { invoke(); }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    /**
+     * Adaptor for Runnables without results
+     */
+    static final class AdaptedRunnableAction extends ForkJoinTask<Void>
+        implements RunnableFuture<Void> {
+        final Runnable runnable;
+        AdaptedRunnableAction(Runnable runnable) {
+            if (runnable == null) throw new NullPointerException();
+            this.runnable = runnable;
         }
-        public void run() { invoke(); }
+        public final Void getRawResult() { return null; }
+        public final void setRawResult(Void v) { }
+        public final boolean exec() { runnable.run(); return true; }
+        public final void run() { invoke(); }
         private static final long serialVersionUID = 5232453952276885070L;
     }
 
@@ -1281,9 +1401,9 @@
             if (callable == null) throw new NullPointerException();
             this.callable = callable;
         }
-        public T getRawResult() { return result; }
-        public void setRawResult(T v) { result = v; }
-        public boolean exec() {
+        public final T getRawResult() { return result; }
+        public final void setRawResult(T v) { result = v; }
+        public final boolean exec() {
             try {
                 result = callable.call();
                 return true;
@@ -1295,7 +1415,7 @@
                 throw new RuntimeException(ex);
             }
         }
-        public void run() { invoke(); }
+        public final void run() { invoke(); }
         private static final long serialVersionUID = 2838392045355241008L;
     }
 
@@ -1308,7 +1428,7 @@
      * @return the task
      */
     public static ForkJoinTask<?> adapt(Runnable runnable) {
-        return new AdaptedRunnable<Void>(runnable, null);
+        return new AdaptedRunnableAction(runnable);
     }
 
     /**
@@ -1342,11 +1462,10 @@
     private static final long serialVersionUID = -7721805057305804111L;
 
     /**
-     * Saves the state to a stream (that is, serializes it).
+     * Saves this task to a stream (that is, serializes it).
      *
      * @serialData the current run status and the exception thrown
      * during execution, or {@code null} if none
-     * @param s the stream
      */
     private void writeObject(java.io.ObjectOutputStream s)
         throws java.io.IOException {
@@ -1355,9 +1474,7 @@
     }
 
     /**
-     * Reconstitutes the instance from a stream (that is, deserializes it).
-     *
-     * @param s the stream
+     * Reconstitutes this task from a stream (that is, deserializes it).
      */
     private void readObject(java.io.ObjectInputStream s)
         throws java.io.IOException, ClassNotFoundException {
@@ -1368,16 +1485,18 @@
     }
 
     // Unsafe mechanics
-    private static final sun.misc.Unsafe UNSAFE;
-    private static final long statusOffset;
+    private static final sun.misc.Unsafe U;
+    private static final long STATUS;
+
     static {
         exceptionTableLock = new ReentrantLock();
         exceptionTableRefQueue = new ReferenceQueue<Object>();
         exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
         try {
-            UNSAFE = sun.misc.Unsafe.getUnsafe();
-            statusOffset = UNSAFE.objectFieldOffset
-                (ForkJoinTask.class.getDeclaredField("status"));
+            U = sun.misc.Unsafe.getUnsafe();
+            Class<?> k = ForkJoinTask.class;
+            STATUS = U.objectFieldOffset
+                (k.getDeclaredField("status"));
         } catch (Exception e) {
             throw new Error(e);
         }
--- a/jdk/src/share/classes/java/util/concurrent/ForkJoinWorkerThread.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/concurrent/ForkJoinWorkerThread.java	Tue Jan 22 11:54:16 2013 -0800
@@ -35,9 +35,6 @@
 
 package java.util.concurrent;
 
-import java.util.Collection;
-import java.util.concurrent.RejectedExecutionException;
-
 /**
  * A thread managed by a {@link ForkJoinPool}, which executes
  * {@link ForkJoinTask}s.
@@ -54,238 +51,20 @@
  */
 public class ForkJoinWorkerThread extends Thread {
     /*
-     * Overview:
-     *
      * ForkJoinWorkerThreads are managed by ForkJoinPools and perform
-     * ForkJoinTasks. This class includes bookkeeping in support of
-     * worker activation, suspension, and lifecycle control described
-     * in more detail in the internal documentation of class
-     * ForkJoinPool. And as described further below, this class also
-     * includes special-cased support for some ForkJoinTask
-     * methods. But the main mechanics involve work-stealing:
-     *
-     * Work-stealing queues are special forms of Deques that support
-     * only three of the four possible end-operations -- push, pop,
-     * and deq (aka steal), under the further constraints that push
-     * and pop are called only from the owning thread, while deq may
-     * be called from other threads.  (If you are unfamiliar with
-     * them, you probably want to read Herlihy and Shavit's book "The
-     * Art of Multiprocessor programming", chapter 16 describing these
-     * in more detail before proceeding.)  The main work-stealing
-     * queue design is roughly similar to those in the papers "Dynamic
-     * Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005
-     * (http://research.sun.com/scalable/pubs/index.html) and
-     * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
-     * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
-     * The main differences ultimately stem from gc requirements that
-     * we null out taken slots as soon as we can, to maintain as small
-     * a footprint as possible even in programs generating huge
-     * numbers of tasks. To accomplish this, we shift the CAS
-     * arbitrating pop vs deq (steal) from being on the indices
-     * ("queueBase" and "queueTop") to the slots themselves (mainly
-     * via method "casSlotNull()"). So, both a successful pop and deq
-     * mainly entail a CAS of a slot from non-null to null.  Because
-     * we rely on CASes of references, we do not need tag bits on
-     * queueBase or queueTop.  They are simple ints as used in any
-     * circular array-based queue (see for example ArrayDeque).
-     * Updates to the indices must still be ordered in a way that
-     * guarantees that queueTop == queueBase means the queue is empty,
-     * but otherwise may err on the side of possibly making the queue
-     * appear nonempty when a push, pop, or deq have not fully
-     * committed. Note that this means that the deq operation,
-     * considered individually, is not wait-free. One thief cannot
-     * successfully continue until another in-progress one (or, if
-     * previously empty, a push) completes.  However, in the
-     * aggregate, we ensure at least probabilistic non-blockingness.
-     * If an attempted steal fails, a thief always chooses a different
-     * random victim target to try next. So, in order for one thief to
-     * progress, it suffices for any in-progress deq or new push on
-     * any empty queue to complete.
+     * ForkJoinTasks. For explanation, see the internal documentation
+     * of class ForkJoinPool.
      *
-     * This approach also enables support for "async mode" where local
-     * task processing is in FIFO, not LIFO order; simply by using a
-     * version of deq rather than pop when locallyFifo is true (as set
-     * by the ForkJoinPool).  This allows use in message-passing
-     * frameworks in which tasks are never joined.  However neither
-     * mode considers affinities, loads, cache localities, etc, so
-     * rarely provide the best possible performance on a given
-     * machine, but portably provide good throughput by averaging over
-     * these factors.  (Further, even if we did try to use such
-     * information, we do not usually have a basis for exploiting
-     * it. For example, some sets of tasks profit from cache
-     * affinities, but others are harmed by cache pollution effects.)
-     *
-     * When a worker would otherwise be blocked waiting to join a
-     * task, it first tries a form of linear helping: Each worker
-     * records (in field currentSteal) the most recent task it stole
-     * from some other worker. Plus, it records (in field currentJoin)
-     * the task it is currently actively joining. Method joinTask uses
-     * these markers to try to find a worker to help (i.e., steal back
-     * a task from and execute it) that could hasten completion of the
-     * actively joined task. In essence, the joiner executes a task
-     * that would be on its own local deque had the to-be-joined task
-     * not been stolen. This may be seen as a conservative variant of
-     * the approach in Wagner & Calder "Leapfrogging: a portable
-     * technique for implementing efficient futures" SIGPLAN Notices,
-     * 1993 (http://portal.acm.org/citation.cfm?id=155354). It differs
-     * in that: (1) We only maintain dependency links across workers
-     * upon steals, rather than use per-task bookkeeping.  This may
-     * require a linear scan of workers array to locate stealers, but
-     * usually doesn't because stealers leave hints (that may become
-     * stale/wrong) of where to locate them. This isolates cost to
-     * when it is needed, rather than adding to per-task overhead.
-     * (2) It is "shallow", ignoring nesting and potentially cyclic
-     * mutual steals.  (3) It is intentionally racy: field currentJoin
-     * is updated only while actively joining, which means that we
-     * miss links in the chain during long-lived tasks, GC stalls etc
-     * (which is OK since blocking in such cases is usually a good
-     * idea).  (4) We bound the number of attempts to find work (see
-     * MAX_HELP) and fall back to suspending the worker and if
-     * necessary replacing it with another.
-     *
-     * Efficient implementation of these algorithms currently relies
-     * on an uncomfortable amount of "Unsafe" mechanics. To maintain
-     * correct orderings, reads and writes of variable queueBase
-     * require volatile ordering.  Variable queueTop need not be
-     * volatile because non-local reads always follow those of
-     * queueBase.  Similarly, because they are protected by volatile
-     * queueBase reads, reads of the queue array and its slots by
-     * other threads do not need volatile load semantics, but writes
-     * (in push) require store order and CASes (in pop and deq)
-     * require (volatile) CAS semantics.  (Michael, Saraswat, and
-     * Vechev's algorithm has similar properties, but without support
-     * for nulling slots.)  Since these combinations aren't supported
-     * using ordinary volatiles, the only way to accomplish these
-     * efficiently is to use direct Unsafe calls. (Using external
-     * AtomicIntegers and AtomicReferenceArrays for the indices and
-     * array is significantly slower because of memory locality and
-     * indirection effects.)
-     *
-     * Further, performance on most platforms is very sensitive to
-     * placement and sizing of the (resizable) queue array.  Even
-     * though these queues don't usually become all that big, the
-     * initial size must be large enough to counteract cache
-     * contention effects across multiple queues (especially in the
-     * presence of GC cardmarking). Also, to improve thread-locality,
-     * queues are initialized after starting.
+     * This class just maintains links to its pool and WorkQueue.  The
+     * pool field is set immediately upon construction, but the
+     * workQueue field is not set until a call to registerWorker
+     * completes. This leads to a visibility race, that is tolerated
+     * by requiring that the workQueue field is only accessed by the
+     * owning thread.
      */
 
-    /**
-     * Mask for pool indices encoded as shorts
-     */
-    private static final int  SMASK  = 0xffff;
-
-    /**
-     * Capacity of work-stealing queue array upon initialization.
-     * Must be a power of two. Initial size must be at least 4, but is
-     * padded to minimize cache effects.
-     */
-    private static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
-
-    /**
-     * Maximum size for queue array. Must be a power of two
-     * less than or equal to 1 << (31 - width of array entry) to
-     * ensure lack of index wraparound, but is capped at a lower
-     * value to help users trap runaway computations.
-     */
-    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 24; // 16M
-
-    /**
-     * The work-stealing queue array. Size must be a power of two.
-     * Initialized when started (as opposed to when constructed), to
-     * improve memory locality.
-     */
-    ForkJoinTask<?>[] queue;
-
-    /**
-     * The pool this thread works in. Accessed directly by ForkJoinTask.
-     */
-    final ForkJoinPool pool;
-
-    /**
-     * Index (mod queue.length) of next queue slot to push to or pop
-     * from. It is written only by owner thread, and accessed by other
-     * threads only after reading (volatile) queueBase.  Both queueTop
-     * and queueBase are allowed to wrap around on overflow, but
-     * (queueTop - queueBase) still estimates size.
-     */
-    int queueTop;
-
-    /**
-     * Index (mod queue.length) of least valid queue slot, which is
-     * always the next position to steal from if nonempty.
-     */
-    volatile int queueBase;
-
-    /**
-     * The index of most recent stealer, used as a hint to avoid
-     * traversal in method helpJoinTask. This is only a hint because a
-     * worker might have had multiple steals and this only holds one
-     * of them (usually the most current). Declared non-volatile,
-     * relying on other prevailing sync to keep reasonably current.
-     */
-    int stealHint;
-
-    /**
-     * Index of this worker in pool array. Set once by pool before
-     * running, and accessed directly by pool to locate this worker in
-     * its workers array.
-     */
-    final int poolIndex;
-
-    /**
-     * Encoded record for pool task waits. Usages are always
-     * surrounded by volatile reads/writes
-     */
-    int nextWait;
-
-    /**
-     * Complement of poolIndex, offset by count of entries of task
-     * waits. Accessed by ForkJoinPool to manage event waiters.
-     */
-    volatile int eventCount;
-
-    /**
-     * Seed for random number generator for choosing steal victims.
-     * Uses Marsaglia xorshift. Must be initialized as nonzero.
-     */
-    int seed;
-
-    /**
-     * Number of steals. Directly accessed (and reset) by pool when
-     * idle.
-     */
-    int stealCount;
-
-    /**
-     * True if this worker should or did terminate
-     */
-    volatile boolean terminate;
-
-    /**
-     * Set to true before LockSupport.park; false on return
-     */
-    volatile boolean parked;
-
-    /**
-     * True if use local fifo, not default lifo, for local polling.
-     * Shadows value from ForkJoinPool.
-     */
-    final boolean locallyFifo;
-
-    /**
-     * The task most recently stolen from another worker (or
-     * submission queue).  All uses are surrounded by enough volatile
-     * reads/writes to maintain as non-volatile.
-     */
-    ForkJoinTask<?> currentSteal;
-
-    /**
-     * The task currently being joined, set only when actively trying
-     * to help other stealers in helpJoinTask. All uses are surrounded
-     * by enough volatile reads/writes to maintain as non-volatile.
-     */
-    ForkJoinTask<?> currentJoin;
+    final ForkJoinPool pool;                // the pool this thread works in
+    final ForkJoinPool.WorkQueue workQueue; // work-stealing mechanics
 
     /**
      * Creates a ForkJoinWorkerThread operating in the given pool.
@@ -294,20 +73,12 @@
      * @throws NullPointerException if pool is null
      */
     protected ForkJoinWorkerThread(ForkJoinPool pool) {
-        super(pool.nextWorkerName());
+        // Use a placeholder until a useful name can be set in registerWorker
+        super("aForkJoinWorkerThread");
         this.pool = pool;
-        int k = pool.registerWorker(this);
-        poolIndex = k;
-        eventCount = ~k & SMASK; // clear wait count
-        locallyFifo = pool.locallyFifo;
-        Thread.UncaughtExceptionHandler ueh = pool.ueh;
-        if (ueh != null)
-            setUncaughtExceptionHandler(ueh);
-        setDaemon(true);
+        this.workQueue = pool.registerWorker(this);
     }
 
-    // Public methods
-
     /**
      * Returns the pool hosting this thread.
      *
@@ -327,28 +98,9 @@
      * @return the index number
      */
     public int getPoolIndex() {
-        return poolIndex;
+        return workQueue.poolIndex;
     }
 
-    // Randomization
-
-    /**
-     * Computes next value for random victim probes and backoffs.
-     * Scans don't require a very high quality generator, but also not
-     * a crummy one.  Marsaglia xor-shift is cheap and works well
-     * enough.  Note: This is manually inlined in FJP.scan() to avoid
-     * writes inside busy loops.
-     */
-    private int nextSeed() {
-        int r = seed;
-        r ^= r << 13;
-        r ^= r >>> 17;
-        r ^= r << 5;
-        return seed = r;
-    }
-
-    // Run State management
-
     /**
      * Initializes internal state after construction but before
      * processing any tasks. If you override this method, you must
@@ -359,9 +111,6 @@
      * processing tasks.
      */
     protected void onStart() {
-        queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
-        int r = ForkJoinPool.workerSeedGenerator.nextInt();
-        seed = (r == 0) ? 1 : r; //  must be nonzero
     }
 
     /**
@@ -373,17 +122,6 @@
      * to an unrecoverable error, or {@code null} if completed normally
      */
     protected void onTermination(Throwable exception) {
-        try {
-            terminate = true;
-            cancelTasks();
-            pool.deregisterWorker(this, exception);
-        } catch (Throwable ex) {        // Shouldn't ever happen
-            if (exception == null)      // but if so, at least rethrown
-                exception = ex;
-        } finally {
-            if (exception != null)
-                UNSAFE.throwException(exception);
-        }
     }
 
     /**
@@ -395,604 +133,18 @@
         Throwable exception = null;
         try {
             onStart();
-            pool.work(this);
+            pool.runWorker(workQueue);
         } catch (Throwable ex) {
             exception = ex;
         } finally {
-            onTermination(exception);
-        }
-    }
-
-    /*
-     * Intrinsics-based atomic writes for queue slots. These are
-     * basically the same as methods in AtomicReferenceArray, but
-     * specialized for (1) ForkJoinTask elements (2) requirement that
-     * nullness and bounds checks have already been performed by
-     * callers and (3) effective offsets are known not to overflow
-     * from int to long (because of MAXIMUM_QUEUE_CAPACITY). We don't
-     * need corresponding version for reads: plain array reads are OK
-     * because they are protected by other volatile reads and are
-     * confirmed by CASes.
-     *
-     * Most uses don't actually call these methods, but instead
-     * contain inlined forms that enable more predictable
-     * optimization.  We don't define the version of write used in
-     * pushTask at all, but instead inline there a store-fenced array
-     * slot write.
-     *
-     * Also in most methods, as a performance (not correctness) issue,
-     * we'd like to encourage compilers not to arbitrarily postpone
-     * setting queueTop after writing slot.  Currently there is no
-     * intrinsic for arranging this, but using Unsafe putOrderedInt
-     * may be a preferable strategy on some compilers even though its
-     * main effect is a pre-, not post- fence. To simplify possible
-     * changes, the option is left in comments next to the associated
-     * assignments.
-     */
-
-    /**
-     * CASes slot i of array q from t to null. Caller must ensure q is
-     * non-null and index is in range.
-     */
-    private static final boolean casSlotNull(ForkJoinTask<?>[] q, int i,
-                                             ForkJoinTask<?> t) {
-        return UNSAFE.compareAndSwapObject(q, (i << ASHIFT) + ABASE, t, null);
-    }
-
-    /**
-     * Performs a volatile write of the given task at given slot of
-     * array q.  Caller must ensure q is non-null and index is in
-     * range. This method is used only during resets and backouts.
-     */
-    private static final void writeSlot(ForkJoinTask<?>[] q, int i,
-                                        ForkJoinTask<?> t) {
-        UNSAFE.putObjectVolatile(q, (i << ASHIFT) + ABASE, t);
-    }
-
-    // queue methods
-
-    /**
-     * Pushes a task. Call only from this thread.
-     *
-     * @param t the task. Caller must ensure non-null.
-     */
-    final void pushTask(ForkJoinTask<?> t) {
-        ForkJoinTask<?>[] q; int s, m;
-        if ((q = queue) != null) {    // ignore if queue removed
-            long u = (((s = queueTop) & (m = q.length - 1)) << ASHIFT) + ABASE;
-            UNSAFE.putOrderedObject(q, u, t);
-            queueTop = s + 1;         // or use putOrderedInt
-            if ((s -= queueBase) <= 2)
-                pool.signalWork();
-            else if (s == m)
-                growQueue();
-        }
-    }
-
-    /**
-     * Creates or doubles queue array.  Transfers elements by
-     * emulating steals (deqs) from old array and placing, oldest
-     * first, into new array.
-     */
-    private void growQueue() {
-        ForkJoinTask<?>[] oldQ = queue;
-        int size = oldQ != null ? oldQ.length << 1 : INITIAL_QUEUE_CAPACITY;
-        if (size > MAXIMUM_QUEUE_CAPACITY)
-            throw new RejectedExecutionException("Queue capacity exceeded");
-        if (size < INITIAL_QUEUE_CAPACITY)
-            size = INITIAL_QUEUE_CAPACITY;
-        ForkJoinTask<?>[] q = queue = new ForkJoinTask<?>[size];
-        int mask = size - 1;
-        int top = queueTop;
-        int oldMask;
-        if (oldQ != null && (oldMask = oldQ.length - 1) >= 0) {
-            for (int b = queueBase; b != top; ++b) {
-                long u = ((b & oldMask) << ASHIFT) + ABASE;
-                Object x = UNSAFE.getObjectVolatile(oldQ, u);
-                if (x != null && UNSAFE.compareAndSwapObject(oldQ, u, x, null))
-                    UNSAFE.putObjectVolatile
-                        (q, ((b & mask) << ASHIFT) + ABASE, x);
+            try {
+                onTermination(exception);
+            } catch (Throwable ex) {
+                if (exception == null)
+                    exception = ex;
+            } finally {
+                pool.deregisterWorker(this, exception);
             }
         }
     }
-
-    /**
-     * Tries to take a task from the base of the queue, failing if
-     * empty or contended. Note: Specializations of this code appear
-     * in locallyDeqTask and elsewhere.
-     *
-     * @return a task, or null if none or contended
-     */
-    final ForkJoinTask<?> deqTask() {
-        ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
-        if (queueTop != (b = queueBase) &&
-            (q = queue) != null && // must read q after b
-            (i = (q.length - 1) & b) >= 0 &&
-            (t = q[i]) != null && queueBase == b &&
-            UNSAFE.compareAndSwapObject(q, (i << ASHIFT) + ABASE, t, null)) {
-            queueBase = b + 1;
-            return t;
-        }
-        return null;
-    }
-
-    /**
-     * Tries to take a task from the base of own queue.  Called only
-     * by this thread.
-     *
-     * @return a task, or null if none
-     */
-    final ForkJoinTask<?> locallyDeqTask() {
-        ForkJoinTask<?> t; int m, b, i;
-        ForkJoinTask<?>[] q = queue;
-        if (q != null && (m = q.length - 1) >= 0) {
-            while (queueTop != (b = queueBase)) {
-                if ((t = q[i = m & b]) != null &&
-                    queueBase == b &&
-                    UNSAFE.compareAndSwapObject(q, (i << ASHIFT) + ABASE,
-                                                t, null)) {
-                    queueBase = b + 1;
-                    return t;
-                }
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Returns a popped task, or null if empty.
-     * Called only by this thread.
-     */
-    private ForkJoinTask<?> popTask() {
-        int m;
-        ForkJoinTask<?>[] q = queue;
-        if (q != null && (m = q.length - 1) >= 0) {
-            for (int s; (s = queueTop) != queueBase;) {
-                int i = m & --s;
-                long u = (i << ASHIFT) + ABASE; // raw offset
-                ForkJoinTask<?> t = q[i];
-                if (t == null)   // lost to stealer
-                    break;
-                if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
-                    queueTop = s; // or putOrderedInt
-                    return t;
-                }
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Specialized version of popTask to pop only if topmost element
-     * is the given task. Called only by this thread.
-     *
-     * @param t the task. Caller must ensure non-null.
-     */
-    final boolean unpushTask(ForkJoinTask<?> t) {
-        ForkJoinTask<?>[] q;
-        int s;
-        if ((q = queue) != null && (s = queueTop) != queueBase &&
-            UNSAFE.compareAndSwapObject
-            (q, (((q.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
-            queueTop = s; // or putOrderedInt
-            return true;
-        }
-        return false;
-    }
-
-    /**
-     * Returns next task, or null if empty or contended.
-     */
-    final ForkJoinTask<?> peekTask() {
-        int m;
-        ForkJoinTask<?>[] q = queue;
-        if (q == null || (m = q.length - 1) < 0)
-            return null;
-        int i = locallyFifo ? queueBase : (queueTop - 1);
-        return q[i & m];
-    }
-
-    // Support methods for ForkJoinPool
-
-    /**
-     * Runs the given task, plus any local tasks until queue is empty
-     */
-    final void execTask(ForkJoinTask<?> t) {
-        currentSteal = t;
-        for (;;) {
-            if (t != null)
-                t.doExec();
-            if (queueTop == queueBase)
-                break;
-            t = locallyFifo ? locallyDeqTask() : popTask();
-        }
-        ++stealCount;
-        currentSteal = null;
-    }
-
-    /**
-     * Removes and cancels all tasks in queue.  Can be called from any
-     * thread.
-     */
-    final void cancelTasks() {
-        ForkJoinTask<?> cj = currentJoin; // try to cancel ongoing tasks
-        if (cj != null && cj.status >= 0)
-            cj.cancelIgnoringExceptions();
-        ForkJoinTask<?> cs = currentSteal;
-        if (cs != null && cs.status >= 0)
-            cs.cancelIgnoringExceptions();
-        while (queueBase != queueTop) {
-            ForkJoinTask<?> t = deqTask();
-            if (t != null)
-                t.cancelIgnoringExceptions();
-        }
-    }
-
-    /**
-     * Drains tasks to given collection c.
-     *
-     * @return the number of tasks drained
-     */
-    final int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
-        int n = 0;
-        while (queueBase != queueTop) {
-            ForkJoinTask<?> t = deqTask();
-            if (t != null) {
-                c.add(t);
-                ++n;
-            }
-        }
-        return n;
-    }
-
-    // Support methods for ForkJoinTask
-
-    /**
-     * Returns an estimate of the number of tasks in the queue.
-     */
-    final int getQueueSize() {
-        return queueTop - queueBase;
-    }
-
-    /**
-     * Gets and removes a local task.
-     *
-     * @return a task, if available
-     */
-    final ForkJoinTask<?> pollLocalTask() {
-        return locallyFifo ? locallyDeqTask() : popTask();
-    }
-
-    /**
-     * Gets and removes a local or stolen task.
-     *
-     * @return a task, if available
-     */
-    final ForkJoinTask<?> pollTask() {
-        ForkJoinWorkerThread[] ws;
-        ForkJoinTask<?> t = pollLocalTask();
-        if (t != null || (ws = pool.workers) == null)
-            return t;
-        int n = ws.length; // cheap version of FJP.scan
-        int steps = n << 1;
-        int r = nextSeed();
-        int i = 0;
-        while (i < steps) {
-            ForkJoinWorkerThread w = ws[(i++ + r) & (n - 1)];
-            if (w != null && w.queueBase != w.queueTop && w.queue != null) {
-                if ((t = w.deqTask()) != null)
-                    return t;
-                i = 0;
-            }
-        }
-        return null;
-    }
-
-    /**
-     * The maximum stolen->joining link depth allowed in helpJoinTask,
-     * as well as the maximum number of retries (allowing on average
-     * one staleness retry per level) per attempt to instead try
-     * compensation.  Depths for legitimate chains are unbounded, but
-     * we use a fixed constant to avoid (otherwise unchecked) cycles
-     * and bound staleness of traversal parameters at the expense of
-     * sometimes blocking when we could be helping.
-     */
-    private static final int MAX_HELP = 16;
-
-    /**
-     * Possibly runs some tasks and/or blocks, until joinMe is done.
-     *
-     * @param joinMe the task to join
-     * @return completion status on exit
-     */
-    final int joinTask(ForkJoinTask<?> joinMe) {
-        ForkJoinTask<?> prevJoin = currentJoin;
-        currentJoin = joinMe;
-        for (int s, retries = MAX_HELP;;) {
-            if ((s = joinMe.status) < 0) {
-                currentJoin = prevJoin;
-                return s;
-            }
-            if (retries > 0) {
-                if (queueTop != queueBase) {
-                    if (!localHelpJoinTask(joinMe))
-                        retries = 0;           // cannot help
-                }
-                else if (retries == MAX_HELP >>> 1) {
-                    --retries;                 // check uncommon case
-                    if (tryDeqAndExec(joinMe) >= 0)
-                        Thread.yield();        // for politeness
-                }
-                else
-                    retries = helpJoinTask(joinMe) ? MAX_HELP : retries - 1;
-            }
-            else {
-                retries = MAX_HELP;           // restart if not done
-                pool.tryAwaitJoin(joinMe);
-            }
-        }
-    }
-
-    /**
-     * If present, pops and executes the given task, or any other
-     * cancelled task
-     *
-     * @return false if any other non-cancelled task exists in local queue
-     */
-    private boolean localHelpJoinTask(ForkJoinTask<?> joinMe) {
-        int s, i; ForkJoinTask<?>[] q; ForkJoinTask<?> t;
-        if ((s = queueTop) != queueBase && (q = queue) != null &&
-            (i = (q.length - 1) & --s) >= 0 &&
-            (t = q[i]) != null) {
-            if (t != joinMe && t.status >= 0)
-                return false;
-            if (UNSAFE.compareAndSwapObject
-                (q, (i << ASHIFT) + ABASE, t, null)) {
-                queueTop = s;           // or putOrderedInt
-                t.doExec();
-            }
-        }
-        return true;
-    }
-
-    /**
-     * Tries to locate and execute tasks for a stealer of the given
-     * task, or in turn one of its stealers, Traces
-     * currentSteal->currentJoin links looking for a thread working on
-     * a descendant of the given task and with a non-empty queue to
-     * steal back and execute tasks from.  The implementation is very
-     * branchy to cope with potential inconsistencies or loops
-     * encountering chains that are stale, unknown, or of length
-     * greater than MAX_HELP links.  All of these cases are dealt with
-     * by just retrying by caller.
-     *
-     * @param joinMe the task to join
-     * @param canSteal true if local queue is empty
-     * @return true if ran a task
-     */
-    private boolean helpJoinTask(ForkJoinTask<?> joinMe) {
-        boolean helped = false;
-        int m = pool.scanGuard & SMASK;
-        ForkJoinWorkerThread[] ws = pool.workers;
-        if (ws != null && ws.length > m && joinMe.status >= 0) {
-            int levels = MAX_HELP;              // remaining chain length
-            ForkJoinTask<?> task = joinMe;      // base of chain
-            outer:for (ForkJoinWorkerThread thread = this;;) {
-                // Try to find v, the stealer of task, by first using hint
-                ForkJoinWorkerThread v = ws[thread.stealHint & m];
-                if (v == null || v.currentSteal != task) {
-                    for (int j = 0; ;) {        // search array
-                        if ((v = ws[j]) != null && v.currentSteal == task) {
-                            thread.stealHint = j;
-                            break;              // save hint for next time
-                        }
-                        if (++j > m)
-                            break outer;        // can't find stealer
-                    }
-                }
-                // Try to help v, using specialized form of deqTask
-                for (;;) {
-                    ForkJoinTask<?>[] q; int b, i;
-                    if (joinMe.status < 0)
-                        break outer;
-                    if ((b = v.queueBase) == v.queueTop ||
-                        (q = v.queue) == null ||
-                        (i = (q.length-1) & b) < 0)
-                        break;                  // empty
-                    long u = (i << ASHIFT) + ABASE;
-                    ForkJoinTask<?> t = q[i];
-                    if (task.status < 0)
-                        break outer;            // stale
-                    if (t != null && v.queueBase == b &&
-                        UNSAFE.compareAndSwapObject(q, u, t, null)) {
-                        v.queueBase = b + 1;
-                        v.stealHint = poolIndex;
-                        ForkJoinTask<?> ps = currentSteal;
-                        currentSteal = t;
-                        t.doExec();
-                        currentSteal = ps;
-                        helped = true;
-                    }
-                }
-                // Try to descend to find v's stealer
-                ForkJoinTask<?> next = v.currentJoin;
-                if (--levels > 0 && task.status >= 0 &&
-                    next != null && next != task) {
-                    task = next;
-                    thread = v;
-                }
-                else
-                    break;  // max levels, stale, dead-end, or cyclic
-            }
-        }
-        return helped;
-    }
-
-    /**
-     * Performs an uncommon case for joinTask: If task t is at base of
-     * some workers queue, steals and executes it.
-     *
-     * @param t the task
-     * @return t's status
-     */
-    private int tryDeqAndExec(ForkJoinTask<?> t) {
-        int m = pool.scanGuard & SMASK;
-        ForkJoinWorkerThread[] ws = pool.workers;
-        if (ws != null && ws.length > m && t.status >= 0) {
-            for (int j = 0; j <= m; ++j) {
-                ForkJoinTask<?>[] q; int b, i;
-                ForkJoinWorkerThread v = ws[j];
-                if (v != null &&
-                    (b = v.queueBase) != v.queueTop &&
-                    (q = v.queue) != null &&
-                    (i = (q.length - 1) & b) >= 0 &&
-                    q[i] == t) {
-                    long u = (i << ASHIFT) + ABASE;
-                    if (v.queueBase == b &&
-                        UNSAFE.compareAndSwapObject(q, u, t, null)) {
-                        v.queueBase = b + 1;
-                        v.stealHint = poolIndex;
-                        ForkJoinTask<?> ps = currentSteal;
-                        currentSteal = t;
-                        t.doExec();
-                        currentSteal = ps;
-                    }
-                    break;
-                }
-            }
-        }
-        return t.status;
-    }
-
-    /**
-     * Implements ForkJoinTask.getSurplusQueuedTaskCount().  Returns
-     * an estimate of the number of tasks, offset by a function of
-     * number of idle workers.
-     *
-     * This method provides a cheap heuristic guide for task
-     * partitioning when programmers, frameworks, tools, or languages
-     * have little or no idea about task granularity.  In essence by
-     * offering this method, we ask users only about tradeoffs in
-     * overhead vs expected throughput and its variance, rather than
-     * how finely to partition tasks.
-     *
-     * In a steady state strict (tree-structured) computation, each
-     * thread makes available for stealing enough tasks for other
-     * threads to remain active. Inductively, if all threads play by
-     * the same rules, each thread should make available only a
-     * constant number of tasks.
-     *
-     * The minimum useful constant is just 1. But using a value of 1
-     * would require immediate replenishment upon each steal to
-     * maintain enough tasks, which is infeasible.  Further,
-     * partitionings/granularities of offered tasks should minimize
-     * steal rates, which in general means that threads nearer the top
-     * of computation tree should generate more than those nearer the
-     * bottom. In perfect steady state, each thread is at
-     * approximately the same level of computation tree. However,
-     * producing extra tasks amortizes the uncertainty of progress and
-     * diffusion assumptions.
-     *
-     * So, users will want to use values larger, but not much larger
-     * than 1 to both smooth over transient shortages and hedge
-     * against uneven progress; as traded off against the cost of
-     * extra task overhead. We leave the user to pick a threshold
-     * value to compare with the results of this call to guide
-     * decisions, but recommend values such as 3.
-     *
-     * When all threads are active, it is on average OK to estimate
-     * surplus strictly locally. In steady-state, if one thread is
-     * maintaining say 2 surplus tasks, then so are others. So we can
-     * just use estimated queue length (although note that (queueTop -
-     * queueBase) can be an overestimate because of stealers lagging
-     * increments of queueBase).  However, this strategy alone leads
-     * to serious mis-estimates in some non-steady-state conditions
-     * (ramp-up, ramp-down, other stalls). We can detect many of these
-     * by further considering the number of "idle" threads, that are
-     * known to have zero queued tasks, so compensate by a factor of
-     * (#idle/#active) threads.
-     */
-    final int getEstimatedSurplusTaskCount() {
-        return queueTop - queueBase - pool.idlePerActive();
-    }
-
-    /**
-     * Runs tasks until {@code pool.isQuiescent()}. We piggyback on
-     * pool's active count ctl maintenance, but rather than blocking
-     * when tasks cannot be found, we rescan until all others cannot
-     * find tasks either. The bracketing by pool quiescerCounts
-     * updates suppresses pool auto-shutdown mechanics that could
-     * otherwise prematurely terminate the pool because all threads
-     * appear to be inactive.
-     */
-    final void helpQuiescePool() {
-        boolean active = true;
-        ForkJoinTask<?> ps = currentSteal; // to restore below
-        ForkJoinPool p = pool;
-        p.addQuiescerCount(1);
-        for (;;) {
-            ForkJoinWorkerThread[] ws = p.workers;
-            ForkJoinWorkerThread v = null;
-            int n;
-            if (queueTop != queueBase)
-                v = this;
-            else if (ws != null && (n = ws.length) > 1) {
-                ForkJoinWorkerThread w;
-                int r = nextSeed(); // cheap version of FJP.scan
-                int steps = n << 1;
-                for (int i = 0; i < steps; ++i) {
-                    if ((w = ws[(i + r) & (n - 1)]) != null &&
-                        w.queueBase != w.queueTop) {
-                        v = w;
-                        break;
-                    }
-                }
-            }
-            if (v != null) {
-                ForkJoinTask<?> t;
-                if (!active) {
-                    active = true;
-                    p.addActiveCount(1);
-                }
-                if ((t = (v != this) ? v.deqTask() :
-                     locallyFifo ? locallyDeqTask() : popTask()) != null) {
-                    currentSteal = t;
-                    t.doExec();
-                    currentSteal = ps;
-                }
-            }
-            else {
-                if (active) {
-                    active = false;
-                    p.addActiveCount(-1);
-                }
-                if (p.isQuiescent()) {
-                    p.addActiveCount(1);
-                    p.addQuiescerCount(-1);
-                    break;
-                }
-            }
-        }
-    }
-
-    // Unsafe mechanics
-    private static final sun.misc.Unsafe UNSAFE;
-    private static final long ABASE;
-    private static final int ASHIFT;
-
-    static {
-        int s;
-        try {
-            UNSAFE = sun.misc.Unsafe.getUnsafe();
-            Class<?> a = ForkJoinTask[].class;
-            ABASE = UNSAFE.arrayBaseOffset(a);
-            s = UNSAFE.arrayIndexScale(a);
-        } catch (Exception e) {
-            throw new Error(e);
-        }
-        if ((s & (s-1)) != 0)
-            throw new Error("data type scale not a power of two");
-        ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
-    }
-
 }
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicBoolean.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicBoolean.java	Tue Jan 22 11:54:16 2013 -0800
@@ -111,7 +111,7 @@
      *
      * @param expect the expected value
      * @param update the new value
-     * @return true if successful.
+     * @return true if successful
      */
     public boolean weakCompareAndSet(boolean expect, boolean update) {
         int e = expect ? 1 : 0;
@@ -146,16 +146,16 @@
      * @return the previous value
      */
     public final boolean getAndSet(boolean newValue) {
-        for (;;) {
-            boolean current = get();
-            if (compareAndSet(current, newValue))
-                return current;
-        }
+        boolean prev;
+        do {
+            prev = get();
+        } while (!compareAndSet(prev, newValue));
+        return prev;
     }
 
     /**
      * Returns the String representation of the current value.
-     * @return the String representation of the current value.
+     * @return the String representation of the current value
      */
     public String toString() {
         return Boolean.toString(get());
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicInteger.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicInteger.java	Tue Jan 22 11:54:16 2013 -0800
@@ -115,11 +115,7 @@
      * @return the previous value
      */
     public final int getAndSet(int newValue) {
-        for (;;) {
-            int current = get();
-            if (compareAndSet(current, newValue))
-                return current;
-        }
+        return unsafe.getAndSetInt(this, valueOffset, newValue);
     }
 
     /**
@@ -145,7 +141,7 @@
      *
      * @param expect the expected value
      * @param update the new value
-     * @return true if successful.
+     * @return true if successful
      */
     public final boolean weakCompareAndSet(int expect, int update) {
         return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
@@ -157,12 +153,7 @@
      * @return the previous value
      */
     public final int getAndIncrement() {
-        for (;;) {
-            int current = get();
-            int next = current + 1;
-            if (compareAndSet(current, next))
-                return current;
-        }
+        return getAndAdd(1);
     }
 
     /**
@@ -171,12 +162,7 @@
      * @return the previous value
      */
     public final int getAndDecrement() {
-        for (;;) {
-            int current = get();
-            int next = current - 1;
-            if (compareAndSet(current, next))
-                return current;
-        }
+        return getAndAdd(-1);
     }
 
     /**
@@ -186,12 +172,7 @@
      * @return the previous value
      */
     public final int getAndAdd(int delta) {
-        for (;;) {
-            int current = get();
-            int next = current + delta;
-            if (compareAndSet(current, next))
-                return current;
-        }
+        return unsafe.getAndAddInt(this, valueOffset, delta);
     }
 
     /**
@@ -200,12 +181,7 @@
      * @return the updated value
      */
     public final int incrementAndGet() {
-        for (;;) {
-            int current = get();
-            int next = current + 1;
-            if (compareAndSet(current, next))
-                return next;
-        }
+        return getAndAdd(1) + 1;
     }
 
     /**
@@ -214,12 +190,7 @@
      * @return the updated value
      */
     public final int decrementAndGet() {
-        for (;;) {
-            int current = get();
-            int next = current - 1;
-            if (compareAndSet(current, next))
-                return next;
-        }
+        return getAndAdd(-1) - 1;
     }
 
     /**
@@ -229,17 +200,12 @@
      * @return the updated value
      */
     public final int addAndGet(int delta) {
-        for (;;) {
-            int current = get();
-            int next = current + delta;
-            if (compareAndSet(current, next))
-                return next;
-        }
+        return getAndAdd(delta) + delta;
     }
 
     /**
      * Returns the String representation of the current value.
-     * @return the String representation of the current value.
+     * @return the String representation of the current value
      */
     public String toString() {
         return Integer.toString(get());
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicIntegerArray.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicIntegerArray.java	Tue Jan 22 11:54:16 2013 -0800
@@ -145,12 +145,7 @@
      * @return the previous value
      */
     public final int getAndSet(int i, int newValue) {
-        long offset = checkedByteOffset(i);
-        while (true) {
-            int current = getRaw(offset);
-            if (compareAndSetRaw(offset, current, newValue))
-                return current;
-        }
+        return unsafe.getAndSetInt(array, checkedByteOffset(i), newValue);
     }
 
     /**
@@ -182,7 +177,7 @@
      * @param i the index
      * @param expect the expected value
      * @param update the new value
-     * @return true if successful.
+     * @return true if successful
      */
     public final boolean weakCompareAndSet(int i, int expect, int update) {
         return compareAndSet(i, expect, update);
@@ -216,12 +211,7 @@
      * @return the previous value
      */
     public final int getAndAdd(int i, int delta) {
-        long offset = checkedByteOffset(i);
-        while (true) {
-            int current = getRaw(offset);
-            if (compareAndSetRaw(offset, current, current + delta))
-                return current;
-        }
+        return unsafe.getAndAddInt(array, checkedByteOffset(i), delta);
     }
 
     /**
@@ -231,7 +221,7 @@
      * @return the updated value
      */
     public final int incrementAndGet(int i) {
-        return addAndGet(i, 1);
+        return getAndAdd(i, 1) + 1;
     }
 
     /**
@@ -241,7 +231,7 @@
      * @return the updated value
      */
     public final int decrementAndGet(int i) {
-        return addAndGet(i, -1);
+        return getAndAdd(i, -1) - 1;
     }
 
     /**
@@ -252,13 +242,7 @@
      * @return the updated value
      */
     public final int addAndGet(int i, int delta) {
-        long offset = checkedByteOffset(i);
-        while (true) {
-            int current = getRaw(offset);
-            int next = current + delta;
-            if (compareAndSetRaw(offset, current, next))
-                return next;
-        }
+        return getAndAdd(i, delta) + delta;
     }
 
     /**
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.java	Tue Jan 22 11:54:16 2013 -0800
@@ -159,11 +159,11 @@
      * @return the previous value
      */
     public int getAndSet(T obj, int newValue) {
-        for (;;) {
-            int current = get(obj);
-            if (compareAndSet(obj, current, newValue))
-                return current;
-        }
+        int prev;
+        do {
+            prev = get(obj);
+        } while (!compareAndSet(obj, prev, newValue));
+        return prev;
     }
 
     /**
@@ -174,12 +174,12 @@
      * @return the previous value
      */
     public int getAndIncrement(T obj) {
-        for (;;) {
-            int current = get(obj);
-            int next = current + 1;
-            if (compareAndSet(obj, current, next))
-                return current;
-        }
+        int prev, next;
+        do {
+            prev = get(obj);
+            next = prev + 1;
+        } while (!compareAndSet(obj, prev, next));
+        return prev;
     }
 
     /**
@@ -190,12 +190,12 @@
      * @return the previous value
      */
     public int getAndDecrement(T obj) {
-        for (;;) {
-            int current = get(obj);
-            int next = current - 1;
-            if (compareAndSet(obj, current, next))
-                return current;
-        }
+        int prev, next;
+        do {
+            prev = get(obj);
+            next = prev - 1;
+        } while (!compareAndSet(obj, prev, next));
+        return prev;
     }
 
     /**
@@ -207,12 +207,12 @@
      * @return the previous value
      */
     public int getAndAdd(T obj, int delta) {
-        for (;;) {
-            int current = get(obj);
-            int next = current + delta;
-            if (compareAndSet(obj, current, next))
-                return current;
-        }
+        int prev, next;
+        do {
+            prev = get(obj);
+            next = prev + delta;
+        } while (!compareAndSet(obj, prev, next));
+        return prev;
     }
 
     /**
@@ -223,12 +223,12 @@
      * @return the updated value
      */
     public int incrementAndGet(T obj) {
-        for (;;) {
-            int current = get(obj);
-            int next = current + 1;
-            if (compareAndSet(obj, current, next))
-                return next;
-        }
+        int prev, next;
+        do {
+            prev = get(obj);
+            next = prev + 1;
+        } while (!compareAndSet(obj, prev, next));
+        return next;
     }
 
     /**
@@ -239,12 +239,12 @@
      * @return the updated value
      */
     public int decrementAndGet(T obj) {
-        for (;;) {
-            int current = get(obj);
-            int next = current - 1;
-            if (compareAndSet(obj, current, next))
-                return next;
-        }
+        int prev, next;
+        do {
+            prev = get(obj);
+            next = prev - 1;
+        } while (!compareAndSet(obj, prev, next));
+        return next;
     }
 
     /**
@@ -256,12 +256,12 @@
      * @return the updated value
      */
     public int addAndGet(T obj, int delta) {
-        for (;;) {
-            int current = get(obj);
-            int next = current + delta;
-            if (compareAndSet(obj, current, next))
-                return next;
-        }
+        int prev, next;
+        do {
+            prev = get(obj);
+            next = prev + delta;
+        } while (!compareAndSet(obj, prev, next));
+        return next;
     }
 
     /**
@@ -361,6 +361,36 @@
             return unsafe.getIntVolatile(obj, offset);
         }
 
+        public int getAndSet(T obj, int newValue) {
+            if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
+            return unsafe.getAndSetInt(obj, offset, newValue);
+        }
+
+        public int getAndIncrement(T obj) {
+            return getAndAdd(obj, 1);
+        }
+
+        public int getAndDecrement(T obj) {
+            return getAndAdd(obj, -1);
+        }
+
+        public int getAndAdd(T obj, int delta) {
+            if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
+            return unsafe.getAndAddInt(obj, offset, delta);
+        }
+
+        public int incrementAndGet(T obj) {
+            return getAndAdd(obj, 1) + 1;
+        }
+
+        public int decrementAndGet(T obj) {
+             return getAndAdd(obj, -1) - 1;
+        }
+
+        public int addAndGet(T obj, int delta) {
+            return getAndAdd(obj, delta) + delta;
+        }
+
         private void ensureProtectedAccess(T obj) {
             if (cclass.isInstance(obj)) {
                 return;
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicLong.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicLong.java	Tue Jan 22 11:54:16 2013 -0800
@@ -129,11 +129,7 @@
      * @return the previous value
      */
     public final long getAndSet(long newValue) {
-        while (true) {
-            long current = get();
-            if (compareAndSet(current, newValue))
-                return current;
-        }
+        return unsafe.getAndSetLong(this, valueOffset, newValue);
     }
 
     /**
@@ -159,7 +155,7 @@
      *
      * @param expect the expected value
      * @param update the new value
-     * @return true if successful.
+     * @return true if successful
      */
     public final boolean weakCompareAndSet(long expect, long update) {
         return unsafe.compareAndSwapLong(this, valueOffset, expect, update);
@@ -171,12 +167,7 @@
      * @return the previous value
      */
     public final long getAndIncrement() {
-        while (true) {
-            long current = get();
-            long next = current + 1;
-            if (compareAndSet(current, next))
-                return current;
-        }
+        return getAndAdd(1);
     }
 
     /**
@@ -185,12 +176,7 @@
      * @return the previous value
      */
     public final long getAndDecrement() {
-        while (true) {
-            long current = get();
-            long next = current - 1;
-            if (compareAndSet(current, next))
-                return current;
-        }
+        return getAndAdd(-1);
     }
 
     /**
@@ -200,12 +186,7 @@
      * @return the previous value
      */
     public final long getAndAdd(long delta) {
-        while (true) {
-            long current = get();
-            long next = current + delta;
-            if (compareAndSet(current, next))
-                return current;
-        }
+        return unsafe.getAndAddLong(this, valueOffset, delta);
     }
 
     /**
@@ -214,12 +195,7 @@
      * @return the updated value
      */
     public final long incrementAndGet() {
-        for (;;) {
-            long current = get();
-            long next = current + 1;
-            if (compareAndSet(current, next))
-                return next;
-        }
+        return getAndAdd(1) + 1;
     }
 
     /**
@@ -228,12 +204,7 @@
      * @return the updated value
      */
     public final long decrementAndGet() {
-        for (;;) {
-            long current = get();
-            long next = current - 1;
-            if (compareAndSet(current, next))
-                return next;
-        }
+        return getAndAdd(-1) - 1;
     }
 
     /**
@@ -243,17 +214,12 @@
      * @return the updated value
      */
     public final long addAndGet(long delta) {
-        for (;;) {
-            long current = get();
-            long next = current + delta;
-            if (compareAndSet(current, next))
-                return next;
-        }
+        return getAndAdd(delta) + delta;
     }
 
     /**
      * Returns the String representation of the current value.
-     * @return the String representation of the current value.
+     * @return the String representation of the current value
      */
     public String toString() {
         return Long.toString(get());
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicLongArray.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicLongArray.java	Tue Jan 22 11:54:16 2013 -0800
@@ -144,12 +144,7 @@
      * @return the previous value
      */
     public final long getAndSet(int i, long newValue) {
-        long offset = checkedByteOffset(i);
-        while (true) {
-            long current = getRaw(offset);
-            if (compareAndSetRaw(offset, current, newValue))
-                return current;
-        }
+        return unsafe.getAndSetLong(array, checkedByteOffset(i), newValue);
     }
 
     /**
@@ -181,7 +176,7 @@
      * @param i the index
      * @param expect the expected value
      * @param update the new value
-     * @return true if successful.
+     * @return true if successful
      */
     public final boolean weakCompareAndSet(int i, long expect, long update) {
         return compareAndSet(i, expect, update);
@@ -215,12 +210,7 @@
      * @return the previous value
      */
     public final long getAndAdd(int i, long delta) {
-        long offset = checkedByteOffset(i);
-        while (true) {
-            long current = getRaw(offset);
-            if (compareAndSetRaw(offset, current, current + delta))
-                return current;
-        }
+        return unsafe.getAndAddLong(array, checkedByteOffset(i), delta);
     }
 
     /**
@@ -230,7 +220,7 @@
      * @return the updated value
      */
     public final long incrementAndGet(int i) {
-        return addAndGet(i, 1);
+        return getAndAdd(i, 1) + 1;
     }
 
     /**
@@ -240,7 +230,7 @@
      * @return the updated value
      */
     public final long decrementAndGet(int i) {
-        return addAndGet(i, -1);
+        return getAndAdd(i, -1) - 1;
     }
 
     /**
@@ -251,13 +241,7 @@
      * @return the updated value
      */
     public long addAndGet(int i, long delta) {
-        long offset = checkedByteOffset(i);
-        while (true) {
-            long current = getRaw(offset);
-            long next = current + delta;
-            if (compareAndSetRaw(offset, current, next))
-                return next;
-        }
+        return getAndAdd(i, delta) + delta;
     }
 
     /**
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java	Tue Jan 22 11:54:16 2013 -0800
@@ -98,7 +98,7 @@
      * @param obj An object whose field to conditionally set
      * @param expect the expected value
      * @param update the new value
-     * @return true if successful.
+     * @return true if successful
      * @throws ClassCastException if {@code obj} is not an instance
      * of the class possessing the field established in the constructor.
      */
@@ -118,7 +118,7 @@
      * @param obj An object whose field to conditionally set
      * @param expect the expected value
      * @param update the new value
-     * @return true if successful.
+     * @return true if successful
      * @throws ClassCastException if {@code obj} is not an instance
      * of the class possessing the field established in the constructor.
      */
@@ -162,11 +162,11 @@
      * @return the previous value
      */
     public long getAndSet(T obj, long newValue) {
-        for (;;) {
-            long current = get(obj);
-            if (compareAndSet(obj, current, newValue))
-                return current;
-        }
+        long prev;
+        do {
+            prev = get(obj);
+        } while (!compareAndSet(obj, prev, newValue));
+        return prev;
     }
 
     /**
@@ -177,12 +177,12 @@
      * @return the previous value
      */
     public long getAndIncrement(T obj) {
-        for (;;) {
-            long current = get(obj);
-            long next = current + 1;
-            if (compareAndSet(obj, current, next))
-                return current;
-        }
+        long prev, next;
+        do {
+            prev = get(obj);
+            next = prev + 1;
+        } while (!compareAndSet(obj, prev, next));
+        return prev;
     }
 
     /**
@@ -193,12 +193,12 @@
      * @return the previous value
      */
     public long getAndDecrement(T obj) {
-        for (;;) {
-            long current = get(obj);
-            long next = current - 1;
-            if (compareAndSet(obj, current, next))
-                return current;
-        }
+        long prev, next;
+        do {
+            prev = get(obj);
+            next = prev - 1;
+        } while (!compareAndSet(obj, prev, next));
+        return prev;
     }
 
     /**
@@ -210,12 +210,12 @@
      * @return the previous value
      */
     public long getAndAdd(T obj, long delta) {
-        for (;;) {
-            long current = get(obj);
-            long next = current + delta;
-            if (compareAndSet(obj, current, next))
-                return current;
-        }
+        long prev, next;
+        do {
+            prev = get(obj);
+            next = prev + delta;
+        } while (!compareAndSet(obj, prev, next));
+        return prev;
     }
 
     /**
@@ -226,12 +226,12 @@
      * @return the updated value
      */
     public long incrementAndGet(T obj) {
-        for (;;) {
-            long current = get(obj);
-            long next = current + 1;
-            if (compareAndSet(obj, current, next))
-                return next;
-        }
+        long prev, next;
+        do {
+            prev = get(obj);
+            next = prev + 1;
+        } while (!compareAndSet(obj, prev, next));
+        return next;
     }
 
     /**
@@ -242,12 +242,12 @@
      * @return the updated value
      */
     public long decrementAndGet(T obj) {
-        for (;;) {
-            long current = get(obj);
-            long next = current - 1;
-            if (compareAndSet(obj, current, next))
-                return next;
-        }
+        long prev, next;
+        do {
+            prev = get(obj);
+            next = prev - 1;
+        } while (!compareAndSet(obj, prev, next));
+        return next;
     }
 
     /**
@@ -259,12 +259,12 @@
      * @return the updated value
      */
     public long addAndGet(T obj, long delta) {
-        for (;;) {
-            long current = get(obj);
-            long next = current + delta;
-            if (compareAndSet(obj, current, next))
-                return next;
-        }
+        long prev, next;
+        do {
+            prev = get(obj);
+            next = prev + delta;
+        } while (!compareAndSet(obj, prev, next));
+        return next;
     }
 
     private static class CASUpdater<T> extends AtomicLongFieldUpdater<T> {
@@ -345,6 +345,36 @@
             return unsafe.getLongVolatile(obj, offset);
         }
 
+        public long getAndSet(T obj, long newValue) {
+            if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
+            return unsafe.getAndSetLong(obj, offset, newValue);
+        }
+
+        public long getAndIncrement(T obj) {
+            return getAndAdd(obj, 1);
+        }
+
+        public long getAndDecrement(T obj) {
+            return getAndAdd(obj, -1);
+        }
+
+        public long getAndAdd(T obj, long delta) {
+            if (obj == null || obj.getClass() != tclass || cclass != null) fullCheck(obj);
+            return unsafe.getAndAddLong(obj, offset, delta);
+        }
+
+        public long incrementAndGet(T obj) {
+            return getAndAdd(obj, 1) + 1;
+        }
+
+        public long decrementAndGet(T obj) {
+             return getAndAdd(obj, -1) - 1;
+        }
+
+        public long addAndGet(T obj, long delta) {
+            return getAndAdd(obj, delta) + delta;
+        }
+
         private void ensureProtectedAccess(T obj) {
             if (cclass.isInstance(obj)) {
                 return;
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicReference.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicReference.java	Tue Jan 22 11:54:16 2013 -0800
@@ -124,7 +124,7 @@
      *
      * @param expect the expected value
      * @param update the new value
-     * @return true if successful.
+     * @return true if successful
      */
     public final boolean weakCompareAndSet(V expect, V update) {
         return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
@@ -136,17 +136,14 @@
      * @param newValue the new value
      * @return the previous value
      */
+    @SuppressWarnings("unchecked")
     public final V getAndSet(V newValue) {
-        while (true) {
-            V x = get();
-            if (compareAndSet(x, newValue))
-                return x;
-        }
+        return (V)unsafe.getAndSetObject(this, valueOffset, newValue);
     }
 
     /**
      * Returns the String representation of the current value.
-     * @return the String representation of the current value.
+     * @return the String representation of the current value
      */
     public String toString() {
         return String.valueOf(get());
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicReferenceArray.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicReferenceArray.java	Tue Jan 22 11:54:16 2013 -0800
@@ -159,13 +159,9 @@
      * @param newValue the new value
      * @return the previous value
      */
+    @SuppressWarnings("unchecked")
     public final E getAndSet(int i, E newValue) {
-        long offset = checkedByteOffset(i);
-        while (true) {
-            E current = getRaw(offset);
-            if (compareAndSetRaw(offset, current, newValue))
-                return current;
-        }
+        return (E)unsafe.getAndSetObject(array, checkedByteOffset(i), newValue);
     }
 
     /**
@@ -197,7 +193,7 @@
      * @param i the index
      * @param expect the expected value
      * @param update the new value
-     * @return true if successful.
+     * @return true if successful
      */
     public final boolean weakCompareAndSet(int i, E expect, E update) {
         return compareAndSet(i, expect, update);
--- a/jdk/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java	Tue Jan 22 11:54:16 2013 -0800
@@ -116,7 +116,7 @@
      * @param obj An object whose field to conditionally set
      * @param expect the expected value
      * @param update the new value
-     * @return true if successful.
+     * @return true if successful
      */
     public abstract boolean compareAndSet(T obj, V expect, V update);
 
@@ -134,7 +134,7 @@
      * @param obj An object whose field to conditionally set
      * @param expect the expected value
      * @param update the new value
-     * @return true if successful.
+     * @return true if successful
      */
     public abstract boolean weakCompareAndSet(T obj, V expect, V update);
 
@@ -176,11 +176,11 @@
      * @return the previous value
      */
     public V getAndSet(T obj, V newValue) {
-        for (;;) {
-            V current = get(obj);
-            if (compareAndSet(obj, current, newValue))
-                return current;
-        }
+        V prev;
+        do {
+            prev = get(obj);
+        } while (!compareAndSet(obj, prev, newValue));
+        return prev;
     }
 
     private static final class AtomicReferenceFieldUpdaterImpl<T,V>
@@ -321,6 +321,15 @@
             return (V)unsafe.getObjectVolatile(obj, offset);
         }
 
+        @SuppressWarnings("unchecked")
+        public V getAndSet(T obj, V newValue) {
+            if (obj == null || obj.getClass() != tclass || cclass != null ||
+                (newValue != null && vclass != null &&
+                 vclass != newValue.getClass()))
+                updateCheck(obj, newValue);
+            return (V)unsafe.getAndSetObject(obj, offset, newValue);
+        }
+
         private void ensureProtectedAccess(T obj) {
             if (cclass.isInstance(obj)) {
                 return;
--- a/jdk/src/share/classes/java/util/function/BinaryOperator.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/function/BinaryOperator.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/classes/java/util/function/Block.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/function/Block.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/classes/java/util/function/DoubleBlock.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/function/DoubleBlock.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/classes/java/util/function/Function.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/function/Function.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/classes/java/util/function/IntBlock.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/function/IntBlock.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/classes/java/util/function/LongBlock.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/function/LongBlock.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/classes/java/util/function/Predicate.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/java/util/function/Predicate.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/classes/javax/crypto/Cipher.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/javax/crypto/Cipher.java	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -104,17 +104,30 @@
  * must be supplied to GCM/CCM implementations (via the {@code
  * updateAAD} methods) <b>before</b> the ciphertext is processed (via
  * the {@code update} and {@code doFinal} methods).
- *
+ * <p>
+ * Note that GCM mode has a uniqueness requirement on IVs used in
+ * encryption with a given key. When IVs are repeated for GCM
+ * encryption, such usages are subject to forgery attacks. Thus, after
+ * each encryption operation using GCM mode, callers should re-initialize
+ * the cipher objects with GCM parameters which has a different IV value.
  * <pre>
- *     GCMParameterSpec s = new GCMParameterSpec(...);
+ *     GCMParameterSpec s = ...;
  *     cipher.init(..., s);
  *
- *     // If the GCMParameterSpec is needed again
- *     cipher.getParameters().getParameterSpec(GCMParameterSpec.class));
+ *     // If the GCM parameters were generated by the provider, it can
+ *     // be retrieved by:
+ *     // cipher.getParameters().getParameterSpec(GCMParameterSpec.class);
  *
  *     cipher.updateAAD(...);  // AAD
  *     cipher.update(...);     // Multi-part update
  *     cipher.doFinal(...);    // conclusion of operation
+ *
+ *     // Use a different IV value for every encryption
+ *     byte[] newIv = ...;
+ *     s = new GCMParameterSpec(s.getTLen(), newIv);
+ *     cipher.init(..., s);
+ *     ...
+ *
  * </pre>
  * Every implementation of the Java platform is required to support
  * the following standard <code>Cipher</code> transformations with the keysizes
--- a/jdk/src/share/classes/javax/crypto/spec/GCMParameterSpec.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/javax/crypto/spec/GCMParameterSpec.java	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -43,7 +43,7 @@
  * (Additional Authenticated Data (AAD), Keys, block ciphers,
  * plain/ciphertext and authentication tags) are handled in the {@code
  * Cipher} class.
-  <p>
+ * <p>
  * Please see <a href="http://www.ietf.org/rfc/rfc5116.txt"> RFC 5116
  * </a> for more information on the Authenticated Encryption with
  * Associated Data (AEAD) algorithm, and <a href=
--- a/jdk/src/share/classes/javax/management/MBeanFeatureInfo.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/javax/management/MBeanFeatureInfo.java	Tue Jan 22 11:54:16 2013 -0800
@@ -239,12 +239,10 @@
         case 1:
             final String[] names = (String[])in.readObject();
 
-            if (names.length == 0) {
-                descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR;
-            } else {
-                final Object[] values = (Object[])in.readObject();
-                descriptor = new ImmutableDescriptor(names, values);
-            }
+            final Object[] values = (Object[]) in.readObject();
+            descriptor = (names.length == 0) ?
+                ImmutableDescriptor.EMPTY_DESCRIPTOR :
+                new ImmutableDescriptor(names, values);
 
             break;
         case 0:
--- a/jdk/src/share/classes/javax/management/MBeanInfo.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/javax/management/MBeanInfo.java	Tue Jan 22 11:54:16 2013 -0800
@@ -704,12 +704,10 @@
         case 1:
             final String[] names = (String[])in.readObject();
 
-            if (names.length == 0) {
-                descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR;
-            } else {
-                final Object[] values = (Object[])in.readObject();
-                descriptor = new ImmutableDescriptor(names, values);
-            }
+            final Object[] values = (Object[]) in.readObject();
+            descriptor = (names.length == 0) ?
+                ImmutableDescriptor.EMPTY_DESCRIPTOR :
+                new ImmutableDescriptor(names, values);
 
             break;
         case 0:
--- a/jdk/src/share/classes/javax/management/remote/JMXConnectorFactory.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/javax/management/remote/JMXConnectorFactory.java	Tue Jan 22 11:54:16 2013 -0800
@@ -137,8 +137,10 @@
  * JAR conventions for service providers</a>, where the service
  * interface is <code>JMXConnectorProvider</code>.</p>
  *
- * <p>Every implementation must support the RMI connector protocols,
- * specified with the string <code>rmi</code> or
+ * <p>Every implementation must support the RMI connector protocol with
+ * the default RMI transport, specified with string <code>rmi</code>.
+ * An implementation may optionally support the RMI connector protocol
+ * with the RMI/IIOP transport, specified with the string
  * <code>iiop</code>.</p>
  *
  * <p>Once a provider is found, the result of the
--- a/jdk/src/share/classes/javax/management/remote/JMXConnectorServerFactory.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/javax/management/remote/JMXConnectorServerFactory.java	Tue Jan 22 11:54:16 2013 -0800
@@ -129,8 +129,10 @@
  * JAR conventions for service providers</a>, where the service
  * interface is <code>JMXConnectorServerProvider</code>.</p>
  *
- * <p>Every implementation must support the RMI connector protocols,
- * specified with the string <code>rmi</code> or
+ * <p>Every implementation must support the RMI connector protocol with
+ * the default RMI transport, specified with string <code>rmi</code>.
+ * An implementation may optionally support the RMI connector protocol
+ * with the RMI/IIOP transport, specified with the string
  * <code>iiop</code>.</p>
  *
  * <p>Once a provider is found, the result of the
--- a/jdk/src/share/classes/javax/management/remote/rmi/RMIConnector.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/javax/management/remote/rmi/RMIConnector.java	Tue Jan 22 11:54:16 2013 -0800
@@ -238,10 +238,21 @@
     //--------------------------------------------------------------------
     // implements JMXConnector interface
     //--------------------------------------------------------------------
+
+    /**
+     * @throws IOException if the connection could not be made because of a
+     *   communication problem, or in the case of the {@code iiop} protocol,
+     *   that RMI/IIOP is not supported
+     */
     public void connect() throws IOException {
         connect(null);
     }
 
+    /**
+     * @throws IOException if the connection could not be made because of a
+     *   communication problem, or in the case of the {@code iiop} protocol,
+     *   that RMI/IIOP is not supported
+     */
     public synchronized void connect(Map<String,?> environment)
     throws IOException {
         final boolean tracing = logger.traceOn();
--- a/jdk/src/share/classes/javax/management/remote/rmi/RMIConnectorServer.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/javax/management/remote/rmi/RMIConnectorServer.java	Tue Jan 22 11:54:16 2013 -0800
@@ -337,7 +337,8 @@
      * @exception IllegalStateException if the connector server has
      * not been attached to an MBean server.
      * @exception IOException if the connector server cannot be
-     * started.
+     * started, or in the case of the {@code iiop} protocol, that
+     * RMI/IIOP is not supported.
      */
     public synchronized void start() throws IOException {
         final boolean tracing = logger.traceOn();
--- a/jdk/src/share/classes/javax/management/remote/rmi/package.html	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/javax/management/remote/rmi/package.html	Tue Jan 22 11:54:16 2013 -0800
@@ -36,8 +36,8 @@
       that different implementations of the RMI connector can
       interoperate.</p>
 
-    <p>The RMI connector supports both the JRMP and the IIOP transports
-      for RMI.</p>
+    <p>The RMI connector supports the JRMP transport for RMI, and
+      optionally the IIOP transport.</p>
 
     <p>Like most connectors in the JMX Remote API, an RMI connector
       usually has an address, which
--- a/jdk/src/share/classes/javax/security/auth/kerberos/package.html	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/javax/security/auth/kerberos/package.html	Tue Jan 22 11:54:16 2013 -0800
@@ -43,10 +43,15 @@
 
     You can provide the name of your default realm and Key Distribution
     Center (KDC) host for that realm using the system properties
-    java.security.krb5.realm and java.security.krb5.kdc. Alternatively, you 
-    can provide an MIT style configuration file called krb5.conf in
-    &lt;java-home&gt;/lib/security. If you place this file elsewhere, you can
-    indicate that location via the system property java.security.krb5.conf.<p>
+    {@code java.security.krb5.realm} and {@code java.security.krb5.kdc}.
+    Both properties must be set.
+    Alternatively, the {@code java.security.krb5.conf} system property can
+    be set to the location of an MIT style {@code krb5.conf} configuration
+    file. If none of these system properties are set, the {@code krb5.conf}
+    file is searched for in an implementation-specific manner. Typically,
+    an implementation will first look for a {@code krb5.conf} file in
+    {@code <java-home>/lib/security} and failing that, in an OS-specific
+    location.<p>
 <!--
 <h2>Package Specification</h2>
 
--- a/jdk/src/share/classes/javax/swing/JTable.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/javax/swing/JTable.java	Tue Jan 22 11:54:16 2013 -0800
@@ -3953,7 +3953,7 @@
                     break;
                 case TableModelEvent.INSERT:
                     modelSelection.insertIndexInterval(change.startModelIndex,
-                                                       change.endModelIndex,
+                                                       change.length,
                                                        true);
                     break;
                 default:
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/org/xml/sax/Attributes.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,281 @@
+/*
+ * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// Attributes.java - attribute list with Namespace support
+// http://www.saxproject.org
+// Written by David Megginson
+// NO WARRANTY!  This class is in the public domain.
+// $Id: Attributes.java,v 1.2 2004/11/03 22:44:51 jsuttor Exp $
+
+package jdk.internal.org.xml.sax;
+
+
+/**
+ * Interface for a list of XML attributes.
+ *
+ * <blockquote>
+ * <em>This module, both source code and documentation, is in the
+ * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
+ * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
+ * for further information.
+ * </blockquote>
+ *
+ * <p>This interface allows access to a list of attributes in
+ * three different ways:</p>
+ *
+ * <ol>
+ * <li>by attribute index;</li>
+ * <li>by Namespace-qualified name; or</li>
+ * <li>by qualified (prefixed) name.</li>
+ * </ol>
+ *
+ * <p>The list will not contain attributes that were declared
+ * #IMPLIED but not specified in the start tag.  It will also not
+ * contain attributes used as Namespace declarations (xmlns*) unless
+ * the <code>http://xml.org/sax/features/namespace-prefixes</code>
+ * feature is set to <var>true</var> (it is <var>false</var> by
+ * default).
+ * Because SAX2 conforms to the original "Namespaces in XML"
+ * recommendation, it normally does not
+ * give namespace declaration attributes a namespace URI.
+ * </p>
+ *
+ * <p>Some SAX2 parsers may support using an optional feature flag
+ * (<code>http://xml.org/sax/features/xmlns-uris</code>) to request
+ * that those attributes be given URIs, conforming to a later
+ * backwards-incompatible revision of that recommendation.  (The
+ * attribute's "local name" will be the prefix, or "xmlns" when
+ * defining a default element namespace.)  For portability, handler
+ * code should always resolve that conflict, rather than requiring
+ * parsers that can change the setting of that feature flag.  </p>
+ *
+ * <p>If the namespace-prefixes feature (see above) is
+ * <var>false</var>, access by qualified name may not be available; if
+ * the <code>http://xml.org/sax/features/namespaces</code> feature is
+ * <var>false</var>, access by Namespace-qualified names may not be
+ * available.</p>
+ *
+ * <p>This interface replaces the now-deprecated SAX1 {@link
+ * org.xml.sax.AttributeList AttributeList} interface, which does not
+ * contain Namespace support.  In addition to Namespace support, it
+ * adds the <var>getIndex</var> methods (below).</p>
+ *
+ * <p>The order of attributes in the list is unspecified, and will
+ * vary from implementation to implementation.</p>
+ *
+ * @since SAX 2.0
+ * @author David Megginson
+ * @see org.xml.sax.helpers.AttributesImpl
+ * @see org.xml.sax.ext.DeclHandler#attributeDecl
+ */
+public interface Attributes
+{
+
+
+    ////////////////////////////////////////////////////////////////////
+    // Indexed access.
+    ////////////////////////////////////////////////////////////////////
+
+
+    /**
+     * Return the number of attributes in the list.
+     *
+     * <p>Once you know the number of attributes, you can iterate
+     * through the list.</p>
+     *
+     * @return The number of attributes in the list.
+     * @see #getURI(int)
+     * @see #getLocalName(int)
+     * @see #getQName(int)
+     * @see #getType(int)
+     * @see #getValue(int)
+     */
+    public abstract int getLength ();
+
+
+    /**
+     * Look up an attribute's Namespace URI by index.
+     *
+     * @param index The attribute index (zero-based).
+     * @return The Namespace URI, or the empty string if none
+     *         is available, or null if the index is out of
+     *         range.
+     * @see #getLength
+     */
+    public abstract String getURI (int index);
+
+
+    /**
+     * Look up an attribute's local name by index.
+     *
+     * @param index The attribute index (zero-based).
+     * @return The local name, or the empty string if Namespace
+     *         processing is not being performed, or null
+     *         if the index is out of range.
+     * @see #getLength
+     */
+    public abstract String getLocalName (int index);
+
+
+    /**
+     * Look up an attribute's XML qualified (prefixed) name by index.
+     *
+     * @param index The attribute index (zero-based).
+     * @return The XML qualified name, or the empty string
+     *         if none is available, or null if the index
+     *         is out of range.
+     * @see #getLength
+     */
+    public abstract String getQName (int index);
+
+
+    /**
+     * Look up an attribute's type by index.
+     *
+     * <p>The attribute type is one of the strings "CDATA", "ID",
+     * "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES",
+     * or "NOTATION" (always in upper case).</p>
+     *
+     * <p>If the parser has not read a declaration for the attribute,
+     * or if the parser does not report attribute types, then it must
+     * return the value "CDATA" as stated in the XML 1.0 Recommendation
+     * (clause 3.3.3, "Attribute-Value Normalization").</p>
+     *
+     * <p>For an enumerated attribute that is not a notation, the
+     * parser will report the type as "NMTOKEN".</p>
+     *
+     * @param index The attribute index (zero-based).
+     * @return The attribute's type as a string, or null if the
+     *         index is out of range.
+     * @see #getLength
+     */
+    public abstract String getType (int index);
+
+
+    /**
+     * Look up an attribute's value by index.
+     *
+     * <p>If the attribute value is a list of tokens (IDREFS,
+     * ENTITIES, or NMTOKENS), the tokens will be concatenated
+     * into a single string with each token separated by a
+     * single space.</p>
+     *
+     * @param index The attribute index (zero-based).
+     * @return The attribute's value as a string, or null if the
+     *         index is out of range.
+     * @see #getLength
+     */
+    public abstract String getValue (int index);
+
+
+
+    ////////////////////////////////////////////////////////////////////
+    // Name-based query.
+    ////////////////////////////////////////////////////////////////////
+
+
+    /**
+     * Look up the index of an attribute by Namespace name.
+     *
+     * @param uri The Namespace URI, or the empty string if
+     *        the name has no Namespace URI.
+     * @param localName The attribute's local name.
+     * @return The index of the attribute, or -1 if it does not
+     *         appear in the list.
+     */
+    public int getIndex (String uri, String localName);
+
+
+    /**
+     * Look up the index of an attribute by XML qualified (prefixed) name.
+     *
+     * @param qName The qualified (prefixed) name.
+     * @return The index of the attribute, or -1 if it does not
+     *         appear in the list.
+     */
+    public int getIndex (String qName);
+
+
+    /**
+     * Look up an attribute's type by Namespace name.
+     *
+     * <p>See {@link #getType(int) getType(int)} for a description
+     * of the possible types.</p>
+     *
+     * @param uri The Namespace URI, or the empty String if the
+     *        name has no Namespace URI.
+     * @param localName The local name of the attribute.
+     * @return The attribute type as a string, or null if the
+     *         attribute is not in the list or if Namespace
+     *         processing is not being performed.
+     */
+    public abstract String getType (String uri, String localName);
+
+
+    /**
+     * Look up an attribute's type by XML qualified (prefixed) name.
+     *
+     * <p>See {@link #getType(int) getType(int)} for a description
+     * of the possible types.</p>
+     *
+     * @param qName The XML qualified name.
+     * @return The attribute type as a string, or null if the
+     *         attribute is not in the list or if qualified names
+     *         are not available.
+     */
+    public abstract String getType (String qName);
+
+
+    /**
+     * Look up an attribute's value by Namespace name.
+     *
+     * <p>See {@link #getValue(int) getValue(int)} for a description
+     * of the possible values.</p>
+     *
+     * @param uri The Namespace URI, or the empty String if the
+     *        name has no Namespace URI.
+     * @param localName The local name of the attribute.
+     * @return The attribute value as a string, or null if the
+     *         attribute is not in the list.
+     */
+    public abstract String getValue (String uri, String localName);
+
+
+    /**
+     * Look up an attribute's value by XML qualified (prefixed) name.
+     *
+     * <p>See {@link #getValue(int) getValue(int)} for a description
+     * of the possible values.</p>
+     *
+     * @param qName The XML qualified name.
+     * @return The attribute value as a string, or null if the
+     *         attribute is not in the list or if qualified names
+     *         are not available.
+     */
+    public abstract String getValue (String qName);
+
+}
+
+// end of Attributes.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/org/xml/sax/ContentHandler.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,443 @@
+/*
+ * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// ContentHandler.java - handle main document content.
+// http://www.saxproject.org
+// Written by David Megginson
+// NO WARRANTY!  This class is in the public domain.
+// $Id: ContentHandler.java,v 1.2 2004/11/03 22:44:51 jsuttor Exp $
+
+package jdk.internal.org.xml.sax;
+
+
+/**
+ * Receive notification of the logical content of a document.
+ *
+ * <blockquote>
+ * <em>This module, both source code and documentation, is in the
+ * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
+ * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
+ * for further information.
+ * </blockquote>
+ *
+ * <p>This is the main interface that most SAX applications
+ * implement: if the application needs to be informed of basic parsing
+ * events, it implements this interface and registers an instance with
+ * the SAX parser using the {@link org.xml.sax.XMLReader#setContentHandler
+ * setContentHandler} method.  The parser uses the instance to report
+ * basic document-related events like the start and end of elements
+ * and character data.</p>
+ *
+ * <p>The order of events in this interface is very important, and
+ * mirrors the order of information in the document itself.  For
+ * example, all of an element's content (character data, processing
+ * instructions, and/or subelements) will appear, in order, between
+ * the startElement event and the corresponding endElement event.</p>
+ *
+ * <p>This interface is similar to the now-deprecated SAX 1.0
+ * DocumentHandler interface, but it adds support for Namespaces
+ * and for reporting skipped entities (in non-validating XML
+ * processors).</p>
+ *
+ * <p>Implementors should note that there is also a
+ * <code>ContentHandler</code> class in the <code>java.net</code>
+ * package; that means that it's probably a bad idea to do</p>
+ *
+ * <pre>import java.net.*;
+ * import org.xml.sax.*;
+ * </pre>
+ *
+ * <p>In fact, "import ...*" is usually a sign of sloppy programming
+ * anyway, so the user should consider this a feature rather than a
+ * bug.</p>
+ *
+ * @since SAX 2.0
+ * @author David Megginson
+ * @see org.xml.sax.XMLReader
+ * @see org.xml.sax.DTDHandler
+ * @see org.xml.sax.ErrorHandler
+ */
+public interface ContentHandler
+{
+
+    /**
+     * Receive an object for locating the origin of SAX document events.
+     *
+     * <p>SAX parsers are strongly encouraged (though not absolutely
+     * required) to supply a locator: if it does so, it must supply
+     * the locator to the application by invoking this method before
+     * invoking any of the other methods in the ContentHandler
+     * interface.</p>
+     *
+     * <p>The locator allows the application to determine the end
+     * position of any document-related event, even if the parser is
+     * not reporting an error.  Typically, the application will
+     * use this information for reporting its own errors (such as
+     * character content that does not match an application's
+     * business rules).  The information returned by the locator
+     * is probably not sufficient for use with a search engine.</p>
+     *
+     * <p>Note that the locator will return correct information only
+     * during the invocation SAX event callbacks after
+     * {@link #startDocument startDocument} returns and before
+     * {@link #endDocument endDocument} is called.  The
+     * application should not attempt to use it at any other time.</p>
+     *
+     * @param locator an object that can return the location of
+     *                any SAX document event
+     * @see org.xml.sax.Locator
+     */
+    public void setDocumentLocator (Locator locator);
+
+
+    /**
+     * Receive notification of the beginning of a document.
+     *
+     * <p>The SAX parser will invoke this method only once, before any
+     * other event callbacks (except for {@link #setDocumentLocator
+     * setDocumentLocator}).</p>
+     *
+     * @throws org.xml.sax.SAXException any SAX exception, possibly
+     *            wrapping another exception
+     * @see #endDocument
+     */
+    public void startDocument ()
+        throws SAXException;
+
+
+    /**
+     * Receive notification of the end of a document.
+     *
+     * <p><strong>There is an apparent contradiction between the
+     * documentation for this method and the documentation for {@link
+     * org.xml.sax.ErrorHandler#fatalError}.  Until this ambiguity is
+     * resolved in a future major release, clients should make no
+     * assumptions about whether endDocument() will or will not be
+     * invoked when the parser has reported a fatalError() or thrown
+     * an exception.</strong></p>
+     *
+     * <p>The SAX parser will invoke this method only once, and it will
+     * be the last method invoked during the parse.  The parser shall
+     * not invoke this method until it has either abandoned parsing
+     * (because of an unrecoverable error) or reached the end of
+     * input.</p>
+     *
+     * @throws org.xml.sax.SAXException any SAX exception, possibly
+     *            wrapping another exception
+     * @see #startDocument
+     */
+    public void endDocument()
+        throws SAXException;
+
+
+    /**
+     * Begin the scope of a prefix-URI Namespace mapping.
+     *
+     * <p>The information from this event is not necessary for
+     * normal Namespace processing: the SAX XML reader will
+     * automatically replace prefixes for element and attribute
+     * names when the <code>http://xml.org/sax/features/namespaces</code>
+     * feature is <var>true</var> (the default).</p>
+     *
+     * <p>There are cases, however, when applications need to
+     * use prefixes in character data or in attribute values,
+     * where they cannot safely be expanded automatically; the
+     * start/endPrefixMapping event supplies the information
+     * to the application to expand prefixes in those contexts
+     * itself, if necessary.</p>
+     *
+     * <p>Note that start/endPrefixMapping events are not
+     * guaranteed to be properly nested relative to each other:
+     * all startPrefixMapping events will occur immediately before the
+     * corresponding {@link #startElement startElement} event,
+     * and all {@link #endPrefixMapping endPrefixMapping}
+     * events will occur immediately after the corresponding
+     * {@link #endElement endElement} event,
+     * but their order is not otherwise
+     * guaranteed.</p>
+     *
+     * <p>There should never be start/endPrefixMapping events for the
+     * "xml" prefix, since it is predeclared and immutable.</p>
+     *
+     * @param prefix the Namespace prefix being declared.
+     *  An empty string is used for the default element namespace,
+     *  which has no prefix.
+     * @param uri the Namespace URI the prefix is mapped to
+     * @throws org.xml.sax.SAXException the client may throw
+     *            an exception during processing
+     * @see #endPrefixMapping
+     * @see #startElement
+     */
+    public void startPrefixMapping (String prefix, String uri)
+        throws SAXException;
+
+
+    /**
+     * End the scope of a prefix-URI mapping.
+     *
+     * <p>See {@link #startPrefixMapping startPrefixMapping} for
+     * details.  These events will always occur immediately after the
+     * corresponding {@link #endElement endElement} event, but the order of
+     * {@link #endPrefixMapping endPrefixMapping} events is not otherwise
+     * guaranteed.</p>
+     *
+     * @param prefix the prefix that was being mapped.
+     *  This is the empty string when a default mapping scope ends.
+     * @throws org.xml.sax.SAXException the client may throw
+     *            an exception during processing
+     * @see #startPrefixMapping
+     * @see #endElement
+     */
+    public void endPrefixMapping (String prefix)
+        throws SAXException;
+
+
+    /**
+     * Receive notification of the beginning of an element.
+     *
+     * <p>The Parser will invoke this method at the beginning of every
+     * element in the XML document; there will be a corresponding
+     * {@link #endElement endElement} event for every startElement event
+     * (even when the element is empty). All of the element's content will be
+     * reported, in order, before the corresponding endElement
+     * event.</p>
+     *
+     * <p>This event allows up to three name components for each
+     * element:</p>
+     *
+     * <ol>
+     * <li>the Namespace URI;</li>
+     * <li>the local name; and</li>
+     * <li>the qualified (prefixed) name.</li>
+     * </ol>
+     *
+     * <p>Any or all of these may be provided, depending on the
+     * values of the <var>http://xml.org/sax/features/namespaces</var>
+     * and the <var>http://xml.org/sax/features/namespace-prefixes</var>
+     * properties:</p>
+     *
+     * <ul>
+     * <li>the Namespace URI and local name are required when
+     * the namespaces property is <var>true</var> (the default), and are
+     * optional when the namespaces property is <var>false</var> (if one is
+     * specified, both must be);</li>
+     * <li>the qualified name is required when the namespace-prefixes property
+     * is <var>true</var>, and is optional when the namespace-prefixes property
+     * is <var>false</var> (the default).</li>
+     * </ul>
+     *
+     * <p>Note that the attribute list provided will contain only
+     * attributes with explicit values (specified or defaulted):
+     * #IMPLIED attributes will be omitted.  The attribute list
+     * will contain attributes used for Namespace declarations
+     * (xmlns* attributes) only if the
+     * <code>http://xml.org/sax/features/namespace-prefixes</code>
+     * property is true (it is false by default, and support for a
+     * true value is optional).</p>
+     *
+     * <p>Like {@link #characters characters()}, attribute values may have
+     * characters that need more than one <code>char</code> value.  </p>
+     *
+     * @param uri the Namespace URI, or the empty string if the
+     *        element has no Namespace URI or if Namespace
+     *        processing is not being performed
+     * @param localName the local name (without prefix), or the
+     *        empty string if Namespace processing is not being
+     *        performed
+     * @param qName the qualified name (with prefix), or the
+     *        empty string if qualified names are not available
+     * @param atts the attributes attached to the element.  If
+     *        there are no attributes, it shall be an empty
+     *        Attributes object.  The value of this object after
+     *        startElement returns is undefined
+     * @throws org.xml.sax.SAXException any SAX exception, possibly
+     *            wrapping another exception
+     * @see #endElement
+     * @see org.xml.sax.Attributes
+     * @see org.xml.sax.helpers.AttributesImpl
+     */
+    public void startElement (String uri, String localName,
+                              String qName, Attributes atts)
+        throws SAXException;
+
+
+    /**
+     * Receive notification of the end of an element.
+     *
+     * <p>The SAX parser will invoke this method at the end of every
+     * element in the XML document; there will be a corresponding
+     * {@link #startElement startElement} event for every endElement
+     * event (even when the element is empty).</p>
+     *
+     * <p>For information on the names, see startElement.</p>
+     *
+     * @param uri the Namespace URI, or the empty string if the
+     *        element has no Namespace URI or if Namespace
+     *        processing is not being performed
+     * @param localName the local name (without prefix), or the
+     *        empty string if Namespace processing is not being
+     *        performed
+     * @param qName the qualified XML name (with prefix), or the
+     *        empty string if qualified names are not available
+     * @throws org.xml.sax.SAXException any SAX exception, possibly
+     *            wrapping another exception
+     */
+    public void endElement (String uri, String localName,
+                            String qName)
+        throws SAXException;
+
+
+    /**
+     * Receive notification of character data.
+     *
+     * <p>The Parser will call this method to report each chunk of
+     * character data.  SAX parsers may return all contiguous character
+     * data in a single chunk, or they may split it into several
+     * chunks; however, all of the characters in any single event
+     * must come from the same external entity so that the Locator
+     * provides useful information.</p>
+     *
+     * <p>The application must not attempt to read from the array
+     * outside of the specified range.</p>
+     *
+     * <p>Individual characters may consist of more than one Java
+     * <code>char</code> value.  There are two important cases where this
+     * happens, because characters can't be represented in just sixteen bits.
+     * In one case, characters are represented in a <em>Surrogate Pair</em>,
+     * using two special Unicode values. Such characters are in the so-called
+     * "Astral Planes", with a code point above U+FFFF.  A second case involves
+     * composite characters, such as a base character combining with one or
+     * more accent characters. </p>
+     *
+     * <p> Your code should not assume that algorithms using
+     * <code>char</code>-at-a-time idioms will be working in character
+     * units; in some cases they will split characters.  This is relevant
+     * wherever XML permits arbitrary characters, such as attribute values,
+     * processing instruction data, and comments as well as in data reported
+     * from this method.  It's also generally relevant whenever Java code
+     * manipulates internationalized text; the issue isn't unique to XML.</p>
+     *
+     * <p>Note that some parsers will report whitespace in element
+     * content using the {@link #ignorableWhitespace ignorableWhitespace}
+     * method rather than this one (validating parsers <em>must</em>
+     * do so).</p>
+     *
+     * @param ch the characters from the XML document
+     * @param start the start position in the array
+     * @param length the number of characters to read from the array
+     * @throws org.xml.sax.SAXException any SAX exception, possibly
+     *            wrapping another exception
+     * @see #ignorableWhitespace
+     * @see org.xml.sax.Locator
+     */
+    public void characters (char ch[], int start, int length)
+        throws SAXException;
+
+
+    /**
+     * Receive notification of ignorable whitespace in element content.
+     *
+     * <p>Validating Parsers must use this method to report each chunk
+     * of whitespace in element content (see the W3C XML 1.0
+     * recommendation, section 2.10): non-validating parsers may also
+     * use this method if they are capable of parsing and using
+     * content models.</p>
+     *
+     * <p>SAX parsers may return all contiguous whitespace in a single
+     * chunk, or they may split it into several chunks; however, all of
+     * the characters in any single event must come from the same
+     * external entity, so that the Locator provides useful
+     * information.</p>
+     *
+     * <p>The application must not attempt to read from the array
+     * outside of the specified range.</p>
+     *
+     * @param ch the characters from the XML document
+     * @param start the start position in the array
+     * @param length the number of characters to read from the array
+     * @throws org.xml.sax.SAXException any SAX exception, possibly
+     *            wrapping another exception
+     * @see #characters
+     */
+    public void ignorableWhitespace (char ch[], int start, int length)
+        throws SAXException;
+
+
+    /**
+     * Receive notification of a processing instruction.
+     *
+     * <p>The Parser will invoke this method once for each processing
+     * instruction found: note that processing instructions may occur
+     * before or after the main document element.</p>
+     *
+     * <p>A SAX parser must never report an XML declaration (XML 1.0,
+     * section 2.8) or a text declaration (XML 1.0, section 4.3.1)
+     * using this method.</p>
+     *
+     * <p>Like {@link #characters characters()}, processing instruction
+     * data may have characters that need more than one <code>char</code>
+     * value. </p>
+     *
+     * @param target the processing instruction target
+     * @param data the processing instruction data, or null if
+     *        none was supplied.  The data does not include any
+     *        whitespace separating it from the target
+     * @throws org.xml.sax.SAXException any SAX exception, possibly
+     *            wrapping another exception
+     */
+    public void processingInstruction (String target, String data)
+        throws SAXException;
+
+
+    /**
+     * Receive notification of a skipped entity.
+     * This is not called for entity references within markup constructs
+     * such as element start tags or markup declarations.  (The XML
+     * recommendation requires reporting skipped external entities.
+     * SAX also reports internal entity expansion/non-expansion, except
+     * within markup constructs.)
+     *
+     * <p>The Parser will invoke this method each time the entity is
+     * skipped.  Non-validating processors may skip entities if they
+     * have not seen the declarations (because, for example, the
+     * entity was declared in an external DTD subset).  All processors
+     * may skip external entities, depending on the values of the
+     * <code>http://xml.org/sax/features/external-general-entities</code>
+     * and the
+     * <code>http://xml.org/sax/features/external-parameter-entities</code>
+     * properties.</p>
+     *
+     * @param name the name of the skipped entity.  If it is a
+     *        parameter entity, the name will begin with '%', and if
+     *        it is the external DTD subset, it will be the string
+     *        "[dtd]"
+     * @throws org.xml.sax.SAXException any SAX exception, possibly
+     *            wrapping another exception
+     */
+    public void skippedEntity (String name)
+        throws SAXException;
+}
+
+// end of ContentHandler.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/org/xml/sax/DTDHandler.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// SAX DTD handler.
+// http://www.saxproject.org
+// No warranty; no copyright -- use this as you will.
+// $Id: DTDHandler.java,v 1.2 2004/11/03 22:44:51 jsuttor Exp $
+
+package jdk.internal.org.xml.sax;
+
+/**
+ * Receive notification of basic DTD-related events.
+ *
+ * <blockquote>
+ * <em>This module, both source code and documentation, is in the
+ * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
+ * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
+ * for further information.
+ * </blockquote>
+ *
+ * <p>If a SAX application needs information about notations and
+ * unparsed entities, then the application implements this
+ * interface and registers an instance with the SAX parser using
+ * the parser's setDTDHandler method.  The parser uses the
+ * instance to report notation and unparsed entity declarations to
+ * the application.</p>
+ *
+ * <p>Note that this interface includes only those DTD events that
+ * the XML recommendation <em>requires</em> processors to report:
+ * notation and unparsed entity declarations.</p>
+ *
+ * <p>The SAX parser may report these events in any order, regardless
+ * of the order in which the notations and unparsed entities were
+ * declared; however, all DTD events must be reported after the
+ * document handler's startDocument event, and before the first
+ * startElement event.
+ * (If the {@link org.xml.sax.ext.LexicalHandler LexicalHandler} is
+ * used, these events must also be reported before the endDTD event.)
+ * </p>
+ *
+ * <p>It is up to the application to store the information for
+ * future use (perhaps in a hash table or object tree).
+ * If the application encounters attributes of type "NOTATION",
+ * "ENTITY", or "ENTITIES", it can use the information that it
+ * obtained through this interface to find the entity and/or
+ * notation corresponding with the attribute value.</p>
+ *
+ * @since SAX 1.0
+ * @author David Megginson
+ * @see org.xml.sax.XMLReader#setDTDHandler
+ */
+public interface DTDHandler {
+
+
+    /**
+     * Receive notification of a notation declaration event.
+     *
+     * <p>It is up to the application to record the notation for later
+     * reference, if necessary;
+     * notations may appear as attribute values and in unparsed entity
+     * declarations, and are sometime used with processing instruction
+     * target names.</p>
+     *
+     * <p>At least one of publicId and systemId must be non-null.
+     * If a system identifier is present, and it is a URL, the SAX
+     * parser must resolve it fully before passing it to the
+     * application through this event.</p>
+     *
+     * <p>There is no guarantee that the notation declaration will be
+     * reported before any unparsed entities that use it.</p>
+     *
+     * @param name The notation name.
+     * @param publicId The notation's public identifier, or null if
+     *        none was given.
+     * @param systemId The notation's system identifier, or null if
+     *        none was given.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see #unparsedEntityDecl
+     * @see org.xml.sax.Attributes
+     */
+    public abstract void notationDecl (String name,
+                                       String publicId,
+                                       String systemId)
+        throws SAXException;
+
+
+    /**
+     * Receive notification of an unparsed entity declaration event.
+     *
+     * <p>Note that the notation name corresponds to a notation
+     * reported by the {@link #notationDecl notationDecl} event.
+     * It is up to the application to record the entity for later
+     * reference, if necessary;
+     * unparsed entities may appear as attribute values.
+     * </p>
+     *
+     * <p>If the system identifier is a URL, the parser must resolve it
+     * fully before passing it to the application.</p>
+     *
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @param name The unparsed entity's name.
+     * @param publicId The entity's public identifier, or null if none
+     *        was given.
+     * @param systemId The entity's system identifier.
+     * @param notationName The name of the associated notation.
+     * @see #notationDecl
+     * @see org.xml.sax.Attributes
+     */
+    public abstract void unparsedEntityDecl (String name,
+                                             String publicId,
+                                             String systemId,
+                                             String notationName)
+        throws SAXException;
+
+}
+
+// end of DTDHandler.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/org/xml/sax/EntityResolver.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// SAX entity resolver.
+// http://www.saxproject.org
+// No warranty; no copyright -- use this as you will.
+// $Id: EntityResolver.java,v 1.2 2004/11/03 22:44:52 jsuttor Exp $
+
+package jdk.internal.org.xml.sax;
+
+import java.io.IOException;
+
+
+/**
+ * Basic interface for resolving entities.
+ *
+ * <blockquote>
+ * <em>This module, both source code and documentation, is in the
+ * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
+ * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
+ * for further information.
+ * </blockquote>
+ *
+ * <p>If a SAX application needs to implement customized handling
+ * for external entities, it must implement this interface and
+ * register an instance with the SAX driver using the
+ * {@link org.xml.sax.XMLReader#setEntityResolver setEntityResolver}
+ * method.</p>
+ *
+ * <p>The XML reader will then allow the application to intercept any
+ * external entities (including the external DTD subset and external
+ * parameter entities, if any) before including them.</p>
+ *
+ * <p>Many SAX applications will not need to implement this interface,
+ * but it will be especially useful for applications that build
+ * XML documents from databases or other specialised input sources,
+ * or for applications that use URI types other than URLs.</p>
+ *
+ * <p>The following resolver would provide the application
+ * with a special character stream for the entity with the system
+ * identifier "http://www.myhost.com/today":</p>
+ *
+ * <pre>
+ * import org.xml.sax.EntityResolver;
+ * import org.xml.sax.InputSource;
+ *
+ * public class MyResolver implements EntityResolver {
+ *   public InputSource resolveEntity (String publicId, String systemId)
+ *   {
+ *     if (systemId.equals("http://www.myhost.com/today")) {
+ *              // return a special input source
+ *       MyReader reader = new MyReader();
+ *       return new InputSource(reader);
+ *     } else {
+ *              // use the default behaviour
+ *       return null;
+ *     }
+ *   }
+ * }
+ * </pre>
+ *
+ * <p>The application can also use this interface to redirect system
+ * identifiers to local URIs or to look up replacements in a catalog
+ * (possibly by using the public identifier).</p>
+ *
+ * @since SAX 1.0
+ * @author David Megginson
+ * @see org.xml.sax.XMLReader#setEntityResolver
+ * @see org.xml.sax.InputSource
+ */
+public interface EntityResolver {
+
+
+    /**
+     * Allow the application to resolve external entities.
+     *
+     * <p>The parser will call this method before opening any external
+     * entity except the top-level document entity.  Such entities include
+     * the external DTD subset and external parameter entities referenced
+     * within the DTD (in either case, only if the parser reads external
+     * parameter entities), and external general entities referenced
+     * within the document element (if the parser reads external general
+     * entities).  The application may request that the parser locate
+     * the entity itself, that it use an alternative URI, or that it
+     * use data provided by the application (as a character or byte
+     * input stream).</p>
+     *
+     * <p>Application writers can use this method to redirect external
+     * system identifiers to secure and/or local URIs, to look up
+     * public identifiers in a catalogue, or to read an entity from a
+     * database or other input source (including, for example, a dialog
+     * box).  Neither XML nor SAX specifies a preferred policy for using
+     * public or system IDs to resolve resources.  However, SAX specifies
+     * how to interpret any InputSource returned by this method, and that
+     * if none is returned, then the system ID will be dereferenced as
+     * a URL.  </p>
+     *
+     * <p>If the system identifier is a URL, the SAX parser must
+     * resolve it fully before reporting it to the application.</p>
+     *
+     * @param publicId The public identifier of the external entity
+     *        being referenced, or null if none was supplied.
+     * @param systemId The system identifier of the external entity
+     *        being referenced.
+     * @return An InputSource object describing the new input source,
+     *         or null to request that the parser open a regular
+     *         URI connection to the system identifier.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @exception java.io.IOException A Java-specific IO exception,
+     *            possibly the result of creating a new InputStream
+     *            or Reader for the InputSource.
+     * @see org.xml.sax.InputSource
+     */
+    public abstract InputSource resolveEntity (String publicId,
+                                               String systemId)
+        throws SAXException, IOException;
+
+}
+
+// end of EntityResolver.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/org/xml/sax/ErrorHandler.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// SAX error handler.
+// http://www.saxproject.org
+// No warranty; no copyright -- use this as you will.
+// $Id: ErrorHandler.java,v 1.2 2004/11/03 22:44:52 jsuttor Exp $
+
+package jdk.internal.org.xml.sax;
+
+
+/**
+ * Basic interface for SAX error handlers.
+ *
+ * <blockquote>
+ * <em>This module, both source code and documentation, is in the
+ * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
+ * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
+ * for further information.
+ * </blockquote>
+ *
+ * <p>If a SAX application needs to implement customized error
+ * handling, it must implement this interface and then register an
+ * instance with the XML reader using the
+ * {@link org.xml.sax.XMLReader#setErrorHandler setErrorHandler}
+ * method.  The parser will then report all errors and warnings
+ * through this interface.</p>
+ *
+ * <p><strong>WARNING:</strong> If an application does <em>not</em>
+ * register an ErrorHandler, XML parsing errors will go unreported,
+ * except that <em>SAXParseException</em>s will be thrown for fatal errors.
+ * In order to detect validity errors, an ErrorHandler that does something
+ * with {@link #error error()} calls must be registered.</p>
+ *
+ * <p>For XML processing errors, a SAX driver must use this interface
+ * in preference to throwing an exception: it is up to the application
+ * to decide whether to throw an exception for different types of
+ * errors and warnings.  Note, however, that there is no requirement that
+ * the parser continue to report additional errors after a call to
+ * {@link #fatalError fatalError}.  In other words, a SAX driver class
+ * may throw an exception after reporting any fatalError.
+ * Also parsers may throw appropriate exceptions for non-XML errors.
+ * For example, {@link XMLReader#parse XMLReader.parse()} would throw
+ * an IOException for errors accessing entities or the document.</p>
+ *
+ * @since SAX 1.0
+ * @author David Megginson
+ * @see org.xml.sax.XMLReader#setErrorHandler
+ * @see org.xml.sax.SAXParseException
+ */
+public interface ErrorHandler {
+
+
+    /**
+     * Receive notification of a warning.
+     *
+     * <p>SAX parsers will use this method to report conditions that
+     * are not errors or fatal errors as defined by the XML
+     * recommendation.  The default behaviour is to take no
+     * action.</p>
+     *
+     * <p>The SAX parser must continue to provide normal parsing events
+     * after invoking this method: it should still be possible for the
+     * application to process the document through to the end.</p>
+     *
+     * <p>Filters may use this method to report other, non-XML warnings
+     * as well.</p>
+     *
+     * @param exception The warning information encapsulated in a
+     *                  SAX parse exception.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.SAXParseException
+     */
+    public abstract void warning (SAXParseException exception)
+        throws SAXException;
+
+
+    /**
+     * Receive notification of a recoverable error.
+     *
+     * <p>This corresponds to the definition of "error" in section 1.2
+     * of the W3C XML 1.0 Recommendation.  For example, a validating
+     * parser would use this callback to report the violation of a
+     * validity constraint.  The default behaviour is to take no
+     * action.</p>
+     *
+     * <p>The SAX parser must continue to provide normal parsing
+     * events after invoking this method: it should still be possible
+     * for the application to process the document through to the end.
+     * If the application cannot do so, then the parser should report
+     * a fatal error even if the XML recommendation does not require
+     * it to do so.</p>
+     *
+     * <p>Filters may use this method to report other, non-XML errors
+     * as well.</p>
+     *
+     * @param exception The error information encapsulated in a
+     *                  SAX parse exception.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.SAXParseException
+     */
+    public abstract void error (SAXParseException exception)
+        throws SAXException;
+
+
+    /**
+     * Receive notification of a non-recoverable error.
+     *
+     * <p><strong>There is an apparent contradiction between the
+     * documentation for this method and the documentation for {@link
+     * org.xml.sax.ContentHandler#endDocument}.  Until this ambiguity
+     * is resolved in a future major release, clients should make no
+     * assumptions about whether endDocument() will or will not be
+     * invoked when the parser has reported a fatalError() or thrown
+     * an exception.</strong></p>
+     *
+     * <p>This corresponds to the definition of "fatal error" in
+     * section 1.2 of the W3C XML 1.0 Recommendation.  For example, a
+     * parser would use this callback to report the violation of a
+     * well-formedness constraint.</p>
+     *
+     * <p>The application must assume that the document is unusable
+     * after the parser has invoked this method, and should continue
+     * (if at all) only for the sake of collecting additional error
+     * messages: in fact, SAX parsers are free to stop reporting any
+     * other events once this method has been invoked.</p>
+     *
+     * @param exception The error information encapsulated in a
+     *                  SAX parse exception.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.SAXParseException
+     */
+    public abstract void fatalError (SAXParseException exception)
+        throws SAXException;
+
+}
+
+// end of ErrorHandler.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/org/xml/sax/InputSource.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,360 @@
+/*
+ * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// SAX input source.
+// http://www.saxproject.org
+// No warranty; no copyright -- use this as you will.
+// $Id: InputSource.java,v 1.2 2004/11/03 22:55:32 jsuttor Exp $
+
+package jdk.internal.org.xml.sax;
+
+import java.io.Reader;
+import java.io.InputStream;
+
+/**
+ * A single input source for an XML entity.
+ *
+ * <blockquote>
+ * <em>This module, both source code and documentation, is in the
+ * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
+ * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
+ * for further information.
+ * </blockquote>
+ *
+ * <p>This class allows a SAX application to encapsulate information
+ * about an input source in a single object, which may include
+ * a public identifier, a system identifier, a byte stream (possibly
+ * with a specified encoding), and/or a character stream.</p>
+ *
+ * <p>There are two places that the application can deliver an
+ * input source to the parser: as the argument to the Parser.parse
+ * method, or as the return value of the EntityResolver.resolveEntity
+ * method.</p>
+ *
+ * <p>The SAX parser will use the InputSource object to determine how
+ * to read XML input.  If there is a character stream available, the
+ * parser will read that stream directly, disregarding any text
+ * encoding declaration found in that stream.
+ * If there is no character stream, but there is
+ * a byte stream, the parser will use that byte stream, using the
+ * encoding specified in the InputSource or else (if no encoding is
+ * specified) autodetecting the character encoding using an algorithm
+ * such as the one in the XML specification.  If neither a character
+ * stream nor a
+ * byte stream is available, the parser will attempt to open a URI
+ * connection to the resource identified by the system
+ * identifier.</p>
+ *
+ * <p>An InputSource object belongs to the application: the SAX parser
+ * shall never modify it in any way (it may modify a copy if
+ * necessary).  However, standard processing of both byte and
+ * character streams is to close them on as part of end-of-parse cleanup,
+ * so applications should not attempt to re-use such streams after they
+ * have been handed to a parser.  </p>
+ *
+ * @since SAX 1.0
+ * @author David Megginson
+ * @see org.xml.sax.XMLReader#parse(org.xml.sax.InputSource)
+ * @see org.xml.sax.EntityResolver#resolveEntity
+ * @see java.io.InputStream
+ * @see java.io.Reader
+ */
+public class InputSource {
+
+    /**
+     * Zero-argument default constructor.
+     *
+     * @see #setPublicId
+     * @see #setSystemId
+     * @see #setByteStream
+     * @see #setCharacterStream
+     * @see #setEncoding
+     */
+    public InputSource ()
+    {
+    }
+
+
+    /**
+     * Create a new input source with a system identifier.
+     *
+     * <p>Applications may use setPublicId to include a
+     * public identifier as well, or setEncoding to specify
+     * the character encoding, if known.</p>
+     *
+     * <p>If the system identifier is a URL, it must be fully
+     * resolved (it may not be a relative URL).</p>
+     *
+     * @param systemId The system identifier (URI).
+     * @see #setPublicId
+     * @see #setSystemId
+     * @see #setByteStream
+     * @see #setEncoding
+     * @see #setCharacterStream
+     */
+    public InputSource (String systemId)
+    {
+        setSystemId(systemId);
+    }
+
+
+    /**
+     * Create a new input source with a byte stream.
+     *
+     * <p>Application writers should use setSystemId() to provide a base
+     * for resolving relative URIs, may use setPublicId to include a
+     * public identifier, and may use setEncoding to specify the object's
+     * character encoding.</p>
+     *
+     * @param byteStream The raw byte stream containing the document.
+     * @see #setPublicId
+     * @see #setSystemId
+     * @see #setEncoding
+     * @see #setByteStream
+     * @see #setCharacterStream
+     */
+    public InputSource (InputStream byteStream)
+    {
+        setByteStream(byteStream);
+    }
+
+
+    /**
+     * Create a new input source with a character stream.
+     *
+     * <p>Application writers should use setSystemId() to provide a base
+     * for resolving relative URIs, and may use setPublicId to include a
+     * public identifier.</p>
+     *
+     * <p>The character stream shall not include a byte order mark.</p>
+     *
+     * @see #setPublicId
+     * @see #setSystemId
+     * @see #setByteStream
+     * @see #setCharacterStream
+     */
+    public InputSource (Reader characterStream)
+    {
+        setCharacterStream(characterStream);
+    }
+
+
+    /**
+     * Set the public identifier for this input source.
+     *
+     * <p>The public identifier is always optional: if the application
+     * writer includes one, it will be provided as part of the
+     * location information.</p>
+     *
+     * @param publicId The public identifier as a string.
+     * @see #getPublicId
+     * @see org.xml.sax.Locator#getPublicId
+     * @see org.xml.sax.SAXParseException#getPublicId
+     */
+    public void setPublicId (String publicId)
+    {
+        this.publicId = publicId;
+    }
+
+
+    /**
+     * Get the public identifier for this input source.
+     *
+     * @return The public identifier, or null if none was supplied.
+     * @see #setPublicId
+     */
+    public String getPublicId ()
+    {
+        return publicId;
+    }
+
+
+    /**
+     * Set the system identifier for this input source.
+     *
+     * <p>The system identifier is optional if there is a byte stream
+     * or a character stream, but it is still useful to provide one,
+     * since the application can use it to resolve relative URIs
+     * and can include it in error messages and warnings (the parser
+     * will attempt to open a connection to the URI only if
+     * there is no byte stream or character stream specified).</p>
+     *
+     * <p>If the application knows the character encoding of the
+     * object pointed to by the system identifier, it can register
+     * the encoding using the setEncoding method.</p>
+     *
+     * <p>If the system identifier is a URL, it must be fully
+     * resolved (it may not be a relative URL).</p>
+     *
+     * @param systemId The system identifier as a string.
+     * @see #setEncoding
+     * @see #getSystemId
+     * @see org.xml.sax.Locator#getSystemId
+     * @see org.xml.sax.SAXParseException#getSystemId
+     */
+    public void setSystemId (String systemId)
+    {
+        this.systemId = systemId;
+    }
+
+
+    /**
+     * Get the system identifier for this input source.
+     *
+     * <p>The getEncoding method will return the character encoding
+     * of the object pointed to, or null if unknown.</p>
+     *
+     * <p>If the system ID is a URL, it will be fully resolved.</p>
+     *
+     * @return The system identifier, or null if none was supplied.
+     * @see #setSystemId
+     * @see #getEncoding
+     */
+    public String getSystemId ()
+    {
+        return systemId;
+    }
+
+
+    /**
+     * Set the byte stream for this input source.
+     *
+     * <p>The SAX parser will ignore this if there is also a character
+     * stream specified, but it will use a byte stream in preference
+     * to opening a URI connection itself.</p>
+     *
+     * <p>If the application knows the character encoding of the
+     * byte stream, it should set it with the setEncoding method.</p>
+     *
+     * @param byteStream A byte stream containing an XML document or
+     *        other entity.
+     * @see #setEncoding
+     * @see #getByteStream
+     * @see #getEncoding
+     * @see java.io.InputStream
+     */
+    public void setByteStream (InputStream byteStream)
+    {
+        this.byteStream = byteStream;
+    }
+
+
+    /**
+     * Get the byte stream for this input source.
+     *
+     * <p>The getEncoding method will return the character
+     * encoding for this byte stream, or null if unknown.</p>
+     *
+     * @return The byte stream, or null if none was supplied.
+     * @see #getEncoding
+     * @see #setByteStream
+     */
+    public InputStream getByteStream ()
+    {
+        return byteStream;
+    }
+
+
+    /**
+     * Set the character encoding, if known.
+     *
+     * <p>The encoding must be a string acceptable for an
+     * XML encoding declaration (see section 4.3.3 of the XML 1.0
+     * recommendation).</p>
+     *
+     * <p>This method has no effect when the application provides a
+     * character stream.</p>
+     *
+     * @param encoding A string describing the character encoding.
+     * @see #setSystemId
+     * @see #setByteStream
+     * @see #getEncoding
+     */
+    public void setEncoding (String encoding)
+    {
+        this.encoding = encoding;
+    }
+
+
+    /**
+     * Get the character encoding for a byte stream or URI.
+     * This value will be ignored when the application provides a
+     * character stream.
+     *
+     * @return The encoding, or null if none was supplied.
+     * @see #setByteStream
+     * @see #getSystemId
+     * @see #getByteStream
+     */
+    public String getEncoding ()
+    {
+        return encoding;
+    }
+
+
+    /**
+     * Set the character stream for this input source.
+     *
+     * <p>If there is a character stream specified, the SAX parser
+     * will ignore any byte stream and will not attempt to open
+     * a URI connection to the system identifier.</p>
+     *
+     * @param characterStream The character stream containing the
+     *        XML document or other entity.
+     * @see #getCharacterStream
+     * @see java.io.Reader
+     */
+    public void setCharacterStream (Reader characterStream)
+    {
+        this.characterStream = characterStream;
+    }
+
+
+    /**
+     * Get the character stream for this input source.
+     *
+     * @return The character stream, or null if none was supplied.
+     * @see #setCharacterStream
+     */
+    public Reader getCharacterStream ()
+    {
+        return characterStream;
+    }
+
+
+
+    ////////////////////////////////////////////////////////////////////
+    // Internal state.
+    ////////////////////////////////////////////////////////////////////
+
+    private String publicId;
+    private String systemId;
+    private InputStream byteStream;
+    private String encoding;
+    private Reader characterStream;
+
+}
+
+// end of InputSource.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/org/xml/sax/Locator.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,160 @@
+/*
+ * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// SAX locator interface for document events.
+// http://www.saxproject.org
+// No warranty; no copyright -- use this as you will.
+// $Id: Locator.java,v 1.2 2004/11/03 22:55:32 jsuttor Exp $
+
+package jdk.internal.org.xml.sax;
+
+
+/**
+ * Interface for associating a SAX event with a document location.
+ *
+ * <blockquote>
+ * <em>This module, both source code and documentation, is in the
+ * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
+ * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
+ * for further information.
+ * </blockquote>
+ *
+ * <p>If a SAX parser provides location information to the SAX
+ * application, it does so by implementing this interface and then
+ * passing an instance to the application using the content
+ * handler's {@link org.xml.sax.ContentHandler#setDocumentLocator
+ * setDocumentLocator} method.  The application can use the
+ * object to obtain the location of any other SAX event
+ * in the XML source document.</p>
+ *
+ * <p>Note that the results returned by the object will be valid only
+ * during the scope of each callback method: the application
+ * will receive unpredictable results if it attempts to use the
+ * locator at any other time, or after parsing completes.</p>
+ *
+ * <p>SAX parsers are not required to supply a locator, but they are
+ * very strongly encouraged to do so.  If the parser supplies a
+ * locator, it must do so before reporting any other document events.
+ * If no locator has been set by the time the application receives
+ * the {@link org.xml.sax.ContentHandler#startDocument startDocument}
+ * event, the application should assume that a locator is not
+ * available.</p>
+ *
+ * @since SAX 1.0
+ * @author David Megginson
+ * @see org.xml.sax.ContentHandler#setDocumentLocator
+ */
+public interface Locator {
+
+
+    /**
+     * Return the public identifier for the current document event.
+     *
+     * <p>The return value is the public identifier of the document
+     * entity or of the external parsed entity in which the markup
+     * triggering the event appears.</p>
+     *
+     * @return A string containing the public identifier, or
+     *         null if none is available.
+     * @see #getSystemId
+     */
+    public abstract String getPublicId ();
+
+
+    /**
+     * Return the system identifier for the current document event.
+     *
+     * <p>The return value is the system identifier of the document
+     * entity or of the external parsed entity in which the markup
+     * triggering the event appears.</p>
+     *
+     * <p>If the system identifier is a URL, the parser must resolve it
+     * fully before passing it to the application.  For example, a file
+     * name must always be provided as a <em>file:...</em> URL, and other
+     * kinds of relative URI are also resolved against their bases.</p>
+     *
+     * @return A string containing the system identifier, or null
+     *         if none is available.
+     * @see #getPublicId
+     */
+    public abstract String getSystemId ();
+
+
+    /**
+     * Return the line number where the current document event ends.
+     * Lines are delimited by line ends, which are defined in
+     * the XML specification.
+     *
+     * <p><strong>Warning:</strong> The return value from the method
+     * is intended only as an approximation for the sake of diagnostics;
+     * it is not intended to provide sufficient information
+     * to edit the character content of the original XML document.
+     * In some cases, these "line" numbers match what would be displayed
+     * as columns, and in others they may not match the source text
+     * due to internal entity expansion.  </p>
+     *
+     * <p>The return value is an approximation of the line number
+     * in the document entity or external parsed entity where the
+     * markup triggering the event appears.</p>
+     *
+     * <p>If possible, the SAX driver should provide the line position
+     * of the first character after the text associated with the document
+     * event.  The first line is line 1.</p>
+     *
+     * @return The line number, or -1 if none is available.
+     * @see #getColumnNumber
+     */
+    public abstract int getLineNumber ();
+
+
+    /**
+     * Return the column number where the current document event ends.
+     * This is one-based number of Java <code>char</code> values since
+     * the last line end.
+     *
+     * <p><strong>Warning:</strong> The return value from the method
+     * is intended only as an approximation for the sake of diagnostics;
+     * it is not intended to provide sufficient information
+     * to edit the character content of the original XML document.
+     * For example, when lines contain combining character sequences, wide
+     * characters, surrogate pairs, or bi-directional text, the value may
+     * not correspond to the column in a text editor's display. </p>
+     *
+     * <p>The return value is an approximation of the column number
+     * in the document entity or external parsed entity where the
+     * markup triggering the event appears.</p>
+     *
+     * <p>If possible, the SAX driver should provide the line position
+     * of the first character after the text associated with the document
+     * event.  The first column in each line is column 1.</p>
+     *
+     * @return The column number, or -1 if none is available.
+     * @see #getLineNumber
+     */
+    public abstract int getColumnNumber ();
+
+}
+
+// end of Locator.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/org/xml/sax/SAXException.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,188 @@
+/*
+ * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// SAX exception class.
+// http://www.saxproject.org
+// No warranty; no copyright -- use this as you will.
+// $Id: SAXException.java,v 1.3 2004/11/03 22:55:32 jsuttor Exp $
+
+package jdk.internal.org.xml.sax;
+
+/**
+ * Encapsulate a general SAX error or warning.
+ *
+ * <blockquote>
+ * <em>This module, both source code and documentation, is in the
+ * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
+ * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
+ * for further information.
+ * </blockquote>
+ *
+ * <p>This class can contain basic error or warning information from
+ * either the XML parser or the application: a parser writer or
+ * application writer can subclass it to provide additional
+ * functionality.  SAX handlers may throw this exception or
+ * any exception subclassed from it.</p>
+ *
+ * <p>If the application needs to pass through other types of
+ * exceptions, it must wrap those exceptions in a SAXException
+ * or an exception derived from a SAXException.</p>
+ *
+ * <p>If the parser or application needs to include information about a
+ * specific location in an XML document, it should use the
+ * {@link org.xml.sax.SAXParseException SAXParseException} subclass.</p>
+ *
+ * @since SAX 1.0
+ * @author David Megginson
+ * @version 2.0.1 (sax2r2)
+ * @see org.xml.sax.SAXParseException
+ */
+public class SAXException extends Exception {
+
+
+    /**
+     * Create a new SAXException.
+     */
+    public SAXException ()
+    {
+        super();
+        this.exception = null;
+    }
+
+
+    /**
+     * Create a new SAXException.
+     *
+     * @param message The error or warning message.
+     */
+    public SAXException (String message) {
+        super(message);
+        this.exception = null;
+    }
+
+
+    /**
+     * Create a new SAXException wrapping an existing exception.
+     *
+     * <p>The existing exception will be embedded in the new
+     * one, and its message will become the default message for
+     * the SAXException.</p>
+     *
+     * @param e The exception to be wrapped in a SAXException.
+     */
+    public SAXException (Exception e)
+    {
+        super();
+        this.exception = e;
+    }
+
+
+    /**
+     * Create a new SAXException from an existing exception.
+     *
+     * <p>The existing exception will be embedded in the new
+     * one, but the new exception will have its own message.</p>
+     *
+     * @param message The detail message.
+     * @param e The exception to be wrapped in a SAXException.
+     */
+    public SAXException (String message, Exception e)
+    {
+        super(message);
+        this.exception = e;
+    }
+
+
+    /**
+     * Return a detail message for this exception.
+     *
+     * <p>If there is an embedded exception, and if the SAXException
+     * has no detail message of its own, this method will return
+     * the detail message from the embedded exception.</p>
+     *
+     * @return The error or warning message.
+     */
+    public String getMessage ()
+    {
+        String message = super.getMessage();
+
+        if (message == null && exception != null) {
+            return exception.getMessage();
+        } else {
+            return message;
+        }
+    }
+
+
+    /**
+     * Return the embedded exception, if any.
+     *
+     * @return The embedded exception, or null if there is none.
+     */
+    public Exception getException ()
+    {
+        return exception;
+    }
+
+    /**
+     * Return the cause of the exception
+     *
+     * @return Return the cause of the exception
+     */
+    public Throwable getCause() {
+        return exception;
+    }
+
+    /**
+     * Override toString to pick up any embedded exception.
+     *
+     * @return A string representation of this exception.
+     */
+    public String toString ()
+    {
+        if (exception != null) {
+            return super.toString() + "\n" + exception.toString();
+        } else {
+            return super.toString();
+        }
+    }
+
+
+
+    //////////////////////////////////////////////////////////////////////
+    // Internal state.
+    //////////////////////////////////////////////////////////////////////
+
+
+    /**
+     * @serial The embedded exception if tunnelling, or null.
+     */
+    private Exception exception;
+
+    // Added serialVersionUID to preserve binary compatibility
+    static final long serialVersionUID = 583241635256073760L;
+}
+
+// end of SAXException.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/org/xml/sax/SAXNotRecognizedException.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// SAXNotRecognizedException.java - unrecognized feature or value.
+// http://www.saxproject.org
+// Written by David Megginson
+// NO WARRANTY!  This class is in the Public Domain.
+// $Id: SAXNotRecognizedException.java,v 1.3 2004/11/03 22:55:32 jsuttor Exp $
+
+package jdk.internal.org.xml.sax;
+
+
+/**
+ * Exception class for an unrecognized identifier.
+ *
+ * <blockquote>
+ * <em>This module, both source code and documentation, is in the
+ * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
+ * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
+ * for further information.
+ * </blockquote>
+ *
+ * <p>An XMLReader will throw this exception when it finds an
+ * unrecognized feature or property identifier; SAX applications and
+ * extensions may use this class for other, similar purposes.</p>
+ *
+ * @since SAX 2.0
+ * @author David Megginson
+ * @see org.xml.sax.SAXNotSupportedException
+ */
+public class SAXNotRecognizedException extends SAXException
+{
+
+    /**
+     * Default constructor.
+     */
+    public SAXNotRecognizedException ()
+    {
+        super();
+    }
+
+
+    /**
+     * Construct a new exception with the given message.
+     *
+     * @param message The text message of the exception.
+     */
+    public SAXNotRecognizedException (String message)
+    {
+        super(message);
+    }
+
+    // Added serialVersionUID to preserve binary compatibility
+    static final long serialVersionUID = 5440506620509557213L;
+}
+
+// end of SAXNotRecognizedException.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/org/xml/sax/SAXNotSupportedException.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// SAXNotSupportedException.java - unsupported feature or value.
+// http://www.saxproject.org
+// Written by David Megginson
+// NO WARRANTY!  This class is in the Public Domain.
+// $Id: SAXNotSupportedException.java,v 1.4 2004/11/03 22:55:32 jsuttor Exp $
+
+package jdk.internal.org.xml.sax;
+
+/**
+ * Exception class for an unsupported operation.
+ *
+ * <blockquote>
+ * <em>This module, both source code and documentation, is in the
+ * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
+ * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
+ * for further information.
+ * </blockquote>
+ *
+ * <p>An XMLReader will throw this exception when it recognizes a
+ * feature or property identifier, but cannot perform the requested
+ * operation (setting a state or value).  Other SAX2 applications and
+ * extensions may use this class for similar purposes.</p>
+ *
+ * @since SAX 2.0
+ * @author David Megginson
+ * @see org.xml.sax.SAXNotRecognizedException
+ */
+public class SAXNotSupportedException extends SAXException
+{
+
+    /**
+     * Construct a new exception with no message.
+     */
+    public SAXNotSupportedException ()
+    {
+        super();
+    }
+
+
+    /**
+     * Construct a new exception with the given message.
+     *
+     * @param message The text message of the exception.
+     */
+    public SAXNotSupportedException (String message)
+    {
+        super(message);
+    }
+
+    // Added serialVersionUID to preserve binary compatibility
+    static final long serialVersionUID = -1422818934641823846L;
+}
+
+// end of SAXNotSupportedException.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/org/xml/sax/SAXParseException.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,313 @@
+/*
+ * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// SAX exception class.
+// http://www.saxproject.org
+// No warranty; no copyright -- use this as you will.
+// $Id: SAXParseException.java,v 1.2 2004/11/03 22:55:32 jsuttor Exp $
+
+package jdk.internal.org.xml.sax;
+
+/**
+ * Encapsulate an XML parse error or warning.
+ *
+ * <blockquote>
+ * <em>This module, both source code and documentation, is in the
+ * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
+ * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
+ * for further information.
+ * </blockquote>
+ *
+ * <p>This exception may include information for locating the error
+ * in the original XML document, as if it came from a {@link Locator}
+ * object.  Note that although the application
+ * will receive a SAXParseException as the argument to the handlers
+ * in the {@link org.xml.sax.ErrorHandler ErrorHandler} interface,
+ * the application is not actually required to throw the exception;
+ * instead, it can simply read the information in it and take a
+ * different action.</p>
+ *
+ * <p>Since this exception is a subclass of {@link org.xml.sax.SAXException
+ * SAXException}, it inherits the ability to wrap another exception.</p>
+ *
+ * @since SAX 1.0
+ * @author David Megginson
+ * @version 2.0.1 (sax2r2)
+ * @see org.xml.sax.SAXException
+ * @see org.xml.sax.Locator
+ * @see org.xml.sax.ErrorHandler
+ */
+public class SAXParseException extends SAXException {
+
+
+    //////////////////////////////////////////////////////////////////////
+    // Constructors.
+    //////////////////////////////////////////////////////////////////////
+
+
+    /**
+     * Create a new SAXParseException from a message and a Locator.
+     *
+     * <p>This constructor is especially useful when an application is
+     * creating its own exception from within a {@link org.xml.sax.ContentHandler
+     * ContentHandler} callback.</p>
+     *
+     * @param message The error or warning message.
+     * @param locator The locator object for the error or warning (may be
+     *        null).
+     * @see org.xml.sax.Locator
+     */
+    public SAXParseException (String message, Locator locator) {
+        super(message);
+        if (locator != null) {
+            init(locator.getPublicId(), locator.getSystemId(),
+                 locator.getLineNumber(), locator.getColumnNumber());
+        } else {
+            init(null, null, -1, -1);
+        }
+    }
+
+
+    /**
+     * Wrap an existing exception in a SAXParseException.
+     *
+     * <p>This constructor is especially useful when an application is
+     * creating its own exception from within a {@link org.xml.sax.ContentHandler
+     * ContentHandler} callback, and needs to wrap an existing exception that is not a
+     * subclass of {@link org.xml.sax.SAXException SAXException}.</p>
+     *
+     * @param message The error or warning message, or null to
+     *                use the message from the embedded exception.
+     * @param locator The locator object for the error or warning (may be
+     *        null).
+     * @param e Any exception.
+     * @see org.xml.sax.Locator
+     */
+    public SAXParseException (String message, Locator locator,
+                              Exception e) {
+        super(message, e);
+        if (locator != null) {
+            init(locator.getPublicId(), locator.getSystemId(),
+                 locator.getLineNumber(), locator.getColumnNumber());
+        } else {
+            init(null, null, -1, -1);
+        }
+    }
+
+
+    /**
+     * Create a new SAXParseException.
+     *
+     * <p>This constructor is most useful for parser writers.</p>
+     *
+     * <p>All parameters except the message are as if
+     * they were provided by a {@link Locator}.  For example, if the
+     * system identifier is a URL (including relative filename), the
+     * caller must resolve it fully before creating the exception.</p>
+     *
+     *
+     * @param message The error or warning message.
+     * @param publicId The public identifier of the entity that generated
+     *                 the error or warning.
+     * @param systemId The system identifier of the entity that generated
+     *                 the error or warning.
+     * @param lineNumber The line number of the end of the text that
+     *                   caused the error or warning.
+     * @param columnNumber The column number of the end of the text that
+     *                     cause the error or warning.
+     */
+    public SAXParseException (String message, String publicId, String systemId,
+                              int lineNumber, int columnNumber)
+    {
+        super(message);
+        init(publicId, systemId, lineNumber, columnNumber);
+    }
+
+
+    /**
+     * Create a new SAXParseException with an embedded exception.
+     *
+     * <p>This constructor is most useful for parser writers who
+     * need to wrap an exception that is not a subclass of
+     * {@link org.xml.sax.SAXException SAXException}.</p>
+     *
+     * <p>All parameters except the message and exception are as if
+     * they were provided by a {@link Locator}.  For example, if the
+     * system identifier is a URL (including relative filename), the
+     * caller must resolve it fully before creating the exception.</p>
+     *
+     * @param message The error or warning message, or null to use
+     *                the message from the embedded exception.
+     * @param publicId The public identifier of the entity that generated
+     *                 the error or warning.
+     * @param systemId The system identifier of the entity that generated
+     *                 the error or warning.
+     * @param lineNumber The line number of the end of the text that
+     *                   caused the error or warning.
+     * @param columnNumber The column number of the end of the text that
+     *                     cause the error or warning.
+     * @param e Another exception to embed in this one.
+     */
+    public SAXParseException (String message, String publicId, String systemId,
+                              int lineNumber, int columnNumber, Exception e)
+    {
+        super(message, e);
+        init(publicId, systemId, lineNumber, columnNumber);
+    }
+
+
+    /**
+     * Internal initialization method.
+     *
+     * @param publicId The public identifier of the entity which generated the exception,
+     *        or null.
+     * @param systemId The system identifier of the entity which generated the exception,
+     *        or null.
+     * @param lineNumber The line number of the error, or -1.
+     * @param columnNumber The column number of the error, or -1.
+     */
+    private void init (String publicId, String systemId,
+                       int lineNumber, int columnNumber)
+    {
+        this.publicId = publicId;
+        this.systemId = systemId;
+        this.lineNumber = lineNumber;
+        this.columnNumber = columnNumber;
+    }
+
+
+    /**
+     * Get the public identifier of the entity where the exception occurred.
+     *
+     * @return A string containing the public identifier, or null
+     *         if none is available.
+     * @see org.xml.sax.Locator#getPublicId
+     */
+    public String getPublicId ()
+    {
+        return this.publicId;
+    }
+
+
+    /**
+     * Get the system identifier of the entity where the exception occurred.
+     *
+     * <p>If the system identifier is a URL, it will have been resolved
+     * fully.</p>
+     *
+     * @return A string containing the system identifier, or null
+     *         if none is available.
+     * @see org.xml.sax.Locator#getSystemId
+     */
+    public String getSystemId ()
+    {
+        return this.systemId;
+    }
+
+
+    /**
+     * The line number of the end of the text where the exception occurred.
+     *
+     * <p>The first line is line 1.</p>
+     *
+     * @return An integer representing the line number, or -1
+     *         if none is available.
+     * @see org.xml.sax.Locator#getLineNumber
+     */
+    public int getLineNumber ()
+    {
+        return this.lineNumber;
+    }
+
+
+    /**
+     * The column number of the end of the text where the exception occurred.
+     *
+     * <p>The first column in a line is position 1.</p>
+     *
+     * @return An integer representing the column number, or -1
+     *         if none is available.
+     * @see org.xml.sax.Locator#getColumnNumber
+     */
+    public int getColumnNumber ()
+    {
+        return this.columnNumber;
+    }
+
+    /**
+     * Override toString to provide more detailed error message.
+     *
+     * @return A string representation of this exception.
+     */
+    public String toString() {
+        StringBuilder buf = new StringBuilder(getClass().getName());
+        String message = getLocalizedMessage();
+        if (publicId!=null)    buf.append("publicId: ").append(publicId);
+        if (systemId!=null)    buf.append("; systemId: ").append(systemId);
+        if (lineNumber!=-1)    buf.append("; lineNumber: ").append(lineNumber);
+        if (columnNumber!=-1)  buf.append("; columnNumber: ").append(columnNumber);
+
+       //append the exception message at the end
+        if (message!=null)     buf.append("; ").append(message);
+        return buf.toString();
+    }
+
+    //////////////////////////////////////////////////////////////////////
+    // Internal state.
+    //////////////////////////////////////////////////////////////////////
+
+
+    /**
+     * @serial The public identifier, or null.
+     * @see #getPublicId
+     */
+    private String publicId;
+
+
+    /**
+     * @serial The system identifier, or null.
+     * @see #getSystemId
+     */
+    private String systemId;
+
+
+    /**
+     * @serial The line number, or -1.
+     * @see #getLineNumber
+     */
+    private int lineNumber;
+
+
+    /**
+     * @serial The column number, or -1.
+     * @see #getColumnNumber
+     */
+    private int columnNumber;
+
+    // Added serialVersionUID to preserve binary compatibility
+    static final long serialVersionUID = -5651165872476709336L;
+}
+
+// end of SAXParseException.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/org/xml/sax/XMLReader.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,428 @@
+/*
+ * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// XMLReader.java - read an XML document.
+// http://www.saxproject.org
+// Written by David Megginson
+// NO WARRANTY!  This class is in the Public Domain.
+// $Id: XMLReader.java,v 1.3 2004/11/03 22:55:32 jsuttor Exp $
+
+package jdk.internal.org.xml.sax;
+
+import java.io.IOException;
+
+
+/**
+ * Interface for reading an XML document using callbacks.
+ *
+ * <blockquote>
+ * <em>This module, both source code and documentation, is in the
+ * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
+ * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
+ * for further information.
+ * </blockquote>
+ *
+ * <p><strong>Note:</strong> despite its name, this interface does
+ * <em>not</em> extend the standard Java {@link java.io.Reader Reader}
+ * interface, because reading XML is a fundamentally different activity
+ * than reading character data.</p>
+ *
+ * <p>XMLReader is the interface that an XML parser's SAX2 driver must
+ * implement.  This interface allows an application to set and
+ * query features and properties in the parser, to register
+ * event handlers for document processing, and to initiate
+ * a document parse.</p>
+ *
+ * <p>All SAX interfaces are assumed to be synchronous: the
+ * {@link #parse parse} methods must not return until parsing
+ * is complete, and readers must wait for an event-handler callback
+ * to return before reporting the next event.</p>
+ *
+ * <p>This interface replaces the (now deprecated) SAX 1.0 {@link
+ * org.xml.sax.Parser Parser} interface.  The XMLReader interface
+ * contains two important enhancements over the old Parser
+ * interface (as well as some minor ones):</p>
+ *
+ * <ol>
+ * <li>it adds a standard way to query and set features and
+ *  properties; and</li>
+ * <li>it adds Namespace support, which is required for many
+ *  higher-level XML standards.</li>
+ * </ol>
+ *
+ * <p>There are adapters available to convert a SAX1 Parser to
+ * a SAX2 XMLReader and vice-versa.</p>
+ *
+ * @since SAX 2.0
+ * @author David Megginson
+ * @see org.xml.sax.XMLFilter
+ * @see org.xml.sax.helpers.ParserAdapter
+ * @see org.xml.sax.helpers.XMLReaderAdapter
+ */
+public interface XMLReader
+{
+
+
+    ////////////////////////////////////////////////////////////////////
+    // Configuration.
+    ////////////////////////////////////////////////////////////////////
+
+
+    /**
+     * Look up the value of a feature flag.
+     *
+     * <p>The feature name is any fully-qualified URI.  It is
+     * possible for an XMLReader to recognize a feature name but
+     * temporarily be unable to return its value.
+     * Some feature values may be available only in specific
+     * contexts, such as before, during, or after a parse.
+     * Also, some feature values may not be programmatically accessible.
+     * (In the case of an adapter for SAX1 {@link Parser}, there is no
+     * implementation-independent way to expose whether the underlying
+     * parser is performing validation, expanding external entities,
+     * and so forth.) </p>
+     *
+     * <p>All XMLReaders are required to recognize the
+     * http://xml.org/sax/features/namespaces and the
+     * http://xml.org/sax/features/namespace-prefixes feature names.</p>
+     *
+     * <p>Typical usage is something like this:</p>
+     *
+     * <pre>
+     * XMLReader r = new MySAXDriver();
+     *
+     *                         // try to activate validation
+     * try {
+     *   r.setFeature("http://xml.org/sax/features/validation", true);
+     * } catch (SAXException e) {
+     *   System.err.println("Cannot activate validation.");
+     * }
+     *
+     *                         // register event handlers
+     * r.setContentHandler(new MyContentHandler());
+     * r.setErrorHandler(new MyErrorHandler());
+     *
+     *                         // parse the first document
+     * try {
+     *   r.parse("http://www.foo.com/mydoc.xml");
+     * } catch (IOException e) {
+     *   System.err.println("I/O exception reading XML document");
+     * } catch (SAXException e) {
+     *   System.err.println("XML exception reading document.");
+     * }
+     * </pre>
+     *
+     * <p>Implementors are free (and encouraged) to invent their own features,
+     * using names built on their own URIs.</p>
+     *
+     * @param name The feature name, which is a fully-qualified URI.
+     * @return The current value of the feature (true or false).
+     * @exception org.xml.sax.SAXNotRecognizedException If the feature
+     *            value can't be assigned or retrieved.
+     * @exception org.xml.sax.SAXNotSupportedException When the
+     *            XMLReader recognizes the feature name but
+     *            cannot determine its value at this time.
+     * @see #setFeature
+     */
+    public boolean getFeature (String name)
+        throws SAXNotRecognizedException, SAXNotSupportedException;
+
+
+    /**
+     * Set the value of a feature flag.
+     *
+     * <p>The feature name is any fully-qualified URI.  It is
+     * possible for an XMLReader to expose a feature value but
+     * to be unable to change the current value.
+     * Some feature values may be immutable or mutable only
+     * in specific contexts, such as before, during, or after
+     * a parse.</p>
+     *
+     * <p>All XMLReaders are required to support setting
+     * http://xml.org/sax/features/namespaces to true and
+     * http://xml.org/sax/features/namespace-prefixes to false.</p>
+     *
+     * @param name The feature name, which is a fully-qualified URI.
+     * @param value The requested value of the feature (true or false).
+     * @exception org.xml.sax.SAXNotRecognizedException If the feature
+     *            value can't be assigned or retrieved.
+     * @exception org.xml.sax.SAXNotSupportedException When the
+     *            XMLReader recognizes the feature name but
+     *            cannot set the requested value.
+     * @see #getFeature
+     */
+    public void setFeature (String name, boolean value)
+        throws SAXNotRecognizedException, SAXNotSupportedException;
+
+
+    /**
+     * Look up the value of a property.
+     *
+     * <p>The property name is any fully-qualified URI.  It is
+     * possible for an XMLReader to recognize a property name but
+     * temporarily be unable to return its value.
+     * Some property values may be available only in specific
+     * contexts, such as before, during, or after a parse.</p>
+     *
+     * <p>XMLReaders are not required to recognize any specific
+     * property names, though an initial core set is documented for
+     * SAX2.</p>
+     *
+     * <p>Implementors are free (and encouraged) to invent their own properties,
+     * using names built on their own URIs.</p>
+     *
+     * @param name The property name, which is a fully-qualified URI.
+     * @return The current value of the property.
+     * @exception org.xml.sax.SAXNotRecognizedException If the property
+     *            value can't be assigned or retrieved.
+     * @exception org.xml.sax.SAXNotSupportedException When the
+     *            XMLReader recognizes the property name but
+     *            cannot determine its value at this time.
+     * @see #setProperty
+     */
+    public Object getProperty (String name)
+        throws SAXNotRecognizedException, SAXNotSupportedException;
+
+
+    /**
+     * Set the value of a property.
+     *
+     * <p>The property name is any fully-qualified URI.  It is
+     * possible for an XMLReader to recognize a property name but
+     * to be unable to change the current value.
+     * Some property values may be immutable or mutable only
+     * in specific contexts, such as before, during, or after
+     * a parse.</p>
+     *
+     * <p>XMLReaders are not required to recognize setting
+     * any specific property names, though a core set is defined by
+     * SAX2.</p>
+     *
+     * <p>This method is also the standard mechanism for setting
+     * extended handlers.</p>
+     *
+     * @param name The property name, which is a fully-qualified URI.
+     * @param value The requested value for the property.
+     * @exception org.xml.sax.SAXNotRecognizedException If the property
+     *            value can't be assigned or retrieved.
+     * @exception org.xml.sax.SAXNotSupportedException When the
+     *            XMLReader recognizes the property name but
+     *            cannot set the requested value.
+     */
+    public void setProperty (String name, Object value)
+        throws SAXNotRecognizedException, SAXNotSupportedException;
+
+
+
+    ////////////////////////////////////////////////////////////////////
+    // Event handlers.
+    ////////////////////////////////////////////////////////////////////
+
+
+    /**
+     * Allow an application to register an entity resolver.
+     *
+     * <p>If the application does not register an entity resolver,
+     * the XMLReader will perform its own default resolution.</p>
+     *
+     * <p>Applications may register a new or different resolver in the
+     * middle of a parse, and the SAX parser must begin using the new
+     * resolver immediately.</p>
+     *
+     * @param resolver The entity resolver.
+     * @see #getEntityResolver
+     */
+    public void setEntityResolver (EntityResolver resolver);
+
+
+    /**
+     * Return the current entity resolver.
+     *
+     * @return The current entity resolver, or null if none
+     *         has been registered.
+     * @see #setEntityResolver
+     */
+    public EntityResolver getEntityResolver ();
+
+
+    /**
+     * Allow an application to register a DTD event handler.
+     *
+     * <p>If the application does not register a DTD handler, all DTD
+     * events reported by the SAX parser will be silently ignored.</p>
+     *
+     * <p>Applications may register a new or different handler in the
+     * middle of a parse, and the SAX parser must begin using the new
+     * handler immediately.</p>
+     *
+     * @param handler The DTD handler.
+     * @see #getDTDHandler
+     */
+    public void setDTDHandler (DTDHandler handler);
+
+
+    /**
+     * Return the current DTD handler.
+     *
+     * @return The current DTD handler, or null if none
+     *         has been registered.
+     * @see #setDTDHandler
+     */
+    public DTDHandler getDTDHandler ();
+
+
+    /**
+     * Allow an application to register a content event handler.
+     *
+     * <p>If the application does not register a content handler, all
+     * content events reported by the SAX parser will be silently
+     * ignored.</p>
+     *
+     * <p>Applications may register a new or different handler in the
+     * middle of a parse, and the SAX parser must begin using the new
+     * handler immediately.</p>
+     *
+     * @param handler The content handler.
+     * @see #getContentHandler
+     */
+    public void setContentHandler (ContentHandler handler);
+
+
+    /**
+     * Return the current content handler.
+     *
+     * @return The current content handler, or null if none
+     *         has been registered.
+     * @see #setContentHandler
+     */
+    public ContentHandler getContentHandler ();
+
+
+    /**
+     * Allow an application to register an error event handler.
+     *
+     * <p>If the application does not register an error handler, all
+     * error events reported by the SAX parser will be silently
+     * ignored; however, normal processing may not continue.  It is
+     * highly recommended that all SAX applications implement an
+     * error handler to avoid unexpected bugs.</p>
+     *
+     * <p>Applications may register a new or different handler in the
+     * middle of a parse, and the SAX parser must begin using the new
+     * handler immediately.</p>
+     *
+     * @param handler The error handler.
+     * @see #getErrorHandler
+     */
+    public void setErrorHandler (ErrorHandler handler);
+
+
+    /**
+     * Return the current error handler.
+     *
+     * @return The current error handler, or null if none
+     *         has been registered.
+     * @see #setErrorHandler
+     */
+    public ErrorHandler getErrorHandler ();
+
+
+
+    ////////////////////////////////////////////////////////////////////
+    // Parsing.
+    ////////////////////////////////////////////////////////////////////
+
+    /**
+     * Parse an XML document.
+     *
+     * <p>The application can use this method to instruct the XML
+     * reader to begin parsing an XML document from any valid input
+     * source (a character stream, a byte stream, or a URI).</p>
+     *
+     * <p>Applications may not invoke this method while a parse is in
+     * progress (they should create a new XMLReader instead for each
+     * nested XML document).  Once a parse is complete, an
+     * application may reuse the same XMLReader object, possibly with a
+     * different input source.
+     * Configuration of the XMLReader object (such as handler bindings and
+     * values established for feature flags and properties) is unchanged
+     * by completion of a parse, unless the definition of that aspect of
+     * the configuration explicitly specifies other behavior.
+     * (For example, feature flags or properties exposing
+     * characteristics of the document being parsed.)
+     * </p>
+     *
+     * <p>During the parse, the XMLReader will provide information
+     * about the XML document through the registered event
+     * handlers.</p>
+     *
+     * <p>This method is synchronous: it will not return until parsing
+     * has ended.  If a client application wants to terminate
+     * parsing early, it should throw an exception.</p>
+     *
+     * @param input The input source for the top-level of the
+     *        XML document.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @exception java.io.IOException An IO exception from the parser,
+     *            possibly from a byte stream or character stream
+     *            supplied by the application.
+     * @see org.xml.sax.InputSource
+     * @see #parse(java.lang.String)
+     * @see #setEntityResolver
+     * @see #setDTDHandler
+     * @see #setContentHandler
+     * @see #setErrorHandler
+     */
+    public void parse (InputSource input)
+        throws IOException, SAXException;
+
+
+    /**
+     * Parse an XML document from a system identifier (URI).
+     *
+     * <p>This method is a shortcut for the common case of reading a
+     * document from a system identifier.  It is the exact
+     * equivalent of the following:</p>
+     *
+     * <pre>
+     * parse(new InputSource(systemId));
+     * </pre>
+     *
+     * <p>If the system identifier is a URL, it must be fully resolved
+     * by the application before it is passed to the parser.</p>
+     *
+     * @param systemId The system identifier (URI).
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @exception java.io.IOException An IO exception from the parser,
+     *            possibly from a byte stream or character stream
+     *            supplied by the application.
+     * @see #parse(org.xml.sax.InputSource)
+     */
+    public void parse (String systemId)
+        throws IOException, SAXException;
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/org/xml/sax/helpers/DefaultHandler.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,491 @@
+/*
+ * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// DefaultHandler.java - default implementation of the core handlers.
+// http://www.saxproject.org
+// Written by David Megginson
+// NO WARRANTY!  This class is in the public domain.
+// $Id: DefaultHandler.java,v 1.3 2006/04/13 02:06:32 jeffsuttor Exp $
+
+package jdk.internal.org.xml.sax.helpers;
+
+import java.io.IOException;
+
+import jdk.internal.org.xml.sax.InputSource;
+import jdk.internal.org.xml.sax.Locator;
+import jdk.internal.org.xml.sax.Attributes;
+import jdk.internal.org.xml.sax.EntityResolver;
+import jdk.internal.org.xml.sax.DTDHandler;
+import jdk.internal.org.xml.sax.ContentHandler;
+import jdk.internal.org.xml.sax.ErrorHandler;
+import jdk.internal.org.xml.sax.SAXException;
+import jdk.internal.org.xml.sax.SAXParseException;
+
+
+/**
+ * Default base class for SAX2 event handlers.
+ *
+ * <blockquote>
+ * <em>This module, both source code and documentation, is in the
+ * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
+ * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
+ * for further information.
+ * </blockquote>
+ *
+ * <p>This class is available as a convenience base class for SAX2
+ * applications: it provides default implementations for all of the
+ * callbacks in the four core SAX2 handler classes:</p>
+ *
+ * <ul>
+ * <li>{@link org.xml.sax.EntityResolver EntityResolver}</li>
+ * <li>{@link org.xml.sax.DTDHandler DTDHandler}</li>
+ * <li>{@link org.xml.sax.ContentHandler ContentHandler}</li>
+ * <li>{@link org.xml.sax.ErrorHandler ErrorHandler}</li>
+ * </ul>
+ *
+ * <p>Application writers can extend this class when they need to
+ * implement only part of an interface; parser writers can
+ * instantiate this class to provide default handlers when the
+ * application has not supplied its own.</p>
+ *
+ * <p>This class replaces the deprecated SAX1
+ * {@link org.xml.sax.HandlerBase HandlerBase} class.</p>
+ *
+ * @since SAX 2.0
+ * @author David Megginson,
+ * @see org.xml.sax.EntityResolver
+ * @see org.xml.sax.DTDHandler
+ * @see org.xml.sax.ContentHandler
+ * @see org.xml.sax.ErrorHandler
+ */
+public class DefaultHandler
+    implements EntityResolver, DTDHandler, ContentHandler, ErrorHandler
+{
+
+
+    ////////////////////////////////////////////////////////////////////
+    // Default implementation of the EntityResolver interface.
+    ////////////////////////////////////////////////////////////////////
+
+    /**
+     * Resolve an external entity.
+     *
+     * <p>Always return null, so that the parser will use the system
+     * identifier provided in the XML document.  This method implements
+     * the SAX default behaviour: application writers can override it
+     * in a subclass to do special translations such as catalog lookups
+     * or URI redirection.</p>
+     *
+     * @param publicId The public identifier, or null if none is
+     *                 available.
+     * @param systemId The system identifier provided in the XML
+     *                 document.
+     * @return The new input source, or null to require the
+     *         default behaviour.
+     * @exception java.io.IOException If there is an error setting
+     *            up the new input source.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.EntityResolver#resolveEntity
+     */
+    public InputSource resolveEntity (String publicId, String systemId)
+        throws IOException, SAXException
+    {
+        return null;
+    }
+
+
+
+    ////////////////////////////////////////////////////////////////////
+    // Default implementation of DTDHandler interface.
+    ////////////////////////////////////////////////////////////////////
+
+
+    /**
+     * Receive notification of a notation declaration.
+     *
+     * <p>By default, do nothing.  Application writers may override this
+     * method in a subclass if they wish to keep track of the notations
+     * declared in a document.</p>
+     *
+     * @param name The notation name.
+     * @param publicId The notation public identifier, or null if not
+     *                 available.
+     * @param systemId The notation system identifier.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.DTDHandler#notationDecl
+     */
+    public void notationDecl (String name, String publicId, String systemId)
+        throws SAXException
+    {
+        // no op
+    }
+
+
+    /**
+     * Receive notification of an unparsed entity declaration.
+     *
+     * <p>By default, do nothing.  Application writers may override this
+     * method in a subclass to keep track of the unparsed entities
+     * declared in a document.</p>
+     *
+     * @param name The entity name.
+     * @param publicId The entity public identifier, or null if not
+     *                 available.
+     * @param systemId The entity system identifier.
+     * @param notationName The name of the associated notation.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.DTDHandler#unparsedEntityDecl
+     */
+    public void unparsedEntityDecl (String name, String publicId,
+                                    String systemId, String notationName)
+        throws SAXException
+    {
+        // no op
+    }
+
+
+
+    ////////////////////////////////////////////////////////////////////
+    // Default implementation of ContentHandler interface.
+    ////////////////////////////////////////////////////////////////////
+
+
+    /**
+     * Receive a Locator object for document events.
+     *
+     * <p>By default, do nothing.  Application writers may override this
+     * method in a subclass if they wish to store the locator for use
+     * with other document events.</p>
+     *
+     * @param locator A locator for all SAX document events.
+     * @see org.xml.sax.ContentHandler#setDocumentLocator
+     * @see org.xml.sax.Locator
+     */
+    public void setDocumentLocator (Locator locator)
+    {
+        // no op
+    }
+
+
+    /**
+     * Receive notification of the beginning of the document.
+     *
+     * <p>By default, do nothing.  Application writers may override this
+     * method in a subclass to take specific actions at the beginning
+     * of a document (such as allocating the root node of a tree or
+     * creating an output file).</p>
+     *
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ContentHandler#startDocument
+     */
+    public void startDocument ()
+        throws SAXException
+    {
+        // no op
+    }
+
+
+    /**
+     * Receive notification of the end of the document.
+     *
+     * <p>By default, do nothing.  Application writers may override this
+     * method in a subclass to take specific actions at the end
+     * of a document (such as finalising a tree or closing an output
+     * file).</p>
+     *
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ContentHandler#endDocument
+     */
+    public void endDocument ()
+        throws SAXException
+    {
+        // no op
+    }
+
+
+    /**
+     * Receive notification of the start of a Namespace mapping.
+     *
+     * <p>By default, do nothing.  Application writers may override this
+     * method in a subclass to take specific actions at the start of
+     * each Namespace prefix scope (such as storing the prefix mapping).</p>
+     *
+     * @param prefix The Namespace prefix being declared.
+     * @param uri The Namespace URI mapped to the prefix.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ContentHandler#startPrefixMapping
+     */
+    public void startPrefixMapping (String prefix, String uri)
+        throws SAXException
+    {
+        // no op
+    }
+
+
+    /**
+     * Receive notification of the end of a Namespace mapping.
+     *
+     * <p>By default, do nothing.  Application writers may override this
+     * method in a subclass to take specific actions at the end of
+     * each prefix mapping.</p>
+     *
+     * @param prefix The Namespace prefix being declared.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ContentHandler#endPrefixMapping
+     */
+    public void endPrefixMapping (String prefix)
+        throws SAXException
+    {
+        // no op
+    }
+
+
+    /**
+     * Receive notification of the start of an element.
+     *
+     * <p>By default, do nothing.  Application writers may override this
+     * method in a subclass to take specific actions at the start of
+     * each element (such as allocating a new tree node or writing
+     * output to a file).</p>
+     *
+     * @param uri The Namespace URI, or the empty string if the
+     *        element has no Namespace URI or if Namespace
+     *        processing is not being performed.
+     * @param localName The local name (without prefix), or the
+     *        empty string if Namespace processing is not being
+     *        performed.
+     * @param qName The qualified name (with prefix), or the
+     *        empty string if qualified names are not available.
+     * @param attributes The attributes attached to the element.  If
+     *        there are no attributes, it shall be an empty
+     *        Attributes object.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ContentHandler#startElement
+     */
+    public void startElement (String uri, String localName,
+                              String qName, Attributes attributes)
+        throws SAXException
+    {
+        // no op
+    }
+
+
+    /**
+     * Receive notification of the end of an element.
+     *
+     * <p>By default, do nothing.  Application writers may override this
+     * method in a subclass to take specific actions at the end of
+     * each element (such as finalising a tree node or writing
+     * output to a file).</p>
+     *
+     * @param uri The Namespace URI, or the empty string if the
+     *        element has no Namespace URI or if Namespace
+     *        processing is not being performed.
+     * @param localName The local name (without prefix), or the
+     *        empty string if Namespace processing is not being
+     *        performed.
+     * @param qName The qualified name (with prefix), or the
+     *        empty string if qualified names are not available.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ContentHandler#endElement
+     */
+    public void endElement (String uri, String localName, String qName)
+        throws SAXException
+    {
+        // no op
+    }
+
+
+    /**
+     * Receive notification of character data inside an element.
+     *
+     * <p>By default, do nothing.  Application writers may override this
+     * method to take specific actions for each chunk of character data
+     * (such as adding the data to a node or buffer, or printing it to
+     * a file).</p>
+     *
+     * @param ch The characters.
+     * @param start The start position in the character array.
+     * @param length The number of characters to use from the
+     *               character array.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ContentHandler#characters
+     */
+    public void characters (char ch[], int start, int length)
+        throws SAXException
+    {
+        // no op
+    }
+
+
+    /**
+     * Receive notification of ignorable whitespace in element content.
+     *
+     * <p>By default, do nothing.  Application writers may override this
+     * method to take specific actions for each chunk of ignorable
+     * whitespace (such as adding data to a node or buffer, or printing
+     * it to a file).</p>
+     *
+     * @param ch The whitespace characters.
+     * @param start The start position in the character array.
+     * @param length The number of characters to use from the
+     *               character array.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ContentHandler#ignorableWhitespace
+     */
+    public void ignorableWhitespace (char ch[], int start, int length)
+        throws SAXException
+    {
+        // no op
+    }
+
+
+    /**
+     * Receive notification of a processing instruction.
+     *
+     * <p>By default, do nothing.  Application writers may override this
+     * method in a subclass to take specific actions for each
+     * processing instruction, such as setting status variables or
+     * invoking other methods.</p>
+     *
+     * @param target The processing instruction target.
+     * @param data The processing instruction data, or null if
+     *             none is supplied.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ContentHandler#processingInstruction
+     */
+    public void processingInstruction (String target, String data)
+        throws SAXException
+    {
+        // no op
+    }
+
+
+    /**
+     * Receive notification of a skipped entity.
+     *
+     * <p>By default, do nothing.  Application writers may override this
+     * method in a subclass to take specific actions for each
+     * processing instruction, such as setting status variables or
+     * invoking other methods.</p>
+     *
+     * @param name The name of the skipped entity.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ContentHandler#processingInstruction
+     */
+    public void skippedEntity (String name)
+        throws SAXException
+    {
+        // no op
+    }
+
+
+
+    ////////////////////////////////////////////////////////////////////
+    // Default implementation of the ErrorHandler interface.
+    ////////////////////////////////////////////////////////////////////
+
+
+    /**
+     * Receive notification of a parser warning.
+     *
+     * <p>The default implementation does nothing.  Application writers
+     * may override this method in a subclass to take specific actions
+     * for each warning, such as inserting the message in a log file or
+     * printing it to the console.</p>
+     *
+     * @param e The warning information encoded as an exception.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ErrorHandler#warning
+     * @see org.xml.sax.SAXParseException
+     */
+    public void warning (SAXParseException e)
+        throws SAXException
+    {
+        // no op
+    }
+
+
+    /**
+     * Receive notification of a recoverable parser error.
+     *
+     * <p>The default implementation does nothing.  Application writers
+     * may override this method in a subclass to take specific actions
+     * for each error, such as inserting the message in a log file or
+     * printing it to the console.</p>
+     *
+     * @param e The error information encoded as an exception.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ErrorHandler#warning
+     * @see org.xml.sax.SAXParseException
+     */
+    public void error (SAXParseException e)
+        throws SAXException
+    {
+        // no op
+    }
+
+
+    /**
+     * Report a fatal XML parsing error.
+     *
+     * <p>The default implementation throws a SAXParseException.
+     * Application writers may override this method in a subclass if
+     * they need to take specific actions for each fatal error (such as
+     * collecting all of the errors into a single report): in any case,
+     * the application must stop all regular processing when this
+     * method is invoked, since the document is no longer reliable, and
+     * the parser may no longer report parsing events.</p>
+     *
+     * @param e The error information encoded as an exception.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly
+     *            wrapping another exception.
+     * @see org.xml.sax.ErrorHandler#fatalError
+     * @see org.xml.sax.SAXParseException
+     */
+    public void fatalError (SAXParseException e)
+        throws SAXException
+    {
+        throw e;
+    }
+
+}
+
+// end of DefaultHandler.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/BasicXmlPropertiesProvider.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package jdk.internal.util.xml;
+
+import java.util.Properties;
+import java.util.InvalidPropertiesFormatException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.IOException;
+
+import sun.util.spi.XmlPropertiesProvider;
+
+/**
+ * A {@code XmlPropertiesProvider} implementation that uses the UKit XML parser.
+ */
+
+public class BasicXmlPropertiesProvider extends XmlPropertiesProvider {
+
+    public BasicXmlPropertiesProvider() { }
+
+    @Override
+    public void load(Properties props, InputStream in)
+        throws IOException, InvalidPropertiesFormatException
+    {
+        PropertiesDefaultHandler handler = new PropertiesDefaultHandler();
+        handler.load(props, in);
+    }
+
+    @Override
+    public void store(Properties props, OutputStream os, String comment,
+                      String encoding)
+        throws IOException
+    {
+        PropertiesDefaultHandler handler = new PropertiesDefaultHandler();
+        handler.store(props, os, comment, encoding);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/PropertiesDefaultHandler.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,232 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml;
+
+import java.io.*;
+import java.util.InvalidPropertiesFormatException;
+import java.util.Properties;
+import jdk.internal.org.xml.sax.Attributes;
+import jdk.internal.org.xml.sax.InputSource;
+import jdk.internal.org.xml.sax.SAXException;
+import jdk.internal.org.xml.sax.SAXParseException;
+import jdk.internal.org.xml.sax.helpers.DefaultHandler;
+import jdk.internal.util.xml.impl.SAXParserImpl;
+import jdk.internal.util.xml.impl.XMLStreamWriterImpl;
+
+/**
+ * A class used to aid in Properties load and save in XML. This class is
+ * re-implemented using a subset of SAX
+ *
+ * @author Joe Wang
+ * @since 8
+ */
+public class PropertiesDefaultHandler extends DefaultHandler {
+
+    // Elements specified in the properties.dtd
+    private static final String ELEMENT_ROOT = "properties";
+    private static final String ELEMENT_COMMENT = "comment";
+    private static final String ELEMENT_ENTRY = "entry";
+    private static final String ATTR_KEY = "key";
+    // The required DTD URI for exported properties
+    private static final String PROPS_DTD_DECL =
+            "<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">";
+    private static final String PROPS_DTD_URI =
+            "http://java.sun.com/dtd/properties.dtd";
+    private static final String PROPS_DTD =
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+            + "<!-- DTD for properties -->"
+            + "<!ELEMENT properties ( comment?, entry* ) >"
+            + "<!ATTLIST properties"
+            + " version CDATA #FIXED \"1.0\">"
+            + "<!ELEMENT comment (#PCDATA) >"
+            + "<!ELEMENT entry (#PCDATA) >"
+            + "<!ATTLIST entry "
+            + " key CDATA #REQUIRED>";
+    /**
+     * Version number for the format of exported properties files.
+     */
+    private static final String EXTERNAL_XML_VERSION = "1.0";
+    private Properties properties;
+
+    public void load(Properties props, InputStream in)
+        throws IOException, InvalidPropertiesFormatException, UnsupportedEncodingException
+    {
+        this.properties = props;
+
+        try {
+            SAXParser parser = new SAXParserImpl();
+            parser.parse(in, this);
+        } catch (SAXException saxe) {
+            throw new InvalidPropertiesFormatException(saxe);
+        }
+
+        /**
+         * String xmlVersion = propertiesElement.getAttribute("version"); if
+         * (xmlVersion.compareTo(EXTERNAL_XML_VERSION) > 0) throw new
+         * InvalidPropertiesFormatException( "Exported Properties file format
+         * version " + xmlVersion + " is not supported. This java installation
+         * can read" + " versions " + EXTERNAL_XML_VERSION + " or older. You" +
+         * " may need to install a newer version of JDK.");
+         */
+    }
+
+    public void store(Properties props, OutputStream os, String comment, String encoding)
+        throws IOException
+    {
+        try {
+            XMLStreamWriter writer = new XMLStreamWriterImpl(os, encoding);
+            writer.writeStartDocument();
+            writer.writeDTD(PROPS_DTD_DECL);
+            writer.writeStartElement(ELEMENT_ROOT);
+            if (comment != null && comment.length() > 0) {
+                writer.writeStartElement(ELEMENT_COMMENT);
+                writer.writeCharacters(comment);
+                writer.writeEndElement();
+            }
+
+            for (String key : props.stringPropertyNames()) {
+                String val = props.getProperty(key);
+                writer.writeStartElement(ELEMENT_ENTRY);
+                writer.writeAttribute(ATTR_KEY, key);
+                writer.writeCharacters(val);
+                writer.writeEndElement();
+            }
+
+            writer.writeEndElement();
+            writer.writeEndDocument();
+            writer.close();
+        } catch (XMLStreamException e) {
+            if (e.getCause() instanceof UnsupportedEncodingException) {
+                throw (UnsupportedEncodingException) e.getCause();
+            }
+            throw new IOException(e);
+        }
+
+    }
+    ////////////////////////////////////////////////////////////////////
+    // Validate while parsing
+    ////////////////////////////////////////////////////////////////////
+    final static String ALLOWED_ELEMENTS = "properties, comment, entry";
+    final static String ALLOWED_COMMENT = "comment";
+    ////////////////////////////////////////////////////////////////////
+    // Handler methods
+    ////////////////////////////////////////////////////////////////////
+    StringBuffer buf = new StringBuffer();
+    boolean sawComment = false;
+    boolean validEntry = false;
+    int rootElem = 0;
+    String key;
+    String rootElm;
+
+    @Override
+    public void startElement(String uri, String localName, String qName, Attributes attributes)
+        throws SAXException
+    {
+        if (rootElem < 2) {
+            rootElem++;
+        }
+
+        if (rootElm == null) {
+            fatalError(new SAXParseException("An XML properties document must contain"
+                    + " the DOCTYPE declaration as defined by java.util.Properties.", null));
+        }
+
+        if (rootElem == 1 && !rootElm.equals(qName)) {
+            fatalError(new SAXParseException("Document root element \"" + qName
+                    + "\", must match DOCTYPE root \"" + rootElm + "\"", null));
+        }
+        if (!ALLOWED_ELEMENTS.contains(qName)) {
+            fatalError(new SAXParseException("Element type \"" + qName + "\" must be declared.", null));
+        }
+        if (qName.equals(ELEMENT_ENTRY)) {
+            validEntry = true;
+            key = attributes.getValue(ATTR_KEY);
+            if (key == null) {
+                fatalError(new SAXParseException("Attribute \"key\" is required and must be specified for element type \"entry\"", null));
+            }
+        } else if (qName.equals(ALLOWED_COMMENT)) {
+            if (sawComment) {
+                fatalError(new SAXParseException("Only one comment element may be allowed. "
+                        + "The content of element type \"properties\" must match \"(comment?,entry*)\"", null));
+            }
+            sawComment = true;
+        }
+    }
+
+    @Override
+    public void characters(char[] ch, int start, int length) throws SAXException {
+        if (validEntry) {
+            buf.append(ch, start, length);
+        }
+    }
+
+    @Override
+    public void endElement(String uri, String localName, String qName) throws SAXException {
+        if (!ALLOWED_ELEMENTS.contains(qName)) {
+            fatalError(new SAXParseException("Element: " + qName + " is invalid, must match  \"(comment?,entry*)\".", null));
+        }
+
+        if (validEntry) {
+            properties.setProperty(key, buf.toString());
+            buf.delete(0, buf.length());
+            validEntry = false;
+        }
+    }
+
+    @Override
+    public void notationDecl(String name, String publicId, String systemId) throws SAXException {
+        rootElm = name;
+    }
+
+    @Override
+    public InputSource resolveEntity(String pubid, String sysid)
+            throws SAXException, IOException {
+        {
+            if (sysid.equals(PROPS_DTD_URI)) {
+                InputSource is;
+                is = new InputSource(new StringReader(PROPS_DTD));
+                is.setSystemId(PROPS_DTD_URI);
+                return is;
+            }
+            throw new SAXException("Invalid system identifier: " + sysid);
+        }
+    }
+
+    @Override
+    public void error(SAXParseException x) throws SAXException {
+        throw x;
+    }
+
+    @Override
+    public void fatalError(SAXParseException x) throws SAXException {
+        throw x;
+    }
+
+    @Override
+    public void warning(SAXParseException x) throws SAXException {
+        throw x;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/SAXParser.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,246 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import jdk.internal.org.xml.sax.InputSource;
+import jdk.internal.org.xml.sax.SAXException;
+import jdk.internal.org.xml.sax.XMLReader;
+import jdk.internal.org.xml.sax.helpers.DefaultHandler;
+
+
+/**
+ * Defines the API that wraps an {@link org.xml.sax.XMLReader}
+ * implementation class. In JAXP 1.0, this class wrapped the
+ * {@link org.xml.sax.Parser} interface, however this interface was
+ * replaced by the {@link org.xml.sax.XMLReader}. For ease
+ * of transition, this class continues to support the same name
+ * and interface as well as supporting new methods.
+ *
+ * An instance of this class can be obtained from the
+ * {@link javax.xml.parsers.SAXParserFactory#newSAXParser()} method.
+ * Once an instance of this class is obtained, XML can be parsed from
+ * a variety of input sources. These input sources are InputStreams,
+ * Files, URLs, and SAX InputSources.<p>
+ *
+ * This static method creates a new factory instance based
+ * on a system property setting or uses the platform default
+ * if no property has been defined.<p>
+ *
+ * The system property that controls which Factory implementation
+ * to create is named <code>&quot;javax.xml.parsers.SAXParserFactory&quot;</code>.
+ * This property names a class that is a concrete subclass of this
+ * abstract class. If no property is defined, a platform default
+ * will be used.</p>
+ *
+ * As the content is parsed by the underlying parser, methods of the
+ * given
+ * {@link org.xml.sax.helpers.DefaultHandler} are called.<p>
+ *
+ * Implementors of this class which wrap an underlaying implementation
+ * can consider using the {@link org.xml.sax.helpers.ParserAdapter}
+ * class to initially adapt their SAX1 implementation to work under
+ * this revised class.
+ *
+ * @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
+ * @version $Revision: 1.8 $, $Date: 2010-11-01 04:36:09 $
+ *
+ * @author Joe Wang
+ * This is a subset of that in JAXP, javax.xml.parsers.SAXParser
+ *
+ */
+public abstract class SAXParser {
+
+    /**
+     * <p>Protected constructor to prevent instantiation.</p>
+     */
+    protected SAXParser() {
+    }
+
+    /**
+     * Parse the content of the given {@link java.io.InputStream}
+     * instance as XML using the specified
+     * {@link org.xml.sax.helpers.DefaultHandler}.
+     *
+     * @param is InputStream containing the content to be parsed.
+     * @param dh The SAX DefaultHandler to use.
+     *
+     * @throws IllegalArgumentException If the given InputStream is null.
+     * @throws IOException If any IO errors occur.
+     * @throws SAXException If any SAX errors occur during processing.
+     *
+     * @see org.xml.sax.DocumentHandler
+     */
+    public void parse(InputStream is, DefaultHandler dh)
+        throws SAXException, IOException
+    {
+        if (is == null) {
+            throw new IllegalArgumentException("InputStream cannot be null");
+        }
+
+        InputSource input = new InputSource(is);
+        this.parse(input, dh);
+    }
+
+    /**
+     * Parse the content described by the giving Uniform Resource
+     * Identifier (URI) as XML using the specified
+     * {@link org.xml.sax.helpers.DefaultHandler}.
+     *
+     * @param uri The location of the content to be parsed.
+     * @param dh The SAX DefaultHandler to use.
+     *
+     * @throws IllegalArgumentException If the uri is null.
+     * @throws IOException If any IO errors occur.
+     * @throws SAXException If any SAX errors occur during processing.
+     *
+     * @see org.xml.sax.DocumentHandler
+     */
+    public void parse(String uri, DefaultHandler dh)
+        throws SAXException, IOException
+    {
+        if (uri == null) {
+            throw new IllegalArgumentException("uri cannot be null");
+        }
+
+        InputSource input = new InputSource(uri);
+        this.parse(input, dh);
+    }
+
+    /**
+     * Parse the content of the file specified as XML using the
+     * specified {@link org.xml.sax.helpers.DefaultHandler}.
+     *
+     * @param f The file containing the XML to parse
+     * @param dh The SAX DefaultHandler to use.
+     *
+     * @throws IllegalArgumentException If the File object is null.
+     * @throws IOException If any IO errors occur.
+     * @throws SAXException If any SAX errors occur during processing.
+     *
+     * @see org.xml.sax.DocumentHandler
+     */
+    public void parse(File f, DefaultHandler dh)
+        throws SAXException, IOException
+    {
+        if (f == null) {
+            throw new IllegalArgumentException("File cannot be null");
+        }
+
+        //convert file to appropriate URI, f.toURI().toASCIIString()
+        //converts the URI to string as per rule specified in
+        //RFC 2396,
+        InputSource input = new InputSource(f.toURI().toASCIIString());
+        this.parse(input, dh);
+    }
+
+    /**
+     * Parse the content given {@link org.xml.sax.InputSource}
+     * as XML using the specified
+     * {@link org.xml.sax.helpers.DefaultHandler}.
+     *
+     * @param is The InputSource containing the content to be parsed.
+     * @param dh The SAX DefaultHandler to use.
+     *
+     * @throws IllegalArgumentException If the <code>InputSource</code> object
+     *   is <code>null</code>.
+     * @throws IOException If any IO errors occur.
+     * @throws SAXException If any SAX errors occur during processing.
+     *
+     * @see org.xml.sax.DocumentHandler
+     */
+    public void parse(InputSource is, DefaultHandler dh)
+        throws SAXException, IOException
+    {
+        if (is == null) {
+            throw new IllegalArgumentException("InputSource cannot be null");
+        }
+
+        XMLReader reader = this.getXMLReader();
+        if (dh != null) {
+            reader.setContentHandler(dh);
+            reader.setEntityResolver(dh);
+            reader.setErrorHandler(dh);
+            reader.setDTDHandler(dh);
+        }
+        reader.parse(is);
+    }
+
+    /**
+     * Returns the {@link org.xml.sax.XMLReader} that is encapsulated by the
+     * implementation of this class.
+     *
+     * @return The XMLReader that is encapsulated by the
+     *         implementation of this class.
+     *
+     * @throws SAXException If any SAX errors occur during processing.
+     */
+    public abstract XMLReader getXMLReader() throws SAXException;
+
+    /**
+     * Indicates whether or not this parser is configured to
+     * understand namespaces.
+     *
+     * @return true if this parser is configured to
+     *         understand namespaces; false otherwise.
+     */
+    public abstract boolean isNamespaceAware();
+
+    /**
+     * Indicates whether or not this parser is configured to
+     * validate XML documents.
+     *
+     * @return true if this parser is configured to
+     *         validate XML documents; false otherwise.
+     */
+    public abstract boolean isValidating();
+
+    /**
+     * <p>Get the XInclude processing mode for this parser.</p>
+     *
+     * @return
+     *      the return value of
+     *      the {@link SAXParserFactory#isXIncludeAware()}
+     *      when this parser was created from factory.
+     *
+     * @throws UnsupportedOperationException When implementation does not
+     *   override this method
+     *
+     * @since 1.5
+     *
+     * @see SAXParserFactory#setXIncludeAware(boolean)
+     */
+    public boolean isXIncludeAware() {
+        throw new UnsupportedOperationException(
+                "This parser does not support specification \""
+                + this.getClass().getPackage().getSpecificationTitle()
+                + "\" version \""
+                + this.getClass().getPackage().getSpecificationVersion()
+                + "\"");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/XMLStreamException.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml;
+
+/**
+ * A copy of the StAX XMLStreamException without Location support
+ *
+ * The base exception for unexpected processing errors.  This Exception
+ * class is used to report well-formedness errors as well as unexpected
+ * processing conditions.
+ * @version 1.0
+ * @author Copyright (c) 2009 by Oracle Corporation. All Rights Reserved.
+ * @since 1.6
+ */
+
+public class XMLStreamException extends Exception {
+    private static final long serialVersionUID = 1L;
+
+
+    protected Throwable nested;
+
+    /**
+     * Default constructor
+     */
+    public XMLStreamException() {
+        super();
+    }
+
+    /**
+     * Construct an exception with the assocated message.
+     *
+     * @param msg the message to report
+     */
+    public XMLStreamException(String msg) {
+        super(msg);
+    }
+
+    /**
+     * Construct an exception with the assocated exception
+     *
+     * @param th a nested exception
+     */
+    public XMLStreamException(Throwable th) {
+        super(th);
+        nested = th;
+    }
+
+    /**
+     * Construct an exception with the assocated message and exception
+     *
+     * @param th a nested exception
+     * @param msg the message to report
+     */
+    public XMLStreamException(String msg, Throwable th) {
+        super(msg, th);
+        nested = th;
+    }
+
+    /**
+     * Gets the nested exception.
+     *
+     * @return Nested exception
+     */
+    public Throwable getNestedException() {
+        return nested;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/XMLStreamWriter.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml;
+
+/**
+ * Basic XMLStreamWriter for writing simple XML files such as those
+ * defined in java.util.Properties
+ *
+ * This is a subset of javax.xml.stream.XMLStreamWriter
+ *
+ * @author Joe Wang
+ */
+public  interface XMLStreamWriter {
+
+    //Defaults the XML version to 1.0, and the encoding to utf-8
+    public final static String DEFAULT_XML_VERSION = "1.0";
+    public final static String DEFAULT_ENCODING = "UTF-8";
+
+    /**
+     * Writes a start tag to the output.  All writeStartElement methods
+     * open a new scope in the internal namespace context.  Writing the
+     * corresponding EndElement causes the scope to be closed.
+     * @param localName local name of the tag, may not be null
+     * @throws XMLStreamException
+     */
+    public void writeStartElement(String localName) throws XMLStreamException;
+
+    /**
+     * Writes an empty element tag to the output
+     * @param localName local name of the tag, may not be null
+     * @throws XMLStreamException
+     */
+    public void writeEmptyElement(String localName) throws XMLStreamException;
+
+    /**
+     * Writes an end tag to the output relying on the internal
+     * state of the writer to determine the prefix and local name
+     * of the event.
+     * @throws XMLStreamException
+     */
+    public void writeEndElement() throws XMLStreamException;
+
+    /**
+     * Closes any start tags and writes corresponding end tags.
+     * @throws XMLStreamException
+     */
+    public void writeEndDocument() throws XMLStreamException;
+
+    /**
+     * Close this writer and free any resources associated with the
+     * writer.  This must not close the underlying output stream.
+     * @throws XMLStreamException
+     */
+    public void close() throws XMLStreamException;
+
+    /**
+     * Write any cached data to the underlying output mechanism.
+     * @throws XMLStreamException
+     */
+    public void flush() throws XMLStreamException;
+
+    /**
+     * Writes an attribute to the output stream without
+     * a prefix.
+     * @param localName the local name of the attribute
+     * @param value the value of the attribute
+     * @throws IllegalStateException if the current state does not allow Attribute writing
+     * @throws XMLStreamException
+     */
+    public void writeAttribute(String localName, String value)
+            throws XMLStreamException;
+
+    /**
+     * Writes a CData section
+     * @param data the data contained in the CData Section, may not be null
+     * @throws XMLStreamException
+     */
+    public void writeCData(String data) throws XMLStreamException;
+
+    /**
+     * Write a DTD section.  This string represents the entire doctypedecl production
+     * from the XML 1.0 specification.
+     *
+     * @param dtd the DTD to be written
+     * @throws XMLStreamException
+     */
+    public void writeDTD(String dtd) throws XMLStreamException;
+
+    /**
+     * Write the XML Declaration. Defaults the XML version to 1.0, and the encoding to utf-8
+     * @throws XMLStreamException
+     */
+    public void writeStartDocument() throws XMLStreamException;
+
+    /**
+     * Write the XML Declaration. Defaults the the encoding to utf-8
+     * @param version version of the xml document
+     * @throws XMLStreamException
+     */
+    public void writeStartDocument(String version) throws XMLStreamException;
+
+    /**
+     * Write the XML Declaration.  Note that the encoding parameter does
+     * not set the actual encoding of the underlying output.  That must
+     * be set when the instance of the XMLStreamWriter is created using the
+     * XMLOutputFactory
+     * @param encoding encoding of the xml declaration
+     * @param version version of the xml document
+     * @throws XMLStreamException If given encoding does not match encoding
+     * of the underlying stream
+     */
+    public void writeStartDocument(String encoding, String version)
+        throws XMLStreamException;
+
+    /**
+     * Write text to the output
+     * @param text the value to write
+     * @throws XMLStreamException
+     */
+    public void writeCharacters(String text) throws XMLStreamException;
+
+    /**
+     * Write text to the output
+     * @param text the value to write
+     * @param start the starting position in the array
+     * @param len the number of characters to write
+     * @throws XMLStreamException
+     */
+    public void writeCharacters(char[] text, int start, int len)
+        throws XMLStreamException;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/impl/Attrs.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,430 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml.impl;
+
+import jdk.internal.org.xml.sax.Attributes;
+
+public class Attrs implements Attributes {
+
+    /**
+     * Attributes string array. Each individual attribute is represented by four
+     * strings: namespace URL(+0), qname(+1), local name(+2), value(+3),
+     * type(+4), declared["d"] and default["D"](+5). In order to find attribute
+     * by the attrubute index, the attribute index MUST be multiplied by 8. The
+     * result will point to the attribute namespace URL.
+     */
+    /* pkg */ String[] mItems;
+    /**
+     * Number of attributes in the attributes string array.
+     */
+    private char mLength;
+    /**
+     * current index
+     */
+    private char mAttrIdx = 0;
+
+    /**
+     * Constructor.
+     */
+    public Attrs() {
+        //              The default number of attributies capacity is 8.
+        mItems = new String[(8 << 3)];
+    }
+
+    /**
+     * Sets up the number of attributes and ensure the capacity of the attribute
+     * string array.
+     *
+     * @param length The number of attributes in the object.
+     */
+    public void setLength(char length) {
+        if (length > ((char) (mItems.length >> 3))) {
+            mItems = new String[length << 3];
+        }
+        mLength = length;
+    }
+
+    /**
+     * Return the number of attributes in the list.
+     *
+     * <p>Once you know the number of attributes, you can iterate through the
+     * list.</p>
+     *
+     * @return The number of attributes in the list.
+     * @see #getURI(int)
+     * @see #getLocalName(int)
+     * @see #getQName(int)
+     * @see #getType(int)
+     * @see #getValue(int)
+     */
+    public int getLength() {
+        return mLength;
+    }
+
+    /**
+     * Look up an attribute's Namespace URI by index.
+     *
+     * @param index The attribute index (zero-based).
+     * @return The Namespace URI, or the empty string if none is available, or
+     * null if the index is out of range.
+     * @see #getLength
+     */
+    public String getURI(int index) {
+        return ((index >= 0) && (index < mLength))
+                ? (mItems[index << 3])
+                : null;
+    }
+
+    /**
+     * Look up an attribute's local name by index.
+     *
+     * @param index The attribute index (zero-based).
+     * @return The local name, or the empty string if Namespace processing is
+     * not being performed, or null if the index is out of range.
+     * @see #getLength
+     */
+    public String getLocalName(int index) {
+        return ((index >= 0) && (index < mLength))
+                ? (mItems[(index << 3) + 2])
+                : null;
+    }
+
+    /**
+     * Look up an attribute's XML 1.0 qualified name by index.
+     *
+     * @param index The attribute index (zero-based).
+     * @return The XML 1.0 qualified name, or the empty string if none is
+     * available, or null if the index is out of range.
+     * @see #getLength
+     */
+    public String getQName(int index) {
+        if ((index < 0) || (index >= mLength)) {
+            return null;
+        }
+        return mItems[(index << 3) + 1];
+    }
+
+    /**
+     * Look up an attribute's type by index.
+     *
+     * <p>The attribute type is one of the strings "CDATA", "ID", "IDREF",
+     * "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", or "NOTATION"
+     * (always in upper case).</p>
+     *
+     * <p>If the parser has not read a declaration for the attribute, or if the
+     * parser does not report attribute types, then it must return the value
+     * "CDATA" as stated in the XML 1.0 Recommentation (clause 3.3.3,
+     * "Attribute-Value Normalization").</p>
+     *
+     * <p>For an enumerated attribute that is not a notation, the parser will
+     * report the type as "NMTOKEN".</p>
+     *
+     * @param index The attribute index (zero-based).
+     * @return The attribute's type as a string, or null if the index is out of
+     * range.
+     * @see #getLength
+     */
+    public String getType(int index) {
+        return ((index >= 0) && (index < (mItems.length >> 3)))
+                ? (mItems[(index << 3) + 4])
+                : null;
+    }
+
+    /**
+     * Look up an attribute's value by index.
+     *
+     * <p>If the attribute value is a list of tokens (IDREFS, ENTITIES, or
+     * NMTOKENS), the tokens will be concatenated into a single string with each
+     * token separated by a single space.</p>
+     *
+     * @param index The attribute index (zero-based).
+     * @return The attribute's value as a string, or null if the index is out of
+     * range.
+     * @see #getLength
+     */
+    public String getValue(int index) {
+        return ((index >= 0) && (index < mLength))
+                ? (mItems[(index << 3) + 3])
+                : null;
+    }
+
+    /**
+     * Look up the index of an attribute by Namespace name.
+     *
+     * @param uri The Namespace URI, or the empty string if the name has no
+     * Namespace URI.
+     * @param localName The attribute's local name.
+     * @return The index of the attribute, or -1 if it does not appear in the
+     * list.
+     */
+    public int getIndex(String uri, String localName) {
+        char len = mLength;
+        for (char idx = 0; idx < len; idx++) {
+            if ((mItems[idx << 3]).equals(uri)
+                    && mItems[(idx << 3) + 2].equals(localName)) {
+                return idx;
+            }
+        }
+        return -1;
+    }
+
+    /**
+     * Look up the index of an attribute by Namespace name.
+     *
+     * @param uri The Namespace URI, or the empty string if the name has no
+     * Namespace URI. <code>null</code> value enforce the search by the local
+     * name only.
+     * @param localName The attribute's local name.
+     * @return The index of the attribute, or -1 if it does not appear in the
+     * list.
+     */
+    /* pkg */ int getIndexNullNS(String uri, String localName) {
+        char len = mLength;
+        if (uri != null) {
+            for (char idx = 0; idx < len; idx++) {
+                if ((mItems[idx << 3]).equals(uri)
+                        && mItems[(idx << 3) + 2].equals(localName)) {
+                    return idx;
+                }
+            }
+        } else {
+            for (char idx = 0; idx < len; idx++) {
+                if (mItems[(idx << 3) + 2].equals(localName)) {
+                    return idx;
+                }
+            }
+        }
+        return -1;
+    }
+
+    /**
+     * Look up the index of an attribute by XML 1.0 qualified name.
+     *
+     * @param qName The qualified (prefixed) name.
+     * @return The index of the attribute, or -1 if it does not appear in the
+     * list.
+     */
+    public int getIndex(String qName) {
+        char len = mLength;
+        for (char idx = 0; idx < len; idx++) {
+            if (mItems[(idx << 3) + 1].equals(qName)) {
+                return idx;
+            }
+        }
+        return -1;
+    }
+
+    /**
+     * Look up an attribute's type by Namespace name.
+     *
+     * <p>See {@link #getType(int) getType(int)} for a description of the
+     * possible types.</p>
+     *
+     * @param uri The Namespace URI, or the empty String if the name has no
+     * Namespace URI.
+     * @param localName The local name of the attribute.
+     * @return The attribute type as a string, or null if the attribute is not
+     * in the list or if Namespace processing is not being performed.
+     */
+    public String getType(String uri, String localName) {
+        int idx = getIndex(uri, localName);
+        return (idx >= 0) ? (mItems[(idx << 3) + 4]) : null;
+    }
+
+    /**
+     * Look up an attribute's type by XML 1.0 qualified name.
+     *
+     * <p>See {@link #getType(int) getType(int)} for a description of the
+     * possible types.</p>
+     *
+     * @param qName The XML 1.0 qualified name.
+     * @return The attribute type as a string, or null if the attribute is not
+     * in the list or if qualified names are not available.
+     */
+    public String getType(String qName) {
+        int idx = getIndex(qName);
+        return (idx >= 0) ? (mItems[(idx << 3) + 4]) : null;
+    }
+
+    /**
+     * Look up an attribute's value by Namespace name.
+     *
+     * <p>See {@link #getValue(int) getValue(int)} for a description of the
+     * possible values.</p>
+     *
+     * @param uri The Namespace URI, or the empty String if the name has no
+     * Namespace URI.
+     * @param localName The local name of the attribute.
+     * @return The attribute value as a string, or null if the attribute is not
+     * in the list.
+     */
+    public String getValue(String uri, String localName) {
+        int idx = getIndex(uri, localName);
+        return (idx >= 0) ? (mItems[(idx << 3) + 3]) : null;
+    }
+
+    /**
+     * Look up an attribute's value by XML 1.0 qualified name.
+     *
+     * <p>See {@link #getValue(int) getValue(int)} for a description of the
+     * possible values.</p>
+     *
+     * @param qName The XML 1.0 qualified name.
+     * @return The attribute value as a string, or null if the attribute is not
+     * in the list or if qualified names are not available.
+     */
+    public String getValue(String qName) {
+        int idx = getIndex(qName);
+        return (idx >= 0) ? (mItems[(idx << 3) + 3]) : null;
+    }
+
+    /**
+     * Returns false unless the attribute was declared in the DTD. This helps
+     * distinguish two kinds of attributes that SAX reports as CDATA: ones that
+     * were declared (and hence are usually valid), and those that were not (and
+     * which are never valid).
+     *
+     * @param index The attribute index (zero-based).
+     * @return true if the attribute was declared in the DTD, false otherwise.
+     * @exception java.lang.ArrayIndexOutOfBoundsException When the supplied
+     * index does not identify an attribute.
+     */
+    public boolean isDeclared(int index) {
+        if ((index < 0) || (index >= mLength)) {
+            throw new ArrayIndexOutOfBoundsException("");
+        }
+
+        return ((mItems[(index << 3) + 5]) != null);
+    }
+
+    /**
+     * Returns false unless the attribute was declared in the DTD. This helps
+     * distinguish two kinds of attributes that SAX reports as CDATA: ones that
+     * were declared (and hence are usually valid), and those that were not (and
+     * which are never valid).
+     *
+     * @param qName The XML qualified (prefixed) name.
+     * @return true if the attribute was declared in the DTD, false otherwise.
+     * @exception java.lang.IllegalArgumentException When the supplied name does
+     * not identify an attribute.
+     */
+    public boolean isDeclared(String qName) {
+        int idx = getIndex(qName);
+        if (idx < 0) {
+            throw new IllegalArgumentException("");
+        }
+
+        return ((mItems[(idx << 3) + 5]) != null);
+    }
+
+    /**
+     * Returns false unless the attribute was declared in the DTD. This helps
+     * distinguish two kinds of attributes that SAX reports as CDATA: ones that
+     * were declared (and hence are usually valid), and those that were not (and
+     * which are never valid).
+     *
+     * <p>Remember that since DTDs do not "understand" namespaces, the namespace
+     * URI associated with an attribute may not have come from the DTD. The
+     * declaration will have applied to the attribute's <em>qName</em>.
+     *
+     * @param uri The Namespace URI, or the empty string if the name has no
+     * Namespace URI.
+     * @param localName The attribute's local name.
+     * @return true if the attribute was declared in the DTD, false otherwise.
+     * @exception java.lang.IllegalArgumentException When the supplied names do
+     * not identify an attribute.
+     */
+    public boolean isDeclared(String uri, String localName) {
+        int idx = getIndex(uri, localName);
+        if (idx < 0) {
+            throw new IllegalArgumentException("");
+        }
+
+        return ((mItems[(idx << 3) + 5]) != null);
+    }
+
+    /**
+     * Returns true unless the attribute value was provided by DTD defaulting.
+     *
+     * @param index The attribute index (zero-based).
+     * @return true if the value was found in the XML text, false if the value
+     * was provided by DTD defaulting.
+     * @exception java.lang.ArrayIndexOutOfBoundsException When the supplied
+     * index does not identify an attribute.
+     */
+    public boolean isSpecified(int index) {
+        if ((index < 0) || (index >= mLength)) {
+            throw new ArrayIndexOutOfBoundsException("");
+        }
+
+        String str = mItems[(index << 3) + 5];
+        return ((str != null) ? (str.charAt(0) == 'd') : true);
+    }
+
+    /**
+     * Returns true unless the attribute value was provided by DTD defaulting.
+     *
+     * <p>Remember that since DTDs do not "understand" namespaces, the namespace
+     * URI associated with an attribute may not have come from the DTD. The
+     * declaration will have applied to the attribute's <em>qName</em>.
+     *
+     * @param uri The Namespace URI, or the empty string if the name has no
+     * Namespace URI.
+     * @param localName The attribute's local name.
+     * @return true if the value was found in the XML text, false if the value
+     * was provided by DTD defaulting.
+     * @exception java.lang.IllegalArgumentException When the supplied names do
+     * not identify an attribute.
+     */
+    public boolean isSpecified(String uri, String localName) {
+        int idx = getIndex(uri, localName);
+        if (idx < 0) {
+            throw new IllegalArgumentException("");
+        }
+
+        String str = mItems[(idx << 3) + 5];
+        return ((str != null) ? (str.charAt(0) == 'd') : true);
+    }
+
+    /**
+     * Returns true unless the attribute value was provided by DTD defaulting.
+     *
+     * @param qName The XML qualified (prefixed) name.
+     * @return true if the value was found in the XML text, false if the value
+     * was provided by DTD defaulting.
+     * @exception java.lang.IllegalArgumentException When the supplied name does
+     * not identify an attribute.
+     */
+    public boolean isSpecified(String qName) {
+        int idx = getIndex(qName);
+        if (idx < 0) {
+            throw new IllegalArgumentException("");
+        }
+
+        String str = mItems[(idx << 3) + 5];
+        return ((str != null) ? (str.charAt(0) == 'd') : true);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/impl/Input.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml.impl;
+
+import java.io.Reader;
+
+/**
+ * A parsed entity input state.
+ *
+ * This class represents a parsed entity input state. The parser uses
+ * an instance of this class to manage input.
+ */
+
+public class Input {
+
+    /** The entity public identifier or null. */
+    public String pubid;
+    /** The entity systen identifier or null. */
+    public String sysid;
+    /** The encoding from XML declaration or null */
+    public String xmlenc;
+    /** The XML version from XML declaration or 0x0000 */
+    public char xmlver;
+    /** The entity reader. */
+    public Reader src;
+    /** The character buffer. */
+    public char[] chars;
+    /** The length of the character buffer. */
+    public int chLen;
+    /** The index of the next character to read. */
+    public int chIdx;
+    /** The next input in a chain. */
+    public Input next;
+
+    /**
+     * Constructor.
+     *
+     * @param buffsize The input buffer size.
+     */
+    public Input(int buffsize) {
+        chars = new char[buffsize];
+        chLen = chars.length;
+    }
+
+    /**
+     * Constructor.
+     *
+     * @param buff The input buffer.
+     */
+    public Input(char[] buff) {
+        chars = buff;
+        chLen = chars.length;
+    }
+
+    /**
+     * Constructor.
+     */
+    public Input() {
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/impl/Pair.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml.impl;
+
+
+/**
+ * A name with value pair.
+ *
+ * This class keeps name with value pair with additional information and
+ * supports pair chaining.
+ */
+public class Pair {
+
+    /** The pair name. */
+    public String name;
+    /** The pair value. */
+    public String value;
+    /** The pair numeric value. */
+    public int num;
+    /** The characters of name. */
+    public char[] chars;
+    /** The pair identifier. */
+    public int id;
+    /** The list of associated pairs. */
+    public Pair list;
+    /** The next pair in a chain. */
+    public Pair next;
+
+    /**
+     * Creates a qualified name string from qualified name.
+     *
+     * @return The qualified name string.
+     */
+    public String qname() {
+        return new String(chars, 1, chars.length - 1);
+    }
+
+    /**
+     * Creates a local name string from qualified name.
+     *
+     * @return The local name string.
+     */
+    public String local() {
+        if (chars[0] != 0) {
+            return new String(chars, chars[0] + 1, chars.length - chars[0] - 1);
+        }
+        return new String(chars, 1, chars.length - 1);
+    }
+
+    /**
+     * Creates a prefix string from qualified name.
+     *
+     * @return The prefix string.
+     */
+    public String pref() {
+        if (chars[0] != 0) {
+            return new String(chars, 1, chars[0] - 1);
+        }
+        return "";
+    }
+
+    /**
+     * Compares two qualified name prefixes.
+     *
+     * @param qname A qualified name.
+     * @return true if prefixes are equal.
+     */
+    public boolean eqpref(char[] qname) {
+        if (chars[0] == qname[0]) {
+            char len = chars[0];
+            for (char i = 1; i < len; i += 1) {
+                if (chars[i] != qname[i]) {
+                    return false;
+                }
+            }
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Compares two qualified names.
+     *
+     * @param qname A qualified name.
+     * @return true if qualified names are equal.
+     */
+    public boolean eqname(char[] qname) {
+        char len = (char) chars.length;
+        if (len == qname.length) {
+            for (char i = 0; i < len; i += 1) {
+                if (chars[i] != qname[i]) {
+                    return false;
+                }
+            }
+            return true;
+        }
+        return false;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/impl/Parser.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,3367 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.UnsupportedEncodingException;
+import java.util.HashMap;
+import java.util.Map;
+import jdk.internal.org.xml.sax.InputSource;
+import jdk.internal.org.xml.sax.SAXException;
+
+/**
+ * XML non-validating parser engine.
+ */
+public abstract class Parser {
+
+    public final static String FAULT = "";
+    protected final static int BUFFSIZE_READER = 512;
+    protected final static int BUFFSIZE_PARSER = 128;
+    /**
+     * The end of stream character.
+     */
+    public final static char EOS = 0xffff;
+    private Pair mNoNS; // there is no namespace
+    private Pair mXml;  // the xml namespace
+    private Map<String, Input> mEnt;  // the entities look up table
+    private Map<String, Input> mPEnt; // the parmeter entities look up table
+    protected boolean mIsSAlone;     // xml decl standalone flag
+    protected boolean mIsSAloneSet;  // standalone is explicitely set
+    protected boolean mIsNSAware;    // if true - namespace aware mode
+    protected int mPh;  // current phase of document processing
+    protected final static int PH_BEFORE_DOC = -1;  // before parsing
+    protected final static int PH_DOC_START = 0;   // document start
+    protected final static int PH_MISC_DTD = 1;   // misc before DTD
+    protected final static int PH_DTD = 2;   // DTD
+    protected final static int PH_DTD_MISC = 3;   // misc after DTD
+    protected final static int PH_DOCELM = 4;   // document's element
+    protected final static int PH_DOCELM_MISC = 5;   // misc after element
+    protected final static int PH_AFTER_DOC = 6;   // after parsing
+    protected int mEvt;  // current event type
+    protected final static int EV_NULL = 0;   // unknown
+    protected final static int EV_ELM = 1;   // empty element
+    protected final static int EV_ELMS = 2;   // start element
+    protected final static int EV_ELME = 3;   // end element
+    protected final static int EV_TEXT = 4;   // textual content
+    protected final static int EV_WSPC = 5;   // white space content
+    protected final static int EV_PI = 6;   // processing instruction
+    protected final static int EV_CDAT = 7;   // character data
+    protected final static int EV_COMM = 8;   // comment
+    protected final static int EV_DTD = 9;   // document type definition
+    protected final static int EV_ENT = 10;  // skipped entity
+    private char mESt; // built-in entity recognizer state
+    // mESt values:
+    //   0x100   : the initial state
+    //   > 0x100 : unrecognized name
+    //   < 0x100 : replacement character
+    protected char[] mBuff;       // parser buffer
+    protected int mBuffIdx;    // index of the last char
+    protected Pair mPref;       // stack of prefixes
+    protected Pair mElm;        // stack of elements
+    // mAttL.chars - element qname
+    // mAttL.next  - next element
+    // mAttL.list  - list of attributes defined on this element
+    // mAttL.list.chars - attribute qname
+    // mAttL.list.id    - a char representing attribute's type see below
+    // mAttL.list.next  - next attribute defined on the element
+    // mAttL.list.list  - devault value structure or null
+    // mAttL.list.list.chars - "name='value' " chars array for Input
+    //
+    // Attribute type character values:
+    // 'i' - "ID"
+    // 'r' - "IDREF"
+    // 'R' - "IDREFS"
+    // 'n' - "ENTITY"
+    // 'N' - "ENTITIES"
+    // 't' - "NMTOKEN"
+    // 'T' - "NMTOKENS"
+    // 'u' - enumeration type
+    // 'o' - "NOTATION"
+    // 'c' - "CDATA"
+    // see also: bkeyword() and atype()
+    //
+    protected Pair mAttL;       // list of defined attrs by element name
+    protected Input mDoc;        // document entity
+    protected Input mInp;        // stack of entities
+    private char[] mChars;      // reading buffer
+    private int mChLen;      // current capacity
+    private int mChIdx;      // index to the next char
+    protected Attrs mAttrs;      // attributes of the curr. element
+    private String[] mItems;      // attributes array of the curr. element
+    private char mAttrIdx;    // attributes counter/index
+    private String mUnent;  // unresolved entity name
+    private Pair mDltd;   // deleted objects for reuse
+    /**
+     * Default prefixes
+     */
+    private final static char NONS[];
+    private final static char XML[];
+    private final static char XMLNS[];
+
+    static {
+        NONS = new char[1];
+        NONS[0] = (char) 0;
+
+        XML = new char[4];
+        XML[0] = (char) 4;
+        XML[1] = 'x';
+        XML[2] = 'm';
+        XML[3] = 'l';
+
+        XMLNS = new char[6];
+        XMLNS[0] = (char) 6;
+        XMLNS[1] = 'x';
+        XMLNS[2] = 'm';
+        XMLNS[3] = 'l';
+        XMLNS[4] = 'n';
+        XMLNS[5] = 's';
+    }
+    /**
+     * ASCII character type array.
+     *
+     * This array maps an ASCII (7 bit) character to the character type.<br />
+     * Possible character type values are:<br /> - ' ' for any kind of white
+     * space character;<br /> - 'a' for any lower case alphabetical character
+     * value;<br /> - 'A' for any upper case alphabetical character value;<br />
+     * - 'd' for any decimal digit character value;<br /> - 'z' for any
+     * character less then ' ' except '\t', '\n', '\r';<br /> An ASCII (7 bit)
+     * character which does not fall in any category listed above is mapped to
+     * it self.
+     */
+    private static final byte asctyp[];
+    /**
+     * NMTOKEN character type array.
+     *
+     * This array maps an ASCII (7 bit) character to the character type.<br />
+     * Possible character type values are:<br /> - 0 for underscore ('_') or any
+     * lower and upper case alphabetical character value;<br /> - 1 for colon
+     * (':') character;<br /> - 2 for dash ('-') and dot ('.') or any decimal
+     * digit character value;<br /> - 3 for any kind of white space character<br
+     * /> An ASCII (7 bit) character which does not fall in any category listed
+     * above is mapped to 0xff.
+     */
+    private static final byte nmttyp[];
+
+    /**
+     * Static constructor.
+     *
+     * Sets up the ASCII character type array which is used by
+     * {@link #asctyp asctyp} method and NMTOKEN character type array.
+     */
+    static {
+        short i = 0;
+
+        asctyp = new byte[0x80];
+        while (i < ' ') {
+            asctyp[i++] = (byte) 'z';
+        }
+        asctyp['\t'] = (byte) ' ';
+        asctyp['\r'] = (byte) ' ';
+        asctyp['\n'] = (byte) ' ';
+        while (i < '0') {
+            asctyp[i] = (byte) i++;
+        }
+        while (i <= '9') {
+            asctyp[i++] = (byte) 'd';
+        }
+        while (i < 'A') {
+            asctyp[i] = (byte) i++;
+        }
+        while (i <= 'Z') {
+            asctyp[i++] = (byte) 'A';
+        }
+        while (i < 'a') {
+            asctyp[i] = (byte) i++;
+        }
+        while (i <= 'z') {
+            asctyp[i++] = (byte) 'a';
+        }
+        while (i < 0x80) {
+            asctyp[i] = (byte) i++;
+        }
+
+        nmttyp = new byte[0x80];
+        for (i = 0; i < '0'; i++) {
+            nmttyp[i] = (byte) 0xff;
+        }
+        while (i <= '9') {
+            nmttyp[i++] = (byte) 2;  // digits
+        }
+        while (i < 'A') {
+            nmttyp[i++] = (byte) 0xff;
+        }
+        // skiped upper case alphabetical character are already 0
+        for (i = '['; i < 'a'; i++) {
+            nmttyp[i] = (byte) 0xff;
+        }
+        // skiped lower case alphabetical character are already 0
+        for (i = '{'; i < 0x80; i++) {
+            nmttyp[i] = (byte) 0xff;
+        }
+        nmttyp['_'] = 0;
+        nmttyp[':'] = 1;
+        nmttyp['.'] = 2;
+        nmttyp['-'] = 2;
+        nmttyp[' '] = 3;
+        nmttyp['\t'] = 3;
+        nmttyp['\r'] = 3;
+        nmttyp['\n'] = 3;
+    }
+
+    /**
+     * Constructor.
+     */
+    protected Parser() {
+        mPh = PH_BEFORE_DOC;  // before parsing
+
+        //              Initialize the parser
+        mBuff = new char[BUFFSIZE_PARSER];
+        mAttrs = new Attrs();
+
+        //              Default namespace
+        mPref = pair(mPref);
+        mPref.name = "";
+        mPref.value = "";
+        mPref.chars = NONS;
+        mNoNS = mPref;  // no namespace
+        //              XML namespace
+        mPref = pair(mPref);
+        mPref.name = "xml";
+        mPref.value = "http://www.w3.org/XML/1998/namespace";
+        mPref.chars = XML;
+        mXml = mPref;  // XML namespace
+    }
+
+    /**
+     * Initializes parser's internals. Note, current input has to be set before
+     * this method is called.
+     */
+    protected void init() {
+        mUnent = null;
+        mElm = null;
+        mPref = mXml;
+        mAttL = null;
+        mPEnt = new HashMap<>();
+        mEnt = new HashMap<>();
+        mDoc = mInp;          // current input is document entity
+        mChars = mInp.chars;    // use document entity buffer
+        mPh = PH_DOC_START;  // the begining of the document
+    }
+
+    /**
+     * Cleans up parser internal resources.
+     */
+    protected void cleanup() {
+        //              Default attributes
+        while (mAttL != null) {
+            while (mAttL.list != null) {
+                if (mAttL.list.list != null) {
+                    del(mAttL.list.list);
+                }
+                mAttL.list = del(mAttL.list);
+            }
+            mAttL = del(mAttL);
+        }
+        //              Element stack
+        while (mElm != null) {
+            mElm = del(mElm);
+        }
+        //              Namespace prefixes
+        while (mPref != mXml) {
+            mPref = del(mPref);
+        }
+        //              Inputs
+        while (mInp != null) {
+            pop();
+        }
+        //              Document reader
+        if ((mDoc != null) && (mDoc.src != null)) {
+            try {
+                mDoc.src.close();
+            } catch (IOException ioe) {
+            }
+        }
+        mPEnt = null;
+        mEnt = null;
+        mDoc = null;
+        mPh = PH_AFTER_DOC;  // before documnet processing
+    }
+
+    /**
+     * Processes a portion of document. This method returns one of EV_*
+     * constants as an identifier of the portion of document have been read.
+     *
+     * @return Identifier of processed document portion.
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    @SuppressWarnings("fallthrough")
+    protected int step() throws Exception {
+        mEvt = EV_NULL;
+        int st = 0;
+        while (mEvt == EV_NULL) {
+            char ch = (mChIdx < mChLen) ? mChars[mChIdx++] : getch();
+            switch (st) {
+                case 0:     // all sorts of markup (dispetcher)
+                    if (ch != '<') {
+                        bkch();
+                        mBuffIdx = -1;  // clean parser buffer
+                        st = 1;
+                        break;
+                    }
+                    switch (getch()) {
+                        case '/':  // the end of the element content
+                            mEvt = EV_ELME;
+                            if (mElm == null) {
+                                panic(FAULT);
+                            }
+                            //          Check element's open/close tags balance
+                            mBuffIdx = -1;  // clean parser buffer
+                            bname(mIsNSAware);
+                            char[] chars = mElm.chars;
+                            if (chars.length == (mBuffIdx + 1)) {
+                                for (char i = 1; i <= mBuffIdx; i += 1) {
+                                    if (chars[i] != mBuff[i]) {
+                                        panic(FAULT);
+                                    }
+                                }
+                            } else {
+                                panic(FAULT);
+                            }
+                            //          Skip white spaces before '>'
+                            if (wsskip() != '>') {
+                                panic(FAULT);
+                            }
+                            getch();  // read '>'
+                            break;
+
+                        case '!':  // a comment or a CDATA
+                            ch = getch();
+                            bkch();
+                            switch (ch) {
+                                case '-':  // must be a comment
+                                    mEvt = EV_COMM;
+                                    comm();
+                                    break;
+
+                                case '[':  // must be a CDATA section
+                                    mEvt = EV_CDAT;
+                                    cdat();
+                                    break;
+
+                                default:   // must be 'DOCTYPE'
+                                    mEvt = EV_DTD;
+                                    dtd();
+                                    break;
+                            }
+                            break;
+
+                        case '?':  // processing instruction
+                            mEvt = EV_PI;
+                            pi();
+                            break;
+
+                        default:  // must be the first char of an xml name
+                            bkch();
+                            //          Read an element name and put it on top of the
+                            //          element stack
+                            mElm = pair(mElm);  // add new element to the stack
+                            mElm.chars = qname(mIsNSAware);
+                            mElm.name = mElm.local();
+                            mElm.id = (mElm.next != null) ? mElm.next.id : 0;  // flags
+                            mElm.num = 0;     // namespace counter
+                            //          Find the list of defined attributs of the current
+                            //          element
+                            Pair elm = find(mAttL, mElm.chars);
+                            mElm.list = (elm != null) ? elm.list : null;
+                            //          Read attributes till the end of the element tag
+                            mAttrIdx = 0;
+                            Pair att = pair(null);
+                            att.num = 0;  // clear attribute's flags
+                            attr(att);     // get all attributes inc. defaults
+                            del(att);
+                            mElm.value = (mIsNSAware) ? rslv(mElm.chars) : null;
+                            //          Skip white spaces before '>'
+                            switch (wsskip()) {
+                                case '>':
+                                    getch();  // read '>'
+                                    mEvt = EV_ELMS;
+                                    break;
+
+                                case '/':
+                                    getch();  // read '/'
+                                    if (getch() != '>') // read '>'
+                                    {
+                                        panic(FAULT);
+                                    }
+                                    mEvt = EV_ELM;
+                                    break;
+
+                                default:
+                                    panic(FAULT);
+                            }
+                            break;
+                    }
+                    break;
+
+                case 1:     // read white space
+                    switch (ch) {
+                        case ' ':
+                        case '\t':
+                        case '\n':
+                            bappend(ch);
+                            break;
+
+                        case '\r':              // EOL processing [#2.11]
+                            if (getch() != '\n') {
+                                bkch();
+                            }
+                            bappend('\n');
+                            break;
+
+                        case '<':
+                            mEvt = EV_WSPC;
+                            bkch();
+                            bflash_ws();
+                            break;
+
+                        default:
+                            bkch();
+                            st = 2;
+                            break;
+                    }
+                    break;
+
+                case 2:     // read the text content of the element
+                    switch (ch) {
+                        case '&':
+                            if (mUnent == null) {
+                                //              There was no unresolved entity on previous step.
+                                if ((mUnent = ent('x')) != null) {
+                                    mEvt = EV_TEXT;
+                                    bkch();      // move back to ';' after entity name
+                                    setch('&');  // parser must be back on next step
+                                    bflash();
+                                }
+                            } else {
+                                //              There was unresolved entity on previous step.
+                                mEvt = EV_ENT;
+                                skippedEnt(mUnent);
+                                mUnent = null;
+                            }
+                            break;
+
+                        case '<':
+                            mEvt = EV_TEXT;
+                            bkch();
+                            bflash();
+                            break;
+
+                        case '\r':  // EOL processing [#2.11]
+                            if (getch() != '\n') {
+                                bkch();
+                            }
+                            bappend('\n');
+                            break;
+
+                        case EOS:
+                            panic(FAULT);
+
+                        default:
+                            bappend(ch);
+                            break;
+                    }
+                    break;
+
+                default:
+                    panic(FAULT);
+            }
+        }
+
+        return mEvt;
+    }
+
+    /**
+     * Parses the document type declaration.
+     *
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    private void dtd() throws Exception {
+        char ch;
+        String str = null;
+        String name = null;
+        Pair psid = null;
+        // read 'DOCTYPE'
+        if ("DOCTYPE".equals(name(false)) != true) {
+            panic(FAULT);
+        }
+        mPh = PH_DTD;  // DTD
+        for (short st = 0; st >= 0;) {
+            ch = getch();
+            switch (st) {
+                case 0:     // read the document type name
+                    if (chtyp(ch) != ' ') {
+                        bkch();
+                        name = name(mIsNSAware);
+                        wsskip();
+                        st = 1;  // read 'PUPLIC' or 'SYSTEM'
+                    }
+                    break;
+
+                case 1:     // read 'PUPLIC' or 'SYSTEM'
+                    switch (chtyp(ch)) {
+                        case 'A':
+                            bkch();
+                            psid = pubsys(' ');
+                            st = 2;  // skip spaces before internal subset
+                            docType(name, psid.name, psid.value);
+                            break;
+
+                        case '[':
+                            bkch();
+                            st = 2;    // skip spaces before internal subset
+                            docType(name, null, null);
+                            break;
+
+                        case '>':
+                            bkch();
+                            st = 3;    // skip spaces after internal subset
+                            docType(name, null, null);
+                            break;
+
+                        default:
+                            panic(FAULT);
+                    }
+                    break;
+
+                case 2:     // skip spaces before internal subset
+                    switch (chtyp(ch)) {
+                        case '[':
+                            //          Process internal subset
+                            dtdsub();
+                            st = 3;  // skip spaces after internal subset
+                            break;
+
+                        case '>':
+                            //          There is no internal subset
+                            bkch();
+                            st = 3;  // skip spaces after internal subset
+                            break;
+
+                        case ' ':
+                            // skip white spaces
+                            break;
+
+                        default:
+                            panic(FAULT);
+                    }
+                    break;
+
+                case 3:     // skip spaces after internal subset
+                    switch (chtyp(ch)) {
+                        case '>':
+                            if (psid != null) {
+                                //              Report the DTD external subset
+                                InputSource is = resolveEnt(name, psid.name, psid.value);
+                                if (is != null) {
+                                    if (mIsSAlone == false) {
+                                        //              Set the end of DTD external subset char
+                                        bkch();
+                                        setch(']');
+                                        //              Set the DTD external subset InputSource
+                                        push(new Input(BUFFSIZE_READER));
+                                        setinp(is);
+                                        mInp.pubid = psid.name;
+                                        mInp.sysid = psid.value;
+                                        //              Parse the DTD external subset
+                                        dtdsub();
+                                    } else {
+                                        //              Unresolved DTD external subset
+                                        skippedEnt("[dtd]");
+                                        //              Release reader and stream
+                                        if (is.getCharacterStream() != null) {
+                                            try {
+                                                is.getCharacterStream().close();
+                                            } catch (IOException ioe) {
+                                            }
+                                        }
+                                        if (is.getByteStream() != null) {
+                                            try {
+                                                is.getByteStream().close();
+                                            } catch (IOException ioe) {
+                                            }
+                                        }
+                                    }
+                                } else {
+                                    //          Unresolved DTD external subset
+                                    skippedEnt("[dtd]");
+                                }
+                                del(psid);
+                            }
+                            st = -1;  // end of DTD
+                            break;
+
+                        case ' ':
+                            // skip white spaces
+                            break;
+
+                        default:
+                            panic(FAULT);
+                    }
+                    break;
+
+                default:
+                    panic(FAULT);
+            }
+        }
+    }
+
+    /**
+     * Parses the document type declaration subset.
+     *
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    private void dtdsub() throws Exception {
+        char ch;
+        for (short st = 0; st >= 0;) {
+            ch = getch();
+            switch (st) {
+                case 0:     // skip white spaces before a declaration
+                    switch (chtyp(ch)) {
+                        case '<':
+                            ch = getch();
+                            switch (ch) {
+                                case '?':
+                                    pi();
+                                    break;
+
+                                case '!':
+                                    ch = getch();
+                                    bkch();
+                                    if (ch == '-') {
+                                        comm();
+                                        break;
+                                    }
+                                    //          A markup or an entity declaration
+                                    bntok();
+                                    switch (bkeyword()) {
+                                        case 'n':
+                                            dtdent();
+                                            break;
+
+                                        case 'a':
+                                            dtdattl();    // parse attributes declaration
+                                            break;
+
+                                        case 'e':
+                                            dtdelm();     // parse element declaration
+                                            break;
+
+                                        case 'o':
+                                            dtdnot();     // parse notation declaration
+                                            break;
+
+                                        default:
+                                            panic(FAULT); // unsupported markup declaration
+                                            break;
+                                    }
+                                    st = 1;  // read the end of declaration
+                                    break;
+
+                                default:
+                                    panic(FAULT);
+                                    break;
+                            }
+                            break;
+
+                        case '%':
+                            //          A parameter entity reference
+                            pent(' ');
+                            break;
+
+                        case ']':
+                            //          End of DTD subset
+                            st = -1;
+                            break;
+
+                        case ' ':
+                            //          Skip white spaces
+                            break;
+
+                        case 'Z':
+                            //          End of stream
+                            if (getch() != ']') {
+                                panic(FAULT);
+                            }
+                            st = -1;
+                            break;
+
+                        default:
+                            panic(FAULT);
+                    }
+                    break;
+
+                case 1:     // read the end of declaration
+                    switch (ch) {
+                        case '>':   // there is no notation
+                            st = 0; // skip white spaces before a declaration
+                            break;
+
+                        case ' ':
+                        case '\n':
+                        case '\r':
+                        case '\t':
+                            //          Skip white spaces
+                            break;
+
+                        default:
+                            panic(FAULT);
+                            break;
+                    }
+                    break;
+
+                default:
+                    panic(FAULT);
+            }
+        }
+    }
+
+    /**
+     * Parses an entity declaration. This method fills the general (
+     * <code>mEnt</code>) and parameter
+     * (
+     * <code>mPEnt</code>) entity look up table.
+     *
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    @SuppressWarnings("fallthrough")
+    private void dtdent() throws Exception {
+        String str = null;
+        char[] val = null;
+        Input inp = null;
+        Pair ids = null;
+        char ch;
+        for (short st = 0; st >= 0;) {
+            ch = getch();
+            switch (st) {
+                case 0:     // skip white spaces before entity name
+                    switch (chtyp(ch)) {
+                        case ' ':
+                            //          Skip white spaces
+                            break;
+
+                        case '%':
+                            //          Parameter entity or parameter entity declaration.
+                            ch = getch();
+                            bkch();
+                            if (chtyp(ch) == ' ') {
+                                //              Parameter entity declaration.
+                                wsskip();
+                                str = name(false);
+                                switch (chtyp(wsskip())) {
+                                    case 'A':
+                                        //              Read the external identifier
+                                        ids = pubsys(' ');
+                                        if (wsskip() == '>') {
+                                            //          External parsed entity
+                                            if (mPEnt.containsKey(str) == false) {      // [#4.2]
+                                                inp = new Input();
+                                                inp.pubid = ids.name;
+                                                inp.sysid = ids.value;
+                                                mPEnt.put(str, inp);
+                                            }
+                                        } else {
+                                            panic(FAULT);
+                                        }
+                                        del(ids);
+                                        st = -1;  // the end of declaration
+                                        break;
+
+                                    case '\"':
+                                    case '\'':
+                                        //              Read the parameter entity value
+                                        bqstr('d');
+                                        //              Create the parameter entity value
+                                        val = new char[mBuffIdx + 1];
+                                        System.arraycopy(mBuff, 1, val, 1, val.length - 1);
+                                        //              Add surrounding spaces [#4.4.8]
+                                        val[0] = ' ';
+                                        //              Add the entity to the entity look up table
+                                        if (mPEnt.containsKey(str) == false) {  // [#4.2]
+                                            inp = new Input(val);
+                                            inp.pubid = mInp.pubid;
+                                            inp.sysid = mInp.sysid;
+                                            inp.xmlenc = mInp.xmlenc;
+                                            inp.xmlver = mInp.xmlver;
+                                            mPEnt.put(str, inp);
+                                        }
+                                        st = -1;  // the end of declaration
+                                        break;
+
+                                    default:
+                                        panic(FAULT);
+                                        break;
+                                }
+                            } else {
+                                //              Parameter entity reference.
+                                pent(' ');
+                            }
+                            break;
+
+                        default:
+                            bkch();
+                            str = name(false);
+                            st = 1;  // read entity declaration value
+                            break;
+                    }
+                    break;
+
+                case 1:     // read entity declaration value
+                    switch (chtyp(ch)) {
+                        case '\"':  // internal entity
+                        case '\'':
+                            bkch();
+                            bqstr('d');  // read a string into the buffer
+                            if (mEnt.get(str) == null) {
+                                //              Create general entity value
+                                val = new char[mBuffIdx];
+                                System.arraycopy(mBuff, 1, val, 0, val.length);
+                                //              Add the entity to the entity look up table
+                                if (mEnt.containsKey(str) == false) {   // [#4.2]
+                                    inp = new Input(val);
+                                    inp.pubid = mInp.pubid;
+                                    inp.sysid = mInp.sysid;
+                                    inp.xmlenc = mInp.xmlenc;
+                                    inp.xmlver = mInp.xmlver;
+                                    mEnt.put(str, inp);
+                                }
+                            }
+                            st = -1;  // the end of declaration
+                            break;
+
+                        case 'A':  // external entity
+                            bkch();
+                            ids = pubsys(' ');
+                            switch (wsskip()) {
+                                case '>':  // external parsed entity
+                                    if (mEnt.containsKey(str) == false) {  // [#4.2]
+                                        inp = new Input();
+                                        inp.pubid = ids.name;
+                                        inp.sysid = ids.value;
+                                        mEnt.put(str, inp);
+                                    }
+                                    break;
+
+                                case 'N':  // external general unparsed entity
+                                    if ("NDATA".equals(name(false)) == true) {
+                                        wsskip();
+                                        unparsedEntDecl(str, ids.name, ids.value, name(false));
+                                        break;
+                                    }
+                                default:
+                                    panic(FAULT);
+                                    break;
+                            }
+                            del(ids);
+                            st = -1;  // the end of declaration
+                            break;
+
+                        case ' ':
+                            //          Skip white spaces
+                            break;
+
+                        default:
+                            panic(FAULT);
+                            break;
+                    }
+                    break;
+
+                default:
+                    panic(FAULT);
+            }
+        }
+    }
+
+    /**
+     * Parses an element declaration.
+     *
+     * This method parses the declaration up to the closing angle bracket.
+     *
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    @SuppressWarnings("fallthrough")
+    private void dtdelm() throws Exception {
+        //              This is stub implementation which skips an element
+        //              declaration.
+        wsskip();
+        name(mIsNSAware);
+
+        char ch;
+        while (true) {
+            ch = getch();
+            switch (ch) {
+                case '>':
+                    bkch();
+                    return;
+
+                case EOS:
+                    panic(FAULT);
+
+                default:
+                    break;
+            }
+        }
+    }
+
+    /**
+     * Parses an attribute list declaration.
+     *
+     * This method parses the declaration up to the closing angle bracket.
+     *
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    private void dtdattl() throws Exception {
+        char elmqn[] = null;
+        Pair elm = null;
+        char ch;
+        for (short st = 0; st >= 0;) {
+            ch = getch();
+            switch (st) {
+                case 0:     // read the element name
+                    switch (chtyp(ch)) {
+                        case 'a':
+                        case 'A':
+                        case '_':
+                        case 'X':
+                        case ':':
+                            bkch();
+                            //          Get the element from the list or add a new one.
+                            elmqn = qname(mIsNSAware);
+                            elm = find(mAttL, elmqn);
+                            if (elm == null) {
+                                elm = pair(mAttL);
+                                elm.chars = elmqn;
+                                mAttL = elm;
+                            }
+                            st = 1;  // read an attribute declaration
+                            break;
+
+                        case ' ':
+                            break;
+
+                        case '%':
+                            pent(' ');
+                            break;
+
+                        default:
+                            panic(FAULT);
+                            break;
+                    }
+                    break;
+
+                case 1:     // read an attribute declaration
+                    switch (chtyp(ch)) {
+                        case 'a':
+                        case 'A':
+                        case '_':
+                        case 'X':
+                        case ':':
+                            bkch();
+                            dtdatt(elm);
+                            if (wsskip() == '>') {
+                                return;
+                            }
+                            break;
+
+                        case ' ':
+                            break;
+
+                        case '%':
+                            pent(' ');
+                            break;
+
+                        default:
+                            panic(FAULT);
+                            break;
+                    }
+                    break;
+
+                default:
+                    panic(FAULT);
+                    break;
+            }
+        }
+    }
+
+    /**
+     * Parses an attribute declaration.
+     *
+     * The attribute uses the following fields of Pair object: chars - characters
+     * of qualified name id - the type identifier of the attribute list - a pair
+     * which holds the default value (chars field)
+     *
+     * @param elm An object which represents all defined attributes on an
+     * element.
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    @SuppressWarnings("fallthrough")
+    private void dtdatt(Pair elm) throws Exception {
+        char attqn[] = null;
+        Pair att = null;
+        char ch;
+        for (short st = 0; st >= 0;) {
+            ch = getch();
+            switch (st) {
+                case 0:     // the attribute name
+                    switch (chtyp(ch)) {
+                        case 'a':
+                        case 'A':
+                        case '_':
+                        case 'X':
+                        case ':':
+                            bkch();
+                            //          Get the attribut from the list or add a new one.
+                            attqn = qname(mIsNSAware);
+                            att = find(elm.list, attqn);
+                            if (att == null) {
+                                //              New attribute declaration
+                                att = pair(elm.list);
+                                att.chars = attqn;
+                                elm.list = att;
+                            } else {
+                                //              Do not override the attribute declaration [#3.3]
+                                att = pair(null);
+                                att.chars = attqn;
+                                att.id = 'c';
+                            }
+                            wsskip();
+                            st = 1;
+                            break;
+
+                        case '%':
+                            pent(' ');
+                            break;
+
+                        case ' ':
+                            break;
+
+                        default:
+                            panic(FAULT);
+                            break;
+                    }
+                    break;
+
+                case 1:     // the attribute type
+                    switch (chtyp(ch)) {
+                        case '(':
+                            att.id = 'u';  // enumeration type
+                            st = 2;        // read the first element of the list
+                            break;
+
+                        case '%':
+                            pent(' ');
+                            break;
+
+                        case ' ':
+                            break;
+
+                        default:
+                            bkch();
+                            bntok();  // read type id
+                            att.id = bkeyword();
+                            switch (att.id) {
+                                case 'o':   // NOTATION
+                                    if (wsskip() != '(') {
+                                        panic(FAULT);
+                                    }
+                                    ch = getch();
+                                    st = 2;  // read the first element of the list
+                                    break;
+
+                                case 'i':     // ID
+                                case 'r':     // IDREF
+                                case 'R':     // IDREFS
+                                case 'n':     // ENTITY
+                                case 'N':     // ENTITIES
+                                case 't':     // NMTOKEN
+                                case 'T':     // NMTOKENS
+                                case 'c':     // CDATA
+                                    wsskip();
+                                    st = 4;  // read default declaration
+                                    break;
+
+                                default:
+                                    panic(FAULT);
+                                    break;
+                            }
+                            break;
+                    }
+                    break;
+
+                case 2:     // read the first element of the list
+                    switch (chtyp(ch)) {
+                        case 'a':
+                        case 'A':
+                        case 'd':
+                        case '.':
+                        case ':':
+                        case '-':
+                        case '_':
+                        case 'X':
+                            bkch();
+                            switch (att.id) {
+                                case 'u':  // enumeration type
+                                    bntok();
+                                    break;
+
+                                case 'o':  // NOTATION
+                                    mBuffIdx = -1;
+                                    bname(false);
+                                    break;
+
+                                default:
+                                    panic(FAULT);
+                                    break;
+                            }
+                            wsskip();
+                            st = 3;  // read next element of the list
+                            break;
+
+                        case '%':
+                            pent(' ');
+                            break;
+
+                        case ' ':
+                            break;
+
+                        default:
+                            panic(FAULT);
+                            break;
+                    }
+                    break;
+
+                case 3:     // read next element of the list
+                    switch (ch) {
+                        case ')':
+                            wsskip();
+                            st = 4;  // read default declaration
+                            break;
+
+                        case '|':
+                            wsskip();
+                            switch (att.id) {
+                                case 'u':  // enumeration type
+                                    bntok();
+                                    break;
+
+                                case 'o':  // NOTATION
+                                    mBuffIdx = -1;
+                                    bname(false);
+                                    break;
+
+                                default:
+                                    panic(FAULT);
+                                    break;
+                            }
+                            wsskip();
+                            break;
+
+                        case '%':
+                            pent(' ');
+                            break;
+
+                        default:
+                            panic(FAULT);
+                            break;
+                    }
+                    break;
+
+                case 4:     // read default declaration
+                    switch (ch) {
+                        case '#':
+                            bntok();
+                            switch (bkeyword()) {
+                                case 'F':  // FIXED
+                                    switch (wsskip()) {
+                                        case '\"':
+                                        case '\'':
+                                            st = 5;  // read the default value
+                                            break;
+
+                                        case EOS:
+                                            panic(FAULT);
+
+                                        default:
+                                            st = -1;
+                                            break;
+                                    }
+                                    break;
+
+                                case 'Q':  // REQUIRED
+                                case 'I':  // IMPLIED
+                                    st = -1;
+                                    break;
+
+                                default:
+                                    panic(FAULT);
+                                    break;
+                            }
+                            break;
+
+                        case '\"':
+                        case '\'':
+                            bkch();
+                            st = 5;  // read the default value
+                            break;
+
+                        case ' ':
+                        case '\n':
+                        case '\r':
+                        case '\t':
+                            break;
+
+                        case '%':
+                            pent(' ');
+                            break;
+
+                        default:
+                            bkch();
+                            st = -1;
+                            break;
+                    }
+                    break;
+
+                case 5:     // read the default value
+                    switch (ch) {
+                        case '\"':
+                        case '\'':
+                            bkch();
+                            bqstr('d');  // the value in the mBuff now
+                            att.list = pair(null);
+                            //          Create a string like "attqname='value' "
+                            att.list.chars = new char[att.chars.length + mBuffIdx + 3];
+                            System.arraycopy(
+                                    att.chars, 1, att.list.chars, 0, att.chars.length - 1);
+                            att.list.chars[att.chars.length - 1] = '=';
+                            att.list.chars[att.chars.length] = ch;
+                            System.arraycopy(
+                                    mBuff, 1, att.list.chars, att.chars.length + 1, mBuffIdx);
+                            att.list.chars[att.chars.length + mBuffIdx + 1] = ch;
+                            att.list.chars[att.chars.length + mBuffIdx + 2] = ' ';
+                            st = -1;
+                            break;
+
+                        default:
+                            panic(FAULT);
+                            break;
+                    }
+                    break;
+
+                default:
+                    panic(FAULT);
+                    break;
+            }
+        }
+    }
+
+    /**
+     * Parses a notation declaration.
+     *
+     * This method parses the declaration up to the closing angle bracket.
+     *
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    private void dtdnot() throws Exception {
+        wsskip();
+        String name = name(false);
+        wsskip();
+        Pair ids = pubsys('N');
+        notDecl(name, ids.name, ids.value);
+        del(ids);
+    }
+
+    /**
+     * Parses an attribute.
+     *
+     * This recursive method is responsible for prefix addition
+     * (
+     * <code>mPref</code>) on the way down. The element's start tag end triggers
+     * the return process. The method then on it's way back resolves prefixes
+     * and accumulates attributes.
+     *
+     * <p><code>att.num</code> carries attribute flags where: 0x1 - attribute is
+     * declared in DTD (attribute decalration had been read); 0x2 - attribute's
+     * default value is used.</p>
+     *
+     * @param att An object which reprecents current attribute.
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    @SuppressWarnings("fallthrough")
+    private void attr(Pair att) throws Exception {
+        switch (wsskip()) {
+            case '/':
+            case '>':
+                if ((att.num & 0x2) == 0) {  // all attributes have been read
+                    att.num |= 0x2;  // set default attribute flag
+                    Input inp = mInp;
+                    //          Go through all attributes defined on current element.
+                    for (Pair def = mElm.list; def != null; def = def.next) {
+                        if (def.list == null) // no default value
+                        {
+                            continue;
+                        }
+                        //              Go through all attributes defined on current
+                        //              element and add defaults.
+                        Pair act = find(att.next, def.chars);
+                        if (act == null) {
+                            push(new Input(def.list.chars));
+                        }
+                    }
+                    if (mInp != inp) {  // defaults have been added
+                        attr(att);
+                        return;
+                    }
+                }
+                //              Ensure the attribute string array capacity
+                mAttrs.setLength(mAttrIdx);
+                mItems = mAttrs.mItems;
+                return;
+
+            case EOS:
+                panic(FAULT);
+
+            default:
+                //              Read the attribute name and value
+                att.chars = qname(mIsNSAware);
+                att.name = att.local();
+                String type = atype(att);  // sets attribute's type on att.id
+                wsskip();
+                if (getch() != '=') {
+                    panic(FAULT);
+                }
+                bqstr((char) att.id);   // read the value with normalization.
+                String val = new String(mBuff, 1, mBuffIdx);
+                Pair next = pair(att);
+                next.num = (att.num & ~0x1);  // inherit attribute flags
+                //              Put a namespace declaration on top of the prefix stack
+                if ((mIsNSAware == false) || (isdecl(att, val) == false)) {
+                    //          An ordinary attribute
+                    mAttrIdx++;
+                    attr(next);     // recursive call to parse the next attribute
+                    mAttrIdx--;
+                    //          Add the attribute to the attributes string array
+                    char idx = (char) (mAttrIdx << 3);
+                    mItems[idx + 1] = att.qname();  // attr qname
+                    mItems[idx + 2] = (mIsNSAware) ? att.name : ""; // attr local name
+                    mItems[idx + 3] = val;          // attr value
+                    mItems[idx + 4] = type;         // attr type
+                    switch (att.num & 0x3) {
+                        case 0x0:
+                            mItems[idx + 5] = null;
+                            break;
+
+                        case 0x1:  // declared attribute
+                            mItems[idx + 5] = "d";
+                            break;
+
+                        default:  // 0x2, 0x3 - default attribute always declared
+                            mItems[idx + 5] = "D";
+                            break;
+                    }
+                    //          Resolve the prefix if any and report the attribute
+                    //          NOTE: The attribute does not accept the default namespace.
+                    mItems[idx + 0] = (att.chars[0] != 0) ? rslv(att.chars) : "";
+                } else {
+                    //          A namespace declaration. mPref.name contains prefix and
+                    //          mPref.value contains namespace URI set by isdecl method.
+                    //          Report a start of the new mapping
+                    newPrefix();
+                    //          Recursive call to parse the next attribute
+                    attr(next);
+                    //          NOTE: The namespace declaration is not reported.
+                }
+                del(next);
+                break;
+        }
+    }
+
+    /**
+     * Retrieves attribute type.
+     *
+     * This method sets the type of normalization in the attribute
+     * <code>id</code> field and returns the name of attribute type.
+     *
+     * @param att An object which represents current attribute.
+     * @return The name of the attribute type.
+     * @exception Exception is parser specific exception form panic method.
+     */
+    private String atype(Pair att)
+            throws Exception {
+        Pair attr;
+
+        // CDATA-type normalization by default [#3.3.3]
+        att.id = 'c';
+        if (mElm.list == null || (attr = find(mElm.list, att.chars)) == null) {
+            return "CDATA";
+        }
+
+        att.num |= 0x1;  // attribute is declared
+
+        // Non-CDATA normalization except when the attribute type is CDATA.
+        att.id = 'i';
+        switch (attr.id) {
+            case 'i':
+                return "ID";
+
+            case 'r':
+                return "IDREF";
+
+            case 'R':
+                return "IDREFS";
+
+            case 'n':
+                return "ENTITY";
+
+            case 'N':
+                return "ENTITIES";
+
+            case 't':
+                return "NMTOKEN";
+
+            case 'T':
+                return "NMTOKENS";
+
+            case 'u':
+                return "NMTOKEN";
+
+            case 'o':
+                return "NOTATION";
+
+            case 'c':
+                att.id = 'c';
+                return "CDATA";
+
+            default:
+                panic(FAULT);
+        }
+        return null;
+    }
+
+    /**
+     * Parses a comment.
+     *
+     * The &apos;&lt;!&apos; part is read in dispatcher so the method starts
+     * with first &apos;-&apos; after &apos;&lt;!&apos;.
+     *
+     * @exception Exception is parser specific exception form panic method.
+     */
+    @SuppressWarnings("fallthrough")
+    private void comm() throws Exception {
+        if (mPh == PH_DOC_START) {
+            mPh = PH_MISC_DTD;  // misc before DTD
+        }               // '<!' has been already read by dispetcher.
+        char ch;
+        mBuffIdx = -1;
+        for (short st = 0; st >= 0;) {
+            ch = (mChIdx < mChLen) ? mChars[mChIdx++] : getch();
+            if (ch == EOS) {
+                panic(FAULT);
+            }
+            switch (st) {
+                case 0:     // first '-' of the comment open
+                    if (ch == '-') {
+                        st = 1;
+                    } else {
+                        panic(FAULT);
+                    }
+                    break;
+
+                case 1:     // secind '-' of the comment open
+                    if (ch == '-') {
+                        st = 2;
+                    } else {
+                        panic(FAULT);
+                    }
+                    break;
+
+                case 2:     // skip the comment body
+                    switch (ch) {
+                        case '-':
+                            st = 3;
+                            break;
+
+                        default:
+                            bappend(ch);
+                            break;
+                    }
+                    break;
+
+                case 3:     // second '-' of the comment close
+                    switch (ch) {
+                        case '-':
+                            st = 4;
+                            break;
+
+                        default:
+                            bappend('-');
+                            bappend(ch);
+                            st = 2;
+                            break;
+                    }
+                    break;
+
+                case 4:     // '>' of the comment close
+                    if (ch == '>') {
+                        comm(mBuff, mBuffIdx + 1);
+                        st = -1;
+                        break;
+                    }
+                // else - panic [#2.5 compatibility note]
+
+                default:
+                    panic(FAULT);
+            }
+        }
+    }
+
+    /**
+     * Parses a processing instruction.
+     *
+     * The &apos;&lt;?&apos; is read in dispatcher so the method starts with
+     * first character of PI target name after &apos;&lt;?&apos;.
+     *
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    private void pi() throws Exception {
+        // '<?' has been already read by dispetcher.
+        char ch;
+        String str = null;
+        mBuffIdx = -1;
+        for (short st = 0; st >= 0;) {
+            ch = getch();
+            if (ch == EOS) {
+                panic(FAULT);
+            }
+            switch (st) {
+                case 0:     // read the PI target name
+                    switch (chtyp(ch)) {
+                        case 'a':
+                        case 'A':
+                        case '_':
+                        case ':':
+                        case 'X':
+                            bkch();
+                            str = name(false);
+                            //          PI target name may not be empty string [#2.6]
+                            //          PI target name 'XML' is reserved [#2.6]
+                            if ((str.length() == 0)
+                                    || (mXml.name.equals(str.toLowerCase()) == true)) {
+                                panic(FAULT);
+                            }
+                            //          This is processing instruction
+                            if (mPh == PH_DOC_START) // the begining of the document
+                            {
+                                mPh = PH_MISC_DTD;    // misc before DTD
+                            }
+                            wsskip();  // skip spaces after the PI target name
+                            st = 1;    // accumulate the PI body
+                            mBuffIdx = -1;
+                            break;
+
+                        default:
+                            panic(FAULT);
+                    }
+                    break;
+
+                case 1:     // accumulate the PI body
+                    switch (ch) {
+                        case '?':
+                            st = 2;  // end of the PI body
+                            break;
+
+                        default:
+                            bappend(ch);
+                            break;
+                    }
+                    break;
+
+                case 2:     // end of the PI body
+                    switch (ch) {
+                        case '>':
+                            //          PI has been read.
+                            pi(str, new String(mBuff, 0, mBuffIdx + 1));
+                            st = -1;
+                            break;
+
+                        case '?':
+                            bappend('?');
+                            break;
+
+                        default:
+                            bappend('?');
+                            bappend(ch);
+                            st = 1;  // accumulate the PI body
+                            break;
+                    }
+                    break;
+
+                default:
+                    panic(FAULT);
+            }
+        }
+    }
+
+    /**
+     * Parses a character data.
+     *
+     * The &apos;&lt;!&apos; part is read in dispatcher so the method starts
+     * with first &apos;[&apos; after &apos;&lt;!&apos;.
+     *
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    private void cdat()
+            throws Exception {
+        // '<!' has been already read by dispetcher.
+        char ch;
+        mBuffIdx = -1;
+        for (short st = 0; st >= 0;) {
+            ch = getch();
+            switch (st) {
+                case 0:     // the first '[' of the CDATA open
+                    if (ch == '[') {
+                        st = 1;
+                    } else {
+                        panic(FAULT);
+                    }
+                    break;
+
+                case 1:     // read "CDATA"
+                    if (chtyp(ch) == 'A') {
+                        bappend(ch);
+                    } else {
+                        if ("CDATA".equals(
+                                new String(mBuff, 0, mBuffIdx + 1)) != true) {
+                            panic(FAULT);
+                        }
+                        bkch();
+                        st = 2;
+                    }
+                    break;
+
+                case 2:     // the second '[' of the CDATA open
+                    if (ch != '[') {
+                        panic(FAULT);
+                    }
+                    mBuffIdx = -1;
+                    st = 3;
+                    break;
+
+                case 3:     // read data before the first ']'
+                    if (ch != ']') {
+                        bappend(ch);
+                    } else {
+                        st = 4;
+                    }
+                    break;
+
+                case 4:     // read the second ']' or continue to read the data
+                    if (ch != ']') {
+                        bappend(']');
+                        bappend(ch);
+                        st = 3;
+                    } else {
+                        st = 5;
+                    }
+                    break;
+
+                case 5:     // read '>' or continue to read the data
+                    switch (ch) {
+                        case ']':
+                            bappend(']');
+                            break;
+
+                        case '>':
+                            bflash();
+                            st = -1;
+                            break;
+
+                        default:
+                            bappend(']');
+                            bappend(']');
+                            bappend(ch);
+                            st = 3;
+                            break;
+                    }
+                    break;
+
+                default:
+                    panic(FAULT);
+            }
+        }
+    }
+
+    /**
+     * Reads a xml name.
+     *
+     * The xml name must conform "Namespaces in XML" specification. Therefore
+     * the ':' character is not allowed in the name. This method should be used
+     * for PI and entity names which may not have a namespace according to the
+     * specification mentioned above.
+     *
+     * @param ns The true value turns namespace conformance on.
+     * @return The name has been read.
+     * @exception Exception When incorrect character appear in the name.
+     * @exception IOException
+     */
+    protected String name(boolean ns)
+            throws Exception {
+        mBuffIdx = -1;
+        bname(ns);
+        return new String(mBuff, 1, mBuffIdx);
+    }
+
+    /**
+     * Reads a qualified xml name.
+     *
+     * The characters of a qualified name is an array of characters. The first
+     * (chars[0]) character is the index of the colon character which separates
+     * the prefix from the local name. If the index is zero, the name does not
+     * contain separator or the parser works in the namespace unaware mode. The
+     * length of qualified name is the length of the array minus one.
+     *
+     * @param ns The true value turns namespace conformance on.
+     * @return The characters of a qualified name.
+     * @exception Exception When incorrect character appear in the name.
+     * @exception IOException
+     */
+    protected char[] qname(boolean ns)
+            throws Exception {
+        mBuffIdx = -1;
+        bname(ns);
+        char chars[] = new char[mBuffIdx + 1];
+        System.arraycopy(mBuff, 0, chars, 0, mBuffIdx + 1);
+        return chars;
+    }
+
+    /**
+     * Reads the public or/and system identifiers.
+     *
+     * @param inp The input object.
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    private void pubsys(Input inp)
+            throws Exception {
+        Pair pair = pubsys(' ');
+        inp.pubid = pair.name;
+        inp.sysid = pair.value;
+        del(pair);
+    }
+
+    /**
+     * Reads the public or/and system identifiers.
+     *
+     * @param flag The 'N' allows public id be without system id.
+     * @return The public or/and system identifiers pair.
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    @SuppressWarnings("fallthrough")
+    private Pair pubsys(char flag) throws Exception {
+        Pair ids = pair(null);
+        String str = name(false);
+        if ("PUBLIC".equals(str) == true) {
+            bqstr('i');  // non-CDATA normalization [#4.2.2]
+            ids.name = new String(mBuff, 1, mBuffIdx);
+            switch (wsskip()) {
+                case '\"':
+                case '\'':
+                    bqstr(' ');
+                    ids.value = new String(mBuff, 1, mBuffIdx);
+                    break;
+
+                case EOS:
+                    panic(FAULT);
+
+                default:
+                    if (flag != 'N') // [#4.7]
+                    {
+                        panic(FAULT);
+                    }
+                    ids.value = null;
+                    break;
+            }
+            return ids;
+        } else if ("SYSTEM".equals(str) == true) {
+            ids.name = null;
+            bqstr(' ');
+            ids.value = new String(mBuff, 1, mBuffIdx);
+            return ids;
+        }
+        panic(FAULT);
+        return null;
+    }
+
+    /**
+     * Reads an attribute value.
+     *
+     * The grammar which this method can read is:<br />
+     * <code>eqstr := S &quot;=&quot; qstr</code><br />
+     * <code>qstr  := S (&quot;'&quot; string &quot;'&quot;) |
+     *  ('&quot;' string '&quot;')</code><br /> This method resolves entities
+     * inside a string unless the parser parses DTD.
+     *
+     * @param flag The '=' character forces the method to accept the '='
+     * character before quoted string and read the following string as not an
+     * attribute ('-'), 'c' - CDATA, 'i' - non CDATA, ' ' - no normalization;
+     * '-' - not an attribute value; 'd' - in DTD context.
+     * @return The content of the quoted strign as a string.
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    protected String eqstr(char flag) throws Exception {
+        if (flag == '=') {
+            wsskip();
+            if (getch() != '=') {
+                panic(FAULT);
+            }
+        }
+        bqstr((flag == '=') ? '-' : flag);
+        return new String(mBuff, 1, mBuffIdx);
+    }
+
+    /**
+     * Resoves an entity.
+     *
+     * This method resolves built-in and character entity references. It is also
+     * reports external entities to the application.
+     *
+     * @param flag The 'x' character forces the method to report a skipped
+     * entity; 'i' character - indicates non-CDATA normalization.
+     * @return Name of unresolved entity or <code>null</code> if entity had been
+     * resolved successfully.
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    @SuppressWarnings("fallthrough")
+    private String ent(char flag) throws Exception {
+        char ch;
+        int idx = mBuffIdx + 1;
+        Input inp = null;
+        String str = null;
+        mESt = 0x100;  // reset the built-in entity recognizer
+        bappend('&');
+        for (short st = 0; st >= 0;) {
+            ch = (mChIdx < mChLen) ? mChars[mChIdx++] : getch();
+            switch (st) {
+                case 0:     // the first character of the entity name
+                case 1:     // read built-in entity name
+                    switch (chtyp(ch)) {
+                        case 'd':
+                        case '.':
+                        case '-':
+                            if (st != 1) {
+                                panic(FAULT);
+                            }
+                        case 'a':
+                        case 'A':
+                        case '_':
+                        case 'X':
+                            bappend(ch);
+                            eappend(ch);
+                            st = 1;
+                            break;
+
+                        case ':':
+                            if (mIsNSAware != false) {
+                                panic(FAULT);
+                            }
+                            bappend(ch);
+                            eappend(ch);
+                            st = 1;
+                            break;
+
+                        case ';':
+                            if (mESt < 0x100) {
+                                //              The entity is a built-in entity
+                                mBuffIdx = idx - 1;
+                                bappend(mESt);
+                                st = -1;
+                                break;
+                            } else if (mPh == PH_DTD) {
+                                //              In DTD entity declaration has to resolve character
+                                //              entities and include "as is" others. [#4.4.7]
+                                bappend(';');
+                                st = -1;
+                                break;
+                            }
+                            //          Convert an entity name to a string
+                            str = new String(mBuff, idx + 1, mBuffIdx - idx);
+                            inp = mEnt.get(str);
+                            //          Restore the buffer offset
+                            mBuffIdx = idx - 1;
+                            if (inp != null) {
+                                if (inp.chars == null) {
+                                    //          External entity
+                                    InputSource is = resolveEnt(str, inp.pubid, inp.sysid);
+                                    if (is != null) {
+                                        push(new Input(BUFFSIZE_READER));
+                                        setinp(is);
+                                        mInp.pubid = inp.pubid;
+                                        mInp.sysid = inp.sysid;
+                                        str = null;  // the entity is resolved
+                                    } else {
+                                        //              Unresolved external entity
+                                        if (flag != 'x') {
+                                            panic(FAULT);  // unknown entity within marckup
+                                        }                                                               //              str is name of unresolved entity
+                                    }
+                                } else {
+                                    //          Internal entity
+                                    push(inp);
+                                    str = null;  // the entity is resolved
+                                }
+                            } else {
+                                //              Unknown or general unparsed entity
+                                if (flag != 'x') {
+                                    panic(FAULT);  // unknown entity within marckup
+                                }                                               //              str is name of unresolved entity
+                            }
+                            st = -1;
+                            break;
+
+                        case '#':
+                            if (st != 0) {
+                                panic(FAULT);
+                            }
+                            st = 2;
+                            break;
+
+                        default:
+                            panic(FAULT);
+                    }
+                    break;
+
+                case 2:     // read character entity
+                    switch (chtyp(ch)) {
+                        case 'd':
+                            bappend(ch);
+                            break;
+
+                        case ';':
+                            //          Convert the character entity to a character
+                            try {
+                                int i = Integer.parseInt(
+                                        new String(mBuff, idx + 1, mBuffIdx - idx), 10);
+                                if (i >= 0xffff) {
+                                    panic(FAULT);
+                                }
+                                ch = (char) i;
+                            } catch (NumberFormatException nfe) {
+                                panic(FAULT);
+                            }
+                            //          Restore the buffer offset
+                            mBuffIdx = idx - 1;
+                            if (ch == ' ' || mInp.next != null) {
+                                bappend(ch, flag);
+                            } else {
+                                bappend(ch);
+                            }
+                            st = -1;
+                            break;
+
+                        case 'a':
+                            //          If the entity buffer is empty and ch == 'x'
+                            if ((mBuffIdx == idx) && (ch == 'x')) {
+                                st = 3;
+                                break;
+                            }
+                        default:
+                            panic(FAULT);
+                    }
+                    break;
+
+                case 3:     // read hex character entity
+                    switch (chtyp(ch)) {
+                        case 'A':
+                        case 'a':
+                        case 'd':
+                            bappend(ch);
+                            break;
+
+                        case ';':
+                            //          Convert the character entity to a character
+                            try {
+                                int i = Integer.parseInt(
+                                        new String(mBuff, idx + 1, mBuffIdx - idx), 16);
+                                if (i >= 0xffff) {
+                                    panic(FAULT);
+                                }
+                                ch = (char) i;
+                            } catch (NumberFormatException nfe) {
+                                panic(FAULT);
+                            }
+                            //          Restore the buffer offset
+                            mBuffIdx = idx - 1;
+                            if (ch == ' ' || mInp.next != null) {
+                                bappend(ch, flag);
+                            } else {
+                                bappend(ch);
+                            }
+                            st = -1;
+                            break;
+
+                        default:
+                            panic(FAULT);
+                    }
+                    break;
+
+                default:
+                    panic(FAULT);
+            }
+        }
+
+        return str;
+    }
+
+    /**
+     * Resoves a parameter entity.
+     *
+     * This method resolves a parameter entity references. It is also reports
+     * external entities to the application.
+     *
+     * @param flag The '-' instruct the method to do not set up surrounding
+     * spaces [#4.4.8].
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    @SuppressWarnings("fallthrough")
+    private void pent(char flag) throws Exception {
+        char ch;
+        int idx = mBuffIdx + 1;
+        Input inp = null;
+        String str = null;
+        bappend('%');
+        if (mPh != PH_DTD) // the DTD internal subset
+        {
+            return;         // Not Recognized [#4.4.1]
+        }               //              Read entity name
+        bname(false);
+        str = new String(mBuff, idx + 2, mBuffIdx - idx - 1);
+        if (getch() != ';') {
+            panic(FAULT);
+        }
+        inp = mPEnt.get(str);
+        //              Restore the buffer offset
+        mBuffIdx = idx - 1;
+        if (inp != null) {
+            if (inp.chars == null) {
+                //              External parameter entity
+                InputSource is = resolveEnt(str, inp.pubid, inp.sysid);
+                if (is != null) {
+                    if (flag != '-') {
+                        bappend(' ');  // tail space
+                    }
+                    push(new Input(BUFFSIZE_READER));
+                    // BUG: there is no leading space! [#4.4.8]
+                    setinp(is);
+                    mInp.pubid = inp.pubid;
+                    mInp.sysid = inp.sysid;
+                } else {
+                    //          Unresolved external parameter entity
+                    skippedEnt("%" + str);
+                }
+            } else {
+                //              Internal parameter entity
+                if (flag == '-') {
+                    //          No surrounding spaces
+                    inp.chIdx = 1;
+                } else {
+                    //          Insert surrounding spaces
+                    bappend(' ');  // tail space
+                    inp.chIdx = 0;
+                }
+                push(inp);
+            }
+        } else {
+            //          Unknown parameter entity
+            skippedEnt("%" + str);
+        }
+    }
+
+    /**
+     * Recognizes and handles a namespace declaration.
+     *
+     * This method identifies a type of namespace declaration if any and puts
+     * new mapping on top of prefix stack.
+     *
+     * @param name The attribute qualified name (<code>name.value</code> is a
+     * <code>String</code> object which represents the attribute prefix).
+     * @param value The attribute value.
+     * @return <code>true</code> if a namespace declaration is recognized.
+     */
+    private boolean isdecl(Pair name, String value) {
+        if (name.chars[0] == 0) {
+            if ("xmlns".equals(name.name) == true) {
+                //              New default namespace declaration
+                mPref = pair(mPref);
+                mPref.list = mElm;  // prefix owner element
+                mPref.value = value;
+                mPref.name = "";
+                mPref.chars = NONS;
+                mElm.num++;  // namespace counter
+                return true;
+            }
+        } else {
+            if (name.eqpref(XMLNS) == true) {
+                //              New prefix declaration
+                int len = name.name.length();
+                mPref = pair(mPref);
+                mPref.list = mElm;  // prefix owner element
+                mPref.value = value;
+                mPref.name = name.name;
+                mPref.chars = new char[len + 1];
+                mPref.chars[0] = (char) (len + 1);
+                name.name.getChars(0, len, mPref.chars, 1);
+                mElm.num++;  // namespace counter
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Resolves a prefix.
+     *
+     * @return The namespace assigned to the prefix.
+     * @exception Exception When mapping for specified prefix is not found.
+     */
+    private String rslv(char[] qname)
+            throws Exception {
+        for (Pair pref = mPref; pref != null; pref = pref.next) {
+            if (pref.eqpref(qname) == true) {
+                return pref.value;
+            }
+        }
+        if (qname[0] == 1) {  // QNames like ':local'
+            for (Pair pref = mPref; pref != null; pref = pref.next) {
+                if (pref.chars[0] == 0) {
+                    return pref.value;
+                }
+            }
+        }
+        panic(FAULT);
+        return null;
+    }
+
+    /**
+     * Skips xml white space characters.
+     *
+     * This method skips white space characters (' ', '\t', '\n', '\r') and
+     * looks ahead not white space character.
+     *
+     * @return The first not white space look ahead character.
+     * @exception IOException
+     */
+    protected char wsskip()
+            throws IOException {
+        char ch;
+        while (true) {
+            //          Read next character
+            ch = (mChIdx < mChLen) ? mChars[mChIdx++] : getch();
+            if (ch < 0x80) {
+                if (nmttyp[ch] != 3) // [ \t\n\r]
+                {
+                    break;
+                }
+            } else {
+                break;
+            }
+        }
+        mChIdx--;  // bkch();
+        return ch;
+    }
+
+    /**
+     * Reports document type.
+     *
+     * @param name The name of the entity.
+     * @param pubid The public identifier of the entity or <code>null</code>.
+     * @param sysid The system identifier of the entity or <code>null</code>.
+     */
+    protected abstract void docType(String name, String pubid, String sysid)
+            throws SAXException;
+
+    /**
+     * Reports a comment.
+     *
+     * @param text The comment text starting from first charcater.
+     * @param length The number of characters in comment.
+     */
+    protected abstract void comm(char[] text, int length);
+
+    /**
+     * Reports a processing instruction.
+     *
+     * @param target The processing instruction target name.
+     * @param body The processing instruction body text.
+     */
+    protected abstract void pi(String target, String body)
+            throws Exception;
+
+    /**
+     * Reports new namespace prefix. The Namespace prefix (
+     * <code>mPref.name</code>) being declared and the Namespace URI (
+     * <code>mPref.value</code>) the prefix is mapped to. An empty string is
+     * used for the default element namespace, which has no prefix.
+     */
+    protected abstract void newPrefix()
+            throws Exception;
+
+    /**
+     * Reports skipped entity name.
+     *
+     * @param name The entity name.
+     */
+    protected abstract void skippedEnt(String name)
+            throws Exception;
+
+    /**
+     * Returns an
+     * <code>InputSource</code> for specified entity or
+     * <code>null</code>.
+     *
+     * @param name The name of the entity.
+     * @param pubid The public identifier of the entity.
+     * @param sysid The system identifier of the entity.
+     */
+    protected abstract InputSource resolveEnt(
+            String name, String pubid, String sysid)
+            throws Exception;
+
+    /**
+     * Reports notation declaration.
+     *
+     * @param name The notation's name.
+     * @param pubid The notation's public identifier, or null if none was given.
+     * @param sysid The notation's system identifier, or null if none was given.
+     */
+    protected abstract void notDecl(String name, String pubid, String sysid)
+            throws Exception;
+
+    /**
+     * Reports unparsed entity name.
+     *
+     * @param name The unparsed entity's name.
+     * @param pubid The entity's public identifier, or null if none was given.
+     * @param sysid The entity's system identifier.
+     * @param notation The name of the associated notation.
+     */
+    protected abstract void unparsedEntDecl(
+            String name, String pubid, String sysid, String notation)
+            throws Exception;
+
+    /**
+     * Notifies the handler about fatal parsing error.
+     *
+     * @param msg The problem description message.
+     */
+    protected abstract void panic(String msg)
+            throws Exception;
+
+    /**
+     * Reads a qualified xml name.
+     *
+     * This is low level routine which leaves a qName in the buffer. The
+     * characters of a qualified name is an array of characters. The first
+     * (chars[0]) character is the index of the colon character which separates
+     * the prefix from the local name. If the index is zero, the name does not
+     * contain separator or the parser works in the namespace unaware mode. The
+     * length of qualified name is the length of the array minus one.
+     *
+     * @param ns The true value turns namespace conformance on.
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    private void bname(boolean ns)
+            throws Exception {
+        char ch;
+        char type;
+        mBuffIdx++;  // allocate a char for colon offset
+        int bqname = mBuffIdx;
+        int bcolon = bqname;
+        int bchidx = bqname + 1;
+        int bstart = bchidx;
+        int cstart = mChIdx;
+        short st = (short) ((ns == true) ? 0 : 2);
+        while (true) {
+            //          Read next character
+            if (mChIdx >= mChLen) {
+                bcopy(cstart, bstart);
+                getch();
+                mChIdx--;  // bkch();
+                cstart = mChIdx;
+                bstart = bchidx;
+            }
+            ch = mChars[mChIdx++];
+            type = (char) 0;  // [X]
+            if (ch < 0x80) {
+                type = (char) nmttyp[ch];
+            } else if (ch == EOS) {
+                panic(FAULT);
+            }
+            //          Parse QName
+            switch (st) {
+                case 0:     // read the first char of the prefix
+                case 2:     // read the first char of the suffix
+                    switch (type) {
+                        case 0:  // [aA_X]
+                            bchidx++;  // append char to the buffer
+                            st++;      // (st == 0)? 1: 3;
+                            break;
+
+                        case 1:  // [:]
+                            mChIdx--;  // bkch();
+                            st++;      // (st == 0)? 1: 3;
+                            break;
+
+                        default:
+                            panic(FAULT);
+                    }
+                    break;
+
+                case 1:     // read the prefix
+                case 3:     // read the suffix
+                    switch (type) {
+                        case 0:  // [aA_X]
+                        case 2:  // [.-d]
+                            bchidx++;  // append char to the buffer
+                            break;
+
+                        case 1:  // [:]
+                            bchidx++;  // append char to the buffer
+                            if (ns == true) {
+                                if (bcolon != bqname) {
+                                    panic(FAULT);  // it must be only one colon
+                                }
+                                bcolon = bchidx - 1;
+                                if (st == 1) {
+                                    st = 2;
+                                }
+                            }
+                            break;
+
+                        default:
+                            mChIdx--;  // bkch();
+                            bcopy(cstart, bstart);
+                            mBuff[bqname] = (char) (bcolon - bqname);
+                            return;
+                    }
+                    break;
+
+                default:
+                    panic(FAULT);
+            }
+        }
+    }
+
+    /**
+     * Reads a nmtoken.
+     *
+     * This is low level routine which leaves a nmtoken in the buffer.
+     *
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    @SuppressWarnings("fallthrough")
+    private void bntok() throws Exception {
+        char ch;
+        mBuffIdx = -1;
+        bappend((char) 0);  // default offset to the colon char
+        while (true) {
+            ch = getch();
+            switch (chtyp(ch)) {
+                case 'a':
+                case 'A':
+                case 'd':
+                case '.':
+                case ':':
+                case '-':
+                case '_':
+                case 'X':
+                    bappend(ch);
+                    break;
+
+                case 'Z':
+                    panic(FAULT);
+
+                default:
+                    bkch();
+                    return;
+            }
+        }
+    }
+
+    /**
+     * Recognizes a keyword.
+     *
+     * This is low level routine which recognizes one of keywords in the buffer.
+     * Keyword Id ID - i IDREF - r IDREFS - R ENTITY - n ENTITIES - N NMTOKEN -
+     * t NMTOKENS - T ELEMENT - e ATTLIST - a NOTATION - o CDATA - c REQUIRED -
+     * Q IMPLIED - I FIXED - F
+     *
+     * @return an id of a keyword or '?'.
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    private char bkeyword()
+            throws Exception {
+        String str = new String(mBuff, 1, mBuffIdx);
+        switch (str.length()) {
+            case 2:  // ID
+                return ("ID".equals(str) == true) ? 'i' : '?';
+
+            case 5:  // IDREF, CDATA, FIXED
+                switch (mBuff[1]) {
+                    case 'I':
+                        return ("IDREF".equals(str) == true) ? 'r' : '?';
+                    case 'C':
+                        return ("CDATA".equals(str) == true) ? 'c' : '?';
+                    case 'F':
+                        return ("FIXED".equals(str) == true) ? 'F' : '?';
+                    default:
+                        break;
+                }
+                break;
+
+            case 6:  // IDREFS, ENTITY
+                switch (mBuff[1]) {
+                    case 'I':
+                        return ("IDREFS".equals(str) == true) ? 'R' : '?';
+                    case 'E':
+                        return ("ENTITY".equals(str) == true) ? 'n' : '?';
+                    default:
+                        break;
+                }
+                break;
+
+            case 7:  // NMTOKEN, IMPLIED, ATTLIST, ELEMENT
+                switch (mBuff[1]) {
+                    case 'I':
+                        return ("IMPLIED".equals(str) == true) ? 'I' : '?';
+                    case 'N':
+                        return ("NMTOKEN".equals(str) == true) ? 't' : '?';
+                    case 'A':
+                        return ("ATTLIST".equals(str) == true) ? 'a' : '?';
+                    case 'E':
+                        return ("ELEMENT".equals(str) == true) ? 'e' : '?';
+                    default:
+                        break;
+                }
+                break;
+
+            case 8:  // ENTITIES, NMTOKENS, NOTATION, REQUIRED
+                switch (mBuff[2]) {
+                    case 'N':
+                        return ("ENTITIES".equals(str) == true) ? 'N' : '?';
+                    case 'M':
+                        return ("NMTOKENS".equals(str) == true) ? 'T' : '?';
+                    case 'O':
+                        return ("NOTATION".equals(str) == true) ? 'o' : '?';
+                    case 'E':
+                        return ("REQUIRED".equals(str) == true) ? 'Q' : '?';
+                    default:
+                        break;
+                }
+                break;
+
+            default:
+                break;
+        }
+        return '?';
+    }
+
+    /**
+     * Reads a single or double quotted string in to the buffer.
+     *
+     * This method resolves entities inside a string unless the parser parses
+     * DTD.
+     *
+     * @param flag 'c' - CDATA, 'i' - non CDATA, ' ' - no normalization; '-' -
+     * not an attribute value; 'd' - in DTD context.
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    @SuppressWarnings("fallthrough")
+    private void bqstr(char flag) throws Exception {
+        Input inp = mInp;  // remember the original input
+        mBuffIdx = -1;
+        bappend((char) 0);  // default offset to the colon char
+        char ch;
+        for (short st = 0; st >= 0;) {
+            ch = (mChIdx < mChLen) ? mChars[mChIdx++] : getch();
+            switch (st) {
+                case 0:     // read a single or double quote
+                    switch (ch) {
+                        case ' ':
+                        case '\n':
+                        case '\r':
+                        case '\t':
+                            break;
+
+                        case '\'':
+                            st = 2;  // read a single quoted string
+                            break;
+
+                        case '\"':
+                            st = 3;  // read a double quoted string
+                            break;
+
+                        default:
+                            panic(FAULT);
+                            break;
+                    }
+                    break;
+
+                case 2:     // read a single quoted string
+                case 3:     // read a double quoted string
+                    switch (ch) {
+                        case '\'':
+                            if ((st == 2) && (mInp == inp)) {
+                                st = -1;
+                            } else {
+                                bappend(ch);
+                            }
+                            break;
+
+                        case '\"':
+                            if ((st == 3) && (mInp == inp)) {
+                                st = -1;
+                            } else {
+                                bappend(ch);
+                            }
+                            break;
+
+                        case '&':
+                            if (flag != 'd') {
+                                ent(flag);
+                            } else {
+                                bappend(ch);
+                            }
+                            break;
+
+                        case '%':
+                            if (flag == 'd') {
+                                pent('-');
+                            } else {
+                                bappend(ch);
+                            }
+                            break;
+
+                        case '<':
+                            if ((flag == '-') || (flag == 'd')) {
+                                bappend(ch);
+                            } else {
+                                panic(FAULT);
+                            }
+                            break;
+
+                        case EOS:               // EOS before single/double quote
+                            panic(FAULT);
+
+                        case '\r':     // EOL processing [#2.11 & #3.3.3]
+                            if (flag != ' ' && mInp.next == null) {
+                                if (getch() != '\n') {
+                                    bkch();
+                                }
+                                ch = '\n';
+                            }
+                        default:
+                            bappend(ch, flag);
+                            break;
+                    }
+                    break;
+
+                default:
+                    panic(FAULT);
+            }
+        }
+        //              There is maximum one space at the end of the string in
+        //              i-mode (non CDATA normalization) and it has to be removed.
+        if ((flag == 'i') && (mBuff[mBuffIdx] == ' ')) {
+            mBuffIdx -= 1;
+        }
+    }
+
+    /**
+     * Reports characters and empties the parser's buffer. This method is called
+     * only if parser is going to return control to the main loop. This means
+     * that this method may use parser buffer to report white space without
+     * copeing characters to temporary buffer.
+     */
+    protected abstract void bflash()
+            throws Exception;
+
+    /**
+     * Reports white space characters and empties the parser's buffer. This
+     * method is called only if parser is going to return control to the main
+     * loop. This means that this method may use parser buffer to report white
+     * space without copeing characters to temporary buffer.
+     */
+    protected abstract void bflash_ws()
+            throws Exception;
+
+    /**
+     * Appends a character to parser's buffer with normalization.
+     *
+     * @param ch The character to append to the buffer.
+     * @param mode The normalization mode.
+     */
+    private void bappend(char ch, char mode) {
+        //              This implements attribute value normalization as
+        //              described in the XML specification [#3.3.3].
+        switch (mode) {
+            case 'i':  // non CDATA normalization
+                switch (ch) {
+                    case ' ':
+                    case '\n':
+                    case '\r':
+                    case '\t':
+                        if ((mBuffIdx > 0) && (mBuff[mBuffIdx] != ' ')) {
+                            bappend(' ');
+                        }
+                        return;
+
+                    default:
+                        break;
+                }
+                break;
+
+            case 'c':  // CDATA normalization
+                switch (ch) {
+                    case '\n':
+                    case '\r':
+                    case '\t':
+                        ch = ' ';
+                        break;
+
+                    default:
+                        break;
+                }
+                break;
+
+            default:  // no normalization
+                break;
+        }
+        mBuffIdx++;
+        if (mBuffIdx < mBuff.length) {
+            mBuff[mBuffIdx] = ch;
+        } else {
+            mBuffIdx--;
+            bappend(ch);
+        }
+    }
+
+    /**
+     * Appends a character to parser's buffer.
+     *
+     * @param ch The character to append to the buffer.
+     */
+    private void bappend(char ch) {
+        try {
+            mBuff[++mBuffIdx] = ch;
+        } catch (Exception exp) {
+            //          Double the buffer size
+            char buff[] = new char[mBuff.length << 1];
+            System.arraycopy(mBuff, 0, buff, 0, mBuff.length);
+            mBuff = buff;
+            mBuff[mBuffIdx] = ch;
+        }
+    }
+
+    /**
+     * Appends (mChIdx - cidx) characters from character buffer (mChars) to
+     * parser's buffer (mBuff).
+     *
+     * @param cidx The character buffer (mChars) start index.
+     * @param bidx The parser buffer (mBuff) start index.
+     */
+    private void bcopy(int cidx, int bidx) {
+        int length = mChIdx - cidx;
+        if ((bidx + length + 1) >= mBuff.length) {
+            //          Expand the buffer
+            char buff[] = new char[mBuff.length + length];
+            System.arraycopy(mBuff, 0, buff, 0, mBuff.length);
+            mBuff = buff;
+        }
+        System.arraycopy(mChars, cidx, mBuff, bidx, length);
+        mBuffIdx += length;
+    }
+
+    /**
+     * Recognizes the built-in entities <i>lt</i>, <i>gt</i>, <i>amp</i>,
+     * <i>apos</i>, <i>quot</i>. The initial state is 0x100. Any state belowe
+     * 0x100 is a built-in entity replacement character.
+     *
+     * @param ch the next character of an entity name.
+     */
+    @SuppressWarnings("fallthrough")
+    private void eappend(char ch) {
+        switch (mESt) {
+            case 0x100:  // "l" or "g" or "a" or "q"
+                switch (ch) {
+                    case 'l':
+                        mESt = 0x101;
+                        break;
+                    case 'g':
+                        mESt = 0x102;
+                        break;
+                    case 'a':
+                        mESt = 0x103;
+                        break;
+                    case 'q':
+                        mESt = 0x107;
+                        break;
+                    default:
+                        mESt = 0x200;
+                        break;
+                }
+                break;
+
+            case 0x101:  // "lt"
+                mESt = (ch == 't') ? '<' : (char) 0x200;
+                break;
+
+            case 0x102:  // "gt"
+                mESt = (ch == 't') ? '>' : (char) 0x200;
+                break;
+
+            case 0x103:  // "am" or "ap"
+                switch (ch) {
+                    case 'm':
+                        mESt = 0x104;
+                        break;
+                    case 'p':
+                        mESt = 0x105;
+                        break;
+                    default:
+                        mESt = 0x200;
+                        break;
+                }
+                break;
+
+            case 0x104:  // "amp"
+                mESt = (ch == 'p') ? '&' : (char) 0x200;
+                break;
+
+            case 0x105:  // "apo"
+                mESt = (ch == 'o') ? (char) 0x106 : (char) 0x200;
+                break;
+
+            case 0x106:  // "apos"
+                mESt = (ch == 's') ? '\'' : (char) 0x200;
+                break;
+
+            case 0x107:  // "qu"
+                mESt = (ch == 'u') ? (char) 0x108 : (char) 0x200;
+                break;
+
+            case 0x108:  // "quo"
+                mESt = (ch == 'o') ? (char) 0x109 : (char) 0x200;
+                break;
+
+            case 0x109:  // "quot"
+                mESt = (ch == 't') ? '\"' : (char) 0x200;
+                break;
+
+            case '<':   // "lt"
+            case '>':   // "gt"
+            case '&':   // "amp"
+            case '\'':  // "apos"
+            case '\"':  // "quot"
+                mESt = 0x200;
+            default:
+                break;
+        }
+    }
+
+    /**
+     * Sets up a new input source on the top of the input stack. Note, the first
+     * byte returned by the entity's byte stream has to be the first byte in the
+     * entity. However, the parser does not expect the byte order mask in both
+     * cases when encoding is provided by the input source.
+     *
+     * @param is A new input source to set up.
+     * @exception IOException If any IO errors occur.
+     * @exception Exception is parser specific exception form panic method.
+     */
+    protected void setinp(InputSource is)
+            throws Exception {
+        Reader reader = null;
+        mChIdx = 0;
+        mChLen = 0;
+        mChars = mInp.chars;
+        mInp.src = null;
+        if (mPh < PH_DOC_START) {
+            mIsSAlone = false;  // default [#2.9]
+        }
+        mIsSAloneSet = false;
+        if (is.getCharacterStream() != null) {
+            //          Ignore encoding in the xml text decl.
+            reader = is.getCharacterStream();
+            xml(reader);
+        } else if (is.getByteStream() != null) {
+            String expenc;
+            if (is.getEncoding() != null) {
+                //              Ignore encoding in the xml text decl.
+                expenc = is.getEncoding().toUpperCase();
+                if (expenc.equals("UTF-16")) {
+                    reader = bom(is.getByteStream(), 'U');  // UTF-16 [#4.3.3]
+                } else {
+                    reader = enc(expenc, is.getByteStream());
+                }
+                xml(reader);
+            } else {
+                //              Get encoding from BOM or the xml text decl.
+                reader = bom(is.getByteStream(), ' ');
+                if (reader == null) {
+                    //          Encoding is defined by the xml text decl.
+                    reader = enc("UTF-8", is.getByteStream());
+                    expenc = xml(reader);
+                    if (expenc.startsWith("UTF-16")) {
+                        panic(FAULT);  // UTF-16 must have BOM [#4.3.3]
+                    }
+                    reader = enc(expenc, is.getByteStream());
+                } else {
+                    //          Encoding is defined by the BOM.
+                    xml(reader);
+                }
+            }
+        } else {
+            //          There is no support for public/system identifiers.
+            panic(FAULT);
+        }
+        mInp.src = reader;
+        mInp.pubid = is.getPublicId();
+        mInp.sysid = is.getSystemId();
+    }
+
+    /**
+     * Determines the entity encoding.
+     *
+     * This method gets encoding from Byte Order Mask [#4.3.3] if any. Note, the
+     * first byte returned by the entity's byte stream has to be the first byte
+     * in the entity. Also, there is no support for UCS-4.
+     *
+     * @param is A byte stream of the entity.
+     * @param hint An encoding hint, character U means UTF-16.
+     * @return a reader constructed from the BOM or UTF-8 by default.
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    private Reader bom(InputStream is, char hint)
+            throws Exception {
+        int val = is.read();
+        switch (val) {
+            case 0xef:     // UTF-8
+                if (hint == 'U') // must be UTF-16
+                {
+                    panic(FAULT);
+                }
+                if (is.read() != 0xbb) {
+                    panic(FAULT);
+                }
+                if (is.read() != 0xbf) {
+                    panic(FAULT);
+                }
+                return new ReaderUTF8(is);
+
+            case 0xfe:     // UTF-16, big-endian
+                if (is.read() != 0xff) {
+                    panic(FAULT);
+                }
+                return new ReaderUTF16(is, 'b');
+
+            case 0xff:     // UTF-16, little-endian
+                if (is.read() != 0xfe) {
+                    panic(FAULT);
+                }
+                return new ReaderUTF16(is, 'l');
+
+            case -1:
+                mChars[mChIdx++] = EOS;
+                return new ReaderUTF8(is);
+
+            default:
+                if (hint == 'U') // must be UTF-16
+                {
+                    panic(FAULT);
+                }
+                //              Read the rest of UTF-8 character
+                switch (val & 0xf0) {
+                    case 0xc0:
+                    case 0xd0:
+                        mChars[mChIdx++] = (char) (((val & 0x1f) << 6) | (is.read() & 0x3f));
+                        break;
+
+                    case 0xe0:
+                        mChars[mChIdx++] = (char) (((val & 0x0f) << 12)
+                                | ((is.read() & 0x3f) << 6) | (is.read() & 0x3f));
+                        break;
+
+                    case 0xf0:  // UCS-4 character
+                        throw new UnsupportedEncodingException();
+
+                    default:
+                        mChars[mChIdx++] = (char) val;
+                        break;
+                }
+                return null;
+        }
+    }
+
+    /**
+     * Parses the xml text declaration.
+     *
+     * This method gets encoding from the xml text declaration [#4.3.1] if any.
+     * The method assumes the buffer (mChars) is big enough to accomodate whole
+     * xml text declaration.
+     *
+     * @param reader is entity reader.
+     * @return The xml text declaration encoding or default UTF-8 encoding.
+     * @exception Exception is parser specific exception form panic method.
+     * @exception IOException
+     */
+    private String xml(Reader reader)
+            throws Exception {
+        String str = null;
+        String enc = "UTF-8";
+        char ch;
+        int val;
+        short st;
+        //              Read the xml text declaration into the buffer
+        if (mChIdx != 0) {
+            //          The bom method have read ONE char into the buffer.
+            st = (short) ((mChars[0] == '<') ? 1 : -1);
+        } else {
+            st = 0;
+        }
+        while (st >= 0 && mChIdx < mChars.length) {
+            ch = ((val = reader.read()) >= 0) ? (char) val : EOS;
+            mChars[mChIdx++] = ch;
+            switch (st) {
+                case 0:     // read '<' of xml declaration
+                    switch (ch) {
+                        case '<':
+                            st = 1;
+                            break;
+
+                        case 0xfeff:    // the byte order mask
+                            ch = ((val = reader.read()) >= 0) ? (char) val : EOS;
+                            mChars[mChIdx - 1] = ch;
+                            st = (short) ((ch == '<') ? 1 : -1);
+                            break;
+
+                        default:
+                            st = -1;
+                            break;
+                    }
+                    break;
+
+                case 1:     // read '?' of xml declaration [#4.3.1]
+                    st = (short) ((ch == '?') ? 2 : -1);
+                    break;
+
+                case 2:     // read 'x' of xml declaration [#4.3.1]
+                    st = (short) ((ch == 'x') ? 3 : -1);
+                    break;
+
+                case 3:     // read 'm' of xml declaration [#4.3.1]
+                    st = (short) ((ch == 'm') ? 4 : -1);
+                    break;
+
+                case 4:     // read 'l' of xml declaration [#4.3.1]
+                    st = (short) ((ch == 'l') ? 5 : -1);
+                    break;
+
+                case 5:     // read white space after 'xml'
+                    switch (ch) {
+                        case ' ':
+                        case '\t':
+                        case '\r':
+                        case '\n':
+                            st = 6;
+                            break;
+
+                        default:
+                            st = -1;
+                            break;
+                    }
+                    break;
+
+                case 6:     // read content of xml declaration
+                    switch (ch) {
+                        case '?':
+                            st = 7;
+                            break;
+
+                        case EOS:
+                            st = -2;
+                            break;
+
+                        default:
+                            break;
+                    }
+                    break;
+
+                case 7:     // read '>' after '?' of xml declaration
+                    switch (ch) {
+                        case '>':
+                        case EOS:
+                            st = -2;
+                            break;
+
+                        default:
+                            st = 6;
+                            break;
+                    }
+                    break;
+
+                default:
+                    panic(FAULT);
+                    break;
+            }
+        }
+        mChLen = mChIdx;
+        mChIdx = 0;
+        //              If there is no xml text declaration, the encoding is default.
+        if (st == -1) {
+            return enc;
+        }
+        mChIdx = 5;  // the first white space after "<?xml"
+        //              Parse the xml text declaration
+        for (st = 0; st >= 0;) {
+            ch = getch();
+            switch (st) {
+                case 0:     // skip spaces after the xml declaration name
+                    if (chtyp(ch) != ' ') {
+                        bkch();
+                        st = 1;
+                    }
+                    break;
+
+                case 1:     // read xml declaration version
+                case 2:     // read xml declaration encoding or standalone
+                case 3:     // read xml declaration standalone
+                    switch (chtyp(ch)) {
+                        case 'a':
+                        case 'A':
+                        case '_':
+                            bkch();
+                            str = name(false).toLowerCase();
+                            if ("version".equals(str) == true) {
+                                if (st != 1) {
+                                    panic(FAULT);
+                                }
+                                if ("1.0".equals(eqstr('=')) != true) {
+                                    panic(FAULT);
+                                }
+                                mInp.xmlver = 0x0100;
+                                st = 2;
+                            } else if ("encoding".equals(str) == true) {
+                                if (st != 2) {
+                                    panic(FAULT);
+                                }
+                                mInp.xmlenc = eqstr('=').toUpperCase();
+                                enc = mInp.xmlenc;
+                                st = 3;
+                            } else if ("standalone".equals(str) == true) {
+                                if ((st == 1) || (mPh >= PH_DOC_START)) // [#4.3.1]
+                                {
+                                    panic(FAULT);
+                                }
+                                str = eqstr('=').toLowerCase();
+                                //              Check the 'standalone' value and use it [#5.1]
+                                if (str.equals("yes") == true) {
+                                    mIsSAlone = true;
+                                } else if (str.equals("no") == true) {
+                                    mIsSAlone = false;
+                                } else {
+                                    panic(FAULT);
+                                }
+                                mIsSAloneSet = true;
+                                st = 4;
+                            } else {
+                                panic(FAULT);
+                            }
+                            break;
+
+                        case ' ':
+                            break;
+
+                        case '?':
+                            if (st == 1) {
+                                panic(FAULT);
+                            }
+                            bkch();
+                            st = 4;
+                            break;
+
+                        default:
+                            panic(FAULT);
+                    }
+                    break;
+
+                case 4:     // end of xml declaration
+                    switch (chtyp(ch)) {
+                        case '?':
+                            if (getch() != '>') {
+                                panic(FAULT);
+                            }
+                            if (mPh <= PH_DOC_START) {
+                                mPh = PH_MISC_DTD;  // misc before DTD
+                            }
+                            st = -1;
+                            break;
+
+                        case ' ':
+                            break;
+
+                        default:
+                            panic(FAULT);
+                    }
+                    break;
+
+                default:
+                    panic(FAULT);
+            }
+        }
+        return enc;
+    }
+
+    /**
+     * Sets up the document reader.
+     *
+     * @param name an encoding name.
+     * @param is the document byte input stream.
+     * @return a reader constructed from encoding name and input stream.
+     * @exception UnsupportedEncodingException
+     */
+    private Reader enc(String name, InputStream is)
+            throws UnsupportedEncodingException {
+        //              DO NOT CLOSE current reader if any!
+        if (name.equals("UTF-8")) {
+            return new ReaderUTF8(is);
+        } else if (name.equals("UTF-16LE")) {
+            return new ReaderUTF16(is, 'l');
+        } else if (name.equals("UTF-16BE")) {
+            return new ReaderUTF16(is, 'b');
+        } else {
+            return new InputStreamReader(is, name);
+        }
+    }
+
+    /**
+     * Sets up current input on the top of the input stack.
+     *
+     * @param inp A new input to set up.
+     */
+    protected void push(Input inp) {
+        mInp.chLen = mChLen;
+        mInp.chIdx = mChIdx;
+        inp.next = mInp;
+        mInp = inp;
+        mChars = inp.chars;
+        mChLen = inp.chLen;
+        mChIdx = inp.chIdx;
+    }
+
+    /**
+     * Restores previous input on the top of the input stack.
+     */
+    protected void pop() {
+        if (mInp.src != null) {
+            try {
+                mInp.src.close();
+            } catch (IOException ioe) {
+            }
+            mInp.src = null;
+        }
+        mInp = mInp.next;
+        if (mInp != null) {
+            mChars = mInp.chars;
+            mChLen = mInp.chLen;
+            mChIdx = mInp.chIdx;
+        } else {
+            mChars = null;
+            mChLen = 0;
+            mChIdx = 0;
+        }
+    }
+
+    /**
+     * Maps a character to it's type.
+     *
+     * Possible character type values are:<br /> - ' ' for any kind of white
+     * space character;<br /> - 'a' for any lower case alphabetical character
+     * value;<br /> - 'A' for any upper case alphabetical character value;<br />
+     * - 'd' for any decimal digit character value;<br /> - 'z' for any
+     * character less then ' ' except '\t', '\n', '\r';<br /> - 'X' for any not
+     * ASCII character;<br /> - 'Z' for EOS character.<br /> An ASCII (7 bit)
+     * character which does not fall in any category listed above is mapped to
+     * it self.
+     *
+     * @param ch The character to map.
+     * @return The type of character.
+     */
+    protected char chtyp(char ch) {
+        if (ch < 0x80) {
+            return (char) asctyp[ch];
+        }
+        return (ch != EOS) ? 'X' : 'Z';
+    }
+
+    /**
+     * Retrives the next character in the document.
+     *
+     * @return The next character in the document.
+     */
+    protected char getch()
+            throws IOException {
+        if (mChIdx >= mChLen) {
+            if (mInp.src == null) {
+                pop();  // remove internal entity
+                return getch();
+            }
+            //          Read new portion of the document characters
+            int Num = mInp.src.read(mChars, 0, mChars.length);
+            if (Num < 0) {
+                if (mInp != mDoc) {
+                    pop();  // restore the previous input
+                    return getch();
+                } else {
+                    mChars[0] = EOS;
+                    mChLen = 1;
+                }
+            } else {
+                mChLen = Num;
+            }
+            mChIdx = 0;
+        }
+        return mChars[mChIdx++];
+    }
+
+    /**
+     * Puts back the last read character.
+     *
+     * This method <strong>MUST NOT</strong> be called more then once after each
+     * call of {@link #getch getch} method.
+     */
+    protected void bkch()
+            throws Exception {
+        if (mChIdx <= 0) {
+            panic(FAULT);
+        }
+        mChIdx--;
+    }
+
+    /**
+     * Sets the current character.
+     *
+     * @param ch The character to set.
+     */
+    protected void setch(char ch) {
+        mChars[mChIdx] = ch;
+    }
+
+    /**
+     * Finds a pair in the pair chain by a qualified name.
+     *
+     * @param chain The first element of the chain of pairs.
+     * @param qname The qualified name.
+     * @return A pair with the specified qualified name or null.
+     */
+    protected Pair find(Pair chain, char[] qname) {
+        for (Pair pair = chain; pair != null; pair = pair.next) {
+            if (pair.eqname(qname) == true) {
+                return pair;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Provedes an instance of a pair.
+     *
+     * @param next The reference to a next pair.
+     * @return An instance of a pair.
+     */
+    protected Pair pair(Pair next) {
+        Pair pair;
+
+        if (mDltd != null) {
+            pair = mDltd;
+            mDltd = pair.next;
+        } else {
+            pair = new Pair();
+        }
+        pair.next = next;
+
+        return pair;
+    }
+
+    /**
+     * Deletes an instance of a pair.
+     *
+     * @param pair The pair to delete.
+     * @return A reference to the next pair in a chain.
+     */
+    protected Pair del(Pair pair) {
+        Pair next = pair.next;
+
+        pair.name = null;
+        pair.value = null;
+        pair.chars = null;
+        pair.list = null;
+        pair.next = mDltd;
+        mDltd = pair;
+
+        return next;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/impl/ParserSAX.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,695 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import jdk.internal.org.xml.sax.ContentHandler;
+import jdk.internal.org.xml.sax.DTDHandler;
+import jdk.internal.org.xml.sax.EntityResolver;
+import jdk.internal.org.xml.sax.ErrorHandler;
+import jdk.internal.org.xml.sax.InputSource;
+import jdk.internal.org.xml.sax.Locator;
+import jdk.internal.org.xml.sax.SAXException;
+import jdk.internal.org.xml.sax.SAXParseException;
+import jdk.internal.org.xml.sax.XMLReader;
+import jdk.internal.org.xml.sax.helpers.DefaultHandler;
+
+/**
+ * XML non-validating push parser.
+ *
+ * This non-validating parser conforms to <a href="http://www.w3.org/TR/REC-xml"
+ * >Extensible Markup Language (XML) 1.0</a> and <a
+ * href="http://www.w3.org/TR/REC-xml-names" >"Namespaces in XML"</a>
+ * specifications. The API supported by the parser are <a
+ * href="http://java.sun.com/aboutJava/communityprocess/final/jsr030/index.html">CLDC
+ * 1.0</a> and <a href="http://www.jcp.org/en/jsr/detail?id=280">JSR-280</a>, a
+ * JavaME subset of <a href="http://java.sun.com/xml/jaxp/index.html">JAXP</a>
+ * and <a href="http://www.saxproject.org/">SAX2</a>.
+ *
+ * @see org.xml.sax.XMLReader
+ */
+
+final class ParserSAX
+    extends Parser implements XMLReader, Locator
+{
+    public final static String FEATURE_NS =
+            "http://xml.org/sax/features/namespaces";
+    public final static String FEATURE_PREF =
+            "http://xml.org/sax/features/namespace-prefixes";
+    //          SAX feature flags
+    private boolean mFNamespaces;
+    private boolean mFPrefixes;
+    //          SAX handlers
+    private DefaultHandler mHand;      // the default handler
+    private ContentHandler mHandCont;  // the content handler
+    private DTDHandler mHandDtd;   // the DTD handler
+    private ErrorHandler mHandErr;   // the error handler
+    private EntityResolver mHandEnt;   // the entity resolver
+
+    /**
+     * Constructor.
+     */
+    public ParserSAX() {
+        super();
+
+        //              SAX feature defaut values
+        mFNamespaces = true;
+        mFPrefixes = false;
+
+        //              Default handler which will be used in case the application
+        //              do not set one of handlers.
+        mHand = new DefaultHandler();
+        mHandCont = mHand;
+        mHandDtd = mHand;
+        mHandErr = mHand;
+        mHandEnt = mHand;
+    }
+
+    /**
+     * Return the current content handler.
+     *
+     * @return The current content handler, or null if none has been registered.
+     * @see #setContentHandler
+     */
+    public ContentHandler getContentHandler() {
+        return (mHandCont != mHand) ? mHandCont : null;
+    }
+
+    /**
+     * Allow an application to register a content event handler.
+     *
+     * <p>If the application does not register a content handler, all content
+     * events reported by the SAX parser will be silently ignored.</p>
+     *
+     * <p>Applications may register a new or different handler in the middle of
+     * a parse, and the SAX parser must begin using the new handler
+     * immediately.</p>
+     *
+     * @param handler The content handler.
+     * @exception java.lang.NullPointerException If the handler argument is
+     * null.
+     * @see #getContentHandler
+     */
+    public void setContentHandler(ContentHandler handler) {
+        if (handler == null) {
+            throw new NullPointerException();
+        }
+        mHandCont = handler;
+    }
+
+    /**
+     * Return the current DTD handler.
+     *
+     * @return The current DTD handler, or null if none has been registered.
+     * @see #setDTDHandler
+     */
+    public DTDHandler getDTDHandler() {
+        return (mHandDtd != mHand) ? mHandDtd : null;
+    }
+
+    /**
+     * Allow an application to register a DTD event handler.
+     *
+     * <p>If the application does not register a DTD handler, all DTD events
+     * reported by the SAX parser will be silently ignored.</p>
+     *
+     * <p>Applications may register a new or different handler in the middle of
+     * a parse, and the SAX parser must begin using the new handler
+     * immediately.</p>
+     *
+     * @param handler The DTD handler.
+     * @exception java.lang.NullPointerException If the handler argument is
+     * null.
+     * @see #getDTDHandler
+     */
+    public void setDTDHandler(DTDHandler handler) {
+        if (handler == null) {
+            throw new NullPointerException();
+        }
+        mHandDtd = handler;
+    }
+
+    /**
+     * Return the current error handler.
+     *
+     * @return The current error handler, or null if none has been registered.
+     * @see #setErrorHandler
+     */
+    public ErrorHandler getErrorHandler() {
+        return (mHandErr != mHand) ? mHandErr : null;
+    }
+
+    /**
+     * Allow an application to register an error event handler.
+     *
+     * <p>If the application does not register an error handler, all error
+     * events reported by the SAX parser will be silently ignored; however,
+     * normal processing may not continue. It is highly recommended that all SAX
+     * applications implement an error handler to avoid unexpected bugs.</p>
+     *
+     * <p>Applications may register a new or different handler in the middle of
+     * a parse, and the SAX parser must begin using the new handler
+     * immediately.</p>
+     *
+     * @param handler The error handler.
+     * @exception java.lang.NullPointerException If the handler argument is
+     * null.
+     * @see #getErrorHandler
+     */
+    public void setErrorHandler(ErrorHandler handler) {
+        if (handler == null) {
+            throw new NullPointerException();
+        }
+        mHandErr = handler;
+    }
+
+    /**
+     * Return the current entity resolver.
+     *
+     * @return The current entity resolver, or null if none has been registered.
+     * @see #setEntityResolver
+     */
+    public EntityResolver getEntityResolver() {
+        return (mHandEnt != mHand) ? mHandEnt : null;
+    }
+
+    /**
+     * Allow an application to register an entity resolver.
+     *
+     * <p>If the application does not register an entity resolver, the XMLReader
+     * will perform its own default resolution.</p>
+     *
+     * <p>Applications may register a new or different resolver in the middle of
+     * a parse, and the SAX parser must begin using the new resolver
+     * immediately.</p>
+     *
+     * @param resolver The entity resolver.
+     * @exception java.lang.NullPointerException If the resolver argument is
+     * null.
+     * @see #getEntityResolver
+     */
+    public void setEntityResolver(EntityResolver resolver) {
+        if (resolver == null) {
+            throw new NullPointerException();
+        }
+        mHandEnt = resolver;
+    }
+
+    /**
+     * Return the public identifier for the current document event.
+     *
+     * <p>The return value is the public identifier of the document entity or of
+     * the external parsed entity in which the markup triggering the event
+     * appears.</p>
+     *
+     * @return A string containing the public identifier, or null if none is
+     * available.
+     *
+     * @see #getSystemId
+     */
+    public String getPublicId() {
+        return (mInp != null) ? mInp.pubid : null;
+    }
+
+    /**
+     * Return the system identifier for the current document event.
+     *
+     * <p>The return value is the system identifier of the document entity or of
+     * the external parsed entity in which the markup triggering the event
+     * appears.</p>
+     *
+     * <p>If the system identifier is a URL, the parser must resolve it fully
+     * before passing it to the application.</p>
+     *
+     * @return A string containing the system identifier, or null if none is
+     * available.
+     *
+     * @see #getPublicId
+     */
+    public String getSystemId() {
+        return (mInp != null) ? mInp.sysid : null;
+    }
+
+    /**
+     * Return the line number where the current document event ends.
+     *
+     * @return Always returns -1 indicating the line number is not available.
+     *
+     * @see #getColumnNumber
+     */
+    public int getLineNumber() {
+        return -1;
+    }
+
+    /**
+     * Return the column number where the current document event ends.
+     *
+     * @return Always returns -1 indicating the column number is not available.
+     *
+     * @see #getLineNumber
+     */
+    public int getColumnNumber() {
+        return -1;
+    }
+
+    /**
+     * Parse an XML document from a system identifier (URI).
+     *
+     * <p>This method is a shortcut for the common case of reading a document
+     * from a system identifier. It is the exact equivalent of the
+     * following:</p>
+     *
+     * <pre>
+     * parse(new InputSource(systemId));
+     * </pre>
+     *
+     * <p>If the system identifier is a URL, it must be fully resolved by the
+     * application before it is passed to the parser.</p>
+     *
+     * @param systemId The system identifier (URI).
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly wrapping
+     * another exception.
+     * @exception java.io.IOException An IO exception from the parser, possibly
+     * from a byte stream or character stream supplied by the application.
+     * @see #parse(org.xml.sax.InputSource)
+     */
+    public void parse(String systemId) throws IOException, SAXException {
+        parse(new InputSource(systemId));
+    }
+
+    /**
+     * Parse an XML document.
+     *
+     * <p>The application can use this method to instruct the XML reader to
+     * begin parsing an XML document from any valid input source (a character
+     * stream, a byte stream, or a URI).</p>
+     *
+     * <p>Applications may not invoke this method while a parse is in progress
+     * (they should create a new XMLReader instead for each nested XML
+     * document). Once a parse is complete, an application may reuse the same
+     * XMLReader object, possibly with a different input source.</p>
+     *
+     * <p>During the parse, the XMLReader will provide information about the XML
+     * document through the registered event handlers.</p>
+     *
+     * <p>This method is synchronous: it will not return until parsing has
+     * ended. If a client application wants to terminate parsing early, it
+     * should throw an exception.</p>
+     *
+     * @param is The input source for the top-level of the XML document.
+     * @exception org.xml.sax.SAXException Any SAX exception, possibly wrapping
+     * another exception.
+     * @exception java.io.IOException An IO exception from the parser, possibly
+     * from a byte stream or character stream supplied by the application.
+     * @see org.xml.sax.InputSource
+     * @see #parse(java.lang.String)
+     * @see #setEntityResolver
+     * @see #setDTDHandler
+     * @see #setContentHandler
+     * @see #setErrorHandler
+     */
+    public void parse(InputSource is) throws IOException, SAXException {
+        if (is == null) {
+            throw new IllegalArgumentException("");
+        }
+        //              Set up the document
+        mInp = new Input(BUFFSIZE_READER);
+        mPh = PH_BEFORE_DOC;  // before parsing
+        try {
+            setinp(is);
+        } catch (SAXException saxe) {
+            throw saxe;
+        } catch (IOException ioe) {
+            throw ioe;
+        } catch (RuntimeException rte) {
+            throw rte;
+        } catch (Exception e) {
+            panic(e.toString());
+        }
+        parse();
+    }
+
+    /**
+     * Parse the content of the given {@link java.io.InputStream} instance as
+     * XML using the specified {@link org.xml.sax.helpers.DefaultHandler}.
+     *
+     * @param src InputStream containing the content to be parsed.
+     * @param handler The SAX DefaultHandler to use.
+     * @exception IOException If any IO errors occur.
+     * @exception IllegalArgumentException If the given InputStream or handler
+     * is null.
+     * @exception SAXException If the underlying parser throws a SAXException
+     * while parsing.
+     * @see org.xml.sax.helpers.DefaultHandler
+     */
+    public void parse(InputStream src, DefaultHandler handler)
+            throws SAXException, IOException {
+        if ((src == null) || (handler == null)) {
+            throw new IllegalArgumentException("");
+        }
+        parse(new InputSource(src), handler);
+    }
+
+    /**
+     * Parse the content given {@link org.xml.sax.InputSource} as XML using the
+     * specified {@link org.xml.sax.helpers.DefaultHandler}.
+     *
+     * @param is The InputSource containing the content to be parsed.
+     * @param handler The SAX DefaultHandler to use.
+     * @exception IOException If any IO errors occur.
+     * @exception IllegalArgumentException If the InputSource or handler is
+     * null.
+     * @exception SAXException If the underlying parser throws a SAXException
+     * while parsing.
+     * @see org.xml.sax.helpers.DefaultHandler
+     */
+    public void parse(InputSource is, DefaultHandler handler)
+        throws SAXException, IOException
+    {
+        if ((is == null) || (handler == null)) {
+            throw new IllegalArgumentException("");
+        }
+        //              Set up the handler
+        mHandCont = handler;
+        mHandDtd = handler;
+        mHandErr = handler;
+        mHandEnt = handler;
+        //              Set up the document
+        mInp = new Input(BUFFSIZE_READER);
+        mPh = PH_BEFORE_DOC;  // before parsing
+        try {
+            setinp(is);
+        } catch (SAXException | IOException | RuntimeException saxe) {
+            throw saxe;
+        } catch (Exception e) {
+            panic(e.toString());
+        }
+        parse();
+    }
+
+    /**
+     * Parse the XML document content using specified handlers and an input
+     * source.
+     *
+     * @exception IOException If any IO errors occur.
+     * @exception SAXException If the underlying parser throws a SAXException
+     * while parsing.
+     */
+    @SuppressWarnings("fallthrough")
+    private void parse() throws SAXException, IOException {
+        init();
+        try {
+            mHandCont.setDocumentLocator(this);
+            mHandCont.startDocument();
+
+            if (mPh != PH_MISC_DTD) {
+                mPh = PH_MISC_DTD;  // misc before DTD
+            }
+            int evt = EV_NULL;
+            //          XML document prolog
+            do {
+                wsskip();
+                switch (evt = step()) {
+                    case EV_ELM:
+                    case EV_ELMS:
+                        mPh = PH_DOCELM;
+                        break;
+
+                    case EV_COMM:
+                    case EV_PI:
+                        break;
+
+                    case EV_DTD:
+                        if (mPh >= PH_DTD_MISC) {
+                            panic(FAULT);
+                        }
+                        mPh = PH_DTD_MISC;  // misc after DTD
+                        break;
+
+                    default:
+                        panic(FAULT);
+                }
+            } while (mPh < PH_DOCELM);  // misc before DTD
+            //          XML document starting with document's element
+            do {
+                switch (evt) {
+                    case EV_ELM:
+                    case EV_ELMS:
+                        //              Report the element
+                        if (mIsNSAware == true) {
+                            mHandCont.startElement(
+                                    mElm.value,
+                                    mElm.name,
+                                    "",
+                                    mAttrs);
+                        } else {
+                            mHandCont.startElement(
+                                    "",
+                                    "",
+                                    mElm.name,
+                                    mAttrs);
+                        }
+                        if (evt == EV_ELMS) {
+                            evt = step();
+                            break;
+                        }
+
+                    case EV_ELME:
+                        //              Report the end of element
+                        if (mIsNSAware == true) {
+                            mHandCont.endElement(mElm.value, mElm.name, "");
+                        } else {
+                            mHandCont.endElement("", "", mElm.name);
+                        }
+                        //              Restore the top of the prefix stack
+                        while (mPref.list == mElm) {
+                            mHandCont.endPrefixMapping(mPref.name);
+                            mPref = del(mPref);
+                        }
+                        //              Remove the top element tag
+                        mElm = del(mElm);
+                        if (mElm == null) {
+                            mPh = PH_DOCELM_MISC;
+                        } else {
+                            evt = step();
+                        }
+                        break;
+
+                    case EV_TEXT:
+                    case EV_WSPC:
+                    case EV_CDAT:
+                    case EV_COMM:
+                    case EV_PI:
+                    case EV_ENT:
+                        evt = step();
+                        break;
+
+                    default:
+                        panic(FAULT);
+                }
+            } while (mPh == PH_DOCELM);
+            //          Misc after document's element
+            do {
+                if (wsskip() == EOS) {
+                    break;
+                }
+
+                switch (step()) {
+                    case EV_COMM:
+                    case EV_PI:
+                        break;
+
+                    default:
+                        panic(FAULT);
+                }
+            } while (mPh == PH_DOCELM_MISC);
+            mPh = PH_AFTER_DOC;  // parsing is completed
+
+        } catch (SAXException saxe) {
+            throw saxe;
+        } catch (IOException ioe) {
+            throw ioe;
+        } catch (RuntimeException rte) {
+            throw rte;
+        } catch (Exception e) {
+            panic(e.toString());
+        } finally {
+            mHandCont.endDocument();
+            cleanup();
+        }
+    }
+
+    /**
+     * Reports document type.
+     *
+     * @param name The name of the entity.
+     * @param pubid The public identifier of the entity or <code>null</code>.
+     * @param sysid The system identifier of the entity or <code>null</code>.
+     */
+    protected void docType(String name, String pubid, String sysid) throws SAXException {
+        mHandDtd.notationDecl(name, pubid, sysid);
+    }
+
+    /**
+     * Reports a comment.
+     *
+     * @param text The comment text starting from first charcater.
+     * @param length The number of characters in comment.
+     */
+    protected void comm(char[] text, int length) {
+    }
+
+    /**
+     * Reports a processing instruction.
+     *
+     * @param target The processing instruction target name.
+     * @param body The processing instruction body text.
+     */
+    protected void pi(String target, String body) throws SAXException {
+        mHandCont.processingInstruction(target, body);
+    }
+
+    /**
+     * Reports new namespace prefix. The Namespace prefix (
+     * <code>mPref.name</code>) being declared and the Namespace URI (
+     * <code>mPref.value</code>) the prefix is mapped to. An empty string is
+     * used for the default element namespace, which has no prefix.
+     */
+    protected void newPrefix() throws SAXException {
+        mHandCont.startPrefixMapping(mPref.name, mPref.value);
+    }
+
+    /**
+     * Reports skipped entity name.
+     *
+     * @param name The entity name.
+     */
+    protected void skippedEnt(String name) throws SAXException {
+        mHandCont.skippedEntity(name);
+    }
+
+    /**
+     * Returns an
+     * <code>InputSource</code> for specified entity or
+     * <code>null</code>.
+     *
+     * @param name The name of the entity.
+     * @param pubid The public identifier of the entity.
+     * @param sysid The system identifier of the entity.
+     */
+    protected InputSource resolveEnt(String name, String pubid, String sysid)
+        throws SAXException, IOException
+    {
+        return mHandEnt.resolveEntity(pubid, sysid);
+    }
+
+    /**
+     * Reports notation declaration.
+     *
+     * @param name The notation's name.
+     * @param pubid The notation's public identifier, or null if none was given.
+     * @param sysid The notation's system identifier, or null if none was given.
+     */
+    protected void notDecl(String name, String pubid, String sysid)
+        throws SAXException
+    {
+        mHandDtd.notationDecl(name, pubid, sysid);
+    }
+
+    /**
+     * Reports unparsed entity name.
+     *
+     * @param name The unparsed entity's name.
+     * @param pubid The entity's public identifier, or null if none was given.
+     * @param sysid The entity's system identifier.
+     * @param notation The name of the associated notation.
+     */
+    protected void unparsedEntDecl(String name, String pubid, String sysid, String notation)
+        throws SAXException
+    {
+        mHandDtd.unparsedEntityDecl(name, pubid, sysid, notation);
+    }
+
+    /**
+     * Notifies the handler about fatal parsing error.
+     *
+     * @param msg The problem description message.
+     */
+    protected void panic(String msg) throws SAXException {
+        SAXParseException spe = new SAXParseException(msg, this);
+        mHandErr.fatalError(spe);
+        throw spe;  // [#1.2] fatal error definition
+    }
+
+    /**
+     * Reports characters and empties the parser's buffer. This method is called
+     * only if parser is going to return control to the main loop. This means
+     * that this method may use parser buffer to report white space without
+     * copeing characters to temporary buffer.
+     */
+    protected void bflash() throws SAXException {
+        if (mBuffIdx >= 0) {
+            //          Textual data has been read
+            mHandCont.characters(mBuff, 0, (mBuffIdx + 1));
+            mBuffIdx = -1;
+        }
+    }
+
+    /**
+     * Reports white space characters and empties the parser's buffer. This
+     * method is called only if parser is going to return control to the main
+     * loop. This means that this method may use parser buffer to report white
+     * space without copeing characters to temporary buffer.
+     */
+    protected void bflash_ws() throws SAXException {
+        if (mBuffIdx >= 0) {
+            // BUG: With additional info from DTD and xml:space attr [#2.10]
+            // the following call can be supported:
+            // mHandCont.ignorableWhitespace(mBuff, 0, (mBuffIdx + 1));
+
+            //          Textual data has been read
+            mHandCont.characters(mBuff, 0, (mBuffIdx + 1));
+            mBuffIdx = -1;
+        }
+    }
+
+    public boolean getFeature(String name) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    public void setFeature(String name, boolean value) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    public Object getProperty(String name) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    public void setProperty(String name, Object value) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/impl/ReaderUTF16.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml.impl;
+
+import java.io.Reader;
+import java.io.InputStream;
+import java.io.IOException;
+
+/**
+ * UTF-16 encoded stream reader.
+ */
+public class ReaderUTF16 extends Reader {
+
+    private InputStream is;
+    private char bo;
+
+    /**
+     * Constructor.
+     *
+     * Byte order argument can be: 'l' for little-endian or 'b' for big-endian.
+     *
+     * @param is A byte input stream.
+     * @param bo A byte order in the input stream.
+     */
+    public ReaderUTF16(InputStream is, char bo) {
+        switch (bo) {
+            case 'l':
+                break;
+
+            case 'b':
+                break;
+
+            default:
+                throw new IllegalArgumentException("");
+        }
+        this.bo = bo;
+        this.is = is;
+    }
+
+    /**
+     * Reads characters into a portion of an array.
+     *
+     * @param cbuf Destination buffer.
+     * @param off Offset at which to start storing characters.
+     * @param len Maximum number of characters to read.
+     * @exception IOException If any IO errors occur.
+     */
+    public int read(char[] cbuf, int off, int len) throws IOException {
+        int num = 0;
+        int val;
+        if (bo == 'b') {
+            while (num < len) {
+                if ((val = is.read()) < 0) {
+                    return (num != 0) ? num : -1;
+                }
+                cbuf[off++] = (char) ((val << 8) | (is.read() & 0xff));
+                num++;
+            }
+        } else {
+            while (num < len) {
+                if ((val = is.read()) < 0) {
+                    return (num != 0) ? num : -1;
+                }
+                cbuf[off++] = (char) ((is.read() << 8) | (val & 0xff));
+                num++;
+            }
+        }
+        return num;
+    }
+
+    /**
+     * Reads a single character.
+     *
+     * @return The character read, as an integer in the range 0 to 65535
+     *  (0x0000-0xffff), or -1 if the end of the stream has been reached.
+     * @exception IOException If any IO errors occur.
+     */
+    public int read() throws IOException {
+        int val;
+        if ((val = is.read()) < 0) {
+            return -1;
+        }
+        if (bo == 'b') {
+            val = (char) ((val << 8) | (is.read() & 0xff));
+        } else {
+            val = (char) ((is.read() << 8) | (val & 0xff));
+        }
+        return val;
+    }
+
+    /**
+     * Closes the stream.
+     *
+     * @exception IOException If any IO errors occur.
+     */
+    public void close() throws IOException {
+        is.close();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/impl/ReaderUTF8.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml.impl;
+
+import java.io.Reader;
+import java.io.InputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+
+/**
+ * UTF-8 transformed UCS-2 character stream reader.
+ *
+ * This reader converts UTF-8 transformed UCS-2 characters to Java characters.
+ * The UCS-2 subset of UTF-8 transformation is described in RFC-2279 #2
+ * "UTF-8 definition":
+ *  0000 0000-0000 007F   0xxxxxxx
+ *  0000 0080-0000 07FF   110xxxxx 10xxxxxx
+ *  0000 0800-0000 FFFF   1110xxxx 10xxxxxx 10xxxxxx
+ *
+ * This reader will return incorrect last character on broken UTF-8 stream.
+ */
+public class ReaderUTF8 extends Reader {
+
+    private InputStream is;
+
+    /**
+     * Constructor.
+     *
+     * @param is A byte input stream.
+     */
+    public ReaderUTF8(InputStream is) {
+        this.is = is;
+    }
+
+    /**
+     * Reads characters into a portion of an array.
+     *
+     * @param cbuf Destination buffer.
+     * @param off Offset at which to start storing characters.
+     * @param len Maximum number of characters to read.
+     * @exception IOException If any IO errors occur.
+     * @exception UnsupportedEncodingException If UCS-4 character occur in the stream.
+     */
+    public int read(char[] cbuf, int off, int len) throws IOException {
+        int num = 0;
+        int val;
+        while (num < len) {
+            if ((val = is.read()) < 0) {
+                return (num != 0) ? num : -1;
+            }
+            switch (val & 0xf0) {
+                case 0xc0:
+                case 0xd0:
+                    cbuf[off++] = (char) (((val & 0x1f) << 6) | (is.read() & 0x3f));
+                    break;
+
+                case 0xe0:
+                    cbuf[off++] = (char) (((val & 0x0f) << 12)
+                            | ((is.read() & 0x3f) << 6) | (is.read() & 0x3f));
+                    break;
+
+                case 0xf0:      // UCS-4 character
+                    throw new UnsupportedEncodingException("UTF-32 (or UCS-4) encoding not supported.");
+
+                default:
+                    cbuf[off++] = (char) val;
+                    break;
+            }
+            num++;
+        }
+        return num;
+    }
+
+    /**
+     * Reads a single character.
+     *
+     * @return The character read, as an integer in the range 0 to 65535
+     *  (0x00-0xffff), or -1 if the end of the stream has been reached.
+     * @exception IOException If any IO errors occur.
+     * @exception UnsupportedEncodingException If UCS-4 character occur in the stream.
+     */
+    public int read() throws IOException {
+        int val;
+        if ((val = is.read()) < 0) {
+            return -1;
+        }
+        switch (val & 0xf0) {
+            case 0xc0:
+            case 0xd0:
+                val = ((val & 0x1f) << 6) | (is.read() & 0x3f);
+                break;
+
+            case 0xe0:
+                val = ((val & 0x0f) << 12)
+                        | ((is.read() & 0x3f) << 6) | (is.read() & 0x3f);
+                break;
+
+            case 0xf0:  // UCS-4 character
+                throw new UnsupportedEncodingException();
+
+            default:
+                break;
+        }
+        return val;
+    }
+
+    /**
+     * Closes the stream.
+     *
+     * @exception IOException If any IO errors occur.
+     */
+    public void close() throws IOException {
+        is.close();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/impl/SAXParserImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import jdk.internal.org.xml.sax.InputSource;
+import jdk.internal.org.xml.sax.SAXException;
+import jdk.internal.org.xml.sax.XMLReader;
+import jdk.internal.org.xml.sax.helpers.DefaultHandler;
+import jdk.internal.util.xml.SAXParser;
+
+public class SAXParserImpl extends SAXParser {
+
+    private ParserSAX parser;
+
+    public SAXParserImpl() {
+        super();
+        parser = new ParserSAX();
+    }
+
+    /**
+     * Returns the {@link org.xml.sax.XMLReader} that is encapsulated by the
+     * implementation of this class.
+     *
+     * @return The XMLReader that is encapsulated by the
+     *         implementation of this class.
+     *
+     * @throws SAXException If any SAX errors occur during processing.
+     */
+    public XMLReader getXMLReader()
+            throws SAXException {
+        return parser;
+    }
+
+    /**
+     * Indicates whether or not this parser is configured to
+     * understand namespaces.
+     *
+     * @return true if this parser is configured to
+     *         understand namespaces; false otherwise.
+     */
+    public boolean isNamespaceAware() {
+        return parser.mIsNSAware;
+    }
+
+    /**
+     * Indicates whether or not this parser is configured to validate
+     * XML documents.
+     *
+     * @return true if this parser is configured to validate XML
+     *          documents; false otherwise.
+     */
+    public boolean isValidating() {
+        return false;
+    }
+
+    /**
+     * Parse the content of the given {@link java.io.InputStream}
+     * instance as XML using the specified
+     * {@link org.xml.sax.helpers.DefaultHandler}.
+     *
+     * @param src InputStream containing the content to be parsed.
+     * @param handler The SAX DefaultHandler to use.
+     * @exception IOException If any IO errors occur.
+     * @exception IllegalArgumentException If the given InputStream or handler is null.
+     * @exception SAXException If the underlying parser throws a
+     * SAXException while parsing.
+     * @see org.xml.sax.helpers.DefaultHandler
+     */
+    public void parse(InputStream src, DefaultHandler handler)
+        throws SAXException, IOException
+    {
+        parser.parse(src, handler);
+    }
+
+    /**
+     * Parse the content given {@link org.xml.sax.InputSource}
+     * as XML using the specified
+     * {@link org.xml.sax.helpers.DefaultHandler}.
+     *
+     * @param is The InputSource containing the content to be parsed.
+     * @param handler The SAX DefaultHandler to use.
+     * @exception IOException If any IO errors occur.
+     * @exception IllegalArgumentException If the InputSource or handler is null.
+     * @exception SAXException If the underlying parser throws a
+     * SAXException while parsing.
+     * @see org.xml.sax.helpers.DefaultHandler
+     */
+    public void parse(InputSource is, DefaultHandler handler)
+        throws SAXException, IOException
+    {
+        parser.parse(is, handler);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/impl/XMLStreamWriterImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,633 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml.impl;
+
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.nio.charset.Charset;
+import java.nio.charset.IllegalCharsetNameException;
+import java.nio.charset.UnsupportedCharsetException;
+import jdk.internal.util.xml.XMLStreamException;
+import jdk.internal.util.xml.XMLStreamWriter;
+
+/**
+ * Implementation of a reduced version of XMLStreamWriter
+ *
+ * @author Joe Wang
+ */
+public class XMLStreamWriterImpl implements XMLStreamWriter {
+    //Document state
+
+    static final int STATE_XML_DECL = 1;
+    static final int STATE_PROLOG = 2;
+    static final int STATE_DTD_DECL = 3;
+    static final int STATE_ELEMENT = 4;
+    //Element state
+    static final int ELEMENT_STARTTAG_OPEN = 10;
+    static final int ELEMENT_STARTTAG_CLOSE = 11;
+    static final int ELEMENT_ENDTAG_OPEN = 12;
+    static final int ELEMENT_ENDTAG_CLOSE = 13;
+    public static final char CLOSE_START_TAG = '>';
+    public static final char OPEN_START_TAG = '<';
+    public static final String OPEN_END_TAG = "</";
+    public static final char CLOSE_END_TAG = '>';
+    public static final String START_CDATA = "<![CDATA[";
+    public static final String END_CDATA = "]]>";
+    public static final String CLOSE_EMPTY_ELEMENT = "/>";
+    public static final String ENCODING_PREFIX = "&#x";
+    public static final char SPACE = ' ';
+    public static final char AMPERSAND = '&';
+    public static final char DOUBLEQUOT = '"';
+    public static final char SEMICOLON = ';';
+    //current state
+    private int _state = 0;
+    private Element _currentEle;
+    private XMLWriter _writer;
+    private String _encoding;
+    /**
+     * This flag can be used to turn escaping off for content. It does
+     * not apply to attribute content.
+     */
+    boolean _escapeCharacters = true;
+    //pretty print by default
+    private boolean _doIndent = true;
+    //The system line separator for writing out line breaks.
+    private char[] _lineSep =
+            System.getProperty("line.separator").toCharArray();
+
+    public XMLStreamWriterImpl(OutputStream os) throws XMLStreamException {
+        this(os, XMLStreamWriter.DEFAULT_ENCODING);
+    }
+
+    public XMLStreamWriterImpl(OutputStream os, String encoding)
+        throws XMLStreamException
+    {
+        Charset cs = null;
+        if (encoding == null) {
+            _encoding = XMLStreamWriter.DEFAULT_ENCODING;
+        } else {
+            try {
+                cs = getCharset(encoding);
+            } catch (UnsupportedEncodingException e) {
+                throw new XMLStreamException(e);
+            }
+
+            this._encoding = encoding;
+        }
+
+        _writer = new XMLWriter(os, encoding, cs);
+    }
+
+    /**
+     * Write the XML Declaration. Defaults the XML version to 1.0, and the
+     * encoding to utf-8.
+     *
+     * @throws XMLStreamException
+     */
+    public void writeStartDocument() throws XMLStreamException {
+        writeStartDocument(_encoding, XMLStreamWriter.DEFAULT_XML_VERSION);
+    }
+
+    /**
+     * Write the XML Declaration. Defaults the encoding to utf-8
+     *
+     * @param version version of the xml document
+     * @throws XMLStreamException
+     */
+    public void writeStartDocument(String version) throws XMLStreamException {
+        writeStartDocument(_encoding, version, null);
+    }
+
+    /**
+     * Write the XML Declaration. Note that the encoding parameter does not set
+     * the actual encoding of the underlying output. That must be set when the
+     * instance of the XMLStreamWriter is created
+     *
+     * @param encoding encoding of the xml declaration
+     * @param version version of the xml document
+     * @throws XMLStreamException If given encoding does not match encoding of the
+     * underlying stream
+     */
+    public void writeStartDocument(String encoding, String version) throws XMLStreamException {
+        writeStartDocument(encoding, version, null);
+    }
+
+    /**
+     * Write the XML Declaration. Note that the encoding parameter does not set
+     * the actual encoding of the underlying output. That must be set when the
+     * instance of the XMLStreamWriter is created
+     *
+     * @param encoding encoding of the xml declaration
+     * @param version version of the xml document
+     * @param standalone indicate if the xml document is standalone
+     * @throws XMLStreamException If given encoding does not match encoding of the
+     * underlying stream
+     */
+    public void writeStartDocument(String encoding, String version, String standalone)
+        throws XMLStreamException
+    {
+        if (_state > 0) {
+            throw new XMLStreamException("XML declaration must be as the first line in the XML document.");
+        }
+        _state = STATE_XML_DECL;
+        String enc = encoding;
+        if (enc == null) {
+            enc = _encoding;
+        } else {
+            //check if the encoding is supported
+            try {
+                getCharset(encoding);
+            } catch (UnsupportedEncodingException e) {
+                throw new XMLStreamException(e);
+            }
+        }
+
+        if (version == null) {
+            version = XMLStreamWriter.DEFAULT_XML_VERSION;
+        }
+
+        _writer.write("<?xml version=\"");
+        _writer.write(version);
+        _writer.write(DOUBLEQUOT);
+
+        if (enc != null) {
+            _writer.write(" encoding=\"");
+            _writer.write(enc);
+            _writer.write(DOUBLEQUOT);
+        }
+
+        if (standalone != null) {
+            _writer.write(" standalone=\"");
+            _writer.write(standalone);
+            _writer.write(DOUBLEQUOT);
+        }
+        _writer.write("?>");
+        writeLineSeparator();
+    }
+
+    /**
+     * Write a DTD section.  This string represents the entire doctypedecl production
+     * from the XML 1.0 specification.
+     *
+     * @param dtd the DTD to be written
+     * @throws XMLStreamException
+     */
+    public void writeDTD(String dtd) throws XMLStreamException {
+        if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
+            closeStartTag();
+        }
+        _writer.write(dtd);
+        writeLineSeparator();
+    }
+
+    /**
+     * Writes a start tag to the output.
+     * @param localName local name of the tag, may not be null
+     * @throws XMLStreamException
+     */
+    public void writeStartElement(String localName) throws XMLStreamException {
+        if (localName == null || localName.length() == 0) {
+            throw new XMLStreamException("Local Name cannot be null or empty");
+        }
+
+        _state = STATE_ELEMENT;
+        if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
+            closeStartTag();
+        }
+
+        _currentEle = new Element(_currentEle, localName, false);
+        openStartTag();
+
+        _writer.write(localName);
+    }
+
+    /**
+     * Writes an empty element tag to the output
+     * @param localName local name of the tag, may not be null
+     * @throws XMLStreamException
+     */
+    public void writeEmptyElement(String localName) throws XMLStreamException {
+        if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
+            closeStartTag();
+        }
+
+        _currentEle = new Element(_currentEle, localName, true);
+
+        openStartTag();
+        _writer.write(localName);
+    }
+
+    /**
+     * Writes an attribute to the output stream without a prefix.
+     * @param localName the local name of the attribute
+     * @param value the value of the attribute
+     * @throws IllegalStateException if the current state does not allow Attribute writing
+     * @throws XMLStreamException
+     */
+    public void writeAttribute(String localName, String value) throws XMLStreamException {
+        if (_currentEle.getState() != ELEMENT_STARTTAG_OPEN) {
+            throw new XMLStreamException(
+                    "Attribute not associated with any element");
+        }
+
+        _writer.write(SPACE);
+        _writer.write(localName);
+        _writer.write("=\"");
+        writeXMLContent(
+                value,
+                true, // true = escapeChars
+                true);  // true = escapeDoubleQuotes
+        _writer.write(DOUBLEQUOT);
+    }
+
+    public void writeEndDocument() throws XMLStreamException {
+        if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
+            closeStartTag();
+        }
+
+        /**
+         * close unclosed elements if any
+         */
+        while (_currentEle != null) {
+
+            if (!_currentEle.isEmpty()) {
+                _writer.write(OPEN_END_TAG);
+                _writer.write(_currentEle.getLocalName());
+                _writer.write(CLOSE_END_TAG);
+            }
+
+            _currentEle = _currentEle.getParent();
+        }
+    }
+
+    public void writeEndElement() throws XMLStreamException {
+        if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
+            closeStartTag();
+        }
+
+        if (_currentEle == null) {
+            throw new XMLStreamException("No element was found to write");
+        }
+
+        if (_currentEle.isEmpty()) {
+            return;
+        }
+
+        _writer.write(OPEN_END_TAG);
+        _writer.write(_currentEle.getLocalName());
+        _writer.write(CLOSE_END_TAG);
+        writeLineSeparator();
+
+        _currentEle = _currentEle.getParent();
+    }
+
+    public void writeCData(String cdata) throws XMLStreamException {
+        if (cdata == null) {
+            throw new XMLStreamException("cdata cannot be null");
+        }
+
+        if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
+            closeStartTag();
+        }
+
+        _writer.write(START_CDATA);
+        _writer.write(cdata);
+        _writer.write(END_CDATA);
+    }
+
+    public void writeCharacters(String data) throws XMLStreamException {
+        if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
+            closeStartTag();
+        }
+
+        writeXMLContent(data);
+    }
+
+    public void writeCharacters(char[] data, int start, int len)
+            throws XMLStreamException {
+        if (_currentEle != null && _currentEle.getState() == ELEMENT_STARTTAG_OPEN) {
+            closeStartTag();
+        }
+
+        writeXMLContent(data, start, len, _escapeCharacters);
+    }
+
+    /**
+     * Close this XMLStreamWriter by closing underlying writer.
+     */
+    public void close() throws XMLStreamException {
+        if (_writer != null) {
+            _writer.close();
+        }
+        _writer = null;
+        _currentEle = null;
+        _state = 0;
+    }
+
+    /**
+     * Flush this XMLStreamWriter by flushing underlying writer.
+     */
+    public void flush() throws XMLStreamException {
+        if (_writer != null) {
+            _writer.flush();
+        }
+    }
+
+    /**
+     * Set the flag to indicate if the writer should add line separator
+     * @param doIndent
+     */
+    public void setDoIndent(boolean doIndent) {
+        _doIndent = doIndent;
+    }
+
+    /**
+     * Writes XML content to underlying writer. Escapes characters unless
+     * escaping character feature is turned off.
+     */
+    private void writeXMLContent(char[] content, int start, int length, boolean escapeChars)
+        throws XMLStreamException
+    {
+        if (!escapeChars) {
+            _writer.write(content, start, length);
+            return;
+        }
+
+        // Index of the next char to be written
+        int startWritePos = start;
+
+        final int end = start + length;
+
+        for (int index = start; index < end; index++) {
+            char ch = content[index];
+
+            if (!_writer.canEncode(ch)) {
+                _writer.write(content, startWritePos, index - startWritePos);
+
+                // Escape this char as underlying encoder cannot handle it
+                _writer.write(ENCODING_PREFIX);
+                _writer.write(Integer.toHexString(ch));
+                _writer.write(SEMICOLON);
+                startWritePos = index + 1;
+                continue;
+            }
+
+            switch (ch) {
+                case OPEN_START_TAG:
+                    _writer.write(content, startWritePos, index - startWritePos);
+                    _writer.write("&lt;");
+                    startWritePos = index + 1;
+
+                    break;
+
+                case AMPERSAND:
+                    _writer.write(content, startWritePos, index - startWritePos);
+                    _writer.write("&amp;");
+                    startWritePos = index + 1;
+
+                    break;
+
+                case CLOSE_START_TAG:
+                    _writer.write(content, startWritePos, index - startWritePos);
+                    _writer.write("&gt;");
+                    startWritePos = index + 1;
+
+                    break;
+            }
+        }
+
+        // Write any pending data
+        _writer.write(content, startWritePos, end - startWritePos);
+    }
+
+    private void writeXMLContent(String content) throws XMLStreamException {
+        if ((content != null) && (content.length() > 0)) {
+            writeXMLContent(content,
+                    _escapeCharacters, // boolean = escapeChars
+                    false);             // false = escapeDoubleQuotes
+        }
+    }
+
+    /**
+     * Writes XML content to underlying writer. Escapes characters unless
+     * escaping character feature is turned off.
+     */
+    private void writeXMLContent(
+            String content,
+            boolean escapeChars,
+            boolean escapeDoubleQuotes)
+        throws XMLStreamException
+    {
+
+        if (!escapeChars) {
+            _writer.write(content);
+
+            return;
+        }
+
+        // Index of the next char to be written
+        int startWritePos = 0;
+
+        final int end = content.length();
+
+        for (int index = 0; index < end; index++) {
+            char ch = content.charAt(index);
+
+            if (!_writer.canEncode(ch)) {
+                _writer.write(content, startWritePos, index - startWritePos);
+
+                // Escape this char as underlying encoder cannot handle it
+                _writer.write(ENCODING_PREFIX);
+                _writer.write(Integer.toHexString(ch));
+                _writer.write(SEMICOLON);
+                startWritePos = index + 1;
+                continue;
+            }
+
+            switch (ch) {
+                case OPEN_START_TAG:
+                    _writer.write(content, startWritePos, index - startWritePos);
+                    _writer.write("&lt;");
+                    startWritePos = index + 1;
+
+                    break;
+
+                case AMPERSAND:
+                    _writer.write(content, startWritePos, index - startWritePos);
+                    _writer.write("&amp;");
+                    startWritePos = index + 1;
+
+                    break;
+
+                case CLOSE_START_TAG:
+                    _writer.write(content, startWritePos, index - startWritePos);
+                    _writer.write("&gt;");
+                    startWritePos = index + 1;
+
+                    break;
+
+                case DOUBLEQUOT:
+                    _writer.write(content, startWritePos, index - startWritePos);
+                    if (escapeDoubleQuotes) {
+                        _writer.write("&quot;");
+                    } else {
+                        _writer.write(DOUBLEQUOT);
+                    }
+                    startWritePos = index + 1;
+
+                    break;
+            }
+        }
+
+        // Write any pending data
+        _writer.write(content, startWritePos, end - startWritePos);
+    }
+
+    /**
+     * marks open of start tag and writes the same into the writer.
+     */
+    private void openStartTag() throws XMLStreamException {
+        _currentEle.setState(ELEMENT_STARTTAG_OPEN);
+        _writer.write(OPEN_START_TAG);
+    }
+
+    /**
+     * marks close of start tag and writes the same into the writer.
+     */
+    private void closeStartTag() throws XMLStreamException {
+        if (_currentEle.isEmpty()) {
+            _writer.write(CLOSE_EMPTY_ELEMENT);
+        } else {
+            _writer.write(CLOSE_START_TAG);
+
+        }
+
+        if (_currentEle.getParent() == null) {
+            writeLineSeparator();
+        }
+
+        _currentEle.setState(ELEMENT_STARTTAG_CLOSE);
+
+    }
+
+    /**
+     * Write a line separator
+     * @throws XMLStreamException
+     */
+    private void writeLineSeparator() throws XMLStreamException {
+        if (_doIndent) {
+            _writer.write(_lineSep, 0, _lineSep.length);
+        }
+    }
+
+    /**
+     * Returns a charset object for the specified encoding
+     * @param encoding
+     * @return a charset object
+     * @throws UnsupportedEncodingException if the encoding is not supported
+     */
+    private Charset getCharset(String encoding) throws UnsupportedEncodingException {
+        if (encoding.equalsIgnoreCase("UTF-32")) {
+            throw new UnsupportedEncodingException("The basic XMLWriter does "
+                    + "not support " + encoding);
+        }
+
+        Charset cs;
+        try {
+            cs = Charset.forName(encoding);
+        } catch (IllegalCharsetNameException | UnsupportedCharsetException ex) {
+            throw new UnsupportedEncodingException(encoding);
+        }
+        return cs;
+    }
+
+    /*
+     * Start of Internal classes.
+     *
+     */
+    protected class Element {
+
+        /**
+         * the parent element
+         */
+        protected Element _parent;
+        /**
+         * The size of the stack.
+         */
+        protected short _Depth;
+        /**
+         * indicate if an element is an empty one
+         */
+        boolean _isEmptyElement = false;
+        String _localpart;
+        int _state;
+
+        /**
+         * Default constructor.
+         */
+        public Element() {
+        }
+
+        /**
+         * @param parent the parent of the element
+         * @param localpart name of the element
+         * @param isEmpty indicate if the element is an empty one
+         */
+        public Element(Element parent, String localpart, boolean isEmpty) {
+            _parent = parent;
+            _localpart = localpart;
+            _isEmptyElement = isEmpty;
+        }
+
+        public Element getParent() {
+            return _parent;
+        }
+
+        public String getLocalName() {
+            return _localpart;
+        }
+
+        /**
+         * get the state of the element
+         */
+        public int getState() {
+            return _state;
+        }
+
+        /**
+         * Set the state of the element
+         *
+         * @param state the state of the element
+         */
+        public void setState(int state) {
+            _state = state;
+        }
+
+        public boolean isEmpty() {
+            return _isEmptyElement;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/jdk/internal/util/xml/impl/XMLWriter.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.internal.util.xml.impl;
+
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.io.Writer;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+import jdk.internal.util.xml.XMLStreamException;
+
+/**
+ *
+ * @author huizwang
+ */
+public class XMLWriter {
+
+    private Writer _writer;
+    /**
+     * In some cases, this charset encoder is used to determine if a char is
+     * encodable by underlying writer. For example, an 8-bit char from the
+     * extended ASCII set is not encodable by 7-bit ASCII encoder. Unencodable
+     * chars are escaped using XML numeric entities.
+     */
+    private CharsetEncoder _encoder = null;
+
+    public XMLWriter(OutputStream os, String encoding, Charset cs) throws XMLStreamException {
+        _encoder = cs.newEncoder();
+        try {
+            _writer = getWriter(os, encoding, cs);
+        } catch (UnsupportedEncodingException ex) {
+            throw new XMLStreamException(ex);
+        }
+
+    }
+
+    public boolean canEncode(char ch) {
+        if (_encoder == null) {
+            return false;
+        }
+        return (_encoder.canEncode(ch));
+    }
+
+    public void write(String s)
+            throws XMLStreamException {
+        try {
+            _writer.write(s.toCharArray());
+//            _writer.write(s.getBytes(Charset.forName(_encoding)));
+        } catch (IOException e) {
+            throw new XMLStreamException("I/O error", e);
+        }
+    }
+
+    public void write(String str, int off, int len)
+            throws XMLStreamException {
+        try {
+            _writer.write(str, off, len);
+        } catch (IOException e) {
+            throw new XMLStreamException("I/O error", e);
+        }
+
+    }
+
+    public void write(char[] cbuf, int off, int len)
+            throws XMLStreamException {
+        try {
+            _writer.write(cbuf, off, len);
+        } catch (IOException e) {
+            throw new XMLStreamException("I/O error", e);
+        }
+
+    }
+
+    void write(int b)
+            throws XMLStreamException {
+        try {
+            _writer.write(b);
+        } catch (IOException e) {
+            throw new XMLStreamException("I/O error", e);
+        }
+    }
+
+    void flush() throws XMLStreamException {
+        try {
+            _writer.flush();
+        } catch (IOException ex) {
+            throw new XMLStreamException(ex);
+        }
+    }
+
+    void close() throws XMLStreamException {
+        try {
+            _writer.close();
+        } catch (IOException ex) {
+            throw new XMLStreamException(ex);
+        }
+    }
+
+    private void nl() throws XMLStreamException {
+        String lineEnd = System.getProperty("line.separator");
+        try {
+            _writer.write(lineEnd);
+        } catch (IOException e) {
+            throw new XMLStreamException("I/O error", e);
+        }
+    }
+
+    /**
+     * Returns a writer for the specified encoding based on an output stream.
+     *
+     * @param output The output stream
+     * @param encoding The encoding
+     * @return A suitable writer
+     * @throws UnsupportedEncodingException There is no convertor to support
+     * this encoding
+     */
+    private Writer getWriter(OutputStream output, String encoding, Charset cs)
+        throws XMLStreamException, UnsupportedEncodingException
+    {
+        if (cs != null) {
+            return (new OutputStreamWriter(new BufferedOutputStream(output), cs));
+        }
+
+        return new OutputStreamWriter(new BufferedOutputStream(output), encoding);
+    }
+}
--- a/jdk/src/share/classes/sun/invoke/util/ValueConversions.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/invoke/util/ValueConversions.java	Tue Jan 22 11:54:16 2013 -0800
@@ -449,8 +449,16 @@
      * @param x an arbitrary reference value
      * @return the same value x
      */
+    @SuppressWarnings("unchecked")
     static <T,U> T castReference(Class<? extends T> t, U x) {
-        return t.cast(x);
+        // inlined Class.cast because we can't ForceInline it
+        if (x != null && !t.isInstance(x))
+            throw newClassCastException(t, x);
+        return (T) x;
+    }
+
+    private static ClassCastException newClassCastException(Class<?> t, Object obj) {
+        return new ClassCastException("Cannot cast " + obj.getClass().getName() + " to " + t.getName());
     }
 
     private static final MethodHandle IDENTITY, CAST_REFERENCE, ZERO_OBJECT, IGNORE, EMPTY,
--- a/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMS.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMS.java	Tue Jan 22 11:54:16 2013 -0800
@@ -53,7 +53,9 @@
     public static native long getProfileID(ICC_Profile profile);
 
     public static native long createNativeTransform(
-        long[] profileIDs, int renderType, int inFormatter, int outFormatter,
+        long[] profileIDs, int renderType,
+        int inFormatter, boolean isInIntPacked,
+        int outFormatter, boolean isOutIntPacked,
         Object disposerRef);
 
    /**
--- a/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMSImageLayout.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMSImageLayout.java	Tue Jan 22 11:54:16 2013 -0800
@@ -196,7 +196,8 @@
             case BufferedImage.TYPE_4BYTE_ABGR:
                 byteRaster = (ByteComponentRaster)image.getRaster();
                 nextRowOffset = byteRaster.getScanlineStride();
-                offset = byteRaster.getDataOffset(0);
+                int firstBand = image.getSampleModel().getNumBands() - 1;
+                offset = byteRaster.getDataOffset(firstBand);
                 dataArray = byteRaster.getDataStorage();
                 dataType = DT_BYTE;
                 break;
--- a/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMSTransform.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMSTransform.java	Tue Jan 22 11:54:16 2013 -0800
@@ -55,8 +55,10 @@
 
 public class LCMSTransform implements ColorTransform {
     long ID;
-    private int inFormatter;
-    private int outFormatter;
+    private int inFormatter = 0;
+    private boolean isInIntPacked = false;
+    private int outFormatter = 0;
+    private boolean isOutIntPacked = false;
 
     ICC_Profile[] profiles;
     long [] profileIDs;
@@ -135,18 +137,23 @@
                                           LCMSImageLayout out) {
         // update native transfrom if needed
         if (ID == 0L ||
-            inFormatter != in.pixelType ||
-            outFormatter != out.pixelType) {
+            inFormatter != in.pixelType || isInIntPacked != in.isIntPacked ||
+            outFormatter != out.pixelType || isOutIntPacked != out.isIntPacked)
+        {
 
             if (ID != 0L) {
                 // Disposer will destroy forgotten transform
                 disposerReferent = new Object();
             }
             inFormatter = in.pixelType;
+            isInIntPacked = in.isIntPacked;
+
             outFormatter = out.pixelType;
+            isOutIntPacked = out.isIntPacked;
 
             ID = LCMS.createNativeTransform(profileIDs, renderType,
-                                            inFormatter, outFormatter,
+                                            inFormatter, isInIntPacked,
+                                            outFormatter, isOutIntPacked,
                                             disposerReferent);
         }
 
--- a/jdk/src/share/classes/sun/java2d/pipe/ParallelogramPipe.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/java2d/pipe/ParallelogramPipe.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/share/classes/sun/launcher/LauncherHelper.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/launcher/LauncherHelper.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -409,6 +409,15 @@
             if (mainValue == null) {
                 abort(null, "java.launcher.jar.error3", jarname);
             }
+            /*
+             * Hand off to FXHelper if it detects a JavaFX application
+             * This must be done after ensuring a Main-Class entry
+             * exists to enforce compliance with the jar specification
+             */
+            if (mainAttrs.containsKey(
+                    new Attributes.Name(FXHelper.JAVAFX_APPLICATION_MARKER))) {
+                return FXHelper.class.getName();
+            }
             return mainValue.trim();
         } catch (IOException ioe) {
             abort(ioe, "java.launcher.jar.error1", jarname);
@@ -483,26 +492,23 @@
         } catch (NoClassDefFoundError | ClassNotFoundException cnfe) {
             abort(cnfe, "java.launcher.cls.error1", cn);
         }
-        // set to mainClass, FXHelper may return something else
+        // set to mainClass
         appClass = mainClass;
 
-        Method m = getMainMethod(mainClass);
-        if (m != null) {
-            // this will abort if main method has the wrong signature
-            validateMainMethod(m);
-            return mainClass;
+        /*
+         * Check if FXHelper can launch it using the FX launcher. In an FX app,
+         * the main class may or may not have a main method, so do this before
+         * validating the main class.
+         */
+        if (mainClass.equals(FXHelper.class) ||
+                FXHelper.doesExtendFXApplication(mainClass)) {
+            // Will abort() if there are problems with the FX runtime
+            FXHelper.setFXLaunchParameters(what, mode);
+            return FXHelper.class;
         }
 
-        // Check if FXHelper can launch it using the FX launcher
-        Class<?> fxClass = FXHelper.getFXMainClass(mainClass);
-        if (fxClass != null) {
-            return fxClass;
-        }
-
-        // not an FX application either, abort with an error
-        abort(null, "java.launcher.cls.error4", mainClass.getName(),
-              FXHelper.JAVAFX_APPLICATION_CLASS_NAME);
-        return null; // avoid compiler error...
+        validateMainClass(mainClass);
+        return mainClass;
     }
 
     /*
@@ -515,16 +521,18 @@
         return appClass;
     }
 
-    // Check for main method or return null if not found
-    static Method getMainMethod(Class<?> clazz) {
+    // Check the existence and signature of main and abort if incorrect
+    static void validateMainClass(Class<?> mainClass) {
+        Method mainMethod;
         try {
-            return clazz.getMethod("main", String[].class);
-        } catch (NoSuchMethodException nsme) {}
-        return null;
-    }
+            mainMethod = mainClass.getMethod("main", String[].class);
+        } catch (NoSuchMethodException nsme) {
+            // invalid main or not FX application, abort with an error
+            abort(null, "java.launcher.cls.error4", mainClass.getName(),
+                  FXHelper.JAVAFX_APPLICATION_CLASS_NAME);
+            return; // Avoid compiler issues
+        }
 
-    // Check the signature of main and abort if it's incorrect
-    static void validateMainMethod(Method mainMethod) {
         /*
          * getMethod (above) will choose the correct method, based
          * on its name and parameter type, however, we still have to
@@ -644,41 +652,78 @@
     }
 
     static final class FXHelper {
+        // Marker entry in jar manifest that designates a JavaFX application jar
+        private static final String JAVAFX_APPLICATION_MARKER =
+                "JavaFX-Application-Class";
         private static final String JAVAFX_APPLICATION_CLASS_NAME =
                 "javafx.application.Application";
         private static final String JAVAFX_LAUNCHER_CLASS_NAME =
                 "com.sun.javafx.application.LauncherImpl";
 
         /*
+         * The launch method used to invoke the JavaFX launcher. These must
+         * match the strings used in the launchApplication method.
+         *
+         * Command line                 JavaFX-App-Class  Launch mode  FX Launch mode
+         * java -cp fxapp.jar FXClass   N/A               LM_CLASS     "LM_CLASS"
+         * java -cp somedir FXClass     N/A               LM_CLASS     "LM_CLASS"
+         * java -jar fxapp.jar          Present           LM_JAR       "LM_JAR"
+         * java -jar fxapp.jar          Not Present       LM_JAR       "LM_JAR"
+         */
+        private static final String JAVAFX_LAUNCH_MODE_CLASS = "LM_CLASS";
+        private static final String JAVAFX_LAUNCH_MODE_JAR = "LM_JAR";
+
+        /*
          * FX application launcher and launch method, so we can launch
          * applications with no main method.
          */
+        private static String fxLaunchName = null;
+        private static String fxLaunchMode = null;
+
         private static Class<?> fxLauncherClass    = null;
         private static Method   fxLauncherMethod   = null;
 
         /*
-         * We can assume that the class does NOT have a main method or it would
-         * have been handled already. We do, however, need to check if the class
-         * extends Application and the launcher is available and abort with an
-         * error if it's not.
+         * Set the launch params according to what was passed to LauncherHelper
+         * so we can use the same launch mode for FX. Abort if there is any
+         * issue with loading the FX runtime or with the launcher method.
          */
-        private static Class<?> getFXMainClass(Class<?> mainClass) {
-            // Check if mainClass extends Application
-            if (!doesExtendFXApplication(mainClass)) {
-                return null;
-            }
-
+        private static void setFXLaunchParameters(String what, int mode) {
             // Check for the FX launcher classes
             try {
                 fxLauncherClass = scloader.loadClass(JAVAFX_LAUNCHER_CLASS_NAME);
+                /*
+                 * signature must be:
+                 * public static void launchApplication(String launchName,
+                 *     String launchMode, String[] args);
+                 */
                 fxLauncherMethod = fxLauncherClass.getMethod("launchApplication",
-                        Class.class, String[].class);
+                        String.class, String.class, String[].class);
+
+                // verify launcher signature as we do when validating the main method
+                int mod = fxLauncherMethod.getModifiers();
+                if (!Modifier.isStatic(mod)) {
+                    abort(null, "java.launcher.javafx.error1");
+                }
+                if (fxLauncherMethod.getReturnType() != java.lang.Void.TYPE) {
+                    abort(null, "java.launcher.javafx.error1");
+                }
             } catch (ClassNotFoundException | NoSuchMethodException ex) {
                 abort(ex, "java.launcher.cls.error5", ex);
             }
 
-            // That's all, return this class so we can launch later
-            return FXHelper.class;
+            fxLaunchName = what;
+            switch (mode) {
+                case LM_CLASS:
+                    fxLaunchMode = JAVAFX_LAUNCH_MODE_CLASS;
+                    break;
+                case LM_JAR:
+                    fxLaunchMode = JAVAFX_LAUNCH_MODE_JAR;
+                    break;
+                default:
+                    // should not have gotten this far...
+                    throw new InternalError(mode + ": Unknown launch mode");
+            }
         }
 
         /*
@@ -696,11 +741,15 @@
             return false;
         }
 
-        // preloader ?
         public static void main(String... args) throws Exception {
+            if (fxLauncherMethod == null
+                    || fxLaunchMode == null
+                    || fxLaunchName == null) {
+                throw new RuntimeException("Invalid JavaFX launch parameters");
+            }
             // launch appClass via fxLauncherMethod
-            fxLauncherMethod.invoke(null, new Object[] {appClass, args});
+            fxLauncherMethod.invoke(null,
+                    new Object[] {fxLaunchName, fxLaunchMode, args});
         }
     }
 }
-
--- a/jdk/src/share/classes/sun/launcher/resources/launcher.properties	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/launcher/resources/launcher.properties	Tue Jan 22 11:54:16 2013 -0800
@@ -140,3 +140,6 @@
 java.launcher.jar.error2=manifest not found in {0}
 java.launcher.jar.error3=no main manifest attribute, in {0}
 java.launcher.init.error=initialization error
+java.launcher.javafx.error1=\
+    Error: The JavaFX launchApplication method has the wrong signature, it\n\
+    must be declared static and return a value of type void
--- a/jdk/src/share/classes/sun/misc/Unsafe.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/misc/Unsafe.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1008,4 +1008,125 @@
      *         if the load average is unobtainable.
      */
     public native int getLoadAverage(double[] loadavg, int nelems);
+
+    // The following contain CAS-based Java implementations used on
+    // platforms not supporting native instructions
+
+    /**
+     * Atomically adds the given value to the current value of a field
+     * or array element within the given object <code>o</code>
+     * at the given <code>offset</code>.
+     *
+     * @param o object/array to update the field/element in
+     * @param offset field/element offset
+     * @param delta the value to add
+     * @return the previous value
+     * @since 1.8
+     */
+    public final int getAndAddInt(Object o, long offset, int delta) {
+        int v;
+        do {
+            v = getIntVolatile(o, offset);
+        } while (!compareAndSwapInt(o, offset, v, v + delta));
+        return v;
+    }
+
+    /**
+     * Atomically adds the given value to the current value of a field
+     * or array element within the given object <code>o</code>
+     * at the given <code>offset</code>.
+     *
+     * @param o object/array to update the field/element in
+     * @param offset field/element offset
+     * @param delta the value to add
+     * @return the previous value
+     * @since 1.8
+     */
+    public final long getAndAddLong(Object o, long offset, long delta) {
+        long v;
+        do {
+            v = getLongVolatile(o, offset);
+        } while (!compareAndSwapLong(o, offset, v, v + delta));
+        return v;
+    }
+
+    /**
+     * Atomically exchanges the given value with the current value of
+     * a field or array element within the given object <code>o</code>
+     * at the given <code>offset</code>.
+     *
+     * @param o object/array to update the field/element in
+     * @param offset field/element offset
+     * @param newValue new value
+     * @return the previous value
+     * @since 1.8
+     */
+    public final int getAndSetInt(Object o, long offset, int newValue) {
+        int v;
+        do {
+            v = getIntVolatile(o, offset);
+        } while (!compareAndSwapInt(o, offset, v, newValue));
+        return v;
+    }
+
+    /**
+     * Atomically exchanges the given value with the current value of
+     * a field or array element within the given object <code>o</code>
+     * at the given <code>offset</code>.
+     *
+     * @param o object/array to update the field/element in
+     * @param offset field/element offset
+     * @param newValue new value
+     * @return the previous value
+     * @since 1.8
+     */
+    public final long getAndSetLong(Object o, long offset, long newValue) {
+        long v;
+        do {
+            v = getLongVolatile(o, offset);
+        } while (!compareAndSwapLong(o, offset, v, newValue));
+        return v;
+    }
+
+    /**
+     * Atomically exchanges the given reference value with the current
+     * reference value of a field or array element within the given
+     * object <code>o</code> at the given <code>offset</code>.
+     *
+     * @param o object/array to update the field/element in
+     * @param offset field/element offset
+     * @param newValue new value
+     * @return the previous value
+     * @since 1.8
+     */
+    public final Object getAndSetObject(Object o, long offset, Object newValue) {
+        Object v;
+        do {
+            v = getObjectVolatile(o, offset);
+        } while (!compareAndSwapObject(o, offset, v, newValue));
+        return v;
+    }
+
+
+    /**
+     * Ensures lack of reordering of loads before the fence
+     * with loads or stores after the fence.
+     * @since 1.8
+     */
+    public native void loadFence();
+
+    /**
+     * Ensures lack of reordering of stores before the fence
+     * with loads or stores after the fence.
+     * @since 1.8
+     */
+    public native void storeFence();
+
+    /**
+     * Ensures lack of reordering of loads or stores before the fence
+     * with loads or stores after the fence.
+     * @since 1.8
+     */
+    public native void fullFence();
+
 }
--- a/jdk/src/share/classes/sun/net/www/http/KeepAliveStream.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/net/www/http/KeepAliveStream.java	Tue Jan 22 11:54:16 2013 -0800
@@ -83,11 +83,8 @@
             if (expected > count) {
                 long nskip = expected - count;
                 if (nskip <= available()) {
-                    long n = 0;
-                    while (n < nskip) {
-                        nskip = nskip - n;
-                        n = skip(nskip);
-                    }
+                    do {} while ((nskip = (expected - count)) > 0L
+                                 && skip(Math.min(nskip, available())) > 0L);
                 } else if (expected <= KeepAliveStreamCleaner.MAX_DATA_REMAINING && !hurried) {
                     //put this KeepAliveStream on the queue so that the data remaining
                     //on the socket can be cleanup asyncronously.
--- a/jdk/src/share/classes/sun/net/www/protocol/http/AuthenticationHeader.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/net/www/protocol/http/AuthenticationHeader.java	Tue Jan 22 11:54:16 2013 -0800
@@ -206,7 +206,8 @@
 
             if(v == null) {
                 if ((v=schemes.get ("digest")) == null) {
-                    if (((v=schemes.get("ntlm"))==null)) {
+                    if (!NTLMAuthenticationProxy.supported
+                        || ((v=schemes.get("ntlm"))==null)) {
                         v = schemes.get ("basic");
                     }
                 }
--- a/jdk/src/share/classes/sun/nio/ch/IOStatus.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/nio/ch/IOStatus.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,6 +25,7 @@
 
 package sun.nio.ch;
 
+import java.lang.annotation.Native;
 
 // Constants for reporting I/O status
 
@@ -32,12 +33,12 @@
 
     private IOStatus() { }
 
-    public static final int EOF = -1;              // End of file
-    public static final int UNAVAILABLE = -2;      // Nothing available (non-blocking)
-    public static final int INTERRUPTED = -3;      // System call interrupted
-    public static final int UNSUPPORTED = -4;      // Operation not supported
-    public static final int THROWN = -5;           // Exception thrown in JNI code
-    public static final int UNSUPPORTED_CASE = -6; // This case not supported
+    @Native public static final int EOF = -1;              // End of file
+    @Native public static final int UNAVAILABLE = -2;      // Nothing available (non-blocking)
+    @Native public static final int INTERRUPTED = -3;      // System call interrupted
+    @Native public static final int UNSUPPORTED = -4;      // Operation not supported
+    @Native public static final int THROWN = -5;           // Exception thrown in JNI code
+    @Native public static final int UNSUPPORTED_CASE = -6; // This case not supported
 
     // The following two methods are for use in try/finally blocks where a
     // status value needs to be normalized before being returned to the invoker
--- a/jdk/src/share/classes/sun/security/jgss/krb5/InitSecContextToken.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/jgss/krb5/InitSecContextToken.java	Tue Jan 22 11:54:16 2013 -0800
@@ -86,7 +86,7 @@
      * For the context acceptor to call. It reads the bytes out of an
      * InputStream and constructs an InitSecContextToken with them.
      */
-    InitSecContextToken(Krb5Context context, EncryptionKey[] keys,
+    InitSecContextToken(Krb5Context context, Krb5AcceptCredential cred,
                                InputStream is)
         throws IOException, GSSException, KrbException  {
 
@@ -105,7 +105,7 @@
         if (context.getChannelBinding() != null) {
             addr = context.getChannelBinding().getInitiatorAddress();
         }
-        apReq = new KrbApReq(apReqBytes, keys, addr);
+        apReq = new KrbApReq(apReqBytes, cred, addr);
         //debug("\nReceived AP-REQ and authenticated it.\n");
 
         EncryptionKey sessionKey = apReq.getCreds().getSessionKey();
--- a/jdk/src/share/classes/sun/security/jgss/krb5/Krb5AcceptCredential.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/jgss/krb5/Krb5AcceptCredential.java	Tue Jan 22 11:54:16 2013 -0800
@@ -45,13 +45,10 @@
 public class Krb5AcceptCredential
     implements Krb5CredElement {
 
-    private static final long serialVersionUID = 7714332137352567952L;
-
-    private Krb5NameElement name;
+    private final Krb5NameElement name;
+    private final ServiceCreds screds;
 
-    private Krb5Util.ServiceCreds screds;
-
-    private Krb5AcceptCredential(Krb5NameElement name, Krb5Util.ServiceCreds creds) {
+    private Krb5AcceptCredential(Krb5NameElement name, ServiceCreds creds) {
         /*
          * Initialize this instance with the data from the acquired
          * KerberosKey. This class needs to be a KerberosKey too
@@ -69,11 +66,11 @@
             name.getKrb5PrincipalName().getName());
         final AccessControlContext acc = AccessController.getContext();
 
-        Krb5Util.ServiceCreds creds = null;
+        ServiceCreds creds = null;
         try {
             creds = AccessController.doPrivileged(
-                        new PrivilegedExceptionAction<Krb5Util.ServiceCreds>() {
-                public Krb5Util.ServiceCreds run() throws Exception {
+                        new PrivilegedExceptionAction<ServiceCreds>() {
+                public ServiceCreds run() throws Exception {
                     return Krb5Util.getServiceCreds(
                         caller == GSSCaller.CALLER_UNKNOWN ? GSSCaller.CALLER_ACCEPT: caller,
                         serverPrinc, acc);
@@ -92,8 +89,10 @@
 
         if (name == null) {
             String fullName = creds.getName();
-            name = Krb5NameElement.getInstance(fullName,
+            if (fullName != null) {
+                name = Krb5NameElement.getInstance(fullName,
                                        Krb5MechFactory.NT_GSS_KRB5_PRINCIPAL);
+            }
         }
 
         return new Krb5AcceptCredential(name, creds);
@@ -153,8 +152,8 @@
         return Krb5MechFactory.PROVIDER;
     }
 
-    EncryptionKey[] getKrb5EncryptionKeys() {
-        return screds.getEKeys();
+    public EncryptionKey[] getKrb5EncryptionKeys(PrincipalName princ) {
+        return screds.getEKeys(princ);
     }
 
     /**
--- a/jdk/src/share/classes/sun/security/jgss/krb5/Krb5Context.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/jgss/krb5/Krb5Context.java	Tue Jan 22 11:54:16 2013 -0800
@@ -818,16 +818,23 @@
                 }
                 myName = (Krb5NameElement) myCred.getName();
 
-                checkPermission(myName.getKrb5PrincipalName().getName(),
-                                "accept");
-
-                EncryptionKey[] secretKeys =
-                 ((Krb5AcceptCredential) myCred).getKrb5EncryptionKeys();
+                // If there is already a bound name, check now
+                if (myName != null) {
+                    Krb5MechFactory.checkAcceptCredPermission(myName, myName);
+                }
 
                 InitSecContextToken token = new InitSecContextToken(this,
-                                                    secretKeys, is);
+                                                    (Krb5AcceptCredential) myCred, is);
                 PrincipalName clientName = token.getKrbApReq().getClient();
                 peerName = Krb5NameElement.getInstance(clientName);
+
+                // If unbound, check after the bound name is found
+                if (myName == null) {
+                    myName = Krb5NameElement.getInstance(
+                        token.getKrbApReq().getCreds().getServer());
+                    Krb5MechFactory.checkAcceptCredPermission(myName, myName);
+                }
+
                 if (getMutualAuthState()) {
                         retVal = new AcceptSecContextToken(this,
                                           token.getKrbApReq()).encode();
--- a/jdk/src/share/classes/sun/security/jgss/krb5/Krb5MechFactory.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/jgss/krb5/Krb5MechFactory.java	Tue Jan 22 11:54:16 2013 -0800
@@ -158,7 +158,7 @@
     public static void checkAcceptCredPermission(Krb5NameElement name,
                                            GSSNameSpi originalName) {
         SecurityManager sm = System.getSecurityManager();
-        if (sm != null) {
+        if (sm != null && name != null) {
             ServicePermission perm = new ServicePermission
                 (name.getKrb5PrincipalName().getName(), "accept");
             try {
--- a/jdk/src/share/classes/sun/security/jgss/krb5/Krb5Util.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/jgss/krb5/Krb5Util.java	Tue Jan 22 11:54:16 2013 -0800
@@ -187,114 +187,6 @@
     }
 
     /**
-     * Credentials of a service, the private secret to authenticate its
-     * identity, which can be:
-     *   1. Some KerberosKeys (generated from password)
-     *   2. A KeyTab (for a typical service)
-     *   3. A TGT (for S4U2proxy extension)
-     *
-     * Note that some creds can coexist. For example, a user2user service
-     * can use its keytab (or keys) if the client can successfully obtain a
-     * normal service ticket, otherwise, it can uses the TGT (actually, the
-     * session key of the TGT) if the client can only acquire a service ticket
-     * of ENC-TKT-IN-SKEY style.
-     */
-    public static class ServiceCreds {
-        private KerberosPrincipal kp;
-        private List<KeyTab> ktabs;
-        private List<KerberosKey> kk;
-        private Subject subj;
-        private KerberosTicket tgt;
-
-        private static ServiceCreds getInstance(
-                Subject subj, String serverPrincipal) {
-
-            ServiceCreds sc = new ServiceCreds();
-            sc.subj = subj;
-
-            for (KerberosPrincipal p: subj.getPrincipals(KerberosPrincipal.class)) {
-                if (serverPrincipal == null ||
-                        p.getName().equals(serverPrincipal)) {
-                    sc.kp = p;
-                    serverPrincipal = p.getName();
-                    break;
-                }
-            }
-            if (sc.kp == null) {
-                // Compatibility with old behavior: even when there is no
-                // KerberosPrincipal, we can find one from KerberosKeys
-                List<KerberosKey> keys = SubjectComber.findMany(
-                        subj, serverPrincipal, null, KerberosKey.class);
-                if (!keys.isEmpty()) {
-                    sc.kp = keys.get(0).getPrincipal();
-                    serverPrincipal = sc.kp.getName();
-                    if (DEBUG) {
-                        System.out.println(">>> ServiceCreds: no kp?"
-                                + " find one from kk: " + serverPrincipal);
-                    }
-                } else {
-                    return null;
-                }
-            }
-            sc.ktabs = SubjectComber.findMany(
-                        subj, null, null, KeyTab.class);
-            sc.kk = SubjectComber.findMany(
-                        subj, serverPrincipal, null, KerberosKey.class);
-            sc.tgt = SubjectComber.find(
-                    subj, null, serverPrincipal, KerberosTicket.class);
-            if (sc.ktabs.isEmpty() && sc.kk.isEmpty() && sc.tgt == null) {
-                return null;
-            }
-            return sc;
-        }
-
-        public String getName() {
-            return kp.getName();
-        }
-
-        public KerberosKey[] getKKeys() {
-            List<KerberosKey> keys = new ArrayList<>();
-            for (KerberosKey k: kk) {
-                keys.add(k);
-            }
-            for (KeyTab ktab: ktabs) {
-                for (KerberosKey k: ktab.getKeys(kp)) {
-                    keys.add(k);
-                }
-            }
-            return keys.toArray(new KerberosKey[keys.size()]);
-        }
-
-        public EncryptionKey[] getEKeys() {
-            KerberosKey[] kkeys = getKKeys();
-            EncryptionKey[] ekeys = new EncryptionKey[kkeys.length];
-            for (int i=0; i<ekeys.length; i++) {
-                ekeys[i] =  new EncryptionKey(
-                            kkeys[i].getEncoded(), kkeys[i].getKeyType(),
-                            new Integer(kkeys[i].getVersionNumber()));
-            }
-            return ekeys;
-        }
-
-        public Credentials getInitCred() {
-            if (tgt == null) {
-                return null;
-            }
-            try {
-                return ticketToCreds(tgt);
-            } catch (KrbException | IOException e) {
-                return null;
-            }
-        }
-
-        public void destroy() {
-            kp = null;
-            ktabs = null;
-            kk = null;
-            tgt = null;
-        }
-    }
-    /**
      * Retrieves the ServiceCreds for the specified server principal from
      * the Subject in the specified AccessControlContext. If not found, and if
      * useSubjectCredsOnly is false, then obtain from a LoginContext.
@@ -361,5 +253,4 @@
         return KerberosSecrets.getJavaxSecurityAuthKerberosAccess().
                 keyTabGetEncryptionKeys(ktab, cname);
     }
-
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/security/jgss/krb5/ServiceCreds.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,229 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.jgss.krb5;
+
+import javax.security.auth.kerberos.KerberosTicket;
+import javax.security.auth.kerberos.KerberosKey;
+import javax.security.auth.kerberos.KerberosPrincipal;
+import javax.security.auth.kerberos.KeyTab;
+import javax.security.auth.Subject;
+
+import sun.security.krb5.Credentials;
+import sun.security.krb5.EncryptionKey;
+import sun.security.krb5.KrbException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import sun.security.krb5.*;
+import sun.security.krb5.internal.Krb5;
+
+/**
+ * Credentials of a kerberos acceptor. A KerberosPrincipal object (kp) is
+ * the principal. It can be specified as the serverPrincipal argument
+ * in the getInstance() method, or uses only KerberosPrincipal in the subject.
+ * Otherwise, the creds object is unbound and kp is null.
+ *
+ * The class also encapsulates various secrets, which can be:
+ *
+ *   1. Some KerberosKeys (generated from password)
+ *   2. Some KeyTabs (for a typical service based on keytabs)
+ *   3. A TGT (for S4U2proxy extension or user2user)
+ *
+ * Note that some secrets can coexist. For example, a user2user service
+ * can use its keytab (or keys) if the client can successfully obtain a
+ * normal service ticket, or it can use the TGT (actually, the session key
+ * of the TGT) if the client can only acquire a service ticket
+ * of ENC-TKT-IN-SKEY style.
+ *
+ * @since 1.8
+ */
+public final class ServiceCreds {
+    // The principal, or null if unbound
+    private KerberosPrincipal kp;
+
+    // All principals in the subject's princ set
+    private Set<KerberosPrincipal> allPrincs;
+
+    // All private credentials that can be used
+    private List<KeyTab> ktabs;
+    private List<KerberosKey> kk;
+    private KerberosTicket tgt;
+
+    private boolean destroyed;
+
+    private ServiceCreds() {
+        // Make sure this class cannot be instantiated externally.
+    }
+
+    /**
+     * Creates a ServiceCreds object based on info in a Subject for
+     * a given principal name (if specified).
+     * @return the object, or null if there is no private creds for it
+     */
+    public static ServiceCreds getInstance(
+            Subject subj, String serverPrincipal) {
+
+        ServiceCreds sc = new ServiceCreds();
+
+        sc.allPrincs =
+                subj.getPrincipals(KerberosPrincipal.class);
+
+        // Compatibility. A key implies its own principal
+        for (KerberosKey key: SubjectComber.findMany(
+                subj, serverPrincipal, null, KerberosKey.class)) {
+            sc.allPrincs.add(key.getPrincipal());
+        }
+
+        if (serverPrincipal != null) {      // A named principal
+            sc.kp = new KerberosPrincipal(serverPrincipal);
+        } else {
+            if (sc.allPrincs.size() == 1) { // choose the only one
+                sc.kp = sc.allPrincs.iterator().next();
+                serverPrincipal = sc.kp.getName();
+            }
+        }
+
+        sc.ktabs = SubjectComber.findMany(
+                    subj, serverPrincipal, null, KeyTab.class);
+        sc.kk = SubjectComber.findMany(
+                    subj, serverPrincipal, null, KerberosKey.class);
+        sc.tgt = SubjectComber.find(
+                subj, null, serverPrincipal, KerberosTicket.class);
+        if (sc.ktabs.isEmpty() && sc.kk.isEmpty() && sc.tgt == null) {
+            return null;
+        }
+
+        sc.destroyed = false;
+
+        return sc;
+    }
+
+    // can be null
+    public String getName() {
+        if (destroyed) {
+            throw new IllegalStateException("This object is destroyed");
+        }
+        return kp == null ? null : kp.getName();
+    }
+
+    /**
+     * Gets keys for someone unknown.
+     * Used by TLS or as a fallback in getEKeys(). Can still return an
+     * empty array.
+     */
+    public KerberosKey[] getKKeys() {
+        if (destroyed) {
+            throw new IllegalStateException("This object is destroyed");
+        }
+        if (kp != null) {
+            return getKKeys(kp);
+        } else if (!allPrincs.isEmpty()) {
+            return getKKeys(allPrincs.iterator().next());
+        }
+        return new KerberosKey[0];
+    }
+
+    /**
+     * Get kkeys for a principal,
+     * @param princ the target name initiator requests. Not null.
+     * @return keys for the princ, never null, might be empty
+     */
+    private KerberosKey[] getKKeys(KerberosPrincipal princ) {
+        ArrayList<KerberosKey> keys = new ArrayList<>();
+        if (kp != null && !princ.equals(kp)) {
+            return new KerberosKey[0];      // Not me
+        }
+        if (!allPrincs.contains(princ)) {
+            return new KerberosKey[0];      // Not someone I know, This check
+                                            // is necessary but a KeyTab has
+                                            // no principal name recorded.
+        }
+        for (KerberosKey k: kk) {
+            if (k.getPrincipal().equals(princ)) {
+                keys.add(k);
+            }
+        }
+        for (KeyTab ktab: ktabs) {
+            for (KerberosKey k: ktab.getKeys(princ)) {
+                keys.add(k);
+            }
+        }
+        return keys.toArray(new KerberosKey[keys.size()]);
+    }
+
+    /**
+     * Gets EKeys for a principal.
+     * @param princ the target name initiator requests. Not null.
+     * @return keys for the princ, never null, might be empty
+     */
+    public EncryptionKey[] getEKeys(PrincipalName princ) {
+        if (destroyed) {
+            throw new IllegalStateException("This object is destroyed");
+        }
+        KerberosKey[] kkeys = getKKeys(new KerberosPrincipal(princ.getName()));
+        if (kkeys.length == 0) {
+            // Note: old JDK does not perform real name checking. If the
+            // acceptor starts by name A but initiator requests for B,
+            // as long as their keys match (i.e. A's keys can decrypt B's
+            // service ticket), the authentication is OK. There are real
+            // customers depending on this to use different names for a
+            // single service.
+            kkeys = getKKeys();
+        }
+        EncryptionKey[] ekeys = new EncryptionKey[kkeys.length];
+        for (int i=0; i<ekeys.length; i++) {
+            ekeys[i] =  new EncryptionKey(
+                        kkeys[i].getEncoded(), kkeys[i].getKeyType(),
+                        new Integer(kkeys[i].getVersionNumber()));
+        }
+        return ekeys;
+    }
+
+    public Credentials getInitCred() {
+        if (destroyed) {
+            throw new IllegalStateException("This object is destroyed");
+        }
+        if (tgt == null) {
+            return null;
+        }
+        try {
+            return Krb5Util.ticketToCreds(tgt);
+        } catch (KrbException | IOException e) {
+            return null;
+        }
+    }
+
+    public void destroy() {
+        // Do not wipe out real keys because they are references to the
+        // priv creds in subject. Just make it useless.
+        destroyed = true;
+        kp = null;
+        ktabs.clear();
+        kk.clear();
+        tgt = null;
+    }
+}
--- a/jdk/src/share/classes/sun/security/jgss/krb5/SubjectComber.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/jgss/krb5/SubjectComber.java	Tue Jan 22 11:54:16 2013 -0800
@@ -33,6 +33,7 @@
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Set;
+import javax.security.auth.kerberos.KerberosPrincipal;
 import javax.security.auth.kerberos.KeyTab;
 
 /**
@@ -84,19 +85,37 @@
         } else {
             List<T> answer = (oneOnly ? null : new ArrayList<T>());
 
-            if (credClass == KeyTab.class) {    // Principal un-related
-                // We are looking for credentials unrelated to serverPrincipal
-                Iterator<T> iterator =
-                    subject.getPrivateCredentials(credClass).iterator();
-                while (iterator.hasNext()) {
-                    T t = iterator.next();
-                    if (DEBUG) {
-                        System.out.println("Found " + credClass.getSimpleName());
+            if (credClass == KeyTab.class) {
+                // TODO: There is currently no good way to filter out keytabs
+                // not for serverPrincipal. We can only check the principal
+                // set. If the server is not there, we can be sure none of the
+                // keytabs should be used, otherwise, use all for safety.
+                boolean useAll = false;
+                if (serverPrincipal != null) {
+                    for (KerberosPrincipal princ:
+                            subject.getPrincipals(KerberosPrincipal.class)) {
+                        if (princ.getName().equals(serverPrincipal)) {
+                            useAll = true;
+                            break;
+                        }
                     }
-                    if (oneOnly) {
-                        return t;
-                    } else {
-                        answer.add(t);
+                } else {
+                    useAll = true;
+                }
+                if (useAll) {
+                    Iterator<KeyTab> iterator =
+                        subject.getPrivateCredentials(KeyTab.class).iterator();
+                    while (iterator.hasNext()) {
+                        KeyTab t = iterator.next();
+                        if (DEBUG) {
+                            System.out.println("Found " + credClass.getSimpleName()
+                                    + " " + t);
+                        }
+                        if (oneOnly) {
+                            return t;
+                        } else {
+                            answer.add(credClass.cast(t));
+                        }
                     }
                 }
             } else if (credClass == KerberosKey.class) {
@@ -114,11 +133,6 @@
                          if (oneOnly) {
                              return t;
                          } else {
-                             if (serverPrincipal == null) {
-                                 // Record name so that keys returned will all
-                                 // belong to the same principal
-                                 serverPrincipal = name;
-                             }
                              answer.add(credClass.cast(t));
                          }
                     }
--- a/jdk/src/share/classes/sun/security/krb5/EncryptionKey.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/krb5/EncryptionKey.java	Tue Jan 22 11:54:16 2013 -0800
@@ -555,6 +555,12 @@
 
         int ktype;
         boolean etypeFound = false;
+
+        // When no matched kvno is found, returns tke key of the same
+        // etype with the highest kvno
+        int kvno_found = 0;
+        EncryptionKey key_found = null;
+
         for (int i = 0; i < keys.length; i++) {
             ktype = keys[i].getEType();
             if (EType.isSupported(ktype)) {
@@ -563,6 +569,10 @@
                     etypeFound = true;
                     if (versionMatches(kvno, kv)) {
                         return keys[i];
+                    } else if (kv > kvno_found) {
+                        // kv is not null
+                        key_found = keys[i];
+                        kvno_found = kv;
                     }
                 }
             }
@@ -580,12 +590,17 @@
                     etypeFound = true;
                     if (versionMatches(kvno, kv)) {
                         return new EncryptionKey(etype, keys[i].getBytes());
+                    } else if (kv > kvno_found) {
+                        key_found = new EncryptionKey(etype, keys[i].getBytes());
+                        kvno_found = kv;
                     }
                 }
             }
         }
         if (etypeFound) {
-            throw new KrbException(Krb5.KRB_AP_ERR_BADKEYVER);
+            return key_found;
+            // For compatibility, will not fail here.
+            //throw new KrbException(Krb5.KRB_AP_ERR_BADKEYVER);
         }
         return null;
     }
--- a/jdk/src/share/classes/sun/security/krb5/KrbApReq.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/krb5/KrbApReq.java	Tue Jan 22 11:54:16 2013 -0800
@@ -34,6 +34,7 @@
 import sun.security.krb5.internal.*;
 import sun.security.krb5.internal.crypto.*;
 import sun.security.krb5.internal.rcache.*;
+import sun.security.jgss.krb5.Krb5AcceptCredential;
 import java.net.InetAddress;
 import sun.security.util.*;
 import java.io.IOException;
@@ -135,13 +136,13 @@
      */
      // Used in InitSecContextToken (for AP_REQ and not TGS REQ)
     public KrbApReq(byte[] message,
-                    EncryptionKey[] keys,
+                    Krb5AcceptCredential cred,
                     InetAddress initiator)
         throws KrbException, IOException {
         obuf = message;
         if (apReqMessg == null)
             decode();
-        authenticate(keys, initiator);
+        authenticate(cred, initiator);
     }
 
     /**
@@ -260,10 +261,11 @@
         }
     }
 
-    private void authenticate(EncryptionKey[] keys, InetAddress initiator)
+    private void authenticate(Krb5AcceptCredential cred, InetAddress initiator)
         throws KrbException, IOException {
         int encPartKeyType = apReqMessg.ticket.encPart.getEType();
         Integer kvno = apReqMessg.ticket.encPart.getKeyVersionNumber();
+        EncryptionKey[] keys = cred.getKrb5EncryptionKeys(apReqMessg.ticket.sname);
         EncryptionKey dkey = EncryptionKey.findKey(encPartKeyType, kvno, keys);
 
         if (dkey == null) {
--- a/jdk/src/share/classes/sun/security/krb5/internal/ktab/KeyTab.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/krb5/internal/ktab/KeyTab.java	Tue Jan 22 11:54:16 2013 -0800
@@ -382,9 +382,15 @@
      */
     public void addEntry(PrincipalName service, char[] psswd,
             int kvno, boolean append) throws KrbException {
+        addEntry(service, service.getSalt(), psswd, kvno, append);
+    }
+
+    // Called by KDC test
+    public void addEntry(PrincipalName service, String salt, char[] psswd,
+            int kvno, boolean append) throws KrbException {
 
         EncryptionKey[] encKeys = EncryptionKey.acquireSecretKeys(
-            psswd, service.getSalt());
+            psswd, salt);
 
         // There should be only one maximum KVNO value for all etypes, so that
         // all added keys can have the same KVNO.
--- a/jdk/src/share/classes/sun/security/provider/ConfigSpiFile.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/provider/ConfigSpiFile.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,81 +25,668 @@
 
 package sun.security.provider;
 
+import java.io.*;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URL;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.security.Security;
 import java.security.URIParameter;
-
+import java.text.MessageFormat;
+import java.util.*;
+import javax.security.auth.AuthPermission;
+import javax.security.auth.login.AppConfigurationEntry;
 import javax.security.auth.login.Configuration;
 import javax.security.auth.login.ConfigurationSpi;
-import javax.security.auth.login.AppConfigurationEntry;
-
-import com.sun.security.auth.login.ConfigFile;
+import sun.security.util.Debug;
+import sun.security.util.PropertyExpander;
+import sun.security.util.ResourcesMgr;
 
 /**
- * This class wraps the ConfigFile subclass implementation of Configuration
- * inside a ConfigurationSpi implementation that is available from the
- * SUN provider via the Configuration.getInstance calls.
+ * This class represents a default implementation for
+ * {@code javax.security.auth.login.Configuration}.
+ *
+ * <p> This object stores the runtime login configuration representation,
+ * and is the amalgamation of multiple static login
+ * configurations that resides in files.
+ * The algorithm for locating the login configuration file(s) and reading their
+ * information into this {@code Configuration} object is:
+ *
+ * <ol>
+ * <li>
+ *   Loop through the security properties,
+ *   <i>login.config.url.1</i>, <i>login.config.url.2</i>, ...,
+ *   <i>login.config.url.X</i>.
+ *   Each property value specifies a <code>URL</code> pointing to a
+ *   login configuration file to be loaded.  Read in and load
+ *   each configuration.
  *
+ * <li>
+ *   The {@code java.lang.System} property
+ *   <i>java.security.auth.login.config</i>
+ *   may also be set to a {@code URL} pointing to another
+ *   login configuration file
+ *   (which is the case when a user uses the -D switch at runtime).
+ *   If this property is defined, and its use is allowed by the
+ *   security property file (the Security property,
+ *   <i>policy.allowSystemProperty</i> is set to <i>true</i>),
+ *   also load that login configuration.
+ *
+ * <li>
+ *   If the <i>java.security.auth.login.config</i> property is defined using
+ *   "==" (rather than "="), then ignore all other specified
+ *   login configurations and only load this configuration.
+ *
+ * <li>
+ *   If no system or security properties were set, try to read from the file,
+ *   ${user.home}/.java.login.config, where ${user.home} is the value
+ *   represented by the "user.home" System property.
+ * </ol>
+ *
+ * <p> The configuration syntax supported by this implementation
+ * is exactly that syntax specified in the
+ * {@code javax.security.auth.login.Configuration} class.
+ *
+ * @see javax.security.auth.login.LoginContext
+ * @see java.security.Security security properties
  */
 public final class ConfigSpiFile extends ConfigurationSpi {
 
-    private ConfigFile cf;
+    private URL url;
+    private boolean expandProp = true;
+    private Map<String, List<AppConfigurationEntry>> configuration;
+    private int linenum;
+    private StreamTokenizer st;
+    private int lookahead;
+
+    private static Debug debugConfig = Debug.getInstance("configfile");
+    private static Debug debugParser = Debug.getInstance("configparser");
+
+    /**
+     * Create a new {@code Configuration} object.
+     *
+     * @throws SecurityException if the {@code Configuration} can not be
+     *                           initialized
+     */
+    public ConfigSpiFile() {
+        try {
+            init();
+        } catch (IOException ioe) {
+            throw new SecurityException(ioe);
+        }
+    }
+
+    /**
+     * Create a new {@code Configuration} object from the specified {@code URI}.
+     *
+     * @param uri the {@code URI}
+     * @throws SecurityException if the {@code Configuration} can not be
+     *                           initialized
+     * @throws NullPointerException if {@code uri} is null
+     */
+    public ConfigSpiFile(URI uri) {
+        // only load config from the specified URI
+        try {
+            url = uri.toURL();
+            init();
+        } catch (IOException ioe) {
+            throw new SecurityException(ioe);
+        }
+    }
 
     public ConfigSpiFile(final Configuration.Parameters params)
-        throws java.io.IOException {
+        throws IOException {
 
         // call in a doPrivileged
         //
         // we have already passed the Configuration.getInstance
         // security check.  also this class is not freely accessible
         // (it is in the "sun" package).
-        //
-        // we can not put doPrivileged calls into
-        // ConfigFile because it is a public com.sun class
 
         try {
-            AccessController.doPrivileged(new PrivilegedAction<Void>() {
+            AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
+                public Void run() throws IOException {
+                    if (params == null) {
+                        init();
+                    } else {
+                        if (!(params instanceof URIParameter)) {
+                            throw new IllegalArgumentException
+                                    ("Unrecognized parameter: " + params);
+                        }
+                        URIParameter uriParam = (URIParameter)params;
+                        url = uriParam.getURI().toURL();
+                        init();
+                    }
+                    return null;
+                }
+            });
+        } catch (PrivilegedActionException pae) {
+            throw (IOException)pae.getException();
+        }
+
+        // if init() throws some other RuntimeException,
+        // let it percolate up naturally.
+    }
+
+    /**
+     * Read and initialize the entire login Configuration from the configured
+     * URL.
+     *
+     * @throws IOException if the Configuration can not be initialized
+     * @throws SecurityException if the caller does not have permission
+     *                           to initialize the Configuration
+     */
+    private void init() throws IOException {
+
+        boolean initialized = false;
+
+        // For policy.expandProperties, check if either a security or system
+        // property is set to false (old code erroneously checked the system
+        // prop so we must check both to preserve compatibility).
+        String expand = Security.getProperty("policy.expandProperties");
+        if (expand == null) {
+            expand = System.getProperty("policy.expandProperties");
+        }
+        if ("false".equals(expand)) {
+            expandProp = false;
+        }
+
+        // new configuration
+        Map<String, List<AppConfigurationEntry>> newConfig = new HashMap<>();
+
+        if (url != null) {
+            /**
+             * If the caller specified a URI via Configuration.getInstance,
+             * we only read from that URI
+             */
+            if (debugConfig != null) {
+                debugConfig.println("reading " + url);
+            }
+            init(url, newConfig);
+            configuration = newConfig;
+            return;
+        }
+
+        /**
+         * Caller did not specify URI via Configuration.getInstance.
+         * Read from URLs listed in the java.security properties file.
+         */
+        String allowSys = Security.getProperty("policy.allowSystemProperty");
+
+        if ("true".equalsIgnoreCase(allowSys)) {
+            String extra_config = System.getProperty
+                                        ("java.security.auth.login.config");
+            if (extra_config != null) {
+                boolean overrideAll = false;
+                if (extra_config.startsWith("=")) {
+                    overrideAll = true;
+                    extra_config = extra_config.substring(1);
+                }
+                try {
+                    extra_config = PropertyExpander.expand(extra_config);
+                } catch (PropertyExpander.ExpandException peee) {
+                    MessageFormat form = new MessageFormat
+                        (ResourcesMgr.getString
+                                ("Unable.to.properly.expand.config",
+                                "sun.security.util.AuthResources"));
+                    Object[] source = {extra_config};
+                    throw new IOException(form.format(source));
+                }
+
+                URL configURL = null;
+                try {
+                    configURL = new URL(extra_config);
+                } catch (MalformedURLException mue) {
+                    File configFile = new File(extra_config);
+                    if (configFile.exists()) {
+                        configURL = configFile.toURI().toURL();
+                    } else {
+                        MessageFormat form = new MessageFormat
+                            (ResourcesMgr.getString
+                                ("extra.config.No.such.file.or.directory.",
+                                "sun.security.util.AuthResources"));
+                        Object[] source = {extra_config};
+                        throw new IOException(form.format(source));
+                    }
+                }
+
+                if (debugConfig != null) {
+                    debugConfig.println("reading "+configURL);
+                }
+                init(configURL, newConfig);
+                initialized = true;
+                if (overrideAll) {
+                    if (debugConfig != null) {
+                        debugConfig.println("overriding other policies!");
+                    }
+                    configuration = newConfig;
+                    return;
+                }
+            }
+        }
+
+        int n = 1;
+        String config_url;
+        while ((config_url = Security.getProperty
+                                        ("login.config.url."+n)) != null) {
+            try {
+                config_url = PropertyExpander.expand
+                        (config_url).replace(File.separatorChar, '/');
+                if (debugConfig != null) {
+                    debugConfig.println("\tReading config: " + config_url);
+                }
+                init(new URL(config_url), newConfig);
+                initialized = true;
+            } catch (PropertyExpander.ExpandException peee) {
+                MessageFormat form = new MessageFormat
+                        (ResourcesMgr.getString
+                                ("Unable.to.properly.expand.config",
+                                "sun.security.util.AuthResources"));
+                Object[] source = {config_url};
+                throw new IOException(form.format(source));
+            }
+            n++;
+        }
+
+        if (initialized == false && n == 1 && config_url == null) {
+
+            // get the config from the user's home directory
+            if (debugConfig != null) {
+                debugConfig.println("\tReading Policy " +
+                                "from ~/.java.login.config");
+            }
+            config_url = System.getProperty("user.home");
+            String userConfigFile = config_url +
+                      File.separatorChar + ".java.login.config";
+
+            // No longer throws an exception when there's no config file
+            // at all. Returns an empty Configuration instead.
+            if (new File(userConfigFile).exists()) {
+                init(new File(userConfigFile).toURI().toURL(),
+                     newConfig);
+            }
+        }
+
+        configuration = newConfig;
+    }
+
+    private void init(URL config,
+                      Map<String, List<AppConfigurationEntry>> newConfig)
+                      throws IOException {
+
+        try (InputStreamReader isr
+                = new InputStreamReader(getInputStream(config), "UTF-8")) {
+            readConfig(isr, newConfig);
+        } catch (FileNotFoundException fnfe) {
+            if (debugConfig != null) {
+                debugConfig.println(fnfe.toString());
+            }
+            throw new IOException(ResourcesMgr.getString
+                    ("Configuration.Error.No.such.file.or.directory",
+                    "sun.security.util.AuthResources"));
+        }
+    }
+
+    /**
+     * Retrieve an entry from the Configuration using an application name
+     * as an index.
+     *
+     * @param applicationName the name used to index the Configuration.
+     * @return an array of AppConfigurationEntries which correspond to
+     *         the stacked configuration of LoginModules for this
+     *         application, or null if this application has no configured
+     *         LoginModules.
+     */
+    @Override
+    public AppConfigurationEntry[] engineGetAppConfigurationEntry
+        (String applicationName) {
+
+        List<AppConfigurationEntry> list = null;
+        synchronized (configuration) {
+            list = configuration.get(applicationName);
+        }
+
+        if (list == null || list.size() == 0)
+            return null;
+
+        AppConfigurationEntry[] entries =
+                                new AppConfigurationEntry[list.size()];
+        Iterator<AppConfigurationEntry> iterator = list.iterator();
+        for (int i = 0; iterator.hasNext(); i++) {
+            AppConfigurationEntry e = iterator.next();
+            entries[i] = new AppConfigurationEntry(e.getLoginModuleName(),
+                                                   e.getControlFlag(),
+                                                   e.getOptions());
+        }
+        return entries;
+    }
+
+    /**
+     * Refresh and reload the Configuration by re-reading all of the
+     * login configurations.
+     *
+     * @throws SecurityException if the caller does not have permission
+     *                           to refresh the Configuration.
+     */
+    @Override
+    public synchronized void engineRefresh() {
+
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null)
+            sm.checkPermission(new AuthPermission("refreshLoginConfiguration"));
+
+        AccessController.doPrivileged(new PrivilegedAction<Void>() {
             public Void run() {
-                if (params == null) {
-                    cf = new ConfigFile();
-                } else {
-                    if (!(params instanceof URIParameter)) {
-                        throw new IllegalArgumentException
-                                ("Unrecognized parameter: " + params);
-                    }
-                    URIParameter uriParam = (URIParameter)params;
-
-                    cf = new ConfigFile(uriParam.getURI());
+                try {
+                    init();
+                } catch (IOException ioe) {
+                    throw new SecurityException(ioe.getLocalizedMessage(), ioe);
                 }
                 return null;
             }
-            });
-        } catch (SecurityException se) {
+        });
+    }
+
+    private void readConfig(Reader reader,
+        Map<String, List<AppConfigurationEntry>> newConfig)
+        throws IOException {
+
+        linenum = 1;
+
+        if (!(reader instanceof BufferedReader))
+            reader = new BufferedReader(reader);
+
+        st = new StreamTokenizer(reader);
+        st.quoteChar('"');
+        st.wordChars('$', '$');
+        st.wordChars('_', '_');
+        st.wordChars('-', '-');
+        st.lowerCaseMode(false);
+        st.slashSlashComments(true);
+        st.slashStarComments(true);
+        st.eolIsSignificant(true);
+
+        lookahead = nextToken();
+        while (lookahead != StreamTokenizer.TT_EOF) {
+            parseLoginEntry(newConfig);
+        }
+    }
+
+    private void parseLoginEntry(
+        Map<String, List<AppConfigurationEntry>> newConfig)
+        throws IOException {
+
+        List<AppConfigurationEntry> configEntries = new LinkedList<>();
+
+        // application name
+        String appName = st.sval;
+        lookahead = nextToken();
+
+        if (debugParser != null) {
+            debugParser.println("\tReading next config entry: " + appName);
+        }
+
+        match("{");
 
-            // if ConfigFile threw a standalone SecurityException
-            // (no cause), re-throw it.
-            //
-            // ConfigFile chains checked IOExceptions to SecurityException.
+        // get the modules
+        while (peek("}") == false) {
+            // get the module class name
+            String moduleClass = match("module class name");
 
-            Throwable cause = se.getCause();
-            if (cause != null && cause instanceof java.io.IOException) {
-                throw (java.io.IOException)cause;
+            // controlFlag (required, optional, etc)
+            AppConfigurationEntry.LoginModuleControlFlag controlFlag;
+            String sflag = match("controlFlag").toUpperCase();
+            switch (sflag) {
+                case "REQUIRED":
+                    controlFlag =
+                        AppConfigurationEntry.LoginModuleControlFlag.REQUIRED;
+                    break;
+                case "REQUISITE":
+                    controlFlag =
+                        AppConfigurationEntry.LoginModuleControlFlag.REQUISITE;
+                    break;
+                case "SUFFICIENT":
+                    controlFlag =
+                        AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT;
+                    break;
+                case "OPTIONAL":
+                    controlFlag =
+                        AppConfigurationEntry.LoginModuleControlFlag.OPTIONAL;
+                    break;
+                default:
+                    MessageFormat form = new MessageFormat(
+                        ResourcesMgr.getString
+                        ("Configuration.Error.Invalid.control.flag.flag",
+                        "sun.security.util.AuthResources"));
+                    Object[] source = {sflag};
+                    throw new IOException(form.format(source));
+            }
+
+            // get the args
+            Map<String, String> options = new HashMap<>();
+            while (peek(";") == false) {
+                String key = match("option key");
+                match("=");
+                try {
+                    options.put(key, expand(match("option value")));
+                } catch (PropertyExpander.ExpandException peee) {
+                    throw new IOException(peee.getLocalizedMessage());
+                }
             }
 
-            // unrecognized cause
-            throw se;
+            lookahead = nextToken();
+
+            // create the new element
+            if (debugParser != null) {
+                debugParser.println("\t\t" + moduleClass + ", " + sflag);
+                for (String key : options.keySet()) {
+                    debugParser.println("\t\t\t" + key +
+                                        "=" + options.get(key));
+                }
+            }
+            configEntries.add(new AppConfigurationEntry(moduleClass,
+                                                        controlFlag, options));
         }
 
-        // if ConfigFile throws some other RuntimeException,
-        // let it percolate up naturally.
+        match("}");
+        match(";");
+
+        // add this configuration entry
+        if (newConfig.containsKey(appName)) {
+            MessageFormat form = new MessageFormat(ResourcesMgr.getString
+                ("Configuration.Error.Can.not.specify.multiple.entries.for.appName",
+                "sun.security.util.AuthResources"));
+            Object[] source = {appName};
+            throw new IOException(form.format(source));
+        }
+        newConfig.put(appName, configEntries);
     }
 
-    protected AppConfigurationEntry[] engineGetAppConfigurationEntry
-                (String name) {
-        return cf.getAppConfigurationEntry(name);
+    private String match(String expect) throws IOException {
+
+        String value = null;
+
+        switch(lookahead) {
+        case StreamTokenizer.TT_EOF:
+
+            MessageFormat form1 = new MessageFormat(ResourcesMgr.getString
+                ("Configuration.Error.expected.expect.read.end.of.file.",
+                "sun.security.util.AuthResources"));
+            Object[] source1 = {expect};
+            throw new IOException(form1.format(source1));
+
+        case '"':
+        case StreamTokenizer.TT_WORD:
+
+            if (expect.equalsIgnoreCase("module class name") ||
+                expect.equalsIgnoreCase("controlFlag") ||
+                expect.equalsIgnoreCase("option key") ||
+                expect.equalsIgnoreCase("option value")) {
+                value = st.sval;
+                lookahead = nextToken();
+            } else {
+                MessageFormat form = new MessageFormat(ResourcesMgr.getString
+                        ("Configuration.Error.Line.line.expected.expect.found.value.",
+                        "sun.security.util.AuthResources"));
+                Object[] source = {new Integer(linenum), expect, st.sval};
+                throw new IOException(form.format(source));
+            }
+            break;
+
+        case '{':
+
+            if (expect.equalsIgnoreCase("{")) {
+                lookahead = nextToken();
+            } else {
+                MessageFormat form = new MessageFormat(ResourcesMgr.getString
+                        ("Configuration.Error.Line.line.expected.expect.",
+                        "sun.security.util.AuthResources"));
+                Object[] source = {new Integer(linenum), expect, st.sval};
+                throw new IOException(form.format(source));
+            }
+            break;
+
+        case ';':
+
+            if (expect.equalsIgnoreCase(";")) {
+                lookahead = nextToken();
+            } else {
+                MessageFormat form = new MessageFormat(ResourcesMgr.getString
+                        ("Configuration.Error.Line.line.expected.expect.",
+                        "sun.security.util.AuthResources"));
+                Object[] source = {new Integer(linenum), expect, st.sval};
+                throw new IOException(form.format(source));
+            }
+            break;
+
+        case '}':
+
+            if (expect.equalsIgnoreCase("}")) {
+                lookahead = nextToken();
+            } else {
+                MessageFormat form = new MessageFormat(ResourcesMgr.getString
+                        ("Configuration.Error.Line.line.expected.expect.",
+                        "sun.security.util.AuthResources"));
+                Object[] source = {new Integer(linenum), expect, st.sval};
+                throw new IOException(form.format(source));
+            }
+            break;
+
+        case '=':
+
+            if (expect.equalsIgnoreCase("=")) {
+                lookahead = nextToken();
+            } else {
+                MessageFormat form = new MessageFormat(ResourcesMgr.getString
+                        ("Configuration.Error.Line.line.expected.expect.",
+                        "sun.security.util.AuthResources"));
+                Object[] source = {new Integer(linenum), expect, st.sval};
+                throw new IOException(form.format(source));
+            }
+            break;
+
+        default:
+            MessageFormat form = new MessageFormat(ResourcesMgr.getString
+                        ("Configuration.Error.Line.line.expected.expect.found.value.",
+                        "sun.security.util.AuthResources"));
+            Object[] source = {new Integer(linenum), expect, st.sval};
+            throw new IOException(form.format(source));
+        }
+        return value;
     }
 
-    protected void engineRefresh() {
-        cf.refresh();
+    private boolean peek(String expect) {
+        boolean found = false;
+
+        switch (lookahead) {
+        case ',':
+            if (expect.equalsIgnoreCase(","))
+                found = true;
+            break;
+        case ';':
+            if (expect.equalsIgnoreCase(";"))
+                found = true;
+            break;
+        case '{':
+            if (expect.equalsIgnoreCase("{"))
+                found = true;
+            break;
+        case '}':
+            if (expect.equalsIgnoreCase("}"))
+                found = true;
+            break;
+        default:
+        }
+        return found;
+    }
+
+    private int nextToken() throws IOException {
+        int tok;
+        while ((tok = st.nextToken()) == StreamTokenizer.TT_EOL) {
+            linenum++;
+        }
+        return tok;
+    }
+
+    private InputStream getInputStream(URL url) throws IOException {
+        if ("file".equalsIgnoreCase(url.getProtocol())) {
+            // Compatibility notes:
+            //
+            // Code changed from
+            //   String path = url.getFile().replace('/', File.separatorChar);
+            //   return new FileInputStream(path);
+            //
+            // The original implementation would search for "/tmp/a%20b"
+            // when url is "file:///tmp/a%20b". This is incorrect. The
+            // current codes fix this bug and searches for "/tmp/a b".
+            // For compatibility reasons, when the file "/tmp/a b" does
+            // not exist, the file named "/tmp/a%20b" will be tried.
+            //
+            // This also means that if both file exists, the behavior of
+            // this method is changed, and the current codes choose the
+            // correct one.
+            try {
+                return url.openStream();
+            } catch (Exception e) {
+                String file = url.getPath();
+                if (url.getHost().length() > 0) {  // For Windows UNC
+                    file = "//" + url.getHost() + file;
+                }
+                if (debugConfig != null) {
+                    debugConfig.println("cannot read " + url +
+                                        ", try " + file);
+                }
+                return new FileInputStream(file);
+            }
+        } else {
+            return url.openStream();
+        }
+    }
+
+    private String expand(String value)
+        throws PropertyExpander.ExpandException, IOException {
+
+        if (value.isEmpty()) {
+            return value;
+        }
+
+        if (expandProp) {
+
+            String s = PropertyExpander.expand(value);
+
+            if (s == null || s.length() == 0) {
+                MessageFormat form = new MessageFormat(ResourcesMgr.getString
+                        ("Configuration.Error.Line.line.system.property.value.expanded.to.empty.value",
+                        "sun.security.util.AuthResources"));
+                Object[] source = {new Integer(linenum), value};
+                throw new IOException(form.format(source));
+            }
+            return s;
+        } else {
+            return value;
+        }
     }
 }
--- a/jdk/src/share/classes/sun/security/provider/PolicyFile.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/provider/PolicyFile.java	Tue Jan 22 11:54:16 2013 -0800
@@ -31,13 +31,7 @@
 import java.net.URL;
 import java.net.URI;
 import java.util.*;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.StringTokenizer;
-import java.util.ArrayList;
-import java.util.ListIterator;
 import java.text.MessageFormat;
-import com.sun.security.auth.PrincipalComparator;
 import java.security.*;
 import java.security.cert.Certificate;
 import java.security.cert.X509Certificate;
@@ -46,19 +40,7 @@
 import java.io.FilePermission;
 import java.net.SocketPermission;
 import java.net.NetPermission;
-import java.util.PropertyPermission;
 import java.util.concurrent.atomic.AtomicReference;
-/*
-import javax.security.auth.AuthPermission;
-import javax.security.auth.kerberos.ServicePermission;
-import javax.security.auth.kerberos.DelegationPermission;
-import java.io.SerializablePermission;
-import java.util.logging.LoggingPermission;
-import java.sql.SQLPermission;
-import java.lang.reflect.ReflectPermission;
-import javax.sound.sampled.AudioPermission;
-import javax.net.ssl.SSLPermission;
-*/
 import sun.misc.JavaSecurityProtectionDomainAccess;
 import static sun.misc.JavaSecurityProtectionDomainAccess.ProtectionDomainCache;
 import sun.misc.SharedSecrets;
@@ -794,12 +776,9 @@
             debug.println("Adding policy entry: ");
             debug.println("  signedBy " + ge.signedBy);
             debug.println("  codeBase " + ge.codeBase);
-            if (ge.principals != null && ge.principals.size() > 0) {
-                ListIterator<PolicyParser.PrincipalEntry> li =
-                                                ge.principals.listIterator();
-                while (li.hasNext()) {
-                    PolicyParser.PrincipalEntry pppe = li.next();
-                debug.println("  " + pppe.toString());
+            if (ge.principals != null) {
+                for (PolicyParser.PrincipalEntry pppe : ge.principals) {
+                    debug.println("  " + pppe.toString());
                 }
             }
         }
@@ -955,11 +934,15 @@
                InvocationTargetException
     {
         //XXX we might want to keep a hash of created factories...
-        Class<?> pc = Class.forName(type);
+        Class<?> pc = Class.forName(type, false, null);
         Permission answer = getKnownInstance(pc, name, actions);
         if (answer != null) {
             return answer;
         }
+        if (!Permission.class.isAssignableFrom(pc)) {
+            // not the right subtype
+            throw new ClassCastException(type + " is not a Permission");
+        }
 
         if (name == null && actions == null) {
             try {
@@ -1001,7 +984,6 @@
      */
     private static final Permission getKnownInstance(Class<?> claz,
         String name, String actions) {
-        // XXX shorten list to most popular ones?
         if (claz.equals(FilePermission.class)) {
             return new FilePermission(name, actions);
         } else if (claz.equals(SocketPermission.class)) {
@@ -1014,30 +996,6 @@
             return new NetPermission(name, actions);
         } else if (claz.equals(AllPermission.class)) {
             return SecurityConstants.ALL_PERMISSION;
-/*
-        } else if (claz.equals(ReflectPermission.class)) {
-            return new ReflectPermission(name, actions);
-        } else if (claz.equals(SecurityPermission.class)) {
-            return new SecurityPermission(name, actions);
-        } else if (claz.equals(PrivateCredentialPermission.class)) {
-            return new PrivateCredentialPermission(name, actions);
-        } else if (claz.equals(AuthPermission.class)) {
-            return new AuthPermission(name, actions);
-        } else if (claz.equals(ServicePermission.class)) {
-            return new ServicePermission(name, actions);
-        } else if (claz.equals(DelegationPermission.class)) {
-            return new DelegationPermission(name, actions);
-        } else if (claz.equals(SerializablePermission.class)) {
-            return new SerializablePermission(name, actions);
-        } else if (claz.equals(AudioPermission.class)) {
-            return new AudioPermission(name, actions);
-        } else if (claz.equals(SSLPermission.class)) {
-            return new SSLPermission(name, actions);
-        } else if (claz.equals(LoggingPermission.class)) {
-            return new LoggingPermission(name, actions);
-        } else if (claz.equals(SQLPermission.class)) {
-            return new SQLPermission(name, actions);
-*/
         } else {
             return null;
         }
@@ -1079,7 +1037,7 @@
 
             if (cert != null) {
                 if (vcerts == null)
-                    vcerts = new ArrayList<Certificate>();
+                    vcerts = new ArrayList<>();
                 vcerts.add(cert);
             }
         }
@@ -1329,7 +1287,7 @@
 
         List<PolicyParser.PrincipalEntry> entryPs = entry.getPrincipals();
         if (debug != null) {
-            ArrayList<PolicyParser.PrincipalEntry> accPs = new ArrayList<>();
+            List<PolicyParser.PrincipalEntry> accPs = new ArrayList<>();
             if (principals != null) {
                 for (int i = 0; i < principals.length; i++) {
                     accPs.add(new PolicyParser.PrincipalEntry
@@ -1368,79 +1326,72 @@
         // has principals.  see if policy entry principals match
         // principals in current ACC
 
-        for (int i = 0; i < entryPs.size(); i++) {
-            PolicyParser.PrincipalEntry pppe = entryPs.get(i);
+        for (PolicyParser.PrincipalEntry pppe : entryPs) {
 
-            // see if principal entry is a PrincipalComparator
+            // Check for wildcards
+            if (pppe.isWildcardClass()) {
+                // a wildcard class matches all principals in current ACC
+                continue;
+            }
 
-            try {
-                Class<?> pClass = Class.forName
-                                (pppe.principalClass,
-                                true,
-                                Thread.currentThread().getContextClassLoader());
+            if (pppe.isWildcardName()) {
+                // a wildcard name matches any principal with the same class
+                for (Principal p : principals) {
+                    if (pppe.principalClass.equals(p.getClass().getName())) {
+                        continue;
+                    }
+                }
+                if (debug != null) {
+                    debug.println("evaluation (principal name wildcard) failed");
+                }
+                // policy entry principal not in current ACC -
+                // immediately return and go to next policy entry
+                return;
+            }
 
-                if (!PrincipalComparator.class.isAssignableFrom(pClass)) {
-
-                    // common case - dealing with regular Principal class.
-                    // see if policy entry principal is in current ACC
+            Set<Principal> pSet = new HashSet<>(Arrays.asList(principals));
+            Subject subject = new Subject(true, pSet,
+                                          Collections.EMPTY_SET,
+                                          Collections.EMPTY_SET);
+            try {
+                ClassLoader cl = Thread.currentThread().getContextClassLoader();
+                Class<?> pClass = Class.forName(pppe.principalClass, false, cl);
+                if (!Principal.class.isAssignableFrom(pClass)) {
+                    // not the right subtype
+                    throw new ClassCastException(pppe.principalClass +
+                                                 " is not a Principal");
+                }
 
-                    if (!checkEntryPs(principals, pppe)) {
-                        if (debug != null) {
-                            debug.println("evaluation (principals) failed");
-                        }
+                Constructor<?> c = pClass.getConstructor(PARAMS1);
+                Principal p = (Principal)c.newInstance(new Object[] {
+                                                       pppe.principalName });
 
-                        // policy entry principal not in current ACC -
-                        // immediately return and go to next policy entry
-                        return;
+                if (debug != null) {
+                    debug.println("found Principal " + p.getClass().getName());
+                }
+
+                // check if the Principal implies the current
+                // thread's principals
+                if (!p.implies(subject)) {
+                    if (debug != null) {
+                        debug.println("evaluation (principal implies) failed");
                     }
 
-                } else {
-
-                    // dealing with a PrincipalComparator
-
-                    Constructor<?> c = pClass.getConstructor(PARAMS1);
-                    PrincipalComparator pc = (PrincipalComparator)c.newInstance
-                                        (new Object[] { pppe.principalName });
-
-                    if (debug != null) {
-                        debug.println("found PrincipalComparator " +
-                                        pc.getClass().getName());
-                    }
-
-                    // check if the PrincipalComparator
-                    // implies the current thread's principals
-
-                    Set<Principal> pSet = new HashSet<>(principals.length);
-                    for (int j = 0; j < principals.length; j++) {
-                        pSet.add(principals[j]);
-                    }
-                    Subject subject = new Subject(true,
-                                                pSet,
-                                                Collections.EMPTY_SET,
-                                                Collections.EMPTY_SET);
-
-                    if (!pc.implies(subject)) {
-                        if (debug != null) {
-                            debug.println
-                                ("evaluation (principal comparator) failed");
-                        }
-
-                        // policy principal does not imply the current Subject -
-                        // immediately return and go to next policy entry
-                        return;
-                    }
+                    // policy principal does not imply the current Subject -
+                    // immediately return and go to next policy entry
+                    return;
                 }
             } catch (Exception e) {
-                // fall back to regular principal comparison.
+                // fall back to default principal comparison.
                 // see if policy entry principal is in current ACC
 
                 if (debug != null) {
                     e.printStackTrace();
                 }
 
-                if (!checkEntryPs(principals, pppe)) {
+                if (!pppe.implies(subject)) {
                     if (debug != null) {
-                        debug.println("evaluation (principals) failed");
+                        debug.println("evaluation (default principal implies) failed");
                     }
 
                     // policy entry principal not in current ACC -
@@ -1450,7 +1401,7 @@
             }
 
             // either the principal information matched,
-            // or the PrincipalComparator.implies succeeded.
+            // or the Principal.implies succeeded.
             // continue loop and test the next policy principal
         }
 
@@ -1485,47 +1436,6 @@
     }
 
     /**
-     * This method returns, true, if the principal in the policy entry,
-     * pppe, is part of the current thread's principal array, pList.
-     * This method also returns, true, if the policy entry's principal
-     * is appropriately wildcarded.
-     *
-     * Note that the provided <i>pppe</i> argument may have
-     * wildcards (*) for both the <code>Principal</code> class and name.
-     *
-     * @param pList an array of principals from the current thread's
-     *          AccessControlContext.
-     *
-     * @param pppe a Principal specified in a policy grant entry.
-     *
-     * @return true if the current thread's pList "contains" the
-     *          principal in the policy entry, pppe.  This method
-     *          also returns true if the policy entry's principal
-     *          appropriately wildcarded.
-     */
-    private boolean checkEntryPs(Principal[] pList,
-                                PolicyParser.PrincipalEntry pppe) {
-
-        for (int i = 0; i < pList.length; i++) {
-
-            if (pppe.principalClass.equals
-                        (PolicyParser.PrincipalEntry.WILDCARD_CLASS) ||
-                pppe.principalClass.equals
-                        (pList[i].getClass().getName())) {
-
-                if (pppe.principalName.equals
-                        (PolicyParser.PrincipalEntry.WILDCARD_NAME) ||
-                    pppe.principalName.equals
-                        (pList[i].getName())) {
-
-                    return true;
-                }
-            }
-        }
-        return false;
-    }
-
-    /**
      * <p>
      *
      * @param sp the SelfPermission that needs to be expanded <p>
@@ -1568,8 +1478,7 @@
             sb.append(sp.getSelfName().substring(startIndex, v));
 
             // expand SELF
-            ListIterator<PolicyParser.PrincipalEntry> pli =
-                                                entryPs.listIterator();
+            Iterator<PolicyParser.PrincipalEntry> pli = entryPs.iterator();
             while (pli.hasNext()) {
                 PolicyParser.PrincipalEntry pppe = pli.next();
                 String[][] principalInfo = getPrincipalInfo(pppe,pdp);
@@ -1596,8 +1505,8 @@
         try {
             // first try to instantiate the permission
             perms.add(getInstance(sp.getSelfType(),
-                                sb.toString(),
-                                sp.getSelfActions()));
+                                  sb.toString(),
+                                  sp.getSelfActions()));
         } catch (ClassNotFoundException cnfe) {
             // ok, the permission is not in the bootclasspath.
             // before we add an UnresolvedPermission, check to see
@@ -1673,10 +1582,7 @@
         // 2) the entry's Principal name is wildcarded only
         // 3) the entry's Principal class and name are wildcarded
 
-        if (!pe.principalClass.equals
-            (PolicyParser.PrincipalEntry.WILDCARD_CLASS) &&
-            !pe.principalName.equals
-            (PolicyParser.PrincipalEntry.WILDCARD_NAME)) {
+        if (!pe.isWildcardClass() && !pe.isWildcardName()) {
 
             // build an info array for the principal
             // from the Policy entry
@@ -1685,24 +1591,19 @@
             info[0][1] = pe.principalName;
             return info;
 
-        } else if (!pe.principalClass.equals
-                   (PolicyParser.PrincipalEntry.WILDCARD_CLASS) &&
-                   pe.principalName.equals
-                   (PolicyParser.PrincipalEntry.WILDCARD_NAME)) {
+        } else if (!pe.isWildcardClass() && pe.isWildcardName()) {
 
             // build an info array for every principal
             // in the current domain which has a principal class
             // that is equal to policy entry principal class name
             List<Principal> plist = new ArrayList<>();
             for (int i = 0; i < pdp.length; i++) {
-                if(pe.principalClass.equals(pdp[i].getClass().getName()))
+                if (pe.principalClass.equals(pdp[i].getClass().getName()))
                     plist.add(pdp[i]);
             }
             String[][] info = new String[plist.size()][2];
             int i = 0;
-            java.util.Iterator<Principal> pIterator = plist.iterator();
-            while (pIterator.hasNext()) {
-                Principal p = pIterator.next();
+            for (Principal p : plist) {
                 info[i][0] = p.getClass().getName();
                 info[i][1] = p.getName();
                 i++;
@@ -1763,7 +1664,7 @@
             // Done
             return certs;
 
-        ArrayList<Certificate> userCertList = new ArrayList<>();
+        List<Certificate> userCertList = new ArrayList<>();
         i = 0;
         while (i < certs.length) {
             userCertList.add(certs[i]);
@@ -1889,10 +1790,8 @@
         if (principals == null || principals.isEmpty() || keystore == null)
             return true;
 
-        ListIterator<PolicyParser.PrincipalEntry> i = principals.listIterator();
-        while (i.hasNext()) {
-            PolicyParser.PrincipalEntry pppe = i.next();
-            if (pppe.principalClass.equals(PolicyParser.REPLACE_NAME)) {
+        for (PolicyParser.PrincipalEntry pppe : principals) {
+            if (pppe.isReplaceName()) {
 
                 // perform replacement
                 // (only X509 replacement is possible now)
@@ -2241,8 +2140,7 @@
 
                     if (this.certs == null) {
                         // extract the signer certs
-                        ArrayList<Certificate> signerCerts =
-                            new ArrayList<>();
+                        List<Certificate> signerCerts = new ArrayList<>();
                         i = 0;
                         while (i < certs.length) {
                             signerCerts.add(certs[i]);
@@ -2406,11 +2304,10 @@
         private java.util.Random random;
 
         PolicyInfo(int numCaches) {
-            policyEntries = new ArrayList<PolicyEntry>();
+            policyEntries = new ArrayList<>();
             identityPolicyEntries =
                 Collections.synchronizedList(new ArrayList<PolicyEntry>(2));
-            aliasMapping = Collections.synchronizedMap(
-                    new HashMap<Object, Object>(11));
+            aliasMapping = Collections.synchronizedMap(new HashMap<>(11));
 
             pdMapping = new ProtectionDomainCache[numCaches];
             JavaSecurityProtectionDomainAccess jspda
--- a/jdk/src/share/classes/sun/security/provider/PolicyParser.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/provider/PolicyParser.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,16 +29,17 @@
 import java.lang.RuntimePermission;
 import java.net.SocketPermission;
 import java.net.URL;
+import java.security.GeneralSecurityException;
+import java.security.Principal;
+import java.text.MessageFormat;
 import java.util.Enumeration;
 import java.util.Hashtable;
+import java.util.Iterator;
 import java.util.LinkedList;
-import java.util.ListIterator;
 import java.util.Vector;
 import java.util.StringTokenizer;
-import java.text.MessageFormat;
 import javax.security.auth.x500.X500Principal;
 
-import java.security.GeneralSecurityException;
 import sun.security.util.Debug;
 import sun.security.util.PropertyExpander;
 import sun.security.util.ResourcesMgr;
@@ -72,7 +73,7 @@
  *  Permissions perms = policy.getPermissions(protectiondomain)
  * </pre>
  *
- * <p>The protection domain contains CodeSource
+ * <p>The protection domain contains a CodeSource
  * object, which encapsulates its codebase (URL) and public key attributes.
  * It also contains the principals associated with the domain.
  * The Policy object evaluates the global policy in light of who the
@@ -87,9 +88,6 @@
 
 public class PolicyParser {
 
-    // needs to be public for PolicyTool
-    public static final String REPLACE_NAME = "PolicyParser.REPLACE_NAME";
-
     private static final String EXTDIRS_PROPERTY = "java.ext.dirs";
     private static final String OLD_EXTDIRS_EXPANSION =
         "${" + EXTDIRS_PROPERTY + "}";
@@ -452,7 +450,7 @@
                 peekAndMatch(",");
             } else if (peekAndMatch("Principal")) {
                 if (principals == null) {
-                    principals = new LinkedList<PrincipalEntry>();
+                    principals = new LinkedList<>();
                 }
 
                 String principalClass;
@@ -461,7 +459,7 @@
                 if (peek("\"")) {
                     // both the principalClass and principalName
                     // will be replaced later
-                    principalClass = REPLACE_NAME;
+                    principalClass = PrincipalEntry.REPLACE_NAME;
                     principalName = match("principal type");
                 } else {
                     // check for principalClass wildcard
@@ -916,7 +914,7 @@
                     out.print(",\n");
             }
             if (principals != null && principals.size() > 0) {
-                ListIterator<PrincipalEntry> pli = principals.listIterator();
+                Iterator<PrincipalEntry> pli = principals.iterator();
                 while (pli.hasNext()) {
                     out.print("      ");
                     PrincipalEntry pe = pli.next();
@@ -949,23 +947,22 @@
     /**
      * Principal info (class and name) in a grant entry
      */
-    public static class PrincipalEntry {
+    public static class PrincipalEntry implements Principal {
 
         public static final String WILDCARD_CLASS = "WILDCARD_PRINCIPAL_CLASS";
         public static final String WILDCARD_NAME = "WILDCARD_PRINCIPAL_NAME";
+        public static final String REPLACE_NAME = "PolicyParser.REPLACE_NAME";
 
         String principalClass;
         String principalName;
 
         /**
-         * A PrincipalEntry consists of the <code>Principal</code>
-         * class and <code>Principal</code> name.
+         * A PrincipalEntry consists of the Principal class and Principal name.
          *
-         * <p>
-         *
-         * @param principalClass the <code>Principal</code> class. <p>
-         *
-         * @param principalName the <code>Principal</code> name. <p>
+         * @param principalClass the Principal class
+         * @param principalName the Principal name
+         * @throws NullPointerException if principalClass or principalName
+         *                              are null
          */
         public PrincipalEntry(String principalClass, String principalName) {
             if (principalClass == null || principalName == null)
@@ -975,6 +972,18 @@
             this.principalName = principalName;
         }
 
+        boolean isWildcardName() {
+            return principalName.equals(WILDCARD_NAME);
+        }
+
+        boolean isWildcardClass() {
+            return principalClass.equals(WILDCARD_CLASS);
+        }
+
+        boolean isReplaceName() {
+            return principalClass.equals(REPLACE_NAME);
+        }
+
         public String getPrincipalClass() {
             return principalClass;
         }
@@ -984,9 +993,9 @@
         }
 
         public String getDisplayClass() {
-            if (principalClass.equals(WILDCARD_CLASS)) {
+            if (isWildcardClass()) {
                 return "*";
-            } else if (principalClass.equals(REPLACE_NAME)) {
+            } else if (isReplaceName()) {
                 return "";
             }
             else return principalClass;
@@ -997,7 +1006,7 @@
         }
 
         public String getDisplayName(boolean addQuote) {
-            if (principalName.equals(WILDCARD_NAME)) {
+            if (isWildcardName()) {
                 return "*";
             }
             else {
@@ -1006,8 +1015,14 @@
             }
         }
 
+        @Override
+        public String getName() {
+            return principalName;
+        }
+
+        @Override
         public String toString() {
-            if (!principalClass.equals(REPLACE_NAME)) {
+            if (!isReplaceName()) {
                 return getDisplayClass() + "/" + getDisplayName();
             } else {
                 return getDisplayName();
@@ -1016,15 +1031,13 @@
 
         /**
          * Test for equality between the specified object and this object.
-         * Two PrincipalEntries are equal if their PrincipalClass and
-         * PrincipalName values are equal.
-         *
-         * <p>
+         * Two PrincipalEntries are equal if their class and name values
+         * are equal.
          *
-         * @param obj the object to test for equality with this object.
-         *
-         * @return true if the objects are equal, false otherwise.
+         * @param obj the object to test for equality with this object
+         * @return true if the objects are equal, false otherwise
          */
+        @Override
         public boolean equals(Object obj) {
             if (this == obj)
                 return true;
@@ -1033,27 +1046,23 @@
                 return false;
 
             PrincipalEntry that = (PrincipalEntry)obj;
-            if (this.principalClass.equals(that.principalClass) &&
-                this.principalName.equals(that.principalName)) {
-                return true;
-            }
-
-            return false;
+            return (principalClass.equals(that.principalClass) &&
+                    principalName.equals(that.principalName));
         }
 
         /**
-         * Return a hashcode for this <code>PrincipalEntry</code>.
+         * Return a hashcode for this PrincipalEntry.
          *
-         * <p>
-         *
-         * @return a hashcode for this <code>PrincipalEntry</code>.
+         * @return a hashcode for this PrincipalEntry
          */
+        @Override
         public int hashCode() {
             return principalClass.hashCode();
         }
+
         public void write(PrintWriter out) {
             out.print("principal " + getDisplayClass() + " " +
-                getDisplayName(true));
+                      getDisplayName(true));
         }
     }
 
@@ -1101,6 +1110,7 @@
          * Calculates a hash code value for the object.  Objects
          * which are equal will also have the same hashcode.
          */
+        @Override
         public int hashCode() {
             int retval = permission.hashCode();
             if (name != null) retval ^= name.hashCode();
@@ -1108,6 +1118,7 @@
             return retval;
         }
 
+        @Override
         public boolean equals(Object obj) {
             if (obj == this)
                 return true;
@@ -1210,28 +1221,18 @@
             i18nMessage = form.format(source);
         }
 
+        @Override
         public String getLocalizedMessage() {
             return i18nMessage;
         }
     }
 
     public static void main(String arg[]) throws Exception {
-        FileReader fr = null;
-        FileWriter fw = null;
-        try {
+        try (FileReader fr = new FileReader(arg[0]);
+             FileWriter fw = new FileWriter(arg[1])) {
             PolicyParser pp = new PolicyParser(true);
-            fr = new FileReader(arg[0]);
             pp.read(fr);
-            fw = new FileWriter(arg[1]);
             pp.write(fw);
-        } finally {
-            if (fr != null) {
-                fr.close();
-            }
-
-            if (fw != null) {
-                fw.close();
-            }
         }
     }
 }
--- a/jdk/src/share/classes/sun/security/ssl/krb5/Krb5ProxyImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/ssl/krb5/Krb5ProxyImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -36,6 +36,7 @@
 
 import sun.security.jgss.GSSCaller;
 import sun.security.jgss.krb5.Krb5Util;
+import sun.security.jgss.krb5.ServiceCreds;
 import sun.security.krb5.PrincipalName;
 import sun.security.ssl.Krb5Proxy;
 
@@ -62,7 +63,7 @@
     @Override
     public SecretKey[] getServerKeys(AccessControlContext acc)
             throws LoginException {
-        Krb5Util.ServiceCreds serviceCreds =
+        ServiceCreds serviceCreds =
             Krb5Util.getServiceCreds(GSSCaller.CALLER_SSL_SERVER, null, acc);
         return serviceCreds != null ? serviceCreds.getKKeys() :
                                         new KerberosKey[0];
--- a/jdk/src/share/classes/sun/security/tools/policytool/PolicyTool.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/security/tools/policytool/PolicyTool.java	Tue Jan 22 11:54:16 2013 -0800
@@ -604,7 +604,7 @@
                InstantiationException
     {
         if (type.equals(PolicyParser.PrincipalEntry.WILDCARD_CLASS) ||
-            type.equals(PolicyParser.REPLACE_NAME)) {
+            type.equals(PolicyParser.PrincipalEntry.REPLACE_NAME)) {
             return;
         }
         Class<?> PRIN = Class.forName("java.security.Principal");
@@ -2094,7 +2094,7 @@
         } else if (pclass.equals("")) {
             // make this consistent with what PolicyParser does
             // when it sees an empty principal class
-            pclass = PolicyParser.REPLACE_NAME;
+            pclass = PolicyParser.PrincipalEntry.REPLACE_NAME;
             tool.warnings.addElement(
                         "Warning: Principal name '" + pname +
                                 "' specified without a Principal class.\n" +
--- a/jdk/src/share/classes/sun/text/bidi/BidiBase.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/text/bidi/BidiBase.java	Tue Jan 22 11:54:16 2013 -0800
@@ -3251,10 +3251,9 @@
     {
         verifyValidParaOrLine();
         BidiLine.getRuns(this);
-        if (runCount == 1) {
+        if (run < 0 || run >= runCount) {
             return getParaLevel();
         }
-        verifyIndex(run, 0, runCount);
         getLogicalToVisualRunsMap();
         return runs[logicalToVisualRunsMap[run]].level;
     }
--- a/jdk/src/share/classes/sun/tools/jcmd/JCmd.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/tools/jcmd/JCmd.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,8 +1,7 @@
 /*
  * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *com.sun.tools.attach.AttachNotSupportedException
-
+ *
  * This code is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License version 2 only, as
  * published by the Free Software Foundation.  Oracle designates this
--- a/jdk/src/share/classes/sun/util/resources/CurrencyNames.properties	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/util/resources/CurrencyNames.properties	Tue Jan 22 11:54:16 2013 -0800
@@ -278,6 +278,7 @@
 YUM=YUM
 ZAR=ZAR
 ZMK=ZMK
+ZMW=ZMW
 ZWD=ZWD
 ZWL=ZWL
 ZWN=ZWN
--- a/jdk/src/share/classes/sun/util/resources/TimeZoneNamesBundle.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/util/resources/TimeZoneNamesBundle.java	Tue Jan 22 11:54:16 2013 -0800
@@ -104,7 +104,7 @@
         if (contents == null) {
             return null;
         }
-        int clen = Math.min(n, contents.length);
+        int clen = Math.min(n - 1, contents.length);
         String[] tmpobj = new String[clen+1];
         tmpobj[0] = key;
         System.arraycopy(contents, 0, tmpobj, 1, clen);
--- a/jdk/src/share/classes/sun/util/resources/sq/LocaleNames_sq.properties	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/classes/sun/util/resources/sq/LocaleNames_sq.properties	Tue Jan 22 11:54:16 2013 -0800
@@ -1,4 +1,4 @@
-# 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
@@ -38,7 +38,7 @@
 # language names
 # key is ISO 639 language code
 
-sq=shqipe
+sq=shqip
 
 # country names
 # key is ISO 3166 country code
--- a/jdk/src/share/demo/java2d/J2DBench/build.xml	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/demo/java2d/J2DBench/build.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -49,7 +49,7 @@
   <target name="compile" depends="init"
         description="compile the source " >
     <!-- Compile the java code from ${src} into ${build} -->
-    <javac debug="false" source="1.2" target="1.2" srcdir="${src}" destdir="${build}"/>
+    <javac debug="flase" source="1.5" target="1.5" srcdir="${src}" destdir="${build}"/>
   </target>
 
   <target name="run" depends="dist" 
--- a/jdk/src/share/demo/java2d/J2DBench/src/j2dbench/J2DBench.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/demo/java2d/J2DBench/src/j2dbench/J2DBench.java	Tue Jan 22 11:54:16 2013 -0800
@@ -69,6 +69,7 @@
 import j2dbench.tests.RenderTests;
 import j2dbench.tests.PixelTests;
 import j2dbench.tests.iio.IIOTests;
+import j2dbench.tests.cmm.CMMTests;
 import j2dbench.tests.text.TextConstructionTests;
 import j2dbench.tests.text.TextMeasureTests;
 import j2dbench.tests.text.TextRenderTests;
@@ -199,6 +200,7 @@
         TextMeasureTests.init();
         TextConstructionTests.init();
         IIOTests.init();
+        CMMTests.init();
 
         boolean gui = true;
         boolean showresults = true;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/java2d/J2DBench/src/j2dbench/tests/cmm/CMMTests.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *   - Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *
+ *   - Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ *
+ *   - Neither the name of Oracle nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+
+package j2dbench.tests.cmm;
+
+import j2dbench.Group;
+import j2dbench.Option;
+import j2dbench.Result;
+import j2dbench.Test;
+import j2dbench.TestEnvironment;
+import java.awt.color.ColorSpace;
+import java.awt.color.ICC_ColorSpace;
+import java.awt.color.ICC_Profile;
+import java.io.IOException;
+import java.io.InputStream;
+
+public class CMMTests extends Test {
+
+    protected static Group cmmRoot;
+    protected static Group cmmOptRoot;
+    protected static Option csList;
+    protected static Option usePlatfromProfiles;
+
+    public static void init() {
+        cmmRoot = new Group("cmm", "Color Management Benchmarks");
+        cmmRoot.setTabbed();
+
+        cmmOptRoot = new Group(cmmRoot, "opts", "General Options");
+
+        /*
+        usePlatfromProfiles =
+                new Option.Enable(cmmOptRoot, "csPlatfrom",
+                        "Use Platfrom Profiles", false);
+        */
+        int[] colorspaces = new int[] {
+            ColorSpace.CS_sRGB,
+            ColorSpace.CS_GRAY,
+            ColorSpace.CS_LINEAR_RGB,
+            ColorSpace.CS_CIEXYZ
+        };
+
+        String[] csNames = new String[]{
+            "CS_sRGB",
+            "CS_GRAY",
+            "CS_LINEAR_RGB",
+            "CS_CIEXYZ"
+        };
+
+        csList = new Option.IntList(cmmOptRoot,
+                "profiles", "Color Profiles",
+                colorspaces, csNames, csNames, 0x8);
+
+        ColorConversionTests.init();
+        ProfileTests.init();
+    }
+
+    protected static ColorSpace getColorSpace(TestEnvironment env) {
+        ColorSpace cs;
+        Boolean usePlatfrom = true; //(Boolean)env.getModifier(usePlatfromProfiles);
+
+        int cs_code = env.getIntValue(csList);
+        if (usePlatfrom) {
+            cs = ColorSpace.getInstance(cs_code);
+        } else {
+            String resource = "profiles/";
+            switch (cs_code) {
+                case ColorSpace.CS_CIEXYZ:
+                    resource += "CIEXYZ.pf";
+                    break;
+                case ColorSpace.CS_GRAY:
+                    resource += "GRAY.pf";
+                    break;
+                case ColorSpace.CS_LINEAR_RGB:
+                    resource += "LINEAR_RGB.pf";
+                    break;
+                case ColorSpace.CS_PYCC:
+                    resource += "PYCC.pf";
+                    break;
+                case ColorSpace.CS_sRGB:
+                    resource += "sRGB.pf";
+                    break;
+                default:
+                    throw new RuntimeException("Unknown color space: " + cs_code);
+            }
+
+            try {
+                InputStream is = CMMTests.class.getResourceAsStream(resource);
+                ICC_Profile p = ICC_Profile.getInstance(is);
+
+                cs = new ICC_ColorSpace(p);
+            } catch (IOException e) {
+                throw new RuntimeException("Unable load profile from resource " + resource, e);
+            }
+        }
+        return cs;
+    }
+
+    protected CMMTests(Group parent, String nodeName, String description) {
+        super(parent, nodeName, description);
+        addDependencies(cmmOptRoot, true);
+    }
+
+    @Override
+    public Object initTest(TestEnvironment te, Result result) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    @Override
+    public void runTest(Object o, int i) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    @Override
+    public void cleanupTest(TestEnvironment te, Object o) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/java2d/J2DBench/src/j2dbench/tests/cmm/ColorConversionTests.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *   - Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *
+ *   - Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ *
+ *   - Neither the name of Oracle nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+
+package j2dbench.tests.cmm;
+
+import j2dbench.Group;
+
+public class ColorConversionTests extends CMMTests {
+
+    protected static Group colorConvRoot;
+
+    public static void init() {
+        colorConvRoot = new Group(cmmRoot, "colorconv", "Color Conversion Benchmarks");
+        colorConvRoot.setTabbed();
+
+        DataConversionTests.init();
+        ColorConvertOpTests.init();
+    }
+
+    protected ColorConversionTests(Group parent, String nodeName, String description) {
+        super(parent, nodeName, description);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/java2d/J2DBench/src/j2dbench/tests/cmm/ColorConvertOpTests.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,383 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *   - Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *
+ *   - Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ *
+ *   - Neither the name of Oracle nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+
+package j2dbench.tests.cmm;
+
+import j2dbench.Group;
+import j2dbench.Option;
+import j2dbench.Result;
+import j2dbench.TestEnvironment;
+import j2dbench.tests.iio.IIOTests;
+import java.awt.AlphaComposite;
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.Image;
+import java.awt.color.ColorSpace;
+import java.awt.image.BufferedImage;
+import java.awt.image.ColorConvertOp;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import javax.imageio.ImageIO;
+
+public class ColorConvertOpTests extends ColorConversionTests {
+
+    private static enum ImageContent {
+        BLANK("bank", "Blank (opaque black)"),
+        RANDOM("random", "Random"),
+        VECTOR("vector", "Vector Art"),
+        PHOTO("photo", "Photograph");
+
+        public final String name;
+        public final String descr;
+
+        private ImageContent(String name, String descr) {
+            this.name = name;
+            this.descr = descr;
+        }
+    }
+
+    private static enum ImageType {
+        INT_ARGB(BufferedImage.TYPE_INT_ARGB, "INT_ARGB", "TYPE_INT_ARGB"),
+        INT_RGB(BufferedImage.TYPE_INT_RGB, "INT_RGB", "TYPE_INT_RGB"),
+        INT_BGR(BufferedImage.TYPE_INT_BGR, "INT_BGR", "TYPE_INT_BGR"),
+        BYTE_3BYTE_BGR(BufferedImage.TYPE_3BYTE_BGR, "3BYTE_BGR", "TYPE_3BYTE_BGR"),
+        BYTE_4BYTE_ABGR(BufferedImage.TYPE_4BYTE_ABGR, "4BYTE_BGR", "TYPE_4BYTE_BGR"),
+        COMPATIBLE_DST(0, "Compatible", "Compatible destination");
+
+        private ImageType(int type, String abbr, String descr) {
+            this.type = type;
+            this.abbrev = abbr;
+            this.descr = descr;
+        }
+
+        public final int type;
+        public final String abbrev;
+        public final String descr;
+    }
+
+    private static enum ListType {
+        SRC("srcType", "Source Images"),
+        DST("dstType", "Destination Images");
+
+        private ListType(String name, String description) {
+            this.name = name;
+            this.description = description;
+        }
+        public final String name;
+        public final String description;
+    }
+
+    public static Option createImageTypeList(ListType listType) {
+
+        ImageType[] allTypes = ImageType.values();
+
+        int num = allTypes.length;
+        if (listType == ListType.SRC) {
+            num -= 1; // exclude compatible destination
+        }
+
+        ImageType[] t = new ImageType[num];
+        String[] names = new String[num];
+        String[] abbrev = new String[num];
+        String[] descr = new String[num];
+
+        for (int i = 0; i < num; i++) {
+            t[i] = allTypes[i];
+            names[i] = t[i].toString();
+            abbrev[i] = t[i].abbrev;
+            descr[i] = t[i].descr;
+        }
+
+        Option list = new Option.ObjectList(opOptionsRoot,
+                listType.name, listType.description,
+                names, t, abbrev, descr, 1);
+        return list;
+    }
+
+    protected static Group opConvRoot;
+
+    protected static Group opOptionsRoot;
+    protected static Option sizeList;
+    protected static Option contentList;
+
+    protected static Option sourceType;
+
+    protected static Option destinationType;
+
+    public static void init() {
+        opConvRoot = new Group(colorConvRoot, "ccop", "ColorConvertOp Tests");
+
+        opOptionsRoot = new Group(opConvRoot, "ccopOptions", "Options");
+
+        // size list
+        int[] sizes = new int[] {1, 20, 250, 1000, 4000};
+        String[] sizeStrs = new String[] {
+            "1x1", "20x20", "250x250", "1000x1000", "4000x4000"
+        };
+        String[] sizeDescs = new String[] {
+            "Tiny Images (1x1)",
+            "Small Images (20x20)",
+            "Medium Images (250x250)",
+            "Large Images (1000x1000)",
+            "Huge Images (4000x4000)",
+        };
+        sizeList = new Option.IntList(opOptionsRoot,
+                                      "size", "Image Size",
+                                      sizes, sizeStrs, sizeDescs, 0x4);
+        ((Option.ObjectList) sizeList).setNumRows(5);
+
+        // image content
+        ImageContent[] c = ImageContent.values();
+
+        String[] contentStrs = new String[c.length];
+        String[] contentDescs = new String[c.length];
+
+        for (int i = 0; i < c.length; i++) {
+            contentStrs[i] = c[i].name;
+            contentDescs[i] = c[i].descr;
+        };
+
+        contentList = new Option.ObjectList(opOptionsRoot,
+                                            "content", "Image Content",
+                                            contentStrs, c,
+                                            contentStrs, contentDescs,
+                                            0x8);
+
+        sourceType = createImageTypeList(ListType.SRC);
+
+        destinationType = createImageTypeList(ListType.DST);
+
+        new ConvertImageTest();
+        new ConvertRasterTest();
+        new DrawImageTest();
+    }
+
+    public ColorConvertOpTests(Group parent, String nodeName, String description) {
+        super(parent, nodeName, description);
+        addDependencies(opOptionsRoot, true);
+    }
+
+    public Object initTest(TestEnvironment env, Result res) {
+        return new Context(env, res);
+    }
+
+    public void cleanupTest(TestEnvironment env, Object o) {
+        Context ctx = (Context)o;
+        ctx.cs = null;
+        ctx.op_img = null;
+        ctx.op_rst = null;
+        ctx.dst = null;
+        ctx.src = null;
+        ctx.graphics = null;
+    }
+
+    private static class Context {
+        ColorSpace cs;
+        Graphics2D graphics;
+        ColorConvertOp op_img;
+        ColorConvertOp op_rst;
+
+        BufferedImage src;
+        BufferedImage dst;
+
+        WritableRaster rsrc;
+        WritableRaster rdst;
+
+        public Context(TestEnvironment env, Result res) {
+
+            graphics = (Graphics2D)env.getGraphics();
+            cs = getColorSpace(env);
+
+            // TODO: provide rendering hints
+            op_img = new ColorConvertOp(cs, null);
+            ColorSpace sRGB = ColorSpace.getInstance(ColorSpace.CS_sRGB);
+            op_rst = new ColorConvertOp(sRGB, cs, null);
+
+            int size = env.getIntValue(sizeList);
+
+            ImageContent content = (ImageContent)env.getModifier(contentList);
+            ImageType srcType = (ImageType)env.getModifier(sourceType);
+
+            src = createBufferedImage(size, size, content, srcType.type);
+            rsrc = src.getRaster();
+
+            ImageType dstType = (ImageType)env.getModifier(destinationType);
+            if (dstType == ImageType.COMPATIBLE_DST) {
+                dst = op_img.createCompatibleDestImage(src, null);
+            } else {
+                dst = createBufferedImage(size, size, content, dstType.type);
+            }
+            // raster always has to be comatible
+            rdst = op_rst.createCompatibleDestRaster(rsrc);
+        }
+    }
+
+    private static class ConvertImageTest extends ColorConvertOpTests {
+        public ConvertImageTest() {
+            super(opConvRoot, "op_img", "op.filetr(BufferedImage)");
+        }
+
+        public void runTest(Object octx, int numReps) {
+            final Context ctx = (Context)octx;
+            final ColorConvertOp op = ctx.op_img;
+
+            final BufferedImage src = ctx.src;
+            BufferedImage dst = ctx.dst;
+            do {
+                try {
+                    dst = op.filter(src, dst);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+            } while (--numReps >= 0);
+        }
+    }
+
+    private static class ConvertRasterTest extends ColorConvertOpTests {
+        public ConvertRasterTest() {
+            super(opConvRoot, "op_rst", "op.filetr(Raster)");
+        }
+
+        public void runTest(Object octx, int numReps) {
+            final Context ctx = (Context)octx;
+            final ColorConvertOp op = ctx.op_rst;
+
+            final Raster src = ctx.rsrc;
+            WritableRaster dst = ctx.rdst;
+            do {
+                try {
+                    dst = op.filter(src, dst);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+            } while (--numReps >= 0);
+        }
+    }
+
+    private static class DrawImageTest extends ColorConvertOpTests {
+        public DrawImageTest() {
+            super(opConvRoot, "op_draw", "drawImage(ColorConvertOp)");
+        }
+
+        public void runTest(Object octx, int numReps) {
+            final Context ctx = (Context)octx;
+            final ColorConvertOp op = ctx.op_img;
+
+            final Graphics2D g = ctx.graphics;
+
+            final BufferedImage src = ctx.src;
+
+            do {
+                g.drawImage(src, op, 0, 0);
+            } while (--numReps >= 0);
+        }
+    }
+
+    /**************************************************************************
+     ******                    Helper routines
+     *************************************************************************/
+    protected static BufferedImage createBufferedImage(int width,
+                                                       int height,
+                                                       ImageContent contentType,
+                                                       int type)
+    {
+        BufferedImage image;
+        image = new BufferedImage(width, height, type);
+        boolean hasAlpha = image.getColorModel().hasAlpha();
+        switch (contentType) {
+            case RANDOM:
+                for (int y = 0; y < height; y++) {
+                    for (int x = 0; x < width; x++) {
+                        int rgb = (int)(Math.random() * 0xffffff);
+                        if (hasAlpha) {
+                            rgb |= 0x7f000000;
+                        }
+                        image.setRGB(x, y, rgb);
+                    }
+                }
+                break;
+            case VECTOR:
+                {
+                    Graphics2D g = image.createGraphics();
+                    if (hasAlpha) {
+                        // fill background with a translucent color
+                        g.setComposite(AlphaComposite.getInstance(
+                                           AlphaComposite.SRC, 0.5f));
+                    }
+                    g.setColor(Color.blue);
+                    g.fillRect(0, 0, width, height);
+                    g.setComposite(AlphaComposite.Src);
+                    g.setColor(Color.yellow);
+                    g.fillOval(2, 2, width-4, height-4);
+                    g.setColor(Color.red);
+                    g.fillOval(4, 4, width-8, height-8);
+                    g.setColor(Color.green);
+                    g.fillRect(8, 8, width-16, height-16);
+                    g.setColor(Color.white);
+                    g.drawLine(0, 0, width, height);
+                    g.drawLine(0, height, width, 0);
+                    g.dispose();
+                    break;
+                }
+            case PHOTO:
+                {
+                    Image photo = null;
+                    try {
+                        photo = ImageIO.read(
+                            IIOTests.class.getResourceAsStream("images/photo.jpg"));
+                    } catch (Exception e) {
+                        System.err.println("error loading photo");
+                        e.printStackTrace();
+                    }
+                    Graphics2D g = image.createGraphics();
+                    if (hasAlpha) {
+                        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC,
+                                                                  0.5f));
+                    }
+                    g.drawImage(photo, 0, 0, width, height, null);
+                    g.dispose();
+                    break;
+                }
+            default:
+                break;
+        }
+
+        return image;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/java2d/J2DBench/src/j2dbench/tests/cmm/DataConversionTests.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,198 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *   - Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *
+ *   - Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ *
+ *   - Neither the name of Oracle nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+
+package j2dbench.tests.cmm;
+
+import j2dbench.Group;
+import j2dbench.Result;
+import j2dbench.TestEnvironment;
+import java.awt.color.ColorSpace;
+
+public class DataConversionTests extends ColorConversionTests {
+
+    protected static Group dataConvRoot;
+
+    public static void init() {
+        dataConvRoot = new Group(colorConvRoot, "data", "Data Conversoion Tests");
+
+        new FromRGBTest();
+        new ToRGBTest();
+        new FromCIEXYZTest();
+        new ToCIEXYZTest();
+    }
+
+    public DataConversionTests(Group parent, String nodeName, String description) {
+        super(parent, nodeName, description);
+    }
+
+    protected static class Context {
+
+        ColorSpace cs;
+        int numComponents;
+        float[] val;
+        float[] rgb;
+        float[] cie;
+        TestEnvironment env;
+        Result res;
+
+        public Context(TestEnvironment env, Result result, ColorSpace cs) {
+            this.cs = cs;
+            this.env = env;
+            this.res = result;
+
+            numComponents = cs.getNumComponents();
+
+            val = new float[numComponents];
+
+            for (int i = 0; i < numComponents; i++) {
+                float min = cs.getMinValue(i);
+                float max = cs.getMaxValue(i);
+
+                val[i] = 0.5f * (max - min);
+            }
+
+            rgb = new float[]{0.5f, 0.5f, 0.5f};
+            cie = new float[]{0.5f, 0.5f, 0.5f};
+        }
+    }
+
+    @Override
+    public Object initTest(TestEnvironment env, Result result) {
+        ColorSpace cs = getColorSpace(env);
+        return new Context(env, result, cs);
+    }
+
+    @Override
+    public void cleanupTest(TestEnvironment te, Object o) {
+    }
+
+    private static class FromRGBTest extends DataConversionTests {
+
+        public FromRGBTest() {
+            super(dataConvRoot,
+                    "fromRGB",
+                    "ColorSpace.fromRGB()");
+        }
+
+        public void runTest(Object ctx, int numReps) {
+            final Context ictx = (Context) ctx;
+            final ColorSpace cs = ictx.cs;
+
+            final float[] rgb = ictx.rgb;
+            do {
+                try {
+                    cs.fromRGB(rgb);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+            } while (--numReps >= 0);
+        }
+    }
+
+    private static class FromCIEXYZTest extends DataConversionTests {
+
+        public FromCIEXYZTest() {
+            super(dataConvRoot,
+                    "fromCIEXYZ",
+                    "ColorSpace.fromCIEXYZ()");
+        }
+
+        public void runTest(Object ctx, int numReps) {
+            final Context ictx = (Context) ctx;
+            final ColorSpace cs = ictx.cs;
+
+            final float[] val = ictx.cie;
+            do {
+                try {
+                    cs.fromCIEXYZ(val);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+            } while (--numReps >= 0);
+        }
+    }
+
+    private static class ToCIEXYZTest extends DataConversionTests {
+
+        public ToCIEXYZTest() {
+            super(dataConvRoot,
+                    "toCIEXYZ",
+                    "ColorSpace.toCIEXYZ()");
+        }
+
+        public void runTest(Object ctx, int numReps) {
+            final Context ictx = (Context) ctx;
+            final ColorSpace cs = ictx.cs;
+
+            final float[] val = ictx.val;
+
+            do {
+                try {
+                    cs.toCIEXYZ(val);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+            } while (--numReps >= 0);
+        }
+    }
+
+    private static class ToRGBTest extends DataConversionTests {
+
+        public ToRGBTest() {
+            super(dataConvRoot,
+                    "toRGB",
+                    "ColorSpace.toRGB()");
+        }
+
+        public void runTest(Object ctx, int numReps) {
+            final Context ictx = (Context) ctx;
+            final ColorSpace cs = ictx.cs;
+
+            final float[] val = ictx.val;
+
+            do {
+                try {
+                    cs.toRGB(val);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+            } while (--numReps >= 0);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/java2d/J2DBench/src/j2dbench/tests/cmm/ProfileTests.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *   - Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *
+ *   - Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ *
+ *   - Neither the name of Oracle nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+package j2dbench.tests.cmm;
+
+import j2dbench.Group;
+import j2dbench.Result;
+import j2dbench.TestEnvironment;
+import java.awt.color.ColorSpace;
+import java.awt.color.ICC_ColorSpace;
+import java.awt.color.ICC_Profile;
+
+public class ProfileTests extends CMMTests {
+
+    protected static Group profileRoot;
+
+    public static void init() {
+        profileRoot = new Group(cmmRoot, "profiles", "Profile Handling Benchmarks");
+
+        new ReadHeaderTest();
+        new GetNumComponentsTest();
+    }
+
+    protected ProfileTests(Group parent, String nodeName, String description) {
+        super(parent, nodeName, description);
+    }
+
+    protected static class Context {
+
+        ICC_Profile profile;
+        TestEnvironment env;
+        Result res;
+
+        public Context(ICC_Profile profile, TestEnvironment env, Result res) {
+            this.profile = profile;
+            this.env = env;
+            this.res = res;
+        }
+    }
+
+    @Override
+    public Object initTest(TestEnvironment env, Result res) {
+        ICC_ColorSpace cs = (ICC_ColorSpace) getColorSpace(env);
+        return new Context(cs.getProfile(), env, res);
+    }
+
+    @Override
+    public void cleanupTest(TestEnvironment env, Object o) {
+    }
+
+    private static class ReadHeaderTest extends ProfileTests {
+
+        public ReadHeaderTest() {
+            super(profileRoot,
+                    "getHeader",
+                    "getData(icSigHead)");
+        }
+
+        @Override
+        public void runTest(Object ctx, int numReps) {
+            final Context ictx = (Context) ctx;
+            final ICC_Profile profile = ictx.profile;
+
+            byte[] data = null;
+            do {
+                try {
+                    data = profile.getData(ICC_Profile.icSigHead);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+            } while (--numReps >= 0);
+        }
+    }
+
+    private static class GetNumComponentsTest extends ProfileTests {
+
+        public GetNumComponentsTest() {
+            super(profileRoot,
+                    "getNumComponents",
+                    "getNumComponents");
+        }
+
+        @Override
+        public void runTest(Object ctx, int numReps) {
+            final Context ictx = (Context) ctx;
+            final ICC_Profile profile = ictx.profile;
+
+            do {
+                try {
+                    int num = profile.getNumComponents();
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+            } while (--numReps >= 0);
+        }
+    }
+}
--- a/jdk/src/share/demo/jfc/CodePointIM/CodePointInputMethod.java	Tue Jan 22 14:27:41 2013 -0500
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,499 +0,0 @@
-/*
- * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- *   - Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- *
- *   - Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- *
- *   - Neither the name of Oracle nor the names of its
- *     contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-package com.sun.inputmethods.internal.codepointim;
-
-
-import java.awt.AWTEvent;
-import java.awt.Toolkit;
-import java.awt.Rectangle;
-import java.awt.event.InputMethodEvent;
-import java.awt.event.KeyEvent;
-import java.awt.font.TextAttribute;
-import java.awt.font.TextHitInfo;
-import java.awt.im.InputMethodHighlight;
-import java.awt.im.spi.InputMethod;
-import java.awt.im.spi.InputMethodContext;
-import java.io.IOException;
-import java.text.AttributedString;
-import java.util.Locale;
-
-
-/**
- * The Code Point Input Method is a simple input method that allows Unicode
- * characters to be entered using their code point or code unit values. See the
- * accompanying file README.txt for more information.
- *
- * @author Brian Beck
- */
-public class CodePointInputMethod implements InputMethod {
-
-    private static final int UNSET = 0;
-    private static final int ESCAPE = 1; // \u0000       - \uFFFF
-    private static final int SPECIAL_ESCAPE = 2; // \U000000     - \U10FFFF
-    private static final int SURROGATE_PAIR = 3; // \uD800\uDC00 - \uDBFF\uDFFF
-    private InputMethodContext context;
-    private Locale locale;
-    private StringBuffer buffer;
-    private int insertionPoint;
-    private int format = UNSET;
-
-    public CodePointInputMethod() throws IOException {
-    }
-
-    /**
-     * This is the input method's main routine.  The composed text is stored
-     * in buffer.
-     */
-    public void dispatchEvent(AWTEvent event) {
-        // This input method handles KeyEvent only.
-        if (!(event instanceof KeyEvent)) {
-            return;
-        }
-
-        KeyEvent e = (KeyEvent) event;
-        int eventID = event.getID();
-        boolean notInCompositionMode = buffer.length() == 0;
-
-        if (eventID == KeyEvent.KEY_PRESSED) {
-            // If we are not in composition mode, pass through
-            if (notInCompositionMode) {
-                return;
-            }
-
-            switch (e.getKeyCode()) {
-                case KeyEvent.VK_LEFT:
-                    moveCaretLeft();
-                    break;
-                case KeyEvent.VK_RIGHT:
-                    moveCaretRight();
-                    break;
-            }
-        } else if (eventID == KeyEvent.KEY_TYPED) {
-            char c = e.getKeyChar();
-
-            // If we are not in composition mode, wait a back slash
-            if (notInCompositionMode) {
-                // If the type character is not a back slash, pass through
-                if (c != '\\') {
-                    return;
-                }
-
-                startComposition();     // Enter to composition mode
-            } else {
-                switch (c) {
-                    case ' ':       // Exit from composition mode
-                        finishComposition();
-                        break;
-                    case '\u007f':  // Delete
-                        deleteCharacter();
-                        break;
-                    case '\b':      // BackSpace
-                        deletePreviousCharacter();
-                        break;
-                    case '\u001b':  // Escape
-                        cancelComposition();
-                        break;
-                    case '\n':      // Return
-                    case '\t':      // Tab
-                        sendCommittedText();
-                        break;
-                    default:
-                        composeUnicodeEscape(c);
-                        break;
-                }
-            }
-        } else {  // KeyEvent.KEY_RELEASED
-            // If we are not in composition mode, pass through
-            if (notInCompositionMode) {
-                return;
-            }
-        }
-
-        e.consume();
-    }
-
-    private void composeUnicodeEscape(char c) {
-        switch (buffer.length()) {
-            case 1:  // \\
-                waitEscapeCharacter(c);
-                break;
-            case 2:  // \\u or \\U
-            case 3:  // \\ux or \\Ux
-            case 4:  // \\uxx or \\Uxx
-                waitDigit(c);
-                break;
-            case 5:  // \\uxxx or \\Uxxx
-                if (format == SPECIAL_ESCAPE) {
-                    waitDigit(c);
-                } else {
-                    waitDigit2(c);
-                }
-                break;
-            case 6:  // \\uxxxx or \\Uxxxx
-                if (format == SPECIAL_ESCAPE) {
-                    waitDigit(c);
-                } else if (format == SURROGATE_PAIR) {
-                    waitBackSlashOrLowSurrogate(c);
-                } else {
-                    beep();
-                }
-                break;
-            case 7:  // \\Uxxxxx
-                // Only SPECIAL_ESCAPE format uses this state.
-                // Since the second "\\u" of SURROGATE_PAIR format is inserted
-                // automatically, users don't have to type these keys.
-                waitDigit(c);
-                break;
-            case 8:  // \\uxxxx\\u
-            case 9:  // \\uxxxx\\ux
-            case 10: // \\uxxxx\\uxx
-            case 11: // \\uxxxx\\uxxx
-                if (format == SURROGATE_PAIR) {
-                    waitDigit(c);
-                } else {
-                    beep();
-                }
-                break;
-            default:
-                beep();
-                break;
-        }
-    }
-
-    private void waitEscapeCharacter(char c) {
-        if (c == 'u' || c == 'U') {
-            buffer.append(c);
-            insertionPoint++;
-            sendComposedText();
-            format = (c == 'u') ? ESCAPE : SPECIAL_ESCAPE;
-        } else {
-            if (c != '\\') {
-                buffer.append(c);
-                insertionPoint++;
-            }
-            sendCommittedText();
-        }
-    }
-
-    private void waitDigit(char c) {
-        if (Character.digit(c, 16) != -1) {
-            buffer.insert(insertionPoint++, c);
-            sendComposedText();
-        } else {
-            beep();
-        }
-    }
-
-    private void waitDigit2(char c) {
-        if (Character.digit(c, 16) != -1) {
-            buffer.insert(insertionPoint++, c);
-            char codePoint = (char) getCodePoint(buffer, 2, 5);
-            if (Character.isHighSurrogate(codePoint)) {
-                format = SURROGATE_PAIR;
-                buffer.append("\\u");
-                insertionPoint = 8;
-            } else {
-                format = ESCAPE;
-            }
-            sendComposedText();
-        } else {
-            beep();
-        }
-    }
-
-    private void waitBackSlashOrLowSurrogate(char c) {
-        if (insertionPoint == 6) {
-            if (c == '\\') {
-                buffer.append(c);
-                buffer.append('u');
-                insertionPoint = 8;
-                sendComposedText();
-            } else if (Character.digit(c, 16) != -1) {
-                buffer.append("\\u");
-                buffer.append(c);
-                insertionPoint = 9;
-                sendComposedText();
-            } else {
-                beep();
-            }
-        } else {
-            beep();
-        }
-    }
-
-    /**
-     * Send the composed text to the client.
-     */
-    private void sendComposedText() {
-        AttributedString as = new AttributedString(buffer.toString());
-        as.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT,
-                InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT);
-        context.dispatchInputMethodEvent(
-                InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
-                as.getIterator(), 0,
-                TextHitInfo.leading(insertionPoint), null);
-    }
-
-    /**
-     * Send the committed text to the client.
-     */
-    private void sendCommittedText() {
-        AttributedString as = new AttributedString(buffer.toString());
-        context.dispatchInputMethodEvent(
-                InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
-                as.getIterator(), buffer.length(),
-                TextHitInfo.leading(insertionPoint), null);
-
-        buffer.setLength(0);
-        insertionPoint = 0;
-        format = UNSET;
-    }
-
-    /**
-     * Move the insertion point one position to the left in the composed text.
-     * Do not let the caret move to the left of the "\\u" or "\\U".
-     */
-    private void moveCaretLeft() {
-        int len = buffer.length();
-        if (--insertionPoint < 2) {
-            insertionPoint++;
-            beep();
-        } else if (format == SURROGATE_PAIR && insertionPoint == 7) {
-            insertionPoint = 8;
-            beep();
-        }
-
-        context.dispatchInputMethodEvent(
-                InputMethodEvent.CARET_POSITION_CHANGED,
-                null, 0,
-                TextHitInfo.leading(insertionPoint), null);
-    }
-
-    /**
-     * Move the insertion point one position to the right in the composed text.
-     */
-    private void moveCaretRight() {
-        int len = buffer.length();
-        if (++insertionPoint > len) {
-            insertionPoint = len;
-            beep();
-        }
-
-        context.dispatchInputMethodEvent(
-                InputMethodEvent.CARET_POSITION_CHANGED,
-                null, 0,
-                TextHitInfo.leading(insertionPoint), null);
-    }
-
-    /**
-     * Delete the character preceding the insertion point in the composed text.
-     * If the insertion point is not at the end of the composed text and the
-     * preceding text is "\\u" or "\\U", ring the bell.
-     */
-    private void deletePreviousCharacter() {
-        if (insertionPoint == 2) {
-            if (buffer.length() == 2) {
-                cancelComposition();
-            } else {
-                // Do not allow deletion of the leading "\\u" or "\\U" if there
-                // are other digits in the composed text.
-                beep();
-            }
-        } else if (insertionPoint == 8) {
-            if (buffer.length() == 8) {
-                if (format == SURROGATE_PAIR) {
-                    buffer.deleteCharAt(--insertionPoint);
-                }
-                buffer.deleteCharAt(--insertionPoint);
-                sendComposedText();
-            } else {
-                // Do not allow deletion of the second "\\u" if there are other
-                // digits in the composed text.
-                beep();
-            }
-        } else {
-            buffer.deleteCharAt(--insertionPoint);
-            if (buffer.length() == 0) {
-                sendCommittedText();
-            } else {
-                sendComposedText();
-            }
-        }
-    }
-
-    /**
-     * Delete the character following the insertion point in the composed text.
-     * If the insertion point is at the end of the composed text, ring the bell.
-     */
-    private void deleteCharacter() {
-        if (insertionPoint < buffer.length()) {
-            buffer.deleteCharAt(insertionPoint);
-            sendComposedText();
-        } else {
-            beep();
-        }
-    }
-
-    private void startComposition() {
-        buffer.append('\\');
-        insertionPoint = 1;
-        sendComposedText();
-    }
-
-    private void cancelComposition() {
-        buffer.setLength(0);
-        insertionPoint = 0;
-        sendCommittedText();
-    }
-
-    private void finishComposition() {
-        int len = buffer.length();
-        if (len == 6 && format != SPECIAL_ESCAPE) {
-            char codePoint = (char) getCodePoint(buffer, 2, 5);
-            if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) {
-                buffer.setLength(0);
-                buffer.append(codePoint);
-                sendCommittedText();
-                return;
-            }
-        } else if (len == 8 && format == SPECIAL_ESCAPE) {
-            int codePoint = getCodePoint(buffer, 2, 7);
-            if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) {
-                buffer.setLength(0);
-                buffer.appendCodePoint(codePoint);
-                sendCommittedText();
-                return;
-            }
-        } else if (len == 12 && format == SURROGATE_PAIR) {
-            char[] codePoint = {
-                (char) getCodePoint(buffer, 2, 5),
-                (char) getCodePoint(buffer, 8, 11)
-            };
-            if (Character.isHighSurrogate(codePoint[0]) && Character.
-                    isLowSurrogate(codePoint[1])) {
-                buffer.setLength(0);
-                buffer.append(codePoint);
-                sendCommittedText();
-                return;
-            }
-        }
-
-        beep();
-    }
-
-    private int getCodePoint(StringBuffer sb, int from, int to) {
-        int value = 0;
-        for (int i = from; i <= to; i++) {
-            value = (value << 4) + Character.digit(sb.charAt(i), 16);
-        }
-        return value;
-    }
-
-    private static void beep() {
-        Toolkit.getDefaultToolkit().beep();
-    }
-
-    public void activate() {
-        if (buffer == null) {
-            buffer = new StringBuffer(12);
-            insertionPoint = 0;
-        }
-    }
-
-    public void deactivate(boolean isTemporary) {
-        if (!isTemporary) {
-            buffer = null;
-        }
-    }
-
-    public void dispose() {
-    }
-
-    public Object getControlObject() {
-        return null;
-    }
-
-    public void endComposition() {
-        sendCommittedText();
-    }
-
-    public Locale getLocale() {
-        return locale;
-    }
-
-    public void hideWindows() {
-    }
-
-    public boolean isCompositionEnabled() {
-        // always enabled
-        return true;
-    }
-
-    public void notifyClientWindowChange(Rectangle location) {
-    }
-
-    public void reconvert() {
-        // not supported yet
-        throw new UnsupportedOperationException();
-    }
-
-    public void removeNotify() {
-    }
-
-    public void setCharacterSubsets(Character.Subset[] subsets) {
-    }
-
-    public void setCompositionEnabled(boolean enable) {
-        // not supported yet
-        throw new UnsupportedOperationException();
-    }
-
-    public void setInputMethodContext(InputMethodContext context) {
-        this.context = context;
-    }
-
-    /*
-     * The Code Point Input Method supports all locales.
-     */
-    public boolean setLocale(Locale locale) {
-        this.locale = locale;
-        return true;
-    }
-}
--- a/jdk/src/share/demo/jfc/CodePointIM/CodePointInputMethodDescriptor.java	Tue Jan 22 14:27:41 2013 -0500
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,94 +0,0 @@
-/*
- * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- *   - Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- *
- *   - Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- *
- *   - Neither the name of Oracle nor the names of its
- *     contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-package com.sun.inputmethods.internal.codepointim;
-
-
-import java.awt.Image;
-import java.awt.im.spi.InputMethodDescriptor;
-import java.awt.im.spi.InputMethod;
-import java.util.Locale;
-
-
-/**
- * The CodePointInputMethod is a simple input method that allows Unicode
- * characters to be entered via their hexadecimal code point values.
- *
- * The class, CodePointInputMethodDescriptor, provides information about the
- * CodePointInputMethod which allows it to be selected and loaded by the
- * Input Method Framework.
- */
-public class CodePointInputMethodDescriptor implements InputMethodDescriptor {
-
-    public CodePointInputMethodDescriptor() {
-    }
-
-    /**
-     * Creates a new instance of the Code Point input method.
-     *
-     * @return a new instance of the Code Point input method
-     * @exception Exception any exception that may occur while creating the
-     * input method instance
-     */
-    public InputMethod createInputMethod() throws Exception {
-        return new CodePointInputMethod();
-    }
-
-    /**
-     * This input method can be used by any locale.
-     */
-    public Locale[] getAvailableLocales() {
-        Locale[] locales = {
-            new Locale("", "", ""), };
-        return locales;
-    }
-
-    public synchronized String getInputMethodDisplayName(Locale inputLocale,
-            Locale displayLanguage) {
-        return "CodePoint Input Method";
-    }
-
-    public Image getInputMethodIcon(Locale inputLocale) {
-        return null;
-    }
-
-    public boolean hasDynamicLocaleList() {
-        return false;
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/jfc/CodePointIM/com/sun/inputmethods/internal/codepointim/CodePointInputMethod.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,499 @@
+/*
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *   - Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *
+ *   - Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ *
+ *   - Neither the name of Oracle nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+
+package com.sun.inputmethods.internal.codepointim;
+
+
+import java.awt.AWTEvent;
+import java.awt.Toolkit;
+import java.awt.Rectangle;
+import java.awt.event.InputMethodEvent;
+import java.awt.event.KeyEvent;
+import java.awt.font.TextAttribute;
+import java.awt.font.TextHitInfo;
+import java.awt.im.InputMethodHighlight;
+import java.awt.im.spi.InputMethod;
+import java.awt.im.spi.InputMethodContext;
+import java.io.IOException;
+import java.text.AttributedString;
+import java.util.Locale;
+
+
+/**
+ * The Code Point Input Method is a simple input method that allows Unicode
+ * characters to be entered using their code point or code unit values. See the
+ * accompanying file README.txt for more information.
+ *
+ * @author Brian Beck
+ */
+public class CodePointInputMethod implements InputMethod {
+
+    private static final int UNSET = 0;
+    private static final int ESCAPE = 1; // \u0000       - \uFFFF
+    private static final int SPECIAL_ESCAPE = 2; // \U000000     - \U10FFFF
+    private static final int SURROGATE_PAIR = 3; // \uD800\uDC00 - \uDBFF\uDFFF
+    private InputMethodContext context;
+    private Locale locale;
+    private StringBuffer buffer;
+    private int insertionPoint;
+    private int format = UNSET;
+
+    public CodePointInputMethod() throws IOException {
+    }
+
+    /**
+     * This is the input method's main routine.  The composed text is stored
+     * in buffer.
+     */
+    public void dispatchEvent(AWTEvent event) {
+        // This input method handles KeyEvent only.
+        if (!(event instanceof KeyEvent)) {
+            return;
+        }
+
+        KeyEvent e = (KeyEvent) event;
+        int eventID = event.getID();
+        boolean notInCompositionMode = buffer.length() == 0;
+
+        if (eventID == KeyEvent.KEY_PRESSED) {
+            // If we are not in composition mode, pass through
+            if (notInCompositionMode) {
+                return;
+            }
+
+            switch (e.getKeyCode()) {
+                case KeyEvent.VK_LEFT:
+                    moveCaretLeft();
+                    break;
+                case KeyEvent.VK_RIGHT:
+                    moveCaretRight();
+                    break;
+            }
+        } else if (eventID == KeyEvent.KEY_TYPED) {
+            char c = e.getKeyChar();
+
+            // If we are not in composition mode, wait a back slash
+            if (notInCompositionMode) {
+                // If the type character is not a back slash, pass through
+                if (c != '\\') {
+                    return;
+                }
+
+                startComposition();     // Enter to composition mode
+            } else {
+                switch (c) {
+                    case ' ':       // Exit from composition mode
+                        finishComposition();
+                        break;
+                    case '\u007f':  // Delete
+                        deleteCharacter();
+                        break;
+                    case '\b':      // BackSpace
+                        deletePreviousCharacter();
+                        break;
+                    case '\u001b':  // Escape
+                        cancelComposition();
+                        break;
+                    case '\n':      // Return
+                    case '\t':      // Tab
+                        sendCommittedText();
+                        break;
+                    default:
+                        composeUnicodeEscape(c);
+                        break;
+                }
+            }
+        } else {  // KeyEvent.KEY_RELEASED
+            // If we are not in composition mode, pass through
+            if (notInCompositionMode) {
+                return;
+            }
+        }
+
+        e.consume();
+    }
+
+    private void composeUnicodeEscape(char c) {
+        switch (buffer.length()) {
+            case 1:  // \\
+                waitEscapeCharacter(c);
+                break;
+            case 2:  // \\u or \\U
+            case 3:  // \\ux or \\Ux
+            case 4:  // \\uxx or \\Uxx
+                waitDigit(c);
+                break;
+            case 5:  // \\uxxx or \\Uxxx
+                if (format == SPECIAL_ESCAPE) {
+                    waitDigit(c);
+                } else {
+                    waitDigit2(c);
+                }
+                break;
+            case 6:  // \\uxxxx or \\Uxxxx
+                if (format == SPECIAL_ESCAPE) {
+                    waitDigit(c);
+                } else if (format == SURROGATE_PAIR) {
+                    waitBackSlashOrLowSurrogate(c);
+                } else {
+                    beep();
+                }
+                break;
+            case 7:  // \\Uxxxxx
+                // Only SPECIAL_ESCAPE format uses this state.
+                // Since the second "\\u" of SURROGATE_PAIR format is inserted
+                // automatically, users don't have to type these keys.
+                waitDigit(c);
+                break;
+            case 8:  // \\uxxxx\\u
+            case 9:  // \\uxxxx\\ux
+            case 10: // \\uxxxx\\uxx
+            case 11: // \\uxxxx\\uxxx
+                if (format == SURROGATE_PAIR) {
+                    waitDigit(c);
+                } else {
+                    beep();
+                }
+                break;
+            default:
+                beep();
+                break;
+        }
+    }
+
+    private void waitEscapeCharacter(char c) {
+        if (c == 'u' || c == 'U') {
+            buffer.append(c);
+            insertionPoint++;
+            sendComposedText();
+            format = (c == 'u') ? ESCAPE : SPECIAL_ESCAPE;
+        } else {
+            if (c != '\\') {
+                buffer.append(c);
+                insertionPoint++;
+            }
+            sendCommittedText();
+        }
+    }
+
+    private void waitDigit(char c) {
+        if (Character.digit(c, 16) != -1) {
+            buffer.insert(insertionPoint++, c);
+            sendComposedText();
+        } else {
+            beep();
+        }
+    }
+
+    private void waitDigit2(char c) {
+        if (Character.digit(c, 16) != -1) {
+            buffer.insert(insertionPoint++, c);
+            char codePoint = (char) getCodePoint(buffer, 2, 5);
+            if (Character.isHighSurrogate(codePoint)) {
+                format = SURROGATE_PAIR;
+                buffer.append("\\u");
+                insertionPoint = 8;
+            } else {
+                format = ESCAPE;
+            }
+            sendComposedText();
+        } else {
+            beep();
+        }
+    }
+
+    private void waitBackSlashOrLowSurrogate(char c) {
+        if (insertionPoint == 6) {
+            if (c == '\\') {
+                buffer.append(c);
+                buffer.append('u');
+                insertionPoint = 8;
+                sendComposedText();
+            } else if (Character.digit(c, 16) != -1) {
+                buffer.append("\\u");
+                buffer.append(c);
+                insertionPoint = 9;
+                sendComposedText();
+            } else {
+                beep();
+            }
+        } else {
+            beep();
+        }
+    }
+
+    /**
+     * Send the composed text to the client.
+     */
+    private void sendComposedText() {
+        AttributedString as = new AttributedString(buffer.toString());
+        as.addAttribute(TextAttribute.INPUT_METHOD_HIGHLIGHT,
+                InputMethodHighlight.SELECTED_RAW_TEXT_HIGHLIGHT);
+        context.dispatchInputMethodEvent(
+                InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
+                as.getIterator(), 0,
+                TextHitInfo.leading(insertionPoint), null);
+    }
+
+    /**
+     * Send the committed text to the client.
+     */
+    private void sendCommittedText() {
+        AttributedString as = new AttributedString(buffer.toString());
+        context.dispatchInputMethodEvent(
+                InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
+                as.getIterator(), buffer.length(),
+                TextHitInfo.leading(insertionPoint), null);
+
+        buffer.setLength(0);
+        insertionPoint = 0;
+        format = UNSET;
+    }
+
+    /**
+     * Move the insertion point one position to the left in the composed text.
+     * Do not let the caret move to the left of the "\\u" or "\\U".
+     */
+    private void moveCaretLeft() {
+        int len = buffer.length();
+        if (--insertionPoint < 2) {
+            insertionPoint++;
+            beep();
+        } else if (format == SURROGATE_PAIR && insertionPoint == 7) {
+            insertionPoint = 8;
+            beep();
+        }
+
+        context.dispatchInputMethodEvent(
+                InputMethodEvent.CARET_POSITION_CHANGED,
+                null, 0,
+                TextHitInfo.leading(insertionPoint), null);
+    }
+
+    /**
+     * Move the insertion point one position to the right in the composed text.
+     */
+    private void moveCaretRight() {
+        int len = buffer.length();
+        if (++insertionPoint > len) {
+            insertionPoint = len;
+            beep();
+        }
+
+        context.dispatchInputMethodEvent(
+                InputMethodEvent.CARET_POSITION_CHANGED,
+                null, 0,
+                TextHitInfo.leading(insertionPoint), null);
+    }
+
+    /**
+     * Delete the character preceding the insertion point in the composed text.
+     * If the insertion point is not at the end of the composed text and the
+     * preceding text is "\\u" or "\\U", ring the bell.
+     */
+    private void deletePreviousCharacter() {
+        if (insertionPoint == 2) {
+            if (buffer.length() == 2) {
+                cancelComposition();
+            } else {
+                // Do not allow deletion of the leading "\\u" or "\\U" if there
+                // are other digits in the composed text.
+                beep();
+            }
+        } else if (insertionPoint == 8) {
+            if (buffer.length() == 8) {
+                if (format == SURROGATE_PAIR) {
+                    buffer.deleteCharAt(--insertionPoint);
+                }
+                buffer.deleteCharAt(--insertionPoint);
+                sendComposedText();
+            } else {
+                // Do not allow deletion of the second "\\u" if there are other
+                // digits in the composed text.
+                beep();
+            }
+        } else {
+            buffer.deleteCharAt(--insertionPoint);
+            if (buffer.length() == 0) {
+                sendCommittedText();
+            } else {
+                sendComposedText();
+            }
+        }
+    }
+
+    /**
+     * Delete the character following the insertion point in the composed text.
+     * If the insertion point is at the end of the composed text, ring the bell.
+     */
+    private void deleteCharacter() {
+        if (insertionPoint < buffer.length()) {
+            buffer.deleteCharAt(insertionPoint);
+            sendComposedText();
+        } else {
+            beep();
+        }
+    }
+
+    private void startComposition() {
+        buffer.append('\\');
+        insertionPoint = 1;
+        sendComposedText();
+    }
+
+    private void cancelComposition() {
+        buffer.setLength(0);
+        insertionPoint = 0;
+        sendCommittedText();
+    }
+
+    private void finishComposition() {
+        int len = buffer.length();
+        if (len == 6 && format != SPECIAL_ESCAPE) {
+            char codePoint = (char) getCodePoint(buffer, 2, 5);
+            if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) {
+                buffer.setLength(0);
+                buffer.append(codePoint);
+                sendCommittedText();
+                return;
+            }
+        } else if (len == 8 && format == SPECIAL_ESCAPE) {
+            int codePoint = getCodePoint(buffer, 2, 7);
+            if (Character.isValidCodePoint(codePoint) && codePoint != 0xFFFF) {
+                buffer.setLength(0);
+                buffer.appendCodePoint(codePoint);
+                sendCommittedText();
+                return;
+            }
+        } else if (len == 12 && format == SURROGATE_PAIR) {
+            char[] codePoint = {
+                (char) getCodePoint(buffer, 2, 5),
+                (char) getCodePoint(buffer, 8, 11)
+            };
+            if (Character.isHighSurrogate(codePoint[0]) && Character.
+                    isLowSurrogate(codePoint[1])) {
+                buffer.setLength(0);
+                buffer.append(codePoint);
+                sendCommittedText();
+                return;
+            }
+        }
+
+        beep();
+    }
+
+    private int getCodePoint(StringBuffer sb, int from, int to) {
+        int value = 0;
+        for (int i = from; i <= to; i++) {
+            value = (value << 4) + Character.digit(sb.charAt(i), 16);
+        }
+        return value;
+    }
+
+    private static void beep() {
+        Toolkit.getDefaultToolkit().beep();
+    }
+
+    public void activate() {
+        if (buffer == null) {
+            buffer = new StringBuffer(12);
+            insertionPoint = 0;
+        }
+    }
+
+    public void deactivate(boolean isTemporary) {
+        if (!isTemporary) {
+            buffer = null;
+        }
+    }
+
+    public void dispose() {
+    }
+
+    public Object getControlObject() {
+        return null;
+    }
+
+    public void endComposition() {
+        sendCommittedText();
+    }
+
+    public Locale getLocale() {
+        return locale;
+    }
+
+    public void hideWindows() {
+    }
+
+    public boolean isCompositionEnabled() {
+        // always enabled
+        return true;
+    }
+
+    public void notifyClientWindowChange(Rectangle location) {
+    }
+
+    public void reconvert() {
+        // not supported yet
+        throw new UnsupportedOperationException();
+    }
+
+    public void removeNotify() {
+    }
+
+    public void setCharacterSubsets(Character.Subset[] subsets) {
+    }
+
+    public void setCompositionEnabled(boolean enable) {
+        // not supported yet
+        throw new UnsupportedOperationException();
+    }
+
+    public void setInputMethodContext(InputMethodContext context) {
+        this.context = context;
+    }
+
+    /*
+     * The Code Point Input Method supports all locales.
+     */
+    public boolean setLocale(Locale locale) {
+        this.locale = locale;
+        return true;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/jfc/CodePointIM/com/sun/inputmethods/internal/codepointim/CodePointInputMethodDescriptor.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *   - Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *
+ *   - Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ *
+ *   - Neither the name of Oracle nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * This source code is provided to illustrate the usage of a given feature
+ * or technique and has been deliberately simplified. Additional steps
+ * required for a production-quality application, such as security checks,
+ * input validation and proper error handling, might not be present in
+ * this sample code.
+ */
+
+package com.sun.inputmethods.internal.codepointim;
+
+
+import java.awt.Image;
+import java.awt.im.spi.InputMethodDescriptor;
+import java.awt.im.spi.InputMethod;
+import java.util.Locale;
+
+
+/**
+ * The CodePointInputMethod is a simple input method that allows Unicode
+ * characters to be entered via their hexadecimal code point values.
+ *
+ * The class, CodePointInputMethodDescriptor, provides information about the
+ * CodePointInputMethod which allows it to be selected and loaded by the
+ * Input Method Framework.
+ */
+public class CodePointInputMethodDescriptor implements InputMethodDescriptor {
+
+    public CodePointInputMethodDescriptor() {
+    }
+
+    /**
+     * Creates a new instance of the Code Point input method.
+     *
+     * @return a new instance of the Code Point input method
+     * @exception Exception any exception that may occur while creating the
+     * input method instance
+     */
+    public InputMethod createInputMethod() throws Exception {
+        return new CodePointInputMethod();
+    }
+
+    /**
+     * This input method can be used by any locale.
+     */
+    public Locale[] getAvailableLocales() {
+        Locale[] locales = {
+            new Locale("", "", ""), };
+        return locales;
+    }
+
+    public synchronized String getInputMethodDisplayName(Locale inputLocale,
+            Locale displayLanguage) {
+        return "CodePoint Input Method";
+    }
+
+    public Image getInputMethodIcon(Locale inputLocale) {
+        return null;
+    }
+
+    public boolean hasDynamicLocaleList() {
+        return false;
+    }
+}
--- a/jdk/src/share/lib/security/java.security-linux	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/lib/security/java.security-linux	Tue Jan 22 11:54:16 2013 -0800
@@ -371,7 +371,7 @@
 #   jdk.certpath.disabledAlgorithms=MD2, DSA, RSA keySize < 2048
 #
 #
-jdk.certpath.disabledAlgorithms=MD2
+jdk.certpath.disabledAlgorithms=MD2, RSA keySize < 1024
 
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
 # (SSL/TLS) processing
--- a/jdk/src/share/lib/security/java.security-macosx	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/lib/security/java.security-macosx	Tue Jan 22 11:54:16 2013 -0800
@@ -372,7 +372,7 @@
 #   jdk.certpath.disabledAlgorithms=MD2, DSA, RSA keySize < 2048
 #
 #
-jdk.certpath.disabledAlgorithms=MD2
+jdk.certpath.disabledAlgorithms=MD2, RSA keySize < 1024
 
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
 # (SSL/TLS) processing
--- a/jdk/src/share/lib/security/java.security-solaris	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/lib/security/java.security-solaris	Tue Jan 22 11:54:16 2013 -0800
@@ -373,7 +373,7 @@
 #   jdk.certpath.disabledAlgorithms=MD2, DSA, RSA keySize < 2048
 #
 #
-jdk.certpath.disabledAlgorithms=MD2
+jdk.certpath.disabledAlgorithms=MD2, RSA keySize < 1024
 
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
 # (SSL/TLS) processing
--- a/jdk/src/share/lib/security/java.security-windows	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/lib/security/java.security-windows	Tue Jan 22 11:54:16 2013 -0800
@@ -372,7 +372,7 @@
 #   jdk.certpath.disabledAlgorithms=MD2, DSA, RSA keySize < 2048
 #
 #
-jdk.certpath.disabledAlgorithms=MD2
+jdk.certpath.disabledAlgorithms=MD2, RSA keySize < 1024
 
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
 # (SSL/TLS) processing
--- a/jdk/src/share/native/java/lang/System.c	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/native/java/lang/System.c	Tue Jan 22 11:54:16 2013 -0800
@@ -389,11 +389,19 @@
         sprops->display_variant, sprops->format_variant, putID, getPropID);
     GETPROP(props, "file.encoding", jVMVal);
     if (jVMVal == NULL) {
+#ifdef MACOSX
+        /*
+         * Since sun_jnu_encoding is now hard-coded to UTF-8 on Mac, we don't
+         * want to use it to overwrite file.encoding
+         */
+        PUTPROP(props, "file.encoding", sprops->encoding);
+#else
         if (fmtdefault) {
             PUTPROP(props, "file.encoding", sprops->encoding);
         } else {
             PUTPROP(props, "file.encoding", sprops->sun_jnu_encoding);
         }
+#endif
     } else {
         (*env)->DeleteLocalRef(env, jVMVal);
     }
--- a/jdk/src/share/native/java/util/zip/zlib-1.2.5/gzlib.c	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/native/java/util/zip/zlib-1.2.5/gzlib.c	Tue Jan 22 11:54:16 2013 -0800
@@ -1,4 +1,5 @@
-/* NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+/*
+ * 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
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/LCMS.c	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/LCMS.c	Tue Jan 22 11:54:16 2013 -0800
@@ -159,7 +159,8 @@
  */
 JNIEXPORT jlong JNICALL Java_sun_java2d_cmm_lcms_LCMS_createNativeTransform
   (JNIEnv *env, jclass cls, jlongArray profileIDs, jint renderType,
-   jint inFormatter, jint outFormatter, jobject disposerRef)
+   jint inFormatter, jboolean isInIntPacked,
+   jint outFormatter, jboolean isOutIntPacked, jobject disposerRef)
 {
     cmsHPROFILE _iccArray[DF_ICC_BUF_SIZE];
     cmsHPROFILE *iccArray = &_iccArray[0];
@@ -170,6 +171,16 @@
     size = (*env)->GetArrayLength (env, profileIDs);
     ids = (*env)->GetPrimitiveArrayCritical(env, profileIDs, 0);
 
+#ifdef _LITTLE_ENDIAN
+    /* Reversing data packed into int for LE archs */
+    if (isInIntPacked) {
+        inFormatter ^= DOSWAP_SH(1);
+    }
+    if (isOutIntPacked) {
+        outFormatter ^= DOSWAP_SH(1);
+    }
+#endif
+
     if (DF_ICC_BUF_SIZE < size*2) {
         iccArray = (cmsHPROFILE*) malloc(
             size*2*sizeof(cmsHPROFILE));
@@ -567,7 +578,7 @@
   (JNIEnv *env, jclass obj, jobject trans, jobject src, jobject dst)
 {
     storeID_t sTrans;
-    int inFmt, outFmt, srcDType, dstDType;
+    int srcDType, dstDType;
     int srcOffset, srcNextRowOffset, dstOffset, dstNextRowOffset;
     int width, height, i;
     void* inputBuffer;
@@ -576,23 +587,13 @@
     char* outputRow;
     jobject srcData, dstData;
 
-    inFmt = (*env)->GetIntField (env, src, IL_pixelType_fID);
-    outFmt = (*env)->GetIntField (env, dst, IL_pixelType_fID);
     srcOffset = (*env)->GetIntField (env, src, IL_offset_fID);
     srcNextRowOffset = (*env)->GetIntField (env, src, IL_nextRowOffset_fID);
     dstOffset = (*env)->GetIntField (env, dst, IL_offset_fID);
     dstNextRowOffset = (*env)->GetIntField (env, dst, IL_nextRowOffset_fID);
     width = (*env)->GetIntField (env, src, IL_width_fID);
     height = (*env)->GetIntField (env, src, IL_height_fID);
-#ifdef _LITTLE_ENDIAN
-    /* Reversing data packed into int for LE archs */
-    if ((*env)->GetBooleanField (env, src, IL_isIntPacked_fID) == JNI_TRUE) {
-        inFmt ^= DOSWAP_SH(1);
-    }
-    if ((*env)->GetBooleanField (env, dst, IL_isIntPacked_fID) == JNI_TRUE) {
-        outFmt ^= DOSWAP_SH(1);
-    }
-#endif
+
     sTrans.j = (*env)->GetLongField (env, trans, Trans_ID_fID);
 
     if (sTrans.xf == NULL) {
--- a/jdk/src/solaris/classes/sun/awt/X11/XBaseWindow.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/solaris/classes/sun/awt/X11/XBaseWindow.java	Tue Jan 22 11:54:16 2013 -0800
@@ -994,10 +994,7 @@
             return;
         }
         int buttonState = 0;
-        final int buttonsNumber = ((SunToolkit)(Toolkit.getDefaultToolkit())).getNumberOfButtons();
-        for (int i = 0; i<buttonsNumber; i++){
-            buttonState |= (xbe.get_state() & XConstants.buttonsMask[i]);
-        }
+        buttonState = xbe.get_state() & XConstants.ALL_BUTTONS_MASK;
         switch (xev.get_type()) {
         case XConstants.ButtonPress:
             if (buttonState == 0) {
@@ -1034,12 +1031,12 @@
      * Checks ButtonRelease released all Mouse buttons
      */
     static boolean isFullRelease(int buttonState, int button) {
-        final int buttonsNumber = ((SunToolkit)(Toolkit.getDefaultToolkit())).getNumberOfButtons();
+        final int buttonsNumber = XToolkit.getNumberOfButtonsForMask();
 
         if (button < 0 || button > buttonsNumber) {
             return buttonState == 0;
         } else {
-            return buttonState == XConstants.buttonsMask[button - 1];
+            return buttonState == XlibUtil.getButtonMask(button);
         }
     }
 
--- a/jdk/src/solaris/classes/sun/awt/X11/XConstants.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/solaris/classes/sun/awt/X11/XConstants.java	Tue Jan 22 11:54:16 2013 -0800
@@ -130,6 +130,9 @@
     public static final long ColormapChangeMask = (1L<<23) ;
     public static final long OwnerGrabButtonMask = (1L<<24) ;
 
+    public static final int MAX_BUTTONS = 5;
+    public static final int ALL_BUTTONS_MASK = (int) (Button1MotionMask | Button2MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask);
+
     /* Event names.  Used in "type" field in XEvent structures.  Not to be
     confused with event masks above.  They start from 2 because 0 and 1
     are reserved in the protocol for errors and replies. */
@@ -194,34 +197,6 @@
     public static final int Mod4MapIndex = 6 ;
     public static final int Mod5MapIndex = 7 ;
 
-
-    /* button masks.  Used in same manner as Key masks above. Not to be confused
-       with button names below. */
-    public static final int [] buttonsMask = new int []{ 1<<8,
-                                                         1<<9,
-                                                         1<<10,
-                                                         1<<11,
-                                                         1<<12,
-                                                         1<<13,
-                                                         1<<14,
-                                                         1<<15,
-                                                         1<<16,
-                                                         1<<17,
-                                                         1<<18,
-                                                         1<<19,
-                                                         1<<20,
-                                                         1<<21,
-                                                         1<<22,
-                                                         1<<23,
-                                                         1<<24,
-                                                         1<<25,
-                                                         1<<26,
-                                                         1<<27,
-                                                         1<<28,
-                                                         1<<29,
-                                                         1<<30,
-                                                         1<<31 };
-
     public static final int AnyModifier = (1<<15) ; /* used in GrabButton, GrabKey */
 
 
--- a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1543,6 +1543,10 @@
         }
     }
 
+    static int getNumberOfButtonsForMask() {
+        return Math.min(XConstants.MAX_BUTTONS, ((SunToolkit) (Toolkit.getDefaultToolkit())).getNumberOfButtons());
+    }
+
     private final static String prefix  = "DnD.Cursor.";
     private final static String postfix = ".32x32";
     private static final String dndPrefix  = "DnD.";
--- a/jdk/src/solaris/classes/sun/awt/X11/XWindow.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/solaris/classes/sun/awt/X11/XWindow.java	Tue Jan 22 11:54:16 2013 -0800
@@ -596,12 +596,12 @@
         /* this is an attempt to refactor button IDs in : MouseEvent, InputEvent, XlibWrapper and XWindow.*/
 
         //reflects a button number similar to MouseEvent.BUTTON1, 2, 3 etc.
-        for (int i = 0; i < XConstants.buttonsMask.length; i ++){
+        for (int i = 0; i < XConstants.buttons.length; i ++){
             //modifier should be added if :
             // 1) current button is now still in PRESSED state (means that user just pressed mouse but not released yet) or
             // 2) if Xsystem reports that "state" represents that button was just released. This only happens on RELEASE with 1,2,3 buttons.
             // ONLY one of these conditions should be TRUE to add that modifier.
-            if (((state & XConstants.buttonsMask[i]) != 0) != (button == XConstants.buttons[i])){
+            if (((state & XlibUtil.getButtonMask(i + 1)) != 0) != (button == XConstants.buttons[i])){
                 //exclude wheel buttons from adding their numbers as modifiers
                 if (!wheel_mouse) {
                     modifiers |= InputEvent.getMaskForButton(i+1);
@@ -689,7 +689,7 @@
 
         if (type == XConstants.ButtonPress) {
             //Allow this mouse button to generate CLICK event on next ButtonRelease
-            mouseButtonClickAllowed |= XConstants.buttonsMask[lbutton];
+            mouseButtonClickAllowed |= XlibUtil.getButtonMask(lbutton);
             XWindow lastWindow = (lastWindowRef != null) ? ((XWindow)lastWindowRef.get()):(null);
             /*
                multiclick checking
@@ -747,7 +747,7 @@
             postEventToEventQueue(me);
 
             if ((type == XConstants.ButtonRelease) &&
-                ((mouseButtonClickAllowed & XConstants.buttonsMask[lbutton]) != 0) ) // No up-button in the drag-state
+                ((mouseButtonClickAllowed & XlibUtil.getButtonMask(lbutton)) != 0) ) // No up-button in the drag-state
             {
                 postEventToEventQueue(me = new MouseEvent((Component)getEventSource(),
                                                      MouseEvent.MOUSE_CLICKED,
@@ -777,7 +777,7 @@
         /* Update the state variable AFTER the CLICKED event post. */
         if (type == XConstants.ButtonRelease) {
             /* Exclude this mouse button from allowed list.*/
-            mouseButtonClickAllowed &= ~XConstants.buttonsMask[lbutton];
+            mouseButtonClickAllowed &= ~ XlibUtil.getButtonMask(lbutton);
         }
     }
 
@@ -793,12 +793,12 @@
         //this doesn't work for extra buttons because Xsystem is sending state==0 for every extra button event.
         // we can't correct it in MouseEvent class as we done it with modifiers, because exact type (DRAG|MOVE)
         // should be passed from XWindow.
-        final int buttonsNumber = ((SunToolkit)(Toolkit.getDefaultToolkit())).getNumberOfButtons();
+        final int buttonsNumber = XToolkit.getNumberOfButtonsForMask();
 
         for (int i = 0; i < buttonsNumber; i++){
             // TODO : here is the bug in WM: extra buttons doesn't have state!=0 as they should.
             if ((i != 4) && (i != 5)) {
-                mouseKeyState = mouseKeyState | (xme.get_state() & XConstants.buttonsMask[i]);
+                mouseKeyState = mouseKeyState | (xme.get_state() & XlibUtil.getButtonMask(i + 1));
             }
         }
 
--- a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java	Tue Jan 22 11:54:16 2013 -0800
@@ -2070,12 +2070,12 @@
         }
         if (isGrabbed()) {
             boolean dragging = false;
-            final int buttonsNumber = ((SunToolkit)(Toolkit.getDefaultToolkit())).getNumberOfButtons();
+            final int buttonsNumber = XToolkit.getNumberOfButtonsForMask();
 
             for (int i = 0; i < buttonsNumber; i++){
                 // here is the bug in WM: extra buttons doesn't have state!=0 as they should.
                 if ((i != 4) && (i != 5)){
-                    dragging = dragging || ((xme.get_state() & XConstants.buttonsMask[i]) != 0);
+                    dragging = dragging || ((xme.get_state() & XlibUtil.getButtonMask(i + 1)) != 0);
                 }
             }
             // When window is grabbed, all events are dispatched to
--- a/jdk/src/solaris/classes/sun/awt/X11/XlibUtil.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/solaris/classes/sun/awt/X11/XlibUtil.java	Tue Jan 22 11:54:16 2013 -0800
@@ -396,4 +396,14 @@
         return isShapingSupported.booleanValue();
     }
 
+    static int getButtonMask(int button) {
+        // Button indices start with 1. The first bit in the button mask is the 8th.
+        // The state mask does not support button indicies > 5, so we need to
+        // cut there.
+        if (button <= 0 || button > XConstants.MAX_BUTTONS) {
+            return 0;
+        } else {
+            return 1 << (7 + button);
+        }
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/solaris/classes/sun/awt/X11/generator/sizes.32	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,1016 @@
+long	4
+int	4
+short	2
+ptr	4
+Bool	4
+Atom	4
+Window	4
+XExtData.number	0
+XExtData.next	4
+XExtData.free_private	8
+XExtData.private_data	12
+XExtData	16
+XIMStringConversionCallbackStruct.position	0
+XIMStringConversionCallbackStruct.direction	4
+XIMStringConversionCallbackStruct.operation	8
+XIMStringConversionCallbackStruct.factor	10
+XIMStringConversionCallbackStruct.text	12
+XIMStringConversionCallbackStruct	16
+XkbNewKeyboardNotifyEvent.type	0
+XkbNewKeyboardNotifyEvent.serial	4
+XkbNewKeyboardNotifyEvent.send_event	8
+XkbNewKeyboardNotifyEvent.display	12
+XkbNewKeyboardNotifyEvent.time	16
+XkbNewKeyboardNotifyEvent.xkb_type	20
+XkbNewKeyboardNotifyEvent.device	24
+XkbNewKeyboardNotifyEvent.old_device	28
+XkbNewKeyboardNotifyEvent.min_key_code	32
+XkbNewKeyboardNotifyEvent.max_key_code	36
+XkbNewKeyboardNotifyEvent.old_min_key_code	40
+XkbNewKeyboardNotifyEvent.old_max_key_code	44
+XkbNewKeyboardNotifyEvent.changed	48
+XkbNewKeyboardNotifyEvent.req_major	52
+XkbNewKeyboardNotifyEvent.req_minor	53
+XkbNewKeyboardNotifyEvent	56
+XTimeCoord.time	0
+XTimeCoord.x	4
+XTimeCoord.y	6
+XTimeCoord	8
+XkbCompatMapNotifyEvent.type	0
+XkbCompatMapNotifyEvent.serial	4
+XkbCompatMapNotifyEvent.send_event	8
+XkbCompatMapNotifyEvent.display	12
+XkbCompatMapNotifyEvent.time	16
+XkbCompatMapNotifyEvent.xkb_type	20
+XkbCompatMapNotifyEvent.device	24
+XkbCompatMapNotifyEvent.changed_groups	28
+XkbCompatMapNotifyEvent.first_si	32
+XkbCompatMapNotifyEvent.num_si	36
+XkbCompatMapNotifyEvent.num_total_si	40
+XkbCompatMapNotifyEvent	44
+XIMStatusDrawCallbackStruct.type	0
+XIMStatusDrawCallbackStruct.data	4
+XIMStatusDrawCallbackStruct	8
+XKeyboardControl.key_click_percent	0
+XKeyboardControl.bell_percent	4
+XKeyboardControl.bell_pitch	8
+XKeyboardControl.bell_duration	12
+XKeyboardControl.led	16
+XKeyboardControl.led_mode	20
+XKeyboardControl.key	24
+XKeyboardControl.auto_repeat_mode	28
+XKeyboardControl	32
+XSelectionClearEvent.type	0
+XSelectionClearEvent.serial	4
+XSelectionClearEvent.send_event	8
+XSelectionClearEvent.display	12
+XSelectionClearEvent.window	16
+XSelectionClearEvent.selection	20
+XSelectionClearEvent.time	24
+XSelectionClearEvent	28
+XWindowChanges.x	0
+XWindowChanges.y	4
+XWindowChanges.width	8
+XWindowChanges.height	12
+XWindowChanges.border_width	16
+XWindowChanges.sibling	20
+XWindowChanges.stack_mode	24
+XWindowChanges	28
+XIMPreeditCaretCallbackStruct.position	0
+XIMPreeditCaretCallbackStruct.direction	4
+XIMPreeditCaretCallbackStruct.style	8
+XIMPreeditCaretCallbackStruct	12
+XOMCharSetList.charset_count	0
+XOMCharSetList.charset_list	4
+XOMCharSetList	8
+XOMFontInfo.num_font	0
+XOMFontInfo.font_struct_list	4
+XOMFontInfo.font_name_list	8
+XOMFontInfo	12
+AwtScreenData.numConfigs	0
+AwtScreenData.root	4
+AwtScreenData.whitepixel	8
+AwtScreenData.blackpixel	12
+AwtScreenData.defaultConfig	16
+AwtScreenData.configs	20
+AwtScreenData	24
+XIMHotKeyTrigger.keysym	0
+XIMHotKeyTrigger.modifier	4
+XIMHotKeyTrigger.modifier_mask	8
+XIMHotKeyTrigger	12
+XCirculateEvent.type	0
+XCirculateEvent.serial	4
+XCirculateEvent.send_event	8
+XCirculateEvent.display	12
+XCirculateEvent.event	16
+XCirculateEvent.window	20
+XCirculateEvent.place	24
+XCirculateEvent	28
+Screen.ext_data	0
+Screen.display	4
+Screen.root	8
+Screen.width	12
+Screen.height	16
+Screen.mwidth	20
+Screen.mheight	24
+Screen.ndepths	28
+Screen.depths	32
+Screen.root_depth	36
+Screen.root_visual	40
+Screen.default_gc	44
+Screen.cmap	48
+Screen.white_pixel	52
+Screen.black_pixel	56
+Screen.max_maps	60
+Screen.min_maps	64
+Screen.backing_store	68
+Screen.save_unders	72
+Screen.root_input_mask	76
+Screen	80
+XMapRequestEvent.type	0
+XMapRequestEvent.serial	4
+XMapRequestEvent.send_event	8
+XMapRequestEvent.display	12
+XMapRequestEvent.parent	16
+XMapRequestEvent.window	20
+XMapRequestEvent	24
+XIMText.length	0
+XIMText.feedback	4
+XIMText.encoding_is_wchar	8
+XIMText.string	12
+XIMText	16
+XGraphicsExposeEvent.type	0
+XGraphicsExposeEvent.serial	4
+XGraphicsExposeEvent.send_event	8
+XGraphicsExposeEvent.display	12
+XGraphicsExposeEvent.drawable	16
+XGraphicsExposeEvent.x	20
+XGraphicsExposeEvent.y	24
+XGraphicsExposeEvent.width	28
+XGraphicsExposeEvent.height	32
+XGraphicsExposeEvent.count	36
+XGraphicsExposeEvent.major_code	40
+XGraphicsExposeEvent.minor_code	44
+XGraphicsExposeEvent	48
+XEvent.type	0
+XEvent.xany	0
+XEvent.xkey	0
+XEvent.xbutton	0
+XEvent.xmotion	0
+XEvent.xcrossing	0
+XEvent.xfocus	0
+XEvent.xexpose	0
+XEvent.xgraphicsexpose	0
+XEvent.xnoexpose	0
+XEvent.xvisibility	0
+XEvent.xcreatewindow	0
+XEvent.xdestroywindow	0
+XEvent.xunmap	0
+XEvent.xmap	0
+XEvent.xmaprequest	0
+XEvent.xreparent	0
+XEvent.xconfigure	0
+XEvent.xgravity	0
+XEvent.xresizerequest	0
+XEvent.xconfigurerequest	0
+XEvent.xcirculate	0
+XEvent.xcirculaterequest	0
+XEvent.xproperty	0
+XEvent.xselectionclear	0
+XEvent.xselectionrequest	0
+XEvent.xselection	0
+XEvent.xcolormap	0
+XEvent.xclient	0
+XEvent.xmapping	0
+XEvent.xerror	0
+XEvent.xkeymap	0
+XEvent.pad	0
+XEvent	96
+XRenderDirectFormat.red	0
+XRenderDirectFormat.redMask	2
+XRenderDirectFormat.green	4
+XRenderDirectFormat.greenMask	6
+XRenderDirectFormat.blue	8
+XRenderDirectFormat.blueMask	10
+XRenderDirectFormat.alpha	12
+XRenderDirectFormat.alphaMask	14
+XRenderDirectFormat	16
+ColorData.awt_Colors	0
+ColorData.awt_numICMcolors	4
+ColorData.awt_icmLUT	8
+ColorData.awt_icmLUT2Colors	12
+ColorData.img_grays	16
+ColorData.img_clr_tbl	20
+ColorData.img_oda_red	24
+ColorData.img_oda_green	28
+ColorData.img_oda_blue	32
+ColorData.pGrayInverseLutData	36
+ColorData.screendata	40
+ColorData	44
+XFontStruct.ext_data	0
+XFontStruct.fid	4
+XFontStruct.direction	8
+XFontStruct.min_char_or_byte2	12
+XFontStruct.max_char_or_byte2	16
+XFontStruct.min_byte1	20
+XFontStruct.max_byte1	24
+XFontStruct.all_chars_exist	28
+XFontStruct.n_properties	36
+XFontStruct.properties	40
+XFontStruct.min_bounds	44
+XFontStruct.max_bounds	56
+XFontStruct.per_char	68
+XFontStruct.ascent	72
+XFontStruct.descent	76
+XFontStruct	80
+XExtCodes.extension	0
+XExtCodes.major_opcode	4
+XExtCodes.first_event	8
+XExtCodes.first_error	12
+XExtCodes	16
+XFontSetExtents.max_ink_extent	0
+XFontSetExtents.max_logical_extent	8
+XFontSetExtents	16
+XSelectionEvent.type	0
+XSelectionEvent.serial	4
+XSelectionEvent.send_event	8
+XSelectionEvent.display	12
+XSelectionEvent.requestor	16
+XSelectionEvent.selection	20
+XSelectionEvent.target	24
+XSelectionEvent.property	28
+XSelectionEvent.time	32
+XSelectionEvent	36
+XArc.x	0
+XArc.y	2
+XArc.width	4
+XArc.height	6
+XArc.angle1	8
+XArc.angle2	10
+XArc	12
+XErrorEvent.type	0
+XErrorEvent.display	4
+XErrorEvent.resourceid	8
+XErrorEvent.serial	12
+XErrorEvent.error_code	16
+XErrorEvent.request_code	17
+XErrorEvent.minor_code	18
+XErrorEvent	20
+XConfigureRequestEvent.type	0
+XConfigureRequestEvent.serial	4
+XConfigureRequestEvent.send_event	8
+XConfigureRequestEvent.display	12
+XConfigureRequestEvent.parent	16
+XConfigureRequestEvent.window	20
+XConfigureRequestEvent.x	24
+XConfigureRequestEvent.y	28
+XConfigureRequestEvent.width	32
+XConfigureRequestEvent.height	36
+XConfigureRequestEvent.border_width	40
+XConfigureRequestEvent.above	44
+XConfigureRequestEvent.detail	48
+XConfigureRequestEvent.value_mask	52
+XConfigureRequestEvent	56
+ScreenFormat.ext_data	0
+ScreenFormat.depth	4
+ScreenFormat.bits_per_pixel	8
+ScreenFormat.scanline_pad	12
+ScreenFormat	16
+XButtonEvent.type	0
+XButtonEvent.serial	4
+XButtonEvent.send_event	8
+XButtonEvent.display	12
+XButtonEvent.window	16
+XButtonEvent.root	20
+XButtonEvent.subwindow	24
+XButtonEvent.time	28
+XButtonEvent.x	32
+XButtonEvent.y	36
+XButtonEvent.x_root	40
+XButtonEvent.y_root	44
+XButtonEvent.state	48
+XButtonEvent.button	52
+XButtonEvent.same_screen	56
+XButtonEvent	60
+XFontProp.name	0
+XFontProp.card32	4
+XFontProp	8
+XIMValuesList.count_values	0
+XIMValuesList.supported_values	4
+XIMValuesList	8
+XKeymapEvent.type	0
+XKeymapEvent.serial	4
+XKeymapEvent.send_event	8
+XKeymapEvent.display	12
+XKeymapEvent.window	16
+XKeymapEvent.key_vector	20
+XKeymapEvent	52
+XTextItem16.chars	0
+XTextItem16.nchars	4
+XTextItem16.delta	8
+XTextItem16.font	12
+XTextItem16	16
+XIMPreeditDrawCallbackStruct.caret	0
+XIMPreeditDrawCallbackStruct.chg_first	4
+XIMPreeditDrawCallbackStruct.chg_length	8
+XIMPreeditDrawCallbackStruct.text	12
+XIMPreeditDrawCallbackStruct	16
+XVisualInfo.visual	0
+XVisualInfo.visualid	4
+XVisualInfo.screen	8
+XVisualInfo.depth	12
+XVisualInfo.class	16
+XVisualInfo.red_mask	20
+XVisualInfo.green_mask	24
+XVisualInfo.blue_mask	28
+XVisualInfo.colormap_size	32
+XVisualInfo.bits_per_rgb	36
+XVisualInfo	40
+XkbControlsNotifyEvent.type	0
+XkbControlsNotifyEvent.serial	4
+XkbControlsNotifyEvent.send_event	8
+XkbControlsNotifyEvent.display	12
+XkbControlsNotifyEvent.time	16
+XkbControlsNotifyEvent.xkb_type	20
+XkbControlsNotifyEvent.device	24
+XkbControlsNotifyEvent.changed_ctrls	28
+XkbControlsNotifyEvent.enabled_ctrls	32
+XkbControlsNotifyEvent.enabled_ctrl_changes	36
+XkbControlsNotifyEvent.num_groups	40
+XkbControlsNotifyEvent.keycode	44
+XkbControlsNotifyEvent.event_type	45
+XkbControlsNotifyEvent.req_major	46
+XkbControlsNotifyEvent.req_minor	47
+XkbControlsNotifyEvent	48
+PropMwmHints.flags	0
+PropMwmHints.functions	4
+PropMwmHints.decorations	8
+PropMwmHints.inputMode	12
+PropMwmHints.status	16
+PropMwmHints	20
+XClientMessageEvent.type	0
+XClientMessageEvent.serial	4
+XClientMessageEvent.send_event	8
+XClientMessageEvent.display	12
+XClientMessageEvent.window	16
+XClientMessageEvent.message_type	20
+XClientMessageEvent.format	24
+XClientMessageEvent.data	28
+XClientMessageEvent	48
+XAnyEvent.type	0
+XAnyEvent.serial	4
+XAnyEvent.send_event	8
+XAnyEvent.display	12
+XAnyEvent.window	16
+XAnyEvent	20
+XkbIndicatorNotifyEvent.type	0
+XkbIndicatorNotifyEvent.serial	4
+XkbIndicatorNotifyEvent.send_event	8
+XkbIndicatorNotifyEvent.display	12
+XkbIndicatorNotifyEvent.time	16
+XkbIndicatorNotifyEvent.xkb_type	20
+XkbIndicatorNotifyEvent.device	24
+XkbIndicatorNotifyEvent.changed	28
+XkbIndicatorNotifyEvent.state	32
+XkbIndicatorNotifyEvent	36
+XIMPreeditStateNotifyCallbackStruct.state	0
+XIMPreeditStateNotifyCallbackStruct	4
+XkbAnyEvent.type	0
+XkbAnyEvent.serial	4
+XkbAnyEvent.send_event	8
+XkbAnyEvent.display	12
+XkbAnyEvent.time	16
+XkbAnyEvent.xkb_type	20
+XkbAnyEvent.device	24
+XkbAnyEvent	28
+XMotionEvent.type	0
+XMotionEvent.serial	4
+XMotionEvent.send_event	8
+XMotionEvent.display	12
+XMotionEvent.window	16
+XMotionEvent.root	20
+XMotionEvent.subwindow	24
+XMotionEvent.time	28
+XMotionEvent.x	32
+XMotionEvent.y	36
+XMotionEvent.x_root	40
+XMotionEvent.y_root	44
+XMotionEvent.state	48
+XMotionEvent.is_hint	52
+XMotionEvent.same_screen	56
+XMotionEvent	60
+XIMHotKeyTriggers.num_hot_key	0
+XIMHotKeyTriggers.key	4
+XIMHotKeyTriggers	8
+XIMStyles.count_styles	0
+XIMStyles.supported_styles	4
+XIMStyles	8
+XkbExtensionDeviceNotifyEvent.type	0
+XkbExtensionDeviceNotifyEvent.serial	4
+XkbExtensionDeviceNotifyEvent.send_event	8
+XkbExtensionDeviceNotifyEvent.display	12
+XkbExtensionDeviceNotifyEvent.time	16
+XkbExtensionDeviceNotifyEvent.xkb_type	20
+XkbExtensionDeviceNotifyEvent.device	24
+XkbExtensionDeviceNotifyEvent.reason	28
+XkbExtensionDeviceNotifyEvent.supported	32
+XkbExtensionDeviceNotifyEvent.unsupported	36
+XkbExtensionDeviceNotifyEvent.first_btn	40
+XkbExtensionDeviceNotifyEvent.num_btns	44
+XkbExtensionDeviceNotifyEvent.leds_defined	48
+XkbExtensionDeviceNotifyEvent.led_state	52
+XkbExtensionDeviceNotifyEvent.led_class	56
+XkbExtensionDeviceNotifyEvent.led_id	60
+XkbExtensionDeviceNotifyEvent	64
+XwcTextItem.chars	0
+XwcTextItem.nchars	4
+XwcTextItem.delta	8
+XwcTextItem.font_set	12
+XwcTextItem	16
+XClassHint.res_name	0
+XClassHint.res_class	4
+XClassHint	8
+XChar2b.byte1	0
+XChar2b.byte2	1
+XChar2b	2
+XSetWindowAttributes.background_pixmap	0
+XSetWindowAttributes.background_pixel	4
+XSetWindowAttributes.border_pixmap	8
+XSetWindowAttributes.border_pixel	12
+XSetWindowAttributes.bit_gravity	16
+XSetWindowAttributes.win_gravity	20
+XSetWindowAttributes.backing_store	24
+XSetWindowAttributes.backing_planes	28
+XSetWindowAttributes.backing_pixel	32
+XSetWindowAttributes.save_under	36
+XSetWindowAttributes.event_mask	40
+XSetWindowAttributes.do_not_propagate_mask	44
+XSetWindowAttributes.override_redirect	48
+XSetWindowAttributes.colormap	52
+XSetWindowAttributes.cursor	56
+XSetWindowAttributes	60
+XRenderPictFormat.id	0
+XRenderPictFormat.type	4
+XRenderPictFormat.depth	8
+XRenderPictFormat.direct	12
+XRenderPictFormat.colormap	28
+XRenderPictFormat	32
+XReparentEvent.type	0
+XReparentEvent.serial	4
+XReparentEvent.send_event	8
+XReparentEvent.display	12
+XReparentEvent.event	16
+XReparentEvent.window	20
+XReparentEvent.parent	24
+XReparentEvent.x	28
+XReparentEvent.y	32
+XReparentEvent.override_redirect	36
+XReparentEvent	40
+XCirculateRequestEvent.type	0
+XCirculateRequestEvent.serial	4
+XCirculateRequestEvent.send_event	8
+XCirculateRequestEvent.display	12
+XCirculateRequestEvent.parent	16
+XCirculateRequestEvent.window	20
+XCirculateRequestEvent.place	24
+XCirculateRequestEvent	28
+XImage.width	0
+XImage.height	4
+XImage.xoffset	8
+XImage.format	12
+XImage.data	16
+XImage.byte_order	20
+XImage.bitmap_unit	24
+XImage.bitmap_bit_order	28
+XImage.bitmap_pad	32
+XImage.depth	36
+XImage.bytes_per_line	40
+XImage.bits_per_pixel	44
+XImage.red_mask	48
+XImage.green_mask	52
+XImage.blue_mask	56
+XImage.obdata	60
+XImage.f.create_image	64
+XImage.f.destroy_image	68
+XImage.f.get_pixel	72
+XImage.f.put_pixel	76
+XImage.f.sub_image	80
+XImage.f.add_pixel	84
+XImage	88
+XKeyEvent.type	0
+XKeyEvent.serial	4
+XKeyEvent.send_event	8
+XKeyEvent.display	12
+XKeyEvent.window	16
+XKeyEvent.root	20
+XKeyEvent.subwindow	24
+XKeyEvent.time	28
+XKeyEvent.x	32
+XKeyEvent.y	36
+XKeyEvent.x_root	40
+XKeyEvent.y_root	44
+XKeyEvent.state	48
+XKeyEvent.keycode	52
+XKeyEvent.same_screen	56
+XKeyEvent	60
+XkbActionMessageEvent.type	0
+XkbActionMessageEvent.serial	4
+XkbActionMessageEvent.send_event	8
+XkbActionMessageEvent.display	12
+XkbActionMessageEvent.time	16
+XkbActionMessageEvent.xkb_type	20
+XkbActionMessageEvent.device	24
+XkbActionMessageEvent.keycode	28
+XkbActionMessageEvent.press	32
+XkbActionMessageEvent.key_event_follows	36
+XkbActionMessageEvent.group	40
+XkbActionMessageEvent.mods	44
+XkbActionMessageEvent.message	48
+XkbActionMessageEvent	56
+XdbeSwapInfo.swap_window	0
+XdbeSwapInfo.swap_action	4
+XdbeSwapInfo	8
+XTextItem.chars	0
+XTextItem.nchars	4
+XTextItem.delta	8
+XTextItem.font	12
+XTextItem	16
+XModifierKeymap.max_keypermod	0
+XModifierKeymap.modifiermap	4
+XModifierKeymap	8
+XCharStruct.lbearing	0
+XCharStruct.rbearing	2
+XCharStruct.width	4
+XCharStruct.ascent	6
+XCharStruct.descent	8
+XCharStruct.attributes	10
+XCharStruct	12
+XGravityEvent.type	0
+XGravityEvent.serial	4
+XGravityEvent.send_event	8
+XGravityEvent.display	12
+XGravityEvent.event	16
+XGravityEvent.window	20
+XGravityEvent.x	24
+XGravityEvent.y	28
+XGravityEvent	32
+Visual.ext_data	0
+Visual.visualid	4
+Visual.class	8
+Visual.red_mask	12
+Visual.green_mask	16
+Visual.blue_mask	20
+Visual.bits_per_rgb	24
+Visual.map_entries	28
+Visual	32
+XOMOrientation.num_orientation	0
+XOMOrientation.orientation	4
+XOMOrientation	8
+XkbAccessXNotifyEvent.type	0
+XkbAccessXNotifyEvent.serial	4
+XkbAccessXNotifyEvent.send_event	8
+XkbAccessXNotifyEvent.display	12
+XkbAccessXNotifyEvent.time	16
+XkbAccessXNotifyEvent.xkb_type	20
+XkbAccessXNotifyEvent.device	24
+XkbAccessXNotifyEvent.detail	28
+XkbAccessXNotifyEvent.keycode	32
+XkbAccessXNotifyEvent.sk_delay	36
+XkbAccessXNotifyEvent.debounce_delay	40
+XkbAccessXNotifyEvent	44
+XWindowAttributes.x	0
+XWindowAttributes.y	4
+XWindowAttributes.width	8
+XWindowAttributes.height	12
+XWindowAttributes.border_width	16
+XWindowAttributes.depth	20
+XWindowAttributes.visual	24
+XWindowAttributes.root	28
+XWindowAttributes.class	32
+XWindowAttributes.bit_gravity	36
+XWindowAttributes.win_gravity	40
+XWindowAttributes.backing_store	44
+XWindowAttributes.backing_planes	48
+XWindowAttributes.backing_pixel	52
+XWindowAttributes.save_under	56
+XWindowAttributes.colormap	60
+XWindowAttributes.map_installed	64
+XWindowAttributes.map_state	68
+XWindowAttributes.all_event_masks	72
+XWindowAttributes.your_event_mask	76
+XWindowAttributes.do_not_propagate_mask	80
+XWindowAttributes.override_redirect	84
+XWindowAttributes.screen	88
+XWindowAttributes	92
+XmbTextItem.chars	0
+XmbTextItem.nchars	4
+XmbTextItem.delta	8
+XmbTextItem.font_set	12
+XmbTextItem	16
+XMappingEvent.type	0
+XMappingEvent.serial	4
+XMappingEvent.send_event	8
+XMappingEvent.display	12
+XMappingEvent.window	16
+XMappingEvent.request	20
+XMappingEvent.first_keycode	24
+XMappingEvent.count	28
+XMappingEvent	32
+XSizeHints.flags	0
+XSizeHints.x	4
+XSizeHints.y	8
+XSizeHints.width	12
+XSizeHints.height	16
+XSizeHints.min_width	20
+XSizeHints.min_height	24
+XSizeHints.max_width	28
+XSizeHints.max_height	32
+XSizeHints.width_inc	36
+XSizeHints.height_inc	40
+XSizeHints.min_aspect.x	44
+XSizeHints.min_aspect.y	48
+XSizeHints.max_aspect.x	52
+XSizeHints.max_aspect.y	56
+XSizeHints.base_width	60
+XSizeHints.base_height	64
+XSizeHints.win_gravity	68
+XSizeHints	72
+XUnmapEvent.type	0
+XUnmapEvent.serial	4
+XUnmapEvent.send_event	8
+XUnmapEvent.display	12
+XUnmapEvent.event	16
+XUnmapEvent.window	20
+XUnmapEvent.from_configure	24
+XUnmapEvent	28
+awtImageData.Depth	0
+awtImageData.wsImageFormat	4
+awtImageData.clrdata	16
+awtImageData.convert	48
+awtImageData	304
+XkbStateNotifyEvent.type	0
+XkbStateNotifyEvent.serial	4
+XkbStateNotifyEvent.send_event	8
+XkbStateNotifyEvent.display	12
+XkbStateNotifyEvent.time	16
+XkbStateNotifyEvent.xkb_type	20
+XkbStateNotifyEvent.device	24
+XkbStateNotifyEvent.changed	28
+XkbStateNotifyEvent.group	32
+XkbStateNotifyEvent.base_group	36
+XkbStateNotifyEvent.latched_group	40
+XkbStateNotifyEvent.locked_group	44
+XkbStateNotifyEvent.mods	48
+XkbStateNotifyEvent.base_mods	52
+XkbStateNotifyEvent.latched_mods	56
+XkbStateNotifyEvent.locked_mods	60
+XkbStateNotifyEvent.compat_state	64
+XkbStateNotifyEvent.grab_mods	68
+XkbStateNotifyEvent.compat_grab_mods	69
+XkbStateNotifyEvent.lookup_mods	70
+XkbStateNotifyEvent.compat_lookup_mods	71
+XkbStateNotifyEvent.ptr_buttons	72
+XkbStateNotifyEvent.keycode	76
+XkbStateNotifyEvent.event_type	77
+XkbStateNotifyEvent.req_major	78
+XkbStateNotifyEvent.req_minor	79
+XkbStateNotifyEvent	80
+XExposeEvent.type	0
+XExposeEvent.serial	4
+XExposeEvent.send_event	8
+XExposeEvent.display	12
+XExposeEvent.window	16
+XExposeEvent.x	20
+XExposeEvent.y	24
+XExposeEvent.width	28
+XExposeEvent.height	32
+XExposeEvent.count	36
+XExposeEvent	40
+XkbMapNotifyEvent.type	0
+XkbMapNotifyEvent.serial	4
+XkbMapNotifyEvent.send_event	8
+XkbMapNotifyEvent.display	12
+XkbMapNotifyEvent.time	16
+XkbMapNotifyEvent.xkb_type	20
+XkbMapNotifyEvent.device	24
+XkbMapNotifyEvent.changed	28
+XkbMapNotifyEvent.flags	32
+XkbMapNotifyEvent.first_type	36
+XkbMapNotifyEvent.num_types	40
+XkbMapNotifyEvent.min_key_code	44
+XkbMapNotifyEvent.max_key_code	45
+XkbMapNotifyEvent.first_key_sym	46
+XkbMapNotifyEvent.first_key_act	47
+XkbMapNotifyEvent.first_key_behavior	48
+XkbMapNotifyEvent.first_key_explicit	49
+XkbMapNotifyEvent.first_modmap_key	50
+XkbMapNotifyEvent.first_vmodmap_key	51
+XkbMapNotifyEvent.num_key_syms	52
+XkbMapNotifyEvent.num_key_acts	56
+XkbMapNotifyEvent.num_key_behaviors	60
+XkbMapNotifyEvent.num_key_explicit	64
+XkbMapNotifyEvent.num_modmap_keys	68
+XkbMapNotifyEvent.num_vmodmap_keys	72
+XkbMapNotifyEvent.vmods	76
+XkbMapNotifyEvent	80
+XGCValues.function	0
+XGCValues.plane_mask	4
+XGCValues.foreground	8
+XGCValues.background	12
+XGCValues.line_width	16
+XGCValues.line_style	20
+XGCValues.cap_style	24
+XGCValues.join_style	28
+XGCValues.fill_style	32
+XGCValues.fill_rule	36
+XGCValues.arc_mode	40
+XGCValues.tile	44
+XGCValues.stipple	48
+XGCValues.ts_x_origin	52
+XGCValues.ts_y_origin	56
+XGCValues.font	60
+XGCValues.subwindow_mode	64
+XGCValues.graphics_exposures	68
+XGCValues.clip_x_origin	72
+XGCValues.clip_y_origin	76
+XGCValues.clip_mask	80
+XGCValues.dash_offset	84
+XGCValues.dashes	88
+XGCValues	92
+XFocusChangeEvent.type	0
+XFocusChangeEvent.serial	4
+XFocusChangeEvent.send_event	8
+XFocusChangeEvent.display	12
+XFocusChangeEvent.window	16
+XFocusChangeEvent.mode	20
+XFocusChangeEvent.detail	24
+XFocusChangeEvent	28
+XPixmapFormatValues.depth	0
+XPixmapFormatValues.bits_per_pixel	4
+XPixmapFormatValues.scanline_pad	8
+XPixmapFormatValues	12
+XMapEvent.type	0
+XMapEvent.serial	4
+XMapEvent.send_event	8
+XMapEvent.display	12
+XMapEvent.event	16
+XMapEvent.window	20
+XMapEvent.override_redirect	24
+XMapEvent	28
+XkbBellNotifyEvent.type	0
+XkbBellNotifyEvent.serial	4
+XkbBellNotifyEvent.send_event	8
+XkbBellNotifyEvent.display	12
+XkbBellNotifyEvent.time	16
+XkbBellNotifyEvent.xkb_type	20
+XkbBellNotifyEvent.device	24
+XkbBellNotifyEvent.percent	28
+XkbBellNotifyEvent.pitch	32
+XkbBellNotifyEvent.duration	36
+XkbBellNotifyEvent.bell_class	40
+XkbBellNotifyEvent.bell_id	44
+XkbBellNotifyEvent.name	48
+XkbBellNotifyEvent.window	52
+XkbBellNotifyEvent.event_only	56
+XkbBellNotifyEvent	60
+XIMStringConversionText.length	0
+XIMStringConversionText.feedback	4
+XIMStringConversionText.encoding_is_wchar	8
+XIMStringConversionText.string	12
+XIMStringConversionText	16
+XKeyboardState.key_click_percent	0
+XKeyboardState.bell_percent	4
+XKeyboardState.bell_pitch	8
+XKeyboardState.bell_duration	12
+XKeyboardState.led_mask	16
+XKeyboardState.global_auto_repeat	20
+XKeyboardState.auto_repeats	24
+XKeyboardState	56
+XkbEvent.type	0
+XkbEvent.any	0
+XkbEvent.new_kbd	0
+XkbEvent.map	0
+XkbEvent.state	0
+XkbEvent.ctrls	0
+XkbEvent.indicators	0
+XkbEvent.names	0
+XkbEvent.compat	0
+XkbEvent.bell	0
+XkbEvent.message	0
+XkbEvent.accessx	0
+XkbEvent.device	0
+XkbEvent.core	0
+XkbEvent	96
+XPoint.x	0
+XPoint.y	2
+XPoint	4
+XSegment.x1	0
+XSegment.y1	2
+XSegment.x2	4
+XSegment.y2	6
+XSegment	8
+XIconSize.min_width	0
+XIconSize.min_height	4
+XIconSize.max_width	8
+XIconSize.max_height	12
+XIconSize.width_inc	16
+XIconSize.height_inc	20
+XIconSize	24
+XIMCallback.client_data	0
+XIMCallback.callback	4
+XIMCallback	8
+XConfigureEvent.type	0
+XConfigureEvent.serial	4
+XConfigureEvent.send_event	8
+XConfigureEvent.display	12
+XConfigureEvent.event	16
+XConfigureEvent.window	20
+XConfigureEvent.x	24
+XConfigureEvent.y	28
+XConfigureEvent.width	32
+XConfigureEvent.height	36
+XConfigureEvent.border_width	40
+XConfigureEvent.above	44
+XConfigureEvent.override_redirect	48
+XConfigureEvent	52
+XRectangle.x	0
+XRectangle.y	2
+XRectangle.width	4
+XRectangle.height	6
+XRectangle	8
+XkbNamesNotifyEvent.type	0
+XkbNamesNotifyEvent.serial	4
+XkbNamesNotifyEvent.send_event	8
+XkbNamesNotifyEvent.display	12
+XkbNamesNotifyEvent.time	16
+XkbNamesNotifyEvent.xkb_type	20
+XkbNamesNotifyEvent.device	24
+XkbNamesNotifyEvent.changed	28
+XkbNamesNotifyEvent.first_type	32
+XkbNamesNotifyEvent.num_types	36
+XkbNamesNotifyEvent.first_lvl	40
+XkbNamesNotifyEvent.num_lvls	44
+XkbNamesNotifyEvent.num_aliases	48
+XkbNamesNotifyEvent.num_radio_groups	52
+XkbNamesNotifyEvent.changed_vmods	56
+XkbNamesNotifyEvent.changed_groups	60
+XkbNamesNotifyEvent.changed_indicators	64
+XkbNamesNotifyEvent.first_key	68
+XkbNamesNotifyEvent.num_keys	72
+XkbNamesNotifyEvent	76
+XCreateWindowEvent.type	0
+XCreateWindowEvent.serial	4
+XCreateWindowEvent.send_event	8
+XCreateWindowEvent.display	12
+XCreateWindowEvent.parent	16
+XCreateWindowEvent.window	20
+XCreateWindowEvent.x	24
+XCreateWindowEvent.y	28
+XCreateWindowEvent.width	32
+XCreateWindowEvent.height	36
+XCreateWindowEvent.border_width	40
+XCreateWindowEvent.override_redirect	44
+XCreateWindowEvent	48
+XVisibilityEvent.type	0
+XVisibilityEvent.serial	4
+XVisibilityEvent.send_event	8
+XVisibilityEvent.display	12
+XVisibilityEvent.window	16
+XVisibilityEvent.state	20
+XVisibilityEvent	24
+XWMHints.flags	0
+XWMHints.initial_state	8
+XWMHints.icon_pixmap	12
+XWMHints.icon_window	16
+XWMHints.icon_x	20
+XWMHints.icon_y	24
+XWMHints.icon_mask	28
+XWMHints.input	4
+XWMHints.window_group	32
+XWMHints	36
+XCrossingEvent.type	0
+XCrossingEvent.serial	4
+XCrossingEvent.send_event	8
+XCrossingEvent.display	12
+XCrossingEvent.window	16
+XCrossingEvent.root	20
+XCrossingEvent.subwindow	24
+XCrossingEvent.time	28
+XCrossingEvent.x	32
+XCrossingEvent.y	36
+XCrossingEvent.x_root	40
+XCrossingEvent.y_root	44
+XCrossingEvent.mode	48
+XCrossingEvent.detail	52
+XCrossingEvent.same_screen	56
+XCrossingEvent.focus	60
+XCrossingEvent.state	64
+XCrossingEvent	68
+XSelectionRequestEvent.type	0
+XSelectionRequestEvent.serial	4
+XSelectionRequestEvent.send_event	8
+XSelectionRequestEvent.display	12
+XSelectionRequestEvent.owner	16
+XSelectionRequestEvent.requestor	20
+XSelectionRequestEvent.selection	24
+XSelectionRequestEvent.target	28
+XSelectionRequestEvent.property	32
+XSelectionRequestEvent.time	36
+XSelectionRequestEvent	40
+XNoExposeEvent.type	0
+XNoExposeEvent.serial	4
+XNoExposeEvent.send_event	8
+XNoExposeEvent.display	12
+XNoExposeEvent.drawable	16
+XNoExposeEvent.major_code	20
+XNoExposeEvent.minor_code	24
+XNoExposeEvent	28
+XHostAddress.family	0
+XHostAddress.length	4
+XHostAddress.address	8
+XHostAddress	12
+XColormapEvent.type	0
+XColormapEvent.serial	4
+XColormapEvent.send_event	8
+XColormapEvent.display	12
+XColormapEvent.window	16
+XColormapEvent.colormap	20
+XColormapEvent.new	24
+XColormapEvent.state	28
+XColormapEvent	32
+ColorEntry.r	0
+ColorEntry.g	1
+ColorEntry.b	2
+ColorEntry.flags	3
+ColorEntry	4
+XResizeRequestEvent.type	0
+XResizeRequestEvent.serial	4
+XResizeRequestEvent.send_event	8
+XResizeRequestEvent.display	12
+XResizeRequestEvent.window	16
+XResizeRequestEvent.width	20
+XResizeRequestEvent.height	24
+XResizeRequestEvent	28
+Depth.depth	0
+Depth.nvisuals	4
+Depth.visuals	8
+Depth	12
+XPropertyEvent.type	0
+XPropertyEvent.serial	4
+XPropertyEvent.send_event	8
+XPropertyEvent.display	12
+XPropertyEvent.window	16
+XPropertyEvent.atom	20
+XPropertyEvent.time	24
+XPropertyEvent.state	28
+XPropertyEvent	32
+XDestroyWindowEvent.type	0
+XDestroyWindowEvent.serial	4
+XDestroyWindowEvent.send_event	8
+XDestroyWindowEvent.display	12
+XDestroyWindowEvent.event	16
+XDestroyWindowEvent.window	20
+XDestroyWindowEvent	24
+XStandardColormap.colormap	0
+XStandardColormap.red_max	4
+XStandardColormap.red_mult	8
+XStandardColormap.green_max	12
+XStandardColormap.green_mult	16
+XStandardColormap.blue_max	20
+XStandardColormap.blue_mult	24
+XStandardColormap.base_pixel	28
+XStandardColormap.visualid	32
+XStandardColormap.killid	36
+XStandardColormap	40
+XComposeStatus.compose_ptr	0
+XComposeStatus.chars_matched	4
+XComposeStatus	8
+AwtGraphicsConfigData.awt_depth	0
+AwtGraphicsConfigData.awt_cmap	4
+AwtGraphicsConfigData.awt_visInfo	8
+AwtGraphicsConfigData.awt_num_colors	48
+AwtGraphicsConfigData.awtImage	52
+AwtGraphicsConfigData.AwtColorMatch	56
+AwtGraphicsConfigData.monoImage	60
+AwtGraphicsConfigData.monoPixmap	64
+AwtGraphicsConfigData.monoPixmapWidth	68
+AwtGraphicsConfigData.monoPixmapHeight	72
+AwtGraphicsConfigData.monoPixmapGC	76
+AwtGraphicsConfigData.pixelStride	80
+AwtGraphicsConfigData.color_data	84
+AwtGraphicsConfigData.glxInfo	88
+AwtGraphicsConfigData.isTranslucencySupported	92
+AwtGraphicsConfigData.renderPictFormat	96
+AwtGraphicsConfigData	128
+XColor.pixel	0
+XColor.red	4
+XColor.green	6
+XColor.blue	8
+XColor.flags	10
+XColor.pad	11
+XColor	12
+XTextProperty.value	0
+XTextProperty.encoding	4
+XTextProperty.format	8
+XTextProperty.nitems	12
+XTextProperty	16
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/solaris/classes/sun/awt/X11/generator/sizes.64	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,1016 @@
+long	8
+int	4
+short	2
+ptr	8
+Bool	4
+Atom	8
+Window	8
+XExtData.number	0
+XExtData.next	8
+XExtData.free_private	16
+XExtData.private_data	24
+XExtData	32
+XIMStringConversionCallbackStruct.position	0
+XIMStringConversionCallbackStruct.direction	4
+XIMStringConversionCallbackStruct.operation	8
+XIMStringConversionCallbackStruct.factor	10
+XIMStringConversionCallbackStruct.text	16
+XIMStringConversionCallbackStruct	24
+XkbNewKeyboardNotifyEvent.type	0
+XkbNewKeyboardNotifyEvent.serial	8
+XkbNewKeyboardNotifyEvent.send_event	16
+XkbNewKeyboardNotifyEvent.display	24
+XkbNewKeyboardNotifyEvent.time	32
+XkbNewKeyboardNotifyEvent.xkb_type	40
+XkbNewKeyboardNotifyEvent.device	44
+XkbNewKeyboardNotifyEvent.old_device	48
+XkbNewKeyboardNotifyEvent.min_key_code	52
+XkbNewKeyboardNotifyEvent.max_key_code	56
+XkbNewKeyboardNotifyEvent.old_min_key_code	60
+XkbNewKeyboardNotifyEvent.old_max_key_code	64
+XkbNewKeyboardNotifyEvent.changed	68
+XkbNewKeyboardNotifyEvent.req_major	72
+XkbNewKeyboardNotifyEvent.req_minor	73
+XkbNewKeyboardNotifyEvent	80
+XTimeCoord.time	0
+XTimeCoord.x	8
+XTimeCoord.y	10
+XTimeCoord	16
+XkbCompatMapNotifyEvent.type	0
+XkbCompatMapNotifyEvent.serial	8
+XkbCompatMapNotifyEvent.send_event	16
+XkbCompatMapNotifyEvent.display	24
+XkbCompatMapNotifyEvent.time	32
+XkbCompatMapNotifyEvent.xkb_type	40
+XkbCompatMapNotifyEvent.device	44
+XkbCompatMapNotifyEvent.changed_groups	48
+XkbCompatMapNotifyEvent.first_si	52
+XkbCompatMapNotifyEvent.num_si	56
+XkbCompatMapNotifyEvent.num_total_si	60
+XkbCompatMapNotifyEvent	64
+XIMStatusDrawCallbackStruct.type	0
+XIMStatusDrawCallbackStruct.data	8
+XIMStatusDrawCallbackStruct	16
+XKeyboardControl.key_click_percent	0
+XKeyboardControl.bell_percent	4
+XKeyboardControl.bell_pitch	8
+XKeyboardControl.bell_duration	12
+XKeyboardControl.led	16
+XKeyboardControl.led_mode	20
+XKeyboardControl.key	24
+XKeyboardControl.auto_repeat_mode	28
+XKeyboardControl	32
+XSelectionClearEvent.type	0
+XSelectionClearEvent.serial	8
+XSelectionClearEvent.send_event	16
+XSelectionClearEvent.display	24
+XSelectionClearEvent.window	32
+XSelectionClearEvent.selection	40
+XSelectionClearEvent.time	48
+XSelectionClearEvent	56
+XWindowChanges.x	0
+XWindowChanges.y	4
+XWindowChanges.width	8
+XWindowChanges.height	12
+XWindowChanges.border_width	16
+XWindowChanges.sibling	24
+XWindowChanges.stack_mode	32
+XWindowChanges	40
+XIMPreeditCaretCallbackStruct.position	0
+XIMPreeditCaretCallbackStruct.direction	4
+XIMPreeditCaretCallbackStruct.style	8
+XIMPreeditCaretCallbackStruct	12
+XOMCharSetList.charset_count	0
+XOMCharSetList.charset_list	8
+XOMCharSetList	16
+XOMFontInfo.num_font	0
+XOMFontInfo.font_struct_list	8
+XOMFontInfo.font_name_list	16
+XOMFontInfo	24
+AwtScreenData.numConfigs	0
+AwtScreenData.root	8
+AwtScreenData.whitepixel	16
+AwtScreenData.blackpixel	24
+AwtScreenData.defaultConfig	32
+AwtScreenData.configs	40
+AwtScreenData	48
+XIMHotKeyTrigger.keysym	0
+XIMHotKeyTrigger.modifier	8
+XIMHotKeyTrigger.modifier_mask	12
+XIMHotKeyTrigger	16
+XCirculateEvent.type	0
+XCirculateEvent.serial	8
+XCirculateEvent.send_event	16
+XCirculateEvent.display	24
+XCirculateEvent.event	32
+XCirculateEvent.window	40
+XCirculateEvent.place	48
+XCirculateEvent	56
+Screen.ext_data	0
+Screen.display	8
+Screen.root	16
+Screen.width	24
+Screen.height	28
+Screen.mwidth	32
+Screen.mheight	36
+Screen.ndepths	40
+Screen.depths	48
+Screen.root_depth	56
+Screen.root_visual	64
+Screen.default_gc	72
+Screen.cmap	80
+Screen.white_pixel	88
+Screen.black_pixel	96
+Screen.max_maps	104
+Screen.min_maps	108
+Screen.backing_store	112
+Screen.save_unders	116
+Screen.root_input_mask	120
+Screen	128
+XMapRequestEvent.type	0
+XMapRequestEvent.serial	8
+XMapRequestEvent.send_event	16
+XMapRequestEvent.display	24
+XMapRequestEvent.parent	32
+XMapRequestEvent.window	40
+XMapRequestEvent	48
+XIMText.length	0
+XIMText.feedback	8
+XIMText.encoding_is_wchar	16
+XIMText.string	24
+XIMText	32
+XGraphicsExposeEvent.type	0
+XGraphicsExposeEvent.serial	8
+XGraphicsExposeEvent.send_event	16
+XGraphicsExposeEvent.display	24
+XGraphicsExposeEvent.drawable	32
+XGraphicsExposeEvent.x	40
+XGraphicsExposeEvent.y	44
+XGraphicsExposeEvent.width	48
+XGraphicsExposeEvent.height	52
+XGraphicsExposeEvent.count	56
+XGraphicsExposeEvent.major_code	60
+XGraphicsExposeEvent.minor_code	64
+XGraphicsExposeEvent	72
+XEvent.type	0
+XEvent.xany	0
+XEvent.xkey	0
+XEvent.xbutton	0
+XEvent.xmotion	0
+XEvent.xcrossing	0
+XEvent.xfocus	0
+XEvent.xexpose	0
+XEvent.xgraphicsexpose	0
+XEvent.xnoexpose	0
+XEvent.xvisibility	0
+XEvent.xcreatewindow	0
+XEvent.xdestroywindow	0
+XEvent.xunmap	0
+XEvent.xmap	0
+XEvent.xmaprequest	0
+XEvent.xreparent	0
+XEvent.xconfigure	0
+XEvent.xgravity	0
+XEvent.xresizerequest	0
+XEvent.xconfigurerequest	0
+XEvent.xcirculate	0
+XEvent.xcirculaterequest	0
+XEvent.xproperty	0
+XEvent.xselectionclear	0
+XEvent.xselectionrequest	0
+XEvent.xselection	0
+XEvent.xcolormap	0
+XEvent.xclient	0
+XEvent.xmapping	0
+XEvent.xerror	0
+XEvent.xkeymap	0
+XEvent.pad	0
+XEvent	192
+XRenderDirectFormat.red	0
+XRenderDirectFormat.redMask	2
+XRenderDirectFormat.green	4
+XRenderDirectFormat.greenMask	6
+XRenderDirectFormat.blue	8
+XRenderDirectFormat.blueMask	10
+XRenderDirectFormat.alpha	12
+XRenderDirectFormat.alphaMask	14
+XRenderDirectFormat	16
+ColorData.awt_Colors	0
+ColorData.awt_numICMcolors	8
+ColorData.awt_icmLUT	16
+ColorData.awt_icmLUT2Colors	24
+ColorData.img_grays	32
+ColorData.img_clr_tbl	40
+ColorData.img_oda_red	48
+ColorData.img_oda_green	56
+ColorData.img_oda_blue	64
+ColorData.pGrayInverseLutData	72
+ColorData.screendata	80
+ColorData	88
+XFontStruct.ext_data	0
+XFontStruct.fid	8
+XFontStruct.direction	16
+XFontStruct.min_char_or_byte2	20
+XFontStruct.max_char_or_byte2	24
+XFontStruct.min_byte1	28
+XFontStruct.max_byte1	32
+XFontStruct.all_chars_exist	36
+XFontStruct.n_properties	44
+XFontStruct.properties	48
+XFontStruct.min_bounds	56
+XFontStruct.max_bounds	68
+XFontStruct.per_char	80
+XFontStruct.ascent	88
+XFontStruct.descent	92
+XFontStruct	96
+XExtCodes.extension	0
+XExtCodes.major_opcode	4
+XExtCodes.first_event	8
+XExtCodes.first_error	12
+XExtCodes	16
+XFontSetExtents.max_ink_extent	0
+XFontSetExtents.max_logical_extent	8
+XFontSetExtents	16
+XSelectionEvent.type	0
+XSelectionEvent.serial	8
+XSelectionEvent.send_event	16
+XSelectionEvent.display	24
+XSelectionEvent.requestor	32
+XSelectionEvent.selection	40
+XSelectionEvent.target	48
+XSelectionEvent.property	56
+XSelectionEvent.time	64
+XSelectionEvent	72
+XArc.x	0
+XArc.y	2
+XArc.width	4
+XArc.height	6
+XArc.angle1	8
+XArc.angle2	10
+XArc	12
+XErrorEvent.type	0
+XErrorEvent.display	8
+XErrorEvent.resourceid	16
+XErrorEvent.serial	24
+XErrorEvent.error_code	32
+XErrorEvent.request_code	33
+XErrorEvent.minor_code	34
+XErrorEvent	40
+XConfigureRequestEvent.type	0
+XConfigureRequestEvent.serial	8
+XConfigureRequestEvent.send_event	16
+XConfigureRequestEvent.display	24
+XConfigureRequestEvent.parent	32
+XConfigureRequestEvent.window	40
+XConfigureRequestEvent.x	48
+XConfigureRequestEvent.y	52
+XConfigureRequestEvent.width	56
+XConfigureRequestEvent.height	60
+XConfigureRequestEvent.border_width	64
+XConfigureRequestEvent.above	72
+XConfigureRequestEvent.detail	80
+XConfigureRequestEvent.value_mask	88
+XConfigureRequestEvent	96
+ScreenFormat.ext_data	0
+ScreenFormat.depth	8
+ScreenFormat.bits_per_pixel	12
+ScreenFormat.scanline_pad	16
+ScreenFormat	24
+XButtonEvent.type	0
+XButtonEvent.serial	8
+XButtonEvent.send_event	16
+XButtonEvent.display	24
+XButtonEvent.window	32
+XButtonEvent.root	40
+XButtonEvent.subwindow	48
+XButtonEvent.time	56
+XButtonEvent.x	64
+XButtonEvent.y	68
+XButtonEvent.x_root	72
+XButtonEvent.y_root	76
+XButtonEvent.state	80
+XButtonEvent.button	84
+XButtonEvent.same_screen	88
+XButtonEvent	96
+XFontProp.name	0
+XFontProp.card32	8
+XFontProp	16
+XIMValuesList.count_values	0
+XIMValuesList.supported_values	8
+XIMValuesList	16
+XKeymapEvent.type	0
+XKeymapEvent.serial	8
+XKeymapEvent.send_event	16
+XKeymapEvent.display	24
+XKeymapEvent.window	32
+XKeymapEvent.key_vector	40
+XKeymapEvent	72
+XTextItem16.chars	0
+XTextItem16.nchars	8
+XTextItem16.delta	12
+XTextItem16.font	16
+XTextItem16	24
+XIMPreeditDrawCallbackStruct.caret	0
+XIMPreeditDrawCallbackStruct.chg_first	4
+XIMPreeditDrawCallbackStruct.chg_length	8
+XIMPreeditDrawCallbackStruct.text	16
+XIMPreeditDrawCallbackStruct	24
+XVisualInfo.visual	0
+XVisualInfo.visualid	8
+XVisualInfo.screen	16
+XVisualInfo.depth	20
+XVisualInfo.class	24
+XVisualInfo.red_mask	32
+XVisualInfo.green_mask	40
+XVisualInfo.blue_mask	48
+XVisualInfo.colormap_size	56
+XVisualInfo.bits_per_rgb	60
+XVisualInfo	64
+XkbControlsNotifyEvent.type	0
+XkbControlsNotifyEvent.serial	8
+XkbControlsNotifyEvent.send_event	16
+XkbControlsNotifyEvent.display	24
+XkbControlsNotifyEvent.time	32
+XkbControlsNotifyEvent.xkb_type	40
+XkbControlsNotifyEvent.device	44
+XkbControlsNotifyEvent.changed_ctrls	48
+XkbControlsNotifyEvent.enabled_ctrls	52
+XkbControlsNotifyEvent.enabled_ctrl_changes	56
+XkbControlsNotifyEvent.num_groups	60
+XkbControlsNotifyEvent.keycode	64
+XkbControlsNotifyEvent.event_type	65
+XkbControlsNotifyEvent.req_major	66
+XkbControlsNotifyEvent.req_minor	67
+XkbControlsNotifyEvent	72
+PropMwmHints.flags	0
+PropMwmHints.functions	8
+PropMwmHints.decorations	16
+PropMwmHints.inputMode	24
+PropMwmHints.status	32
+PropMwmHints	40
+XClientMessageEvent.type	0
+XClientMessageEvent.serial	8
+XClientMessageEvent.send_event	16
+XClientMessageEvent.display	24
+XClientMessageEvent.window	32
+XClientMessageEvent.message_type	40
+XClientMessageEvent.format	48
+XClientMessageEvent.data	56
+XClientMessageEvent	96
+XAnyEvent.type	0
+XAnyEvent.serial	8
+XAnyEvent.send_event	16
+XAnyEvent.display	24
+XAnyEvent.window	32
+XAnyEvent	40
+XkbIndicatorNotifyEvent.type	0
+XkbIndicatorNotifyEvent.serial	8
+XkbIndicatorNotifyEvent.send_event	16
+XkbIndicatorNotifyEvent.display	24
+XkbIndicatorNotifyEvent.time	32
+XkbIndicatorNotifyEvent.xkb_type	40
+XkbIndicatorNotifyEvent.device	44
+XkbIndicatorNotifyEvent.changed	48
+XkbIndicatorNotifyEvent.state	52
+XkbIndicatorNotifyEvent	56
+XIMPreeditStateNotifyCallbackStruct.state	0
+XIMPreeditStateNotifyCallbackStruct	8
+XkbAnyEvent.type	0
+XkbAnyEvent.serial	8
+XkbAnyEvent.send_event	16
+XkbAnyEvent.display	24
+XkbAnyEvent.time	32
+XkbAnyEvent.xkb_type	40
+XkbAnyEvent.device	44
+XkbAnyEvent	48
+XMotionEvent.type	0
+XMotionEvent.serial	8
+XMotionEvent.send_event	16
+XMotionEvent.display	24
+XMotionEvent.window	32
+XMotionEvent.root	40
+XMotionEvent.subwindow	48
+XMotionEvent.time	56
+XMotionEvent.x	64
+XMotionEvent.y	68
+XMotionEvent.x_root	72
+XMotionEvent.y_root	76
+XMotionEvent.state	80
+XMotionEvent.is_hint	84
+XMotionEvent.same_screen	88
+XMotionEvent	96
+XIMHotKeyTriggers.num_hot_key	0
+XIMHotKeyTriggers.key	8
+XIMHotKeyTriggers	16
+XIMStyles.count_styles	0
+XIMStyles.supported_styles	8
+XIMStyles	16
+XkbExtensionDeviceNotifyEvent.type	0
+XkbExtensionDeviceNotifyEvent.serial	8
+XkbExtensionDeviceNotifyEvent.send_event	16
+XkbExtensionDeviceNotifyEvent.display	24
+XkbExtensionDeviceNotifyEvent.time	32
+XkbExtensionDeviceNotifyEvent.xkb_type	40
+XkbExtensionDeviceNotifyEvent.device	44
+XkbExtensionDeviceNotifyEvent.reason	48
+XkbExtensionDeviceNotifyEvent.supported	52
+XkbExtensionDeviceNotifyEvent.unsupported	56
+XkbExtensionDeviceNotifyEvent.first_btn	60
+XkbExtensionDeviceNotifyEvent.num_btns	64
+XkbExtensionDeviceNotifyEvent.leds_defined	68
+XkbExtensionDeviceNotifyEvent.led_state	72
+XkbExtensionDeviceNotifyEvent.led_class	76
+XkbExtensionDeviceNotifyEvent.led_id	80
+XkbExtensionDeviceNotifyEvent	88
+XwcTextItem.chars	0
+XwcTextItem.nchars	8
+XwcTextItem.delta	12
+XwcTextItem.font_set	16
+XwcTextItem	24
+XClassHint.res_name	0
+XClassHint.res_class	8
+XClassHint	16
+XChar2b.byte1	0
+XChar2b.byte2	1
+XChar2b	2
+XSetWindowAttributes.background_pixmap	0
+XSetWindowAttributes.background_pixel	8
+XSetWindowAttributes.border_pixmap	16
+XSetWindowAttributes.border_pixel	24
+XSetWindowAttributes.bit_gravity	32
+XSetWindowAttributes.win_gravity	36
+XSetWindowAttributes.backing_store	40
+XSetWindowAttributes.backing_planes	48
+XSetWindowAttributes.backing_pixel	56
+XSetWindowAttributes.save_under	64
+XSetWindowAttributes.event_mask	72
+XSetWindowAttributes.do_not_propagate_mask	80
+XSetWindowAttributes.override_redirect	88
+XSetWindowAttributes.colormap	96
+XSetWindowAttributes.cursor	104
+XSetWindowAttributes	112
+XRenderPictFormat.id	0
+XRenderPictFormat.type	8
+XRenderPictFormat.depth	12
+XRenderPictFormat.direct	16
+XRenderPictFormat.colormap	32
+XRenderPictFormat	40
+XReparentEvent.type	0
+XReparentEvent.serial	8
+XReparentEvent.send_event	16
+XReparentEvent.display	24
+XReparentEvent.event	32
+XReparentEvent.window	40
+XReparentEvent.parent	48
+XReparentEvent.x	56
+XReparentEvent.y	60
+XReparentEvent.override_redirect	64
+XReparentEvent	72
+XCirculateRequestEvent.type	0
+XCirculateRequestEvent.serial	8
+XCirculateRequestEvent.send_event	16
+XCirculateRequestEvent.display	24
+XCirculateRequestEvent.parent	32
+XCirculateRequestEvent.window	40
+XCirculateRequestEvent.place	48
+XCirculateRequestEvent	56
+XImage.width	0
+XImage.height	4
+XImage.xoffset	8
+XImage.format	12
+XImage.data	16
+XImage.byte_order	24
+XImage.bitmap_unit	28
+XImage.bitmap_bit_order	32
+XImage.bitmap_pad	36
+XImage.depth	40
+XImage.bytes_per_line	44
+XImage.bits_per_pixel	48
+XImage.red_mask	56
+XImage.green_mask	64
+XImage.blue_mask	72
+XImage.obdata	80
+XImage.f.create_image	88
+XImage.f.destroy_image	96
+XImage.f.get_pixel	104
+XImage.f.put_pixel	112
+XImage.f.sub_image	120
+XImage.f.add_pixel	128
+XImage	136
+XKeyEvent.type	0
+XKeyEvent.serial	8
+XKeyEvent.send_event	16
+XKeyEvent.display	24
+XKeyEvent.window	32
+XKeyEvent.root	40
+XKeyEvent.subwindow	48
+XKeyEvent.time	56
+XKeyEvent.x	64
+XKeyEvent.y	68
+XKeyEvent.x_root	72
+XKeyEvent.y_root	76
+XKeyEvent.state	80
+XKeyEvent.keycode	84
+XKeyEvent.same_screen	88
+XKeyEvent	96
+XkbActionMessageEvent.type	0
+XkbActionMessageEvent.serial	8
+XkbActionMessageEvent.send_event	16
+XkbActionMessageEvent.display	24
+XkbActionMessageEvent.time	32
+XkbActionMessageEvent.xkb_type	40
+XkbActionMessageEvent.device	44
+XkbActionMessageEvent.keycode	48
+XkbActionMessageEvent.press	52
+XkbActionMessageEvent.key_event_follows	56
+XkbActionMessageEvent.group	60
+XkbActionMessageEvent.mods	64
+XkbActionMessageEvent.message	68
+XkbActionMessageEvent	80
+XdbeSwapInfo.swap_window	0
+XdbeSwapInfo.swap_action	8
+XdbeSwapInfo	16
+XTextItem.chars	0
+XTextItem.nchars	8
+XTextItem.delta	12
+XTextItem.font	16
+XTextItem	24
+XModifierKeymap.max_keypermod	0
+XModifierKeymap.modifiermap	8
+XModifierKeymap	16
+XCharStruct.lbearing	0
+XCharStruct.rbearing	2
+XCharStruct.width	4
+XCharStruct.ascent	6
+XCharStruct.descent	8
+XCharStruct.attributes	10
+XCharStruct	12
+XGravityEvent.type	0
+XGravityEvent.serial	8
+XGravityEvent.send_event	16
+XGravityEvent.display	24
+XGravityEvent.event	32
+XGravityEvent.window	40
+XGravityEvent.x	48
+XGravityEvent.y	52
+XGravityEvent	56
+Visual.ext_data	0
+Visual.visualid	8
+Visual.class	16
+Visual.red_mask	24
+Visual.green_mask	32
+Visual.blue_mask	40
+Visual.bits_per_rgb	48
+Visual.map_entries	52
+Visual	56
+XOMOrientation.num_orientation	0
+XOMOrientation.orientation	8
+XOMOrientation	16
+XkbAccessXNotifyEvent.type	0
+XkbAccessXNotifyEvent.serial	8
+XkbAccessXNotifyEvent.send_event	16
+XkbAccessXNotifyEvent.display	24
+XkbAccessXNotifyEvent.time	32
+XkbAccessXNotifyEvent.xkb_type	40
+XkbAccessXNotifyEvent.device	44
+XkbAccessXNotifyEvent.detail	48
+XkbAccessXNotifyEvent.keycode	52
+XkbAccessXNotifyEvent.sk_delay	56
+XkbAccessXNotifyEvent.debounce_delay	60
+XkbAccessXNotifyEvent	64
+XWindowAttributes.x	0
+XWindowAttributes.y	4
+XWindowAttributes.width	8
+XWindowAttributes.height	12
+XWindowAttributes.border_width	16
+XWindowAttributes.depth	20
+XWindowAttributes.visual	24
+XWindowAttributes.root	32
+XWindowAttributes.class	40
+XWindowAttributes.bit_gravity	44
+XWindowAttributes.win_gravity	48
+XWindowAttributes.backing_store	52
+XWindowAttributes.backing_planes	56
+XWindowAttributes.backing_pixel	64
+XWindowAttributes.save_under	72
+XWindowAttributes.colormap	80
+XWindowAttributes.map_installed	88
+XWindowAttributes.map_state	92
+XWindowAttributes.all_event_masks	96
+XWindowAttributes.your_event_mask	104
+XWindowAttributes.do_not_propagate_mask	112
+XWindowAttributes.override_redirect	120
+XWindowAttributes.screen	128
+XWindowAttributes	136
+XmbTextItem.chars	0
+XmbTextItem.nchars	8
+XmbTextItem.delta	12
+XmbTextItem.font_set	16
+XmbTextItem	24
+XMappingEvent.type	0
+XMappingEvent.serial	8
+XMappingEvent.send_event	16
+XMappingEvent.display	24
+XMappingEvent.window	32
+XMappingEvent.request	40
+XMappingEvent.first_keycode	44
+XMappingEvent.count	48
+XMappingEvent	56
+XSizeHints.flags	0
+XSizeHints.x	8
+XSizeHints.y	12
+XSizeHints.width	16
+XSizeHints.height	20
+XSizeHints.min_width	24
+XSizeHints.min_height	28
+XSizeHints.max_width	32
+XSizeHints.max_height	36
+XSizeHints.width_inc	40
+XSizeHints.height_inc	44
+XSizeHints.min_aspect.x	48
+XSizeHints.min_aspect.y	52
+XSizeHints.max_aspect.x	56
+XSizeHints.max_aspect.y	60
+XSizeHints.base_width	64
+XSizeHints.base_height	68
+XSizeHints.win_gravity	72
+XSizeHints	80
+XUnmapEvent.type	0
+XUnmapEvent.serial	8
+XUnmapEvent.send_event	16
+XUnmapEvent.display	24
+XUnmapEvent.event	32
+XUnmapEvent.window	40
+XUnmapEvent.from_configure	48
+XUnmapEvent	56
+awtImageData.Depth	0
+awtImageData.wsImageFormat	4
+awtImageData.clrdata	16
+awtImageData.convert	48
+awtImageData	560
+XkbStateNotifyEvent.type	0
+XkbStateNotifyEvent.serial	8
+XkbStateNotifyEvent.send_event	16
+XkbStateNotifyEvent.display	24
+XkbStateNotifyEvent.time	32
+XkbStateNotifyEvent.xkb_type	40
+XkbStateNotifyEvent.device	44
+XkbStateNotifyEvent.changed	48
+XkbStateNotifyEvent.group	52
+XkbStateNotifyEvent.base_group	56
+XkbStateNotifyEvent.latched_group	60
+XkbStateNotifyEvent.locked_group	64
+XkbStateNotifyEvent.mods	68
+XkbStateNotifyEvent.base_mods	72
+XkbStateNotifyEvent.latched_mods	76
+XkbStateNotifyEvent.locked_mods	80
+XkbStateNotifyEvent.compat_state	84
+XkbStateNotifyEvent.grab_mods	88
+XkbStateNotifyEvent.compat_grab_mods	89
+XkbStateNotifyEvent.lookup_mods	90
+XkbStateNotifyEvent.compat_lookup_mods	91
+XkbStateNotifyEvent.ptr_buttons	92
+XkbStateNotifyEvent.keycode	96
+XkbStateNotifyEvent.event_type	97
+XkbStateNotifyEvent.req_major	98
+XkbStateNotifyEvent.req_minor	99
+XkbStateNotifyEvent	104
+XExposeEvent.type	0
+XExposeEvent.serial	8
+XExposeEvent.send_event	16
+XExposeEvent.display	24
+XExposeEvent.window	32
+XExposeEvent.x	40
+XExposeEvent.y	44
+XExposeEvent.width	48
+XExposeEvent.height	52
+XExposeEvent.count	56
+XExposeEvent	64
+XkbMapNotifyEvent.type	0
+XkbMapNotifyEvent.serial	8
+XkbMapNotifyEvent.send_event	16
+XkbMapNotifyEvent.display	24
+XkbMapNotifyEvent.time	32
+XkbMapNotifyEvent.xkb_type	40
+XkbMapNotifyEvent.device	44
+XkbMapNotifyEvent.changed	48
+XkbMapNotifyEvent.flags	52
+XkbMapNotifyEvent.first_type	56
+XkbMapNotifyEvent.num_types	60
+XkbMapNotifyEvent.min_key_code	64
+XkbMapNotifyEvent.max_key_code	65
+XkbMapNotifyEvent.first_key_sym	66
+XkbMapNotifyEvent.first_key_act	67
+XkbMapNotifyEvent.first_key_behavior	68
+XkbMapNotifyEvent.first_key_explicit	69
+XkbMapNotifyEvent.first_modmap_key	70
+XkbMapNotifyEvent.first_vmodmap_key	71
+XkbMapNotifyEvent.num_key_syms	72
+XkbMapNotifyEvent.num_key_acts	76
+XkbMapNotifyEvent.num_key_behaviors	80
+XkbMapNotifyEvent.num_key_explicit	84
+XkbMapNotifyEvent.num_modmap_keys	88
+XkbMapNotifyEvent.num_vmodmap_keys	92
+XkbMapNotifyEvent.vmods	96
+XkbMapNotifyEvent	104
+XGCValues.function	0
+XGCValues.plane_mask	8
+XGCValues.foreground	16
+XGCValues.background	24
+XGCValues.line_width	32
+XGCValues.line_style	36
+XGCValues.cap_style	40
+XGCValues.join_style	44
+XGCValues.fill_style	48
+XGCValues.fill_rule	52
+XGCValues.arc_mode	56
+XGCValues.tile	64
+XGCValues.stipple	72
+XGCValues.ts_x_origin	80
+XGCValues.ts_y_origin	84
+XGCValues.font	88
+XGCValues.subwindow_mode	96
+XGCValues.graphics_exposures	100
+XGCValues.clip_x_origin	104
+XGCValues.clip_y_origin	108
+XGCValues.clip_mask	112
+XGCValues.dash_offset	120
+XGCValues.dashes	124
+XGCValues	128
+XFocusChangeEvent.type	0
+XFocusChangeEvent.serial	8
+XFocusChangeEvent.send_event	16
+XFocusChangeEvent.display	24
+XFocusChangeEvent.window	32
+XFocusChangeEvent.mode	40
+XFocusChangeEvent.detail	44
+XFocusChangeEvent	48
+XPixmapFormatValues.depth	0
+XPixmapFormatValues.bits_per_pixel	4
+XPixmapFormatValues.scanline_pad	8
+XPixmapFormatValues	12
+XMapEvent.type	0
+XMapEvent.serial	8
+XMapEvent.send_event	16
+XMapEvent.display	24
+XMapEvent.event	32
+XMapEvent.window	40
+XMapEvent.override_redirect	48
+XMapEvent	56
+XkbBellNotifyEvent.type	0
+XkbBellNotifyEvent.serial	8
+XkbBellNotifyEvent.send_event	16
+XkbBellNotifyEvent.display	24
+XkbBellNotifyEvent.time	32
+XkbBellNotifyEvent.xkb_type	40
+XkbBellNotifyEvent.device	44
+XkbBellNotifyEvent.percent	48
+XkbBellNotifyEvent.pitch	52
+XkbBellNotifyEvent.duration	56
+XkbBellNotifyEvent.bell_class	60
+XkbBellNotifyEvent.bell_id	64
+XkbBellNotifyEvent.name	72
+XkbBellNotifyEvent.window	80
+XkbBellNotifyEvent.event_only	88
+XkbBellNotifyEvent	96
+XIMStringConversionText.length	0
+XIMStringConversionText.feedback	8
+XIMStringConversionText.encoding_is_wchar	16
+XIMStringConversionText.string	24
+XIMStringConversionText	32
+XKeyboardState.key_click_percent	0
+XKeyboardState.bell_percent	4
+XKeyboardState.bell_pitch	8
+XKeyboardState.bell_duration	12
+XKeyboardState.led_mask	16
+XKeyboardState.global_auto_repeat	24
+XKeyboardState.auto_repeats	28
+XKeyboardState	64
+XkbEvent.type	0
+XkbEvent.any	0
+XkbEvent.new_kbd	0
+XkbEvent.map	0
+XkbEvent.state	0
+XkbEvent.ctrls	0
+XkbEvent.indicators	0
+XkbEvent.names	0
+XkbEvent.compat	0
+XkbEvent.bell	0
+XkbEvent.message	0
+XkbEvent.accessx	0
+XkbEvent.device	0
+XkbEvent.core	0
+XkbEvent	192
+XPoint.x	0
+XPoint.y	2
+XPoint	4
+XSegment.x1	0
+XSegment.y1	2
+XSegment.x2	4
+XSegment.y2	6
+XSegment	8
+XIconSize.min_width	0
+XIconSize.min_height	4
+XIconSize.max_width	8
+XIconSize.max_height	12
+XIconSize.width_inc	16
+XIconSize.height_inc	20
+XIconSize	24
+XIMCallback.client_data	0
+XIMCallback.callback	8
+XIMCallback	16
+XConfigureEvent.type	0
+XConfigureEvent.serial	8
+XConfigureEvent.send_event	16
+XConfigureEvent.display	24
+XConfigureEvent.event	32
+XConfigureEvent.window	40
+XConfigureEvent.x	48
+XConfigureEvent.y	52
+XConfigureEvent.width	56
+XConfigureEvent.height	60
+XConfigureEvent.border_width	64
+XConfigureEvent.above	72
+XConfigureEvent.override_redirect	80
+XConfigureEvent	88
+XRectangle.x	0
+XRectangle.y	2
+XRectangle.width	4
+XRectangle.height	6
+XRectangle	8
+XkbNamesNotifyEvent.type	0
+XkbNamesNotifyEvent.serial	8
+XkbNamesNotifyEvent.send_event	16
+XkbNamesNotifyEvent.display	24
+XkbNamesNotifyEvent.time	32
+XkbNamesNotifyEvent.xkb_type	40
+XkbNamesNotifyEvent.device	44
+XkbNamesNotifyEvent.changed	48
+XkbNamesNotifyEvent.first_type	52
+XkbNamesNotifyEvent.num_types	56
+XkbNamesNotifyEvent.first_lvl	60
+XkbNamesNotifyEvent.num_lvls	64
+XkbNamesNotifyEvent.num_aliases	68
+XkbNamesNotifyEvent.num_radio_groups	72
+XkbNamesNotifyEvent.changed_vmods	76
+XkbNamesNotifyEvent.changed_groups	80
+XkbNamesNotifyEvent.changed_indicators	84
+XkbNamesNotifyEvent.first_key	88
+XkbNamesNotifyEvent.num_keys	92
+XkbNamesNotifyEvent	96
+XCreateWindowEvent.type	0
+XCreateWindowEvent.serial	8
+XCreateWindowEvent.send_event	16
+XCreateWindowEvent.display	24
+XCreateWindowEvent.parent	32
+XCreateWindowEvent.window	40
+XCreateWindowEvent.x	48
+XCreateWindowEvent.y	52
+XCreateWindowEvent.width	56
+XCreateWindowEvent.height	60
+XCreateWindowEvent.border_width	64
+XCreateWindowEvent.override_redirect	68
+XCreateWindowEvent	72
+XVisibilityEvent.type	0
+XVisibilityEvent.serial	8
+XVisibilityEvent.send_event	16
+XVisibilityEvent.display	24
+XVisibilityEvent.window	32
+XVisibilityEvent.state	40
+XVisibilityEvent	48
+XWMHints.flags	0
+XWMHints.initial_state	12
+XWMHints.icon_pixmap	16
+XWMHints.icon_window	24
+XWMHints.icon_x	32
+XWMHints.icon_y	36
+XWMHints.icon_mask	40
+XWMHints.input	8
+XWMHints.window_group	48
+XWMHints	56
+XCrossingEvent.type	0
+XCrossingEvent.serial	8
+XCrossingEvent.send_event	16
+XCrossingEvent.display	24
+XCrossingEvent.window	32
+XCrossingEvent.root	40
+XCrossingEvent.subwindow	48
+XCrossingEvent.time	56
+XCrossingEvent.x	64
+XCrossingEvent.y	68
+XCrossingEvent.x_root	72
+XCrossingEvent.y_root	76
+XCrossingEvent.mode	80
+XCrossingEvent.detail	84
+XCrossingEvent.same_screen	88
+XCrossingEvent.focus	92
+XCrossingEvent.state	96
+XCrossingEvent	104
+XSelectionRequestEvent.type	0
+XSelectionRequestEvent.serial	8
+XSelectionRequestEvent.send_event	16
+XSelectionRequestEvent.display	24
+XSelectionRequestEvent.owner	32
+XSelectionRequestEvent.requestor	40
+XSelectionRequestEvent.selection	48
+XSelectionRequestEvent.target	56
+XSelectionRequestEvent.property	64
+XSelectionRequestEvent.time	72
+XSelectionRequestEvent	80
+XNoExposeEvent.type	0
+XNoExposeEvent.serial	8
+XNoExposeEvent.send_event	16
+XNoExposeEvent.display	24
+XNoExposeEvent.drawable	32
+XNoExposeEvent.major_code	40
+XNoExposeEvent.minor_code	44
+XNoExposeEvent	48
+XHostAddress.family	0
+XHostAddress.length	4
+XHostAddress.address	8
+XHostAddress	16
+XColormapEvent.type	0
+XColormapEvent.serial	8
+XColormapEvent.send_event	16
+XColormapEvent.display	24
+XColormapEvent.window	32
+XColormapEvent.colormap	40
+XColormapEvent.new	48
+XColormapEvent.state	52
+XColormapEvent	56
+ColorEntry.r	0
+ColorEntry.g	1
+ColorEntry.b	2
+ColorEntry.flags	3
+ColorEntry	4
+XResizeRequestEvent.type	0
+XResizeRequestEvent.serial	8
+XResizeRequestEvent.send_event	16
+XResizeRequestEvent.display	24
+XResizeRequestEvent.window	32
+XResizeRequestEvent.width	40
+XResizeRequestEvent.height	44
+XResizeRequestEvent	48
+Depth.depth	0
+Depth.nvisuals	4
+Depth.visuals	8
+Depth	16
+XPropertyEvent.type	0
+XPropertyEvent.serial	8
+XPropertyEvent.send_event	16
+XPropertyEvent.display	24
+XPropertyEvent.window	32
+XPropertyEvent.atom	40
+XPropertyEvent.time	48
+XPropertyEvent.state	56
+XPropertyEvent	64
+XDestroyWindowEvent.type	0
+XDestroyWindowEvent.serial	8
+XDestroyWindowEvent.send_event	16
+XDestroyWindowEvent.display	24
+XDestroyWindowEvent.event	32
+XDestroyWindowEvent.window	40
+XDestroyWindowEvent	48
+XStandardColormap.colormap	0
+XStandardColormap.red_max	8
+XStandardColormap.red_mult	16
+XStandardColormap.green_max	24
+XStandardColormap.green_mult	32
+XStandardColormap.blue_max	40
+XStandardColormap.blue_mult	48
+XStandardColormap.base_pixel	56
+XStandardColormap.visualid	64
+XStandardColormap.killid	72
+XStandardColormap	80
+XComposeStatus.compose_ptr	0
+XComposeStatus.chars_matched	8
+XComposeStatus	16
+AwtGraphicsConfigData.awt_depth	0
+AwtGraphicsConfigData.awt_cmap	8
+AwtGraphicsConfigData.awt_visInfo	16
+AwtGraphicsConfigData.awt_num_colors	80
+AwtGraphicsConfigData.awtImage	88
+AwtGraphicsConfigData.AwtColorMatch	96
+AwtGraphicsConfigData.monoImage	104
+AwtGraphicsConfigData.monoPixmap	112
+AwtGraphicsConfigData.monoPixmapWidth	120
+AwtGraphicsConfigData.monoPixmapHeight	124
+AwtGraphicsConfigData.monoPixmapGC	128
+AwtGraphicsConfigData.pixelStride	136
+AwtGraphicsConfigData.color_data	144
+AwtGraphicsConfigData.glxInfo	152
+AwtGraphicsConfigData.isTranslucencySupported	160
+AwtGraphicsConfigData.renderPictFormat	168
+AwtGraphicsConfigData	208
+XColor.pixel	0
+XColor.red	8
+XColor.green	10
+XColor.blue	12
+XColor.flags	14
+XColor.pad	15
+XColor	16
+XTextProperty.value	0
+XTextProperty.encoding	8
+XTextProperty.format	16
+XTextProperty.nitems	24
+XTextProperty	32
--- a/jdk/src/solaris/native/common/jdk_util_md.h	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/solaris/native/common/jdk_util_md.h	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/solaris/native/java/lang/java_props_md.c	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/solaris/native/java/lang/java_props_md.c	Tue Jan 22 11:54:16 2013 -0800
@@ -538,7 +538,12 @@
     sprops.display_script = sprops.script;
     sprops.display_country = sprops.country;
     sprops.display_variant = sprops.variant;
+
+#ifdef MACOSX
+    sprops.sun_jnu_encoding = "UTF-8";
+#else
     sprops.sun_jnu_encoding = sprops.encoding;
+#endif
 
 #ifdef _ALLBSD_SOURCE
 #if BYTE_ORDER == _LITTLE_ENDIAN
--- a/jdk/src/solaris/native/sun/tools/attach/BsdVirtualMachine.c	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/solaris/native/sun/tools/attach/BsdVirtualMachine.c	Tue Jan 22 11:54:16 2013 -0800
@@ -1,12 +1,12 @@
 /*
- * Copyright 2005, 2012, Oracle and/or its affiliates. All Rights Reserved.
+ * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Sun designates this
+ * published by the Free Software Foundation.  Oracle designates this
  * particular file as subject to the "Classpath" exception as provided
- * by Sun in the LICENSE file that accompanied this code.
+ * by Oracle in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
@@ -18,9 +18,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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 "jni.h"
--- a/jdk/src/windows/classes/java/net/DualStackPlainDatagramSocketImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/windows/classes/java/net/DualStackPlainDatagramSocketImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007,2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/windows/classes/sun/nio/ch/PipeImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/windows/classes/sun/nio/ch/PipeImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -72,67 +72,97 @@
 
         private final SelectorProvider sp;
 
+        private IOException ioe = null;
+
         private Initializer(SelectorProvider sp) {
             this.sp = sp;
         }
 
+        @Override
         public Void run() throws IOException {
-            ServerSocketChannel ssc = null;
-            SocketChannel sc1 = null;
-            SocketChannel sc2 = null;
-
-            try {
-                // loopback address
-                InetAddress lb = InetAddress.getByName("127.0.0.1");
-                assert(lb.isLoopbackAddress());
-
-                // bind ServerSocketChannel to a port on the loopback address
-                ssc = ServerSocketChannel.open();
-                ssc.socket().bind(new InetSocketAddress(lb, 0));
-
-                // Establish connection (assumes connections are eagerly
-                // accepted)
-                InetSocketAddress sa
-                    = new InetSocketAddress(lb, ssc.socket().getLocalPort());
-                sc1 = SocketChannel.open(sa);
-
-                ByteBuffer bb = ByteBuffer.allocate(8);
-                long secret = rnd.nextLong();
-                bb.putLong(secret).flip();
-                sc1.write(bb);
-
-                // Get a connection and verify it is legitimate
+            LoopbackConnector connector = new LoopbackConnector();
+            connector.run();
+            if (ioe instanceof ClosedByInterruptException) {
+                ioe = null;
+                Thread connThread = new Thread(connector) {
+                    @Override
+                    public void interrupt() {}
+                };
+                connThread.start();
                 for (;;) {
-                    sc2 = ssc.accept();
-                    bb.clear();
-                    sc2.read(bb);
-                    bb.rewind();
-                    if (bb.getLong() == secret)
+                    try {
+                        connThread.join();
                         break;
-                    sc2.close();
+                    } catch (InterruptedException ex) {}
                 }
+                Thread.currentThread().interrupt();
+            }
+
+            if (ioe != null)
+                throw new IOException("Unable to establish loopback connection", ioe);
 
-                // Create source and sink channels
-                source = new SourceChannelImpl(sp, sc1);
-                sink = new SinkChannelImpl(sp, sc2);
-            } catch (IOException e) {
+            return null;
+        }
+
+        private class LoopbackConnector implements Runnable {
+
+            @Override
+            public void run() {
+                ServerSocketChannel ssc = null;
+                SocketChannel sc1 = null;
+                SocketChannel sc2 = null;
+
                 try {
-                    if (sc1 != null)
-                        sc1.close();
-                    if (sc2 != null)
+                    // Loopback address
+                    InetAddress lb = InetAddress.getByName("127.0.0.1");
+                    assert(lb.isLoopbackAddress());
+                    InetSocketAddress sa = null;
+                    for(;;) {
+                        // Bind ServerSocketChannel to a port on the loopback
+                        // address
+                        if (ssc == null || !ssc.isOpen()) {
+                            ssc = ServerSocketChannel.open();
+                            ssc.socket().bind(new InetSocketAddress(lb, 0));
+                            sa = new InetSocketAddress(lb, ssc.socket().getLocalPort());
+                        }
+
+                        // Establish connection (assume connections are eagerly
+                        // accepted)
+                        sc1 = SocketChannel.open(sa);
+                        ByteBuffer bb = ByteBuffer.allocate(8);
+                        long secret = rnd.nextLong();
+                        bb.putLong(secret).flip();
+                        sc1.write(bb);
+
+                        // Get a connection and verify it is legitimate
+                        sc2 = ssc.accept();
+                        bb.clear();
+                        sc2.read(bb);
+                        bb.rewind();
+                        if (bb.getLong() == secret)
+                            break;
                         sc2.close();
-                } catch (IOException e2) { }
-                IOException x = new IOException("Unable to establish"
-                                                + " loopback connection");
-                x.initCause(e);
-                throw x;
-            } finally {
-                try {
-                    if (ssc != null)
-                        ssc.close();
-                } catch (IOException e2) { }
+                        sc1.close();
+                    }
+
+                    // Create source and sink channels
+                    source = new SourceChannelImpl(sp, sc1);
+                    sink = new SinkChannelImpl(sp, sc2);
+                } catch (IOException e) {
+                    try {
+                        if (sc1 != null)
+                            sc1.close();
+                        if (sc2 != null)
+                            sc2.close();
+                    } catch (IOException e2) {}
+                    ioe = e;
+                } finally {
+                    try {
+                        if (ssc != null)
+                            ssc.close();
+                    } catch (IOException e2) {}
+                }
             }
-            return null;
         }
     }
 
@@ -144,7 +174,6 @@
         }
     }
 
-
     public SourceChannel source() {
         return source;
     }
--- a/jdk/src/windows/classes/sun/nio/ch/PollArrayWrapper.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/windows/classes/sun/nio/ch/PollArrayWrapper.java	Tue Jan 22 11:54:16 2013 -0800
@@ -28,6 +28,8 @@
 
 package sun.nio.ch;
 
+import java.lang.annotation.Native;
+
 /**
  * Manipulates a native array of structs corresponding to (fd, events) pairs.
  *
@@ -46,19 +48,19 @@
 
     long pollArrayAddress; // pollArrayAddress
 
-    private static final short FD_OFFSET     = 0; // fd offset in pollfd
-    private static final short EVENT_OFFSET  = 4; // events offset in pollfd
+    @Native private static final short FD_OFFSET     = 0; // fd offset in pollfd
+    @Native private static final short EVENT_OFFSET  = 4; // events offset in pollfd
 
     static short SIZE_POLLFD = 8; // sizeof pollfd struct
 
     // events masks
-    static final short POLLIN     = AbstractPollArrayWrapper.POLLIN;
-    static final short POLLOUT    = AbstractPollArrayWrapper.POLLOUT;
-    static final short POLLERR    = AbstractPollArrayWrapper.POLLERR;
-    static final short POLLHUP    = AbstractPollArrayWrapper.POLLHUP;
-    static final short POLLNVAL   = AbstractPollArrayWrapper.POLLNVAL;
-    static final short POLLREMOVE = AbstractPollArrayWrapper.POLLREMOVE;
-    static final short POLLCONN   = 0x0002;
+    @Native static final short POLLIN     = AbstractPollArrayWrapper.POLLIN;
+    @Native static final short POLLOUT    = AbstractPollArrayWrapper.POLLOUT;
+    @Native static final short POLLERR    = AbstractPollArrayWrapper.POLLERR;
+    @Native static final short POLLHUP    = AbstractPollArrayWrapper.POLLHUP;
+    @Native static final short POLLNVAL   = AbstractPollArrayWrapper.POLLNVAL;
+    @Native static final short POLLREMOVE = AbstractPollArrayWrapper.POLLREMOVE;
+    @Native static final short POLLCONN   = 0x0002;
 
     private int size; // Size of the pollArray
 
--- a/jdk/src/windows/native/common/jdk_util_md.h	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/windows/native/common/jdk_util_md.h	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/src/windows/native/sun/windows/awt_Debug.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/src/windows/native/sun/windows/awt_Debug.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -147,6 +147,24 @@
     DTrace_Shutdown();
 }
 
+static jboolean isHeadless() {
+    jmethodID headlessFn;
+    JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
+    jclass graphicsEnvClass = env->FindClass(
+        "java/awt/GraphicsEnvironment");
+
+    if (graphicsEnvClass != NULL) {
+        headlessFn = env->GetStaticMethodID(
+            graphicsEnvClass, "isHeadless", "()Z");
+        if (headlessFn != NULL) {
+            return env->CallStaticBooleanMethod(graphicsEnvClass,
+                                                headlessFn);
+        }
+    }
+    return true;
+}
+
+
 void AwtDebugSupport::AssertCallback(const char * expr, const char * file, int line) {
     static const int ASSERT_MSG_SIZE = 1024;
     static const char * AssertFmt =
@@ -158,7 +176,8 @@
     static char assertMsg[ASSERT_MSG_SIZE+1];
     DWORD   lastError = GetLastError();
     LPSTR       msgBuffer = NULL;
-    int     ret;
+    int     ret = IDNO;
+    static jboolean headless = isHeadless();
 
     FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                   FORMAT_MESSAGE_FROM_SYSTEM |
@@ -183,8 +202,11 @@
     fprintf(stderr, "*********************\n");
     fprintf(stderr, "%s\n", assertMsg);
     fprintf(stderr, "*********************\n");
-    ret = MessageBoxA(NULL, assertMsg, "AWT Assertion Failure",
-        MB_YESNO|MB_ICONSTOP|MB_TASKMODAL);
+
+    if (!headless) {
+        ret = MessageBoxA(NULL, assertMsg, "AWT Assertion Failure",
+                          MB_YESNO|MB_ICONSTOP|MB_TASKMODAL);
+    }
 
     // if clicked Yes, break into the debugger
     if ( ret == IDYES ) {
--- a/jdk/test/ProblemList.txt	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/ProblemList.txt	Tue Jan 22 11:54:16 2013 -0800
@@ -1,6 +1,6 @@
 ###########################################################################
 #
-# Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -122,9 +122,6 @@
 
 # jdk_lang
 
-# 7194607
-java/lang/instrument/VerifyLocalVariableTableOnRetransformTest.sh generic-all
-
 # 6944188
 java/lang/management/ThreadMXBean/ThreadStateTest.java          generic-all
 
@@ -141,9 +138,6 @@
 
 # jdk_management
 
-# 7158614
-sun/management/jmxremote/startstop/JMXStartStopTest.sh		linux-all
-
 ############################################################################
 
 # jdk_jmx
@@ -151,8 +145,8 @@
 # 6959636
 javax/management/loading/LibraryLoader/LibraryLoaderTest.java	windows-all
 
-# 7120365
-javax/management/remote/mandatory/notif/DiffHBTest.java 	generic-all
+# 8005472
+com/sun/jmx/remote/NotificationMarshalVersions/TestSerializationMismatch.sh windows-all
 
 ############################################################################
 
@@ -244,9 +238,6 @@
 # 7146541
 java/rmi/transport/rapidExportUnexport/RapidExportUnexport.java	linux-all
 
-# 7187882
-java/rmi/activation/checkusage/CheckUsage.java                  generic-all
-
 # 7190106
 java/rmi/reliability/benchmark/runRmiBench.sh                   generic-all
 
@@ -330,6 +321,9 @@
 # 7150569
 tools/launcher/UnicodeTest.java                                 macosx-all
 
+# 8005252
+tools/pack200/AttributeTests.java                               generic-all
+
 ############################################################################
 
 # jdk_jdi
--- a/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4512524.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4512524.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -40,13 +40,13 @@
 public class Test4512524 {
 
     private static final String ALGO = "AES";
-    private static final String MODE = "CBC";
     private static final String PADDING = "NoPadding";
     private static final int KEYSIZE = 16; // in bytes
 
-    public boolean execute() throws Exception {
+    public void execute(String mode) throws Exception {
 
-        Cipher ci = Cipher.getInstance(ALGO+"/"+MODE+"/"+PADDING, "SunJCE");
+        String transformation = ALGO+"/"+mode+"/"+PADDING;
+        Cipher ci = Cipher.getInstance(transformation, "SunJCE");
 
         // TEST FIX 4512524
         KeyGenerator kg = KeyGenerator.getInstance(ALGO, "SunJCE");
@@ -61,17 +61,14 @@
         }
 
         // passed all tests...hooray!
-        return true;
+        System.out.println(transformation + ": Passed");
     }
 
     public static void main (String[] args) throws Exception {
         Security.addProvider(new com.sun.crypto.provider.SunJCE());
 
         Test4512524 test = new Test4512524();
-        String testName = test.getClass().getName() + "[" + ALGO +
-            "/" + MODE + "/" + PADDING + "]";
-        if (test.execute()) {
-            System.out.println(testName + ": Passed!");
-        }
+        test.execute("CBC");
+        test.execute("GCM");
     }
 }
--- a/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4512704.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4512704.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -39,14 +39,14 @@
 
 public class Test4512704 {
     private static final String ALGO = "AES";
-    private static final String MODE = "CBC";
-    private static final String PADDING = "PKCS5Padding";
+    private static final String PADDING = "NoPadding";
     private static final int KEYSIZE = 16; // in bytes
 
-    public boolean execute() throws Exception {
+    public void execute(String mode) throws Exception {
+
         AlgorithmParameterSpec aps = null;
-
-        Cipher ci = Cipher.getInstance(ALGO+"/"+MODE+"/"+PADDING, "SunJCE");
+        String transformation = ALGO + "/" + mode + "/"+PADDING;
+        Cipher ci = Cipher.getInstance(transformation, "SunJCE");
 
         KeyGenerator kg = KeyGenerator.getInstance(ALGO, "SunJCE");
         kg.init(KEYSIZE*8);
@@ -57,19 +57,14 @@
         } catch(InvalidAlgorithmParameterException ex) {
             throw new Exception("parameter should be generated when null is specified!");
         }
-
-        // passed all tests...hooray!
-        return true;
+        System.out.println(transformation + ": Passed");
     }
 
     public static void main (String[] args) throws Exception {
         Security.addProvider(new com.sun.crypto.provider.SunJCE());
 
         Test4512704 test = new Test4512704();
-        String testName = test.getClass().getName() + "[" + ALGO +
-            "/" + MODE + "/" + PADDING + "]";
-        if (test.execute()) {
-            System.out.println(testName + ": Passed!");
-        }
+        test.execute("CBC");
+        test.execute("GCM");
     }
 }
--- a/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4517355.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4517355.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,16 +41,14 @@
 public class Test4517355 {
 
     private static final String ALGO = "AES";
-    private static final String MODE = "CBC";
-    private static final String PADDING = "PKCS5Padding";
     private static final int KEYSIZE = 16; // in bytes
 
-    public boolean execute() throws Exception {
-        Random rdm = new Random();
-        byte[] plainText=new byte[125];
-        rdm.nextBytes(plainText);
+    private static byte[] plainText = new byte[125];
 
-        Cipher ci = Cipher.getInstance(ALGO+"/"+MODE+"/"+PADDING, "SunJCE");
+    public void execute(String mode, String padding) throws Exception {
+        String transformation = ALGO + "/" + mode + "/" + padding;
+
+        Cipher ci = Cipher.getInstance(transformation, "SunJCE");
         KeyGenerator kg = KeyGenerator.getInstance(ALGO, "SunJCE");
         kg.init(KEYSIZE*8);
         SecretKey key = kg.generateKey();
@@ -59,9 +57,14 @@
         ci.init(Cipher.ENCRYPT_MODE, key);
         byte[] cipherText = ci.doFinal(plainText);
 
-        byte[] iv = ci.getIV();
-        AlgorithmParameterSpec aps = new IvParameterSpec(iv);
-        ci.init(Cipher.DECRYPT_MODE, key, aps);
+        if (mode.equalsIgnoreCase("GCM")) {
+            AlgorithmParameters params = ci.getParameters();
+            ci.init(Cipher.DECRYPT_MODE, key, params);
+        } else {
+            byte[] iv = ci.getIV();
+            AlgorithmParameterSpec aps = new IvParameterSpec(iv);
+            ci.init(Cipher.DECRYPT_MODE, key, aps);
+        }
         byte[] recoveredText = new byte[plainText.length];
         try {
             int len = ci.doFinal(cipherText, 0, cipherText.length,
@@ -80,21 +83,22 @@
             throw new Exception("encryption does not work!");
         }
         // 3. make sure padding is working
-        if ((cipherText.length/16)*16 != cipherText.length) {
-            throw new Exception("padding does not work!");
+        if (padding.equalsIgnoreCase("PKCS5Padding")) {
+            if ((cipherText.length/16)*16 != cipherText.length) {
+                throw new Exception("padding does not work!");
+            }
         }
-        // passed all tests...hooray!
-        return true;
+        System.out.println(transformation + ": Passed");
     }
 
     public static void main (String[] args) throws Exception {
         Security.addProvider(new com.sun.crypto.provider.SunJCE());
 
         Test4517355 test = new Test4517355();
-        String testName = test.getClass().getName() + "[" + ALGO +
-            "/" + MODE + "/" + PADDING + "]";
-        if (test.execute()) {
-            System.out.println(testName + ": Passed!");
-        }
+        Random rdm = new Random();
+        rdm.nextBytes(test.plainText);
+
+        test.execute("CBC", "PKCS5Padding");
+        test.execute("GCM", "NoPadding");
     }
 }
--- a/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4626070.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/Test4626070.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,13 +34,11 @@
 
 public class Test4626070 {
     private static final String ALGO = "AES";
-    private static final String MODE = "CBC";
-    private static final String PADDING = "PKCS5Padding";
     private static final int KEYSIZE = 16; // in bytes
 
-    public boolean execute() throws Exception {
-
-        Cipher ci = Cipher.getInstance(ALGO+"/"+MODE+"/"+PADDING, "SunJCE");
+    public void execute(String mode, String padding) throws Exception {
+        String transformation = ALGO + "/" + mode + "/" + padding;
+        Cipher ci = Cipher.getInstance(transformation, "SunJCE");
         KeyGenerator kg = KeyGenerator.getInstance(ALGO, "SunJCE");
         kg.init(KEYSIZE*8);
         SecretKey key = kg.generateKey();
@@ -58,18 +56,14 @@
             throw new Exception(
                 "key after wrap/unwrap is different from the original!");
         }
-        // passed all tests...hooray!
-        return true;
+        System.out.println(transformation + ": Passed");
     }
 
     public static void main (String[] args) throws Exception {
         Security.addProvider(new com.sun.crypto.provider.SunJCE());
 
         Test4626070 test = new Test4626070();
-        String testName = test.getClass().getName() + "[" + ALGO +
-            "/" + MODE + "/" + PADDING + "]";
-        if (test.execute()) {
-            System.out.println(testName + ": Passed!");
-        }
+        test.execute("CBC", "PKCS5Padding");
+        test.execute("GCM", "NoPadding");
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestGCMKeyAndIvCheck.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,178 @@
+/*
+ * 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 6996769
+ * @library ../UTIL
+ * @build TestUtil
+ * @run main TestGCMKeyAndIvCheck
+ * @summary Ensure that same key+iv can't be repeated used for encryption.
+ * @author Valerie Peng
+ */
+
+
+import java.security.*;
+import javax.crypto.*;
+import javax.crypto.spec.*;
+import java.math.*;
+import com.sun.crypto.provider.*;
+
+import java.util.*;
+
+public class TestGCMKeyAndIvCheck {
+
+    private static final byte[] AAD = new byte[5];
+    private static final byte[] PT = new byte[18];
+
+    private static void checkISE(Cipher c) throws Exception {
+        // Subsequent encryptions should fail
+        try {
+            c.updateAAD(AAD);
+            throw new Exception("Should throw ISE for updateAAD()");
+        } catch (IllegalStateException ise) {
+            // expected
+        }
+
+        try {
+            c.update(PT);
+            throw new Exception("Should throw ISE for update()");
+        } catch (IllegalStateException ise) {
+            // expected
+        }
+        try {
+            c.doFinal(PT);
+            throw new Exception("Should throw ISE for doFinal()");
+        } catch (IllegalStateException ise) {
+            // expected
+        }
+    }
+
+    public void test() throws Exception {
+        Cipher c = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE");
+
+        SecretKey key = new SecretKeySpec(new byte[16], "AES");
+        // First try parameter-less init.
+        c.init(Cipher.ENCRYPT_MODE, key);
+        c.updateAAD(AAD);
+        byte[] ctPlusTag = c.doFinal(PT);
+
+        // subsequent encryption should fail unless re-init w/ different key+iv
+        checkISE(c);
+
+        // Validate the retrieved parameters against the IV and tag length.
+        AlgorithmParameters params = c.getParameters();
+        if (params == null) {
+            throw new Exception("getParameters() should not return null");
+        }
+        GCMParameterSpec spec = params.getParameterSpec(GCMParameterSpec.class);
+        if (spec.getTLen() != (ctPlusTag.length - PT.length)*8) {
+            throw new Exception("Parameters contains incorrect TLen value");
+        }
+        if (!Arrays.equals(spec.getIV(), c.getIV())) {
+            throw new Exception("Parameters contains incorrect IV value");
+        }
+
+        // Should be ok to use the same key+iv for decryption
+        c.init(Cipher.DECRYPT_MODE, key, params);
+        c.updateAAD(AAD);
+        byte[] recovered = c.doFinal(ctPlusTag);
+        if (!Arrays.equals(recovered, PT)) {
+            throw new Exception("decryption result mismatch");
+        }
+
+        // Now try to encrypt again using the same key+iv; should fail also
+        try {
+            c.init(Cipher.ENCRYPT_MODE, key, params);
+            throw new Exception("Should throw exception when same key+iv is used");
+        } catch (InvalidAlgorithmParameterException iape) {
+            // expected
+        }
+
+        // Now try to encrypt again using parameter-less init; should work
+        c.init(Cipher.ENCRYPT_MODE, key);
+        c.doFinal(PT);
+
+        // make sure a different iv is used
+        byte[] iv = c.getIV();
+        if (Arrays.equals(spec.getIV(), iv)) {
+            throw new Exception("IV should be different now");
+        }
+
+        // Now try to encrypt again using a different parameter; should work
+        c.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, new byte[30]));
+        c.updateAAD(AAD);
+        c.doFinal(PT);
+        // subsequent encryption should fail unless re-init w/ different key+iv
+        checkISE(c);
+
+        // Now try decryption twice in a row; no re-init required and
+        // same parameters is used.
+        c.init(Cipher.DECRYPT_MODE, key, params);
+        c.updateAAD(AAD);
+        recovered = c.doFinal(ctPlusTag);
+
+        c.updateAAD(AAD);
+        recovered = c.doFinal(ctPlusTag);
+        if (!Arrays.equals(recovered, PT)) {
+            throw new Exception("decryption result mismatch");
+        }
+
+        // Now try decryption again and re-init using the same parameters
+        c.init(Cipher.DECRYPT_MODE, key, params);
+        c.updateAAD(AAD);
+        recovered = c.doFinal(ctPlusTag);
+
+        // init to decrypt w/o parameters; should fail with IKE as
+        // javadoc specified
+        try {
+            c.init(Cipher.DECRYPT_MODE, key);
+            throw new Exception("Should throw IKE for dec w/o params");
+        } catch (InvalidKeyException ike) {
+            // expected
+        }
+
+        // Lastly, try encryption AND decryption w/ wrong type of parameters,
+        // e.g. IvParameterSpec
+        try {
+            c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
+            throw new Exception("Should throw IAPE");
+        } catch (InvalidAlgorithmParameterException iape) {
+            // expected
+        }
+        try {
+            c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
+            throw new Exception("Should throw IAPE");
+        } catch (InvalidAlgorithmParameterException iape) {
+            // expected
+        }
+
+        System.out.println("Test Passed!");
+    }
+
+    public static void main (String[] args) throws Exception {
+        TestGCMKeyAndIvCheck t = new TestGCMKeyAndIvCheck();
+        t.test();
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestKATForGCM.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,314 @@
+/*
+ * 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 6996769
+ * @library ../UTIL
+ * @build TestUtil
+ * @run main TestKATForGCM
+ * @summary Known Answer Test for AES cipher with GCM mode support in
+ * SunJCE provider.
+ * @author Valerie Peng
+ */
+
+
+import java.security.*;
+import javax.crypto.*;
+import javax.crypto.spec.*;
+import java.math.*;
+import com.sun.crypto.provider.*;
+
+import java.util.*;
+
+public class TestKATForGCM {
+
+    // Utility methods
+    private static byte[] HexToBytes(String hexVal) {
+        if (hexVal == null) return new byte[0];
+        byte[] result = new byte[hexVal.length()/2];
+        for (int i = 0; i < result.length; i++) {
+            // 2 characters at a time
+            String byteVal = hexVal.substring(2*i, 2*i +2);
+            result[i] = Integer.valueOf(byteVal, 16).byteValue();
+        }
+        return result;
+    }
+
+    private static class TestVector {
+        SecretKey key;
+        byte[] plainText;
+        byte[] aad;
+        byte[] cipherText;
+        byte[] tag;
+        GCMParameterSpec spec;
+        String info;
+
+        TestVector(String key, String iv, String pt, String aad,
+                   String ct, String tag) {
+            this.key = new SecretKeySpec(HexToBytes(key), "AES");
+            this.plainText = HexToBytes(pt);
+            this.aad = HexToBytes(aad);
+            this.cipherText = HexToBytes(ct);
+            this.tag = HexToBytes(tag);
+            this.spec = new GCMParameterSpec(this.tag.length * 8, HexToBytes(iv));
+            this.info = "key=" + key + ", iv=" + iv + ", pt=" + pt +
+                ",aad=" + aad + ", ct=" + ct + ", tag=" + tag;
+        }
+
+        public String toString() {
+            return info;
+        }
+    }
+
+    // These test vectors are found off NIST's CAVP page
+    // http://csrc.nist.gov/groups/STM/cavp/index.html
+    // inside the link named "GCM Test Vectors", i.e.
+    // http://csrc.nist.gov/groups/STM/cavp/documents/mac/gcmtestvectors.zip
+    // CAVS 14.0, set of test vectors w/ count = 0, keysize = 128
+    private static TestVector[] testValues = {
+        // 96-bit iv w/ 128/120/112/104/96-bit tags
+        // no plain text, no aad
+        new TestVector("11754cd72aec309bf52f7687212e8957",
+                       "3c819d9a9bed087615030b65",
+                       null, null, null,
+                       "250327c674aaf477aef2675748cf6971"),
+        new TestVector("272f16edb81a7abbea887357a58c1917",
+                       "794ec588176c703d3d2a7a07",
+                       null, null, null,
+                       "b6e6f197168f5049aeda32dafbdaeb"),
+        new TestVector("81b6844aab6a568c4556a2eb7eae752f",
+                       "ce600f59618315a6829bef4d",
+                       null, null, null,
+                       "89b43e9dbc1b4f597dbbc7655bb5"),
+        new TestVector("cde2f9a9b1a004165ef9dc981f18651b",
+                       "29512c29566c7322e1e33e8e",
+                       null, null, null,
+                       "2e58ce7dabd107c82759c66a75"),
+        new TestVector("b01e45cc3088aaba9fa43d81d481823f",
+                       "5a2c4a66468713456a4bd5e1",
+                       null, null, null,
+                       "014280f944f53c681164b2ff"),
+        // 96-bit iv w/ 128/120/112/104/96-bit tags
+        // no plain text, 16-byte aad
+        new TestVector("77be63708971c4e240d1cb79e8d77feb",
+                       "e0e00f19fed7ba0136a797f3",
+                       null,
+                       "7a43ec1d9c0a5a78a0b16533a6213cab",
+                       null,
+                       "209fcc8d3675ed938e9c7166709dd946"),
+        new TestVector("da0b615656135194ba6d3c851099bc48",
+                       "d39d4b4d3cc927885090e6c3",
+                       null,
+                       "e7e5e6f8dac913036cb2ff29e8625e0e",
+                       null,
+                       "ab967711a5770461724460b07237e2"),
+        new TestVector("7e0986937a88eef894235aba4a2f43b2",
+                       "92c4a631695907166b422d60",
+                       null,
+                       "85c185f8518f9f2cd597a8f9208fc76b",
+                       null,
+                       "3bb916b728df94fe9d1916736be1"),
+        new TestVector("c3db570d7f0c21e86b028f11465d1dc9",
+                       "f86970f58ceef89fc7cb679e",
+                       null,
+                       "c095240708c0f57c288d86090ae34ee1",
+                       null,
+                       "e043c52160d652e82c7262fcf4"),
+        new TestVector("bea48ae4980d27f357611014d4486625",
+                       "32bddb5c3aa998a08556454c",
+                       null,
+                       "8a50b0b8c7654bced884f7f3afda2ead",
+                       null,
+                       "8e0f6d8bf05ffebe6f500eb1"),
+        // 96-bit iv w/ 128/120/112/104/96-bit tags
+        // no plain text, 20-byte aad
+        new TestVector("2fb45e5b8f993a2bfebc4b15b533e0b4",
+                       "5b05755f984d2b90f94b8027",
+                       null,
+                       "e85491b2202caf1d7dce03b97e09331c32473941",
+                       null,
+                       "c75b7832b2a2d9bd827412b6ef5769db"),
+        new TestVector("9bf406339fcef9675bbcf156aa1a0661",
+                       "8be4a9543d40f542abacac95",
+                       null,
+                       "7167cbf56971793186333a6685bbd58d47d379b3",
+                       null,
+                       "5e7968d7bbd5ba58cfcc750e2ef8f1"),
+        new TestVector("a2e962fff70fd0f4d63be728b80556fc",
+                       "1fa7103483de43d09bc23db4",
+                       null,
+                       "2a58edf1d53f46e4e7ee5e77ee7aeb60fc360658",
+                       null,
+                       "fa37f2dbbefab1451eae1d0d74ca"),
+        new TestVector("6bf4fdce82926dcdfc52616ed5f23695",
+                       "cc0f5899a10615567e1193ed",
+                       null,
+                       "3340655592374c1da2f05aac3ee111014986107f",
+                       null,
+                       "8ad3385cce3b5e7c985908192c"),
+        new TestVector("4df7a13e43c3d7b66b1a72fac5ba398e",
+                       "97179a3a2d417908dcf0fb28",
+                       null,
+                       "cbb7fc0010c255661e23b07dbd804b1e06ae70ac",
+                       null,
+                       "37791edae6c137ea946cfb40"),
+        // 96-bit iv w/ 128-bit tags, 13/16/32/51-byte plain text, no aad
+        new TestVector("fe9bb47deb3a61e423c2231841cfd1fb",
+                       "4d328eb776f500a2f7fb47aa",
+                       "f1cc3818e421876bb6b8bbd6c9",
+                       null,
+                       "b88c5c1977b35b517b0aeae967",
+                       "43fd4727fe5cdb4b5b42818dea7ef8c9"),
+        new TestVector("7fddb57453c241d03efbed3ac44e371c",
+                       "ee283a3fc75575e33efd4887",
+                       "d5de42b461646c255c87bd2962d3b9a2",
+                       null,
+                       "2ccda4a5415cb91e135c2a0f78c9b2fd",
+                       "b36d1df9b9d5e596f83e8b7f52971cb3"),
+        new TestVector("9971071059abc009e4f2bd69869db338",
+                       "07a9a95ea3821e9c13c63251",
+                       "f54bc3501fed4f6f6dfb5ea80106df0bd836e6826225b75c0222f6e859b35983",
+                       null,
+                       "0556c159f84ef36cb1602b4526b12009c775611bffb64dc0d9ca9297cd2c6a01",
+                       "7870d9117f54811a346970f1de090c41"),
+        new TestVector("594157ec4693202b030f33798b07176d",
+                       "49b12054082660803a1df3df",
+
+"3feef98a976a1bd634f364ac428bb59cd51fb159ec1789946918dbd50ea6c9d594a3a31a5269b0da6936c29d063a5fa2cc8a1c",
+                      null,
+
+"c1b7a46a335f23d65b8db4008a49796906e225474f4fe7d39e55bf2efd97fd82d4167de082ae30fa01e465a601235d8d68bc69",
+                      "ba92d3661ce8b04687e8788d55417dc2"),
+        // 96-bit iv w/ 128-bit tags, 16-byte plain text, 16/20/48/90-byte aad
+        new TestVector("c939cc13397c1d37de6ae0e1cb7c423c",
+                       "b3d8cc017cbb89b39e0f67e2",
+                       "c3b3c41f113a31b73d9a5cd432103069",
+                       "24825602bd12a984e0092d3e448eda5f",
+                       "93fe7d9e9bfd10348a5606e5cafa7354",
+                       "0032a1dc85f1c9786925a2e71d8272dd"),
+        new TestVector("d4a22488f8dd1d5c6c19a7d6ca17964c",
+                       "f3d5837f22ac1a0425e0d1d5",
+                       "7b43016a16896497fb457be6d2a54122",
+                       "f1c5d424b83f96c6ad8cb28ca0d20e475e023b5a",
+                       "c2bd67eef5e95cac27e3b06e3031d0a8",
+                       "f23eacf9d1cdf8737726c58648826e9c"),
+        new TestVector("89850dd398e1f1e28443a33d40162664",
+                       "e462c58482fe8264aeeb7231",
+                       "2805cdefb3ef6cc35cd1f169f98da81a",
+
+"d74e99d1bdaa712864eec422ac507bddbe2b0d4633cd3dff29ce5059b49fe868526c59a2a3a604457bc2afea866e7606",
+                       "ba80e244b7fc9025cd031d0f63677e06",
+                       "d84a8c3eac57d1bb0e890a8f461d1065"),
+        new TestVector("bd7c5c63b7542b56a00ebe71336a1588",
+                       "87721f23ba9c3c8ea5571abc",
+                       "de15ddbb1e202161e8a79af6a55ac6f3",
+
+"a6ec8075a0d3370eb7598918f3b93e48444751624997b899a87fa6a9939f844e008aa8b70e9f4c3b1a19d3286bf543e7127bfecba1ad17a5ec53fccc26faecacc4c75369498eaa7d706aef634d0009279b11e4ba6c993e5e9ed9",
+                       "41eb28c0fee4d762de972361c863bc80",
+                       "9cb567220d0b252eb97bff46e4b00ff8"),
+        // 8/1024-bit iv w/ 128-bit tag, no plain text, no aad
+        new TestVector("1672c3537afa82004c6b8a46f6f0d026",
+                       "05",
+                       null, null, null,
+                       "8e2ad721f9455f74d8b53d3141f27e8e"),
+        new TestVector("d0f1f4defa1e8c08b4b26d576392027c",
+
+"42b4f01eb9f5a1ea5b1eb73b0fb0baed54f387ecaa0393c7d7dffc6af50146ecc021abf7eb9038d4303d91f8d741a11743166c0860208bcc02c6258fd9511a2fa626f96d60b72fcff773af4e88e7a923506e4916ecbd814651e9f445adef4ad6a6b6c7290cc13b956130eef5b837c939fcac0cbbcc9656cd75b13823ee5acdac",
+                       null, null, null,
+                       "7ab49b57ddf5f62c427950111c5c4f0d"),
+        // 8-bit iv w/ 128-bit tag, 13-byte plain text, 90-byte aad
+        new TestVector("9f79239f0904eace50784b863e723f6b",
+                       "d9",
+                       "bdb0bb10c87965acd34d146171",
+
+"44db436089327726c5f01139e1f339735c9e85514ccc2f167bad728010fb34a9072a9794c8a5e7361b1d0dbcdc9ac4091e354bb2896561f0486645252e9c78c86beece91bfa4f7cc4a8794ce1f305b1b735efdbf1ed1563c0be0",
+                       "7e5a7c8dadb3f0c7335b4d9d8d",
+                       "6b6ef1f53723a89f3bb7c6d043840717"),
+        // 1024-bit iv w/ 128-bit tag, 51-byte plain text, 48-byte aad
+        new TestVector("141f1ce91989b07e7eb6ae1dbd81ea5e",
+
+"49451da24bd6074509d3cebc2c0394c972e6934b45a1d91f3ce1d3ca69e194aa1958a7c21b6f21d530ce6d2cc5256a3f846b6f9d2f38df0102c4791e57df038f6e69085646007df999751e248e06c47245f4cd3b8004585a7470dee1690e9d2d63169a58d243c0b57b3e5b4a481a3e4e8c60007094ef3adea2e8f05dd3a1396f",
+
+"d384305af2388699aa302f510913fed0f2cb63ba42efa8c5c9de2922a2ec2fe87719dadf1eb0aef212b51e74c9c5b934104a43",
+
+"630cf18a91cc5a6481ac9eefd65c24b1a3c93396bd7294d6b8ba323951727666c947a21894a079ef061ee159c05beeb4",
+
+"f4c34e5fbe74c0297313268296cd561d59ccc95bbfcdfcdc71b0097dbd83240446b28dc088abd42b0fc687f208190ff24c0548",
+                      "dbb93bbb56d0439cd09f620a57687f5d"),
+    };
+
+    public boolean execute(TestVector[] testValues) throws Exception {
+        boolean testFailed = false;
+        Cipher c = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE");
+        for (int i = 0; i < testValues.length; i++) {
+            try {
+                c.init(Cipher.ENCRYPT_MODE, testValues[i].key, testValues[i].spec);
+                c.updateAAD(testValues[i].aad);
+                byte[] ctPlusTag = c.doFinal(testValues[i].plainText);
+
+                c.init(Cipher.DECRYPT_MODE, testValues[i].key, testValues[i].spec);
+                c.updateAAD(testValues[i].aad);
+                byte[] pt = c.doFinal(ctPlusTag); // should fail if tag mismatched
+
+                // check encryption/decryption results just to be sure
+                if (!Arrays.equals(testValues[i].plainText, pt)) {
+                    System.out.println("PlainText diff failed for test# " + i);
+                    testFailed = true;
+                }
+                int ctLen = testValues[i].cipherText.length;
+                if (!Arrays.equals(testValues[i].cipherText,
+                                   Arrays.copyOf(ctPlusTag, ctLen))) {
+                    System.out.println("CipherText diff failed for test# " + i);
+                    testFailed = true;
+                }
+                int tagLen = testValues[i].tag.length;
+                if (!Arrays.equals
+                    (testValues[i].tag,
+                     Arrays.copyOfRange(ctPlusTag, ctLen, ctLen+tagLen))) {
+                    System.out.println("Tag diff failed for test# " + i);
+                    testFailed = true;
+                }
+            } catch (Exception ex) {
+                // continue testing other test vectors
+                System.out.println("Failed Test Vector: " + testValues[i]);
+                ex.printStackTrace();
+                testFailed = true;
+                continue;
+            }
+        }
+        if (testFailed) {
+            throw new Exception("Test Failed");
+        }
+        // passed all tests...hooray!
+        return true;
+    }
+
+    public static void main (String[] args) throws Exception {
+        TestKATForGCM test = new TestKATForGCM();
+        if (test.execute(testValues)) {
+            System.out.println("Test Passed!");
+        }
+    }
+}
+
--- a/jdk/test/com/sun/java/swing/plaf/windows/WindowsRadioButtonUI/7089914/bug7089914.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/com/sun/java/swing/plaf/windows/WindowsRadioButtonUI/7089914/bug7089914.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/jmx/remote/CCAdminReconnectTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 7009998
+ * @summary Tests the correct processing of concurrent ClientComunicatorAdmin reconnect requests.
+ * @author Jaroslav Bachorik
+ * @run clean CCAdminReconnectTest
+ * @run build CCAdminReconnectTest
+ * @run main CCAdminReconnectTest
+ */
+
+import com.sun.jmx.remote.internal.ClientCommunicatorAdmin;
+import java.io.*;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+public class CCAdminReconnectTest {
+    final private static int THREAD_COUNT = 3;
+
+    public static void main(String ... args) throws Exception {
+        final ExecutorService e = Executors.newFixedThreadPool(THREAD_COUNT);
+        final AtomicBoolean beingReconnected = new AtomicBoolean();
+        final Collection<Exception> thrownExceptions = new LinkedList<>();
+
+        System.out.println(": Testing concurrent restart of ClientCommunicatorAdmin");
+
+        final ClientCommunicatorAdmin cca = new ClientCommunicatorAdmin(50) {
+
+            @Override
+            protected void checkConnection() throws IOException {
+                // empty
+            }
+
+            @Override
+            protected void doStart() throws IOException {
+                if (!beingReconnected.compareAndSet(false, true)) {
+                    IOException e = new IOException("Detected overlayed reconnect requests");
+                    thrownExceptions.add(e);
+                    throw e;
+                }
+                try {
+                    Thread.sleep(800); // simulating a workload
+                    beingReconnected.set(false);
+                } catch (InterruptedException e) {
+                }
+            }
+
+            @Override
+            protected void doStop() {
+                // empty
+            }
+        };
+
+        Runnable r = new Runnable() {
+            final private IOException e = new IOException("Forced reconnect");
+            @Override
+            public void run() {
+                try {
+                    // forcing the reconnect request
+                    cca.gotIOException(e);
+                } catch (Exception ex) {
+                    ex.printStackTrace();
+                }
+            }
+        };
+
+        System.out.println(": Spawning " + THREAD_COUNT + " concurrent reconnect requests");
+
+        for(int i=0;i<THREAD_COUNT;i++) {
+            e.execute(r);
+        }
+
+        Thread.sleep(THREAD_COUNT * 1000);
+        e.shutdown();
+        e.awaitTermination(10, TimeUnit.SECONDS);
+
+        cca.terminate();
+
+        for(Exception thrown : thrownExceptions) {
+            throw thrown;
+        }
+        System.out.println(": Requests processed successfully");
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/jmx/remote/NotificationMarshalVersions/Client/Client.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,47 @@
+
+import java.nio.charset.Charset;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardWatchEventKinds;
+import java.nio.file.WatchEvent;
+import java.nio.file.WatchService;
+import javax.management.MBeanServerConnection;
+import javax.management.Notification;
+import javax.management.NotificationListener;
+import javax.management.ObjectName;
+import javax.management.remote.JMXConnector;
+import javax.management.remote.JMXConnectorFactory;
+import javax.management.remote.JMXServiceURL;
+
+public class Client {
+    public static void main(String[] argv) throws Exception {
+        if (argv.length != 1) throw new IllegalArgumentException("Expecting exactly one jmx url argument");
+
+        JMXServiceURL serverUrl = new JMXServiceURL(argv[0]);
+
+        ObjectName name = new ObjectName("test", "foo", "bar");
+        JMXConnector jmxConnector = JMXConnectorFactory.connect(serverUrl);
+        System.out.println("client connected");
+        jmxConnector.addConnectionNotificationListener(new NotificationListener() {
+            public void handleNotification(Notification notification, Object handback) {
+                System.err.println("no!" + notification);
+            }
+        }, null, null);
+        MBeanServerConnection jmxServer = jmxConnector.getMBeanServerConnection();
+
+        jmxServer.addNotificationListener(name, new NotificationListener() {
+            public void handleNotification(Notification notification, Object handback) {
+                System.out.println("client got:" + notification);
+            }
+        }, null, null);
+
+        for(int i=0;i<10;i++) {
+            System.out.println("client invoking foo");
+            jmxServer.invoke(name, "foo", new Object[]{}, new String[]{});
+            Thread.sleep(50);
+        }
+
+        System.err.println("happy!");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/jmx/remote/NotificationMarshalVersions/Client/ConfigKey.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,3 @@
+public enum ConfigKey {
+    CONSTANT3, CONSTANT2;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/jmx/remote/NotificationMarshalVersions/Client/TestNotification.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,25 @@
+
+import javax.management.Notification;
+
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+/**
+ *
+ * @author Jaroslav Bachorik <jaroslav.bachorik at oracle.com>
+ */
+public class TestNotification extends Notification {
+    private ConfigKey key;
+
+    public TestNotification(String type, Object source, long sequenceNumber) {
+        super(type, source, sequenceNumber);
+        key = ConfigKey.CONSTANT3;
+    }
+
+    @Override
+    public String toString() {
+        return "TestNotification{" + "key=" + key + '}';
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/jmx/remote/NotificationMarshalVersions/Server/ConfigKey.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,3 @@
+public enum ConfigKey {
+    CONSTANT1, CONSTANT2;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/jmx/remote/NotificationMarshalVersions/Server/Server.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,46 @@
+import java.lang.management.ManagementFactory;
+import java.net.BindException;
+import java.nio.charset.Charset;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.rmi.registry.LocateRegistry;
+import java.rmi.server.ExportException;
+import java.util.Random;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+import javax.management.remote.JMXConnectorServer;
+import javax.management.remote.JMXConnectorServerFactory;
+import javax.management.remote.JMXServiceURL;
+
+public class Server {
+    public static void main(String[] argv) throws Exception {
+        int serverPort = 12345;
+        ObjectName name = new ObjectName("test", "foo", "bar");
+        MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
+        SteMBean bean = new Ste();
+        jmxServer.registerMBean(bean, name);
+        boolean exported = false;
+        Random rnd = new Random(System.currentTimeMillis());
+        do {
+            try {
+                LocateRegistry.createRegistry(serverPort);
+                exported = true;
+            } catch (ExportException ee) {
+                if (ee.getCause() instanceof BindException) {
+                    serverPort = rnd.nextInt(10000) + 4096;
+                } else {
+                    throw ee;
+                }
+            }
+
+        } while (!exported);
+        JMXServiceURL serverUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + serverPort + "/test");
+        JMXConnectorServer jmxConnector = JMXConnectorServerFactory.newJMXConnectorServer(serverUrl, null, jmxServer);
+        jmxConnector.start();
+        System.out.println(serverUrl);
+        System.err.println("server listening on " + serverUrl);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/jmx/remote/NotificationMarshalVersions/Server/Ste.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,10 @@
+
+import javax.management.NotificationBroadcasterSupport;
+
+public class Ste extends NotificationBroadcasterSupport implements SteMBean {
+    private long count = 0;
+
+    public void foo() {
+        sendNotification(new TestNotification("test", this, count++));
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/jmx/remote/NotificationMarshalVersions/Server/SteMBean.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,3 @@
+public interface SteMBean {
+    public void foo();
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/jmx/remote/NotificationMarshalVersions/Server/TestNotification.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,25 @@
+
+import javax.management.Notification;
+
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+/**
+ *
+ * @author Jaroslav Bachorik <jaroslav.bachorik at oracle.com>
+ */
+public class TestNotification extends Notification {
+    private ConfigKey key;
+
+    public TestNotification(String type, Object source, long sequenceNumber) {
+        super(type, source, sequenceNumber);
+        key = ConfigKey.CONSTANT1;
+    }
+
+    @Override
+    public String toString() {
+        return "TestNotification{" + "key=" + key + '}';
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/jmx/remote/NotificationMarshalVersions/TestSerializationMismatch.sh	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,93 @@
+#
+# Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+# 
+# @test
+# @summary  Tests for the RMI unmarshalling errors not to cause silent failure.
+# @author   Jaroslav Bachorik
+# @bug      6937053
+#
+# @run shell TestSerializationMismatch.sh
+#
+
+#set -x
+
+#Set appropriate jdk
+#
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+SERVER_TESTCLASSES=$TESTCLASSES/Server
+CLIENT_TESTCLASSES=$TESTCLASSES/Client
+
+URL_PATH=$SERVER_TESTCLASSES/jmxurl
+
+rm $URL_PATH
+
+mkdir -p $SERVER_TESTCLASSES
+mkdir -p $CLIENT_TESTCLASSES
+
+$TESTJAVA/bin/javac -d $CLIENT_TESTCLASSES $TESTSRC/Client/ConfigKey.java $TESTSRC/Client/TestNotification.java $TESTSRC/Client/Client.java
+$TESTJAVA/bin/javac -d $SERVER_TESTCLASSES $TESTSRC/Server/ConfigKey.java $TESTSRC/Server/TestNotification.java $TESTSRC/Server/SteMBean.java $TESTSRC/Server/Ste.java $TESTSRC/Server/Server.java
+
+startServer()
+{
+   ($TESTJAVA/bin/java -classpath $SERVER_TESTCLASSES Server) 1>$URL_PATH &
+   SERVER_PID=$!
+}
+
+runClient() 
+{
+   while true
+   do
+      [ -f $URL_PATH ] && break
+      sleep 2
+   done
+   read JMXURL < $URL_PATH
+   
+   HAS_ERRORS=`($TESTJAVA/bin/java -classpath $CLIENT_TESTCLASSES Client $JMXURL) 2>&1 | grep -i "SEVERE: Failed to fetch notification, stopping thread. Error is: java.rmi.UnmarshalException"`
+}
+
+startServer
+
+runClient
+
+sleep 1 # wait for notifications to arrive
+
+kill "$SERVER_PID"
+
+if [ -z "$HAS_ERRORS" ]
+then
+  echo "Test PASSED"
+  exit 0
+fi
+
+echo "Test FAILED"
+echo $HAS_ERRORS 1>&2
+exit 1
+
--- a/jdk/test/java/awt/Focus/6981400/Test1.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/Focus/6981400/Test1.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/awt/Focus/6981400/Test2.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/Focus/6981400/Test2.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/awt/Focus/6981400/Test3.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/Focus/6981400/Test3.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/awt/Frame/ResizeAfterSetFont/ResizeAfterSetFont.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/Frame/ResizeAfterSetFont/ResizeAfterSetFont.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/awt/JAWT/JAWT.sh	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/JAWT/JAWT.sh	Tue Jan 22 11:54:16 2013 -0800
@@ -1,6 +1,6 @@
 #!/bin/sh
 
-# Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/awt/JAWT/Makefile.cygwin	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/JAWT/Makefile.cygwin	Tue Jan 22 11:54:16 2013 -0800
@@ -1,4 +1,4 @@
-# Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/awt/JAWT/Makefile.unix	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/JAWT/Makefile.unix	Tue Jan 22 11:54:16 2013 -0800
@@ -1,4 +1,4 @@
-# Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/awt/JAWT/Makefile.win	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/JAWT/Makefile.win	Tue Jan 22 11:54:16 2013 -0800
@@ -1,4 +1,4 @@
-# Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/awt/JAWT/MyCanvas.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/JAWT/MyCanvas.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /**
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/awt/JAWT/myfile.c	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/JAWT/myfile.c	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/awt/JAWT/myfile.cpp	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/JAWT/myfile.cpp	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/awt/TextArea/DisposeTest/TestDispose.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/TextArea/DisposeTest/TestDispose.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/awt/TextArea/TextAreaCaretVisibilityTest/bug7129742.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/TextArea/TextAreaCaretVisibilityTest/bug7129742.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/awt/TextField/DisposeTest/TestDispose.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/awt/TextField/DisposeTest/TestDispose.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/beans/Introspector/Test8005065.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8005065
+ * @summary Tests that all arrays in JavaBeans are guarded
+ * @author Sergey Malenkov
+ */
+
+import java.beans.DefaultPersistenceDelegate;
+import java.beans.Encoder;
+import java.beans.EventSetDescriptor;
+import java.beans.ExceptionListener;
+import java.beans.Expression;
+import java.beans.Statement;
+import java.beans.MethodDescriptor;
+import java.beans.ParameterDescriptor;
+
+public class Test8005065 {
+
+    public static void main(String[] args) {
+        testDefaultPersistenceDelegate();
+        testEventSetDescriptor();
+        testMethodDescriptor();
+        testStatement();
+    }
+
+    private static void testDefaultPersistenceDelegate() {
+        Encoder encoder = new Encoder();
+        String[] array = { "array" };
+        MyDPD dpd = new MyDPD(array);
+        dpd.instantiate(dpd, encoder);
+        array[0] = null;
+        dpd.instantiate(dpd, encoder);
+    }
+
+    private static void testEventSetDescriptor() {
+        try {
+            MethodDescriptor[] array = { new MethodDescriptor(MyDPD.class.getMethod("getArray")) };
+            EventSetDescriptor descriptor = new EventSetDescriptor(null, null, array, null, null);
+            test(descriptor.getListenerMethodDescriptors());
+            array[0] = null;
+            test(descriptor.getListenerMethodDescriptors());
+            descriptor.getListenerMethodDescriptors()[0] = null;
+            test(descriptor.getListenerMethodDescriptors());
+        }
+        catch (Exception exception) {
+            throw new Error("unexpected error", exception);
+        }
+    }
+
+    private static void testMethodDescriptor() {
+        try {
+            ParameterDescriptor[] array = { new ParameterDescriptor() };
+            MethodDescriptor descriptor = new MethodDescriptor(MyDPD.class.getMethod("getArray"), array);
+            test(descriptor.getParameterDescriptors());
+            array[0] = null;
+            test(descriptor.getParameterDescriptors());
+            descriptor.getParameterDescriptors()[0] = null;
+            test(descriptor.getParameterDescriptors());
+        }
+        catch (Exception exception) {
+            throw new Error("unexpected error", exception);
+        }
+    }
+
+    private static void testStatement() {
+        Object[] array = { new Object() };
+        Statement statement = new Statement(null, null, array);
+        test(statement.getArguments());
+        array[0] = null;
+        test(statement.getArguments());
+        statement.getArguments()[0] = null;
+        test(statement.getArguments());
+    }
+
+    private static <T> void test(T[] array) {
+        if (array.length != 1) {
+            throw new Error("unexpected array length");
+        }
+        if (array[0] == null) {
+            throw new Error("unexpected array content");
+        }
+    }
+
+    public static class MyDPD
+            extends DefaultPersistenceDelegate
+            implements ExceptionListener {
+
+        private final String[] array;
+
+        public MyDPD(String[] array) {
+            super(array);
+            this.array = array;
+        }
+
+        public Expression instantiate(Object instance, Encoder encoder) {
+            encoder.setExceptionListener(this);
+            return super.instantiate(instance, encoder);
+        }
+
+        public String[] getArray() {
+            return this.array;
+        }
+
+        public void exceptionThrown(Exception exception) {
+            throw new Error("unexpected error", exception);
+        }
+    }
+}
--- a/jdk/test/java/io/Serializable/resolveProxyClass/NonPublicInterface.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/io/Serializable/resolveProxyClass/NonPublicInterface.java	Tue Jan 22 11:54:16 2013 -0800
@@ -22,14 +22,17 @@
  */
 
 /* @test
- * @bug 4413817
+ * @bug 4413817 8004928
  * @summary Verify that ObjectInputStream.resolveProxyClass can properly
  *          resolve a dynamic proxy class which implements a non-public
  *          interface not defined in the latest user defined class loader.
  */
 
 import java.io.*;
-import java.lang.reflect.*;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Proxy;
 
 public class NonPublicInterface {
 
@@ -39,35 +42,19 @@
         }
     }
 
+    public static final String nonPublicIntrfaceName = "java.util.zip.ZipConstants";
+
     public static void main(String[] args) throws Exception {
-        Class nonPublic = null;
-        String[] nonPublicInterfaces = new String[] {
-            "java.awt.Conditional",
-            "java.util.zip.ZipConstants",
-            "javax.swing.GraphicsWrapper",
-            "javax.swing.JPopupMenu$Popup",
-            "javax.swing.JTable$Resizable2",
-            "javax.swing.JTable$Resizable3",
-            "javax.swing.ToolTipManager$Popup",
-            "sun.audio.Format",
-            "sun.audio.HaePlayable",
-            "sun.tools.agent.StepConstants",
-        };
-        for (int i = 0; i < nonPublicInterfaces.length; i++) {
-            try {
-                nonPublic = Class.forName(nonPublicInterfaces[i]);
-                break;
-            } catch (ClassNotFoundException ex) {
-            }
-        }
-        if (nonPublic == null) {
-            throw new Error("couldn't find system non-public interface");
+        Class<?> nonPublic = Class.forName(nonPublicIntrfaceName);
+        if (Modifier.isPublic(nonPublic.getModifiers())) {
+            throw new Error("Interface " + nonPublicIntrfaceName +
+                    " is public and need to be changed!");
         }
 
         ByteArrayOutputStream bout = new ByteArrayOutputStream();
         ObjectOutputStream oout = new ObjectOutputStream(bout);
         oout.writeObject(Proxy.newProxyInstance(nonPublic.getClassLoader(),
-            new Class[]{ nonPublic }, new Handler()));
+            new Class<?>[]{ nonPublic }, new Handler()));
         oout.close();
         ObjectInputStream oin = new ObjectInputStream(
             new ByteArrayInputStream(bout.toByteArray()));
--- a/jdk/test/java/lang/Integer/Unsigned.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/Integer/Unsigned.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  */
 
 /*
--- a/jdk/test/java/lang/Long/Unsigned.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/Long/Unsigned.java	Tue Jan 22 11:54:16 2013 -0800
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  */
 
 /*
--- a/jdk/test/java/lang/Math/CubeRootTests.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/Math/CubeRootTests.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/lang/Math/Expm1Tests.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/Math/Expm1Tests.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/lang/Math/HyperbolicTests.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/Math/HyperbolicTests.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/lang/Math/Log10Tests.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/Math/Log10Tests.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/lang/Math/Log1pTests.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/Math/Log1pTests.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/lang/Math/Tests.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/Math/Tests.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/lang/Runtime/exec/WinCommand.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/Runtime/exec/WinCommand.java	Tue Jan 22 11:54:16 2013 -0800
@@ -135,24 +135,19 @@
 
         // Win9x systems don't have a cmd.exe
         if (new File(systemDirW, "cmd.exe").exists()) {
-            try {
-                out.println("Running cmd.exe tests...");
-                writeFile("cdcmd.cmd", "@echo off\r\nCD\r\n");
-                writeFile("cdbat.bat", "@echo off\r\nCD\r\n");
-                checkCD("cmd",
-                        "cmd.exe",
-                        systemDirW + "\\cmd.exe",
-                        // Only the ".exe" extension can be omitted
-                        systemDirW + "\\cmd",
-                        systemDirM + "/cmd.exe",
-                        systemDirM + "/cmd",
-                        "/" + systemDirM + "/cmd",
-                        "cdcmd.cmd", "./cdcmd.cmd", ".\\cdcmd.cmd",
-                        "cdbat.bat", "./cdbat.bat", ".\\cdbat.bat");
-            } finally {
-                new File("cdcmd.cmd").delete();
-                new File("cdbat.bat").delete();
-            }
+            out.println("Running cmd.exe tests...");
+            writeFile("cdcmd.cmd", "@echo off\r\nCD\r\n");
+            writeFile("cdbat.bat", "@echo off\r\nCD\r\n");
+            checkCD("cmd",
+                    "cmd.exe",
+                    systemDirW + "\\cmd.exe",
+                    // Only the ".exe" extension can be omitted
+                    systemDirW + "\\cmd",
+                    systemDirM + "/cmd.exe",
+                    systemDirM + "/cmd",
+                    "/" + systemDirM + "/cmd",
+                    "cdcmd.cmd", "./cdcmd.cmd", ".\\cdcmd.cmd",
+                    "cdbat.bat", "./cdbat.bat", ".\\cdbat.bat");
         }
 
         // 16-bit apps like command.com must have a console;
--- a/jdk/test/java/lang/StringBuffer/TestSynchronization.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/StringBuffer/TestSynchronization.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/System/MacJNUEncoding/ExpectedEncoding.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * Check that the value of file.encoding and sun.jnu.encoding match the expected
+ * values passed in on the command-line.
+ */
+public class ExpectedEncoding {
+    public static void main(String[] args) {
+        boolean failed = false;
+        if (args.length != 2) {
+            System.out.println("Usage:");
+            System.out.println("$ java ExpectedEncoding <expected file.encoding> <expected sun.jnu.encoding>");
+            System.exit(1);
+        }
+        String expectFileEnc = args[0];
+        String expectSunJnuEnc = args[1];
+
+        String fileEnc = System.getProperty("file.encoding");
+        String jnuEnc = System.getProperty("sun.jnu.encoding");
+
+        if (fileEnc == null || !fileEnc.equals(expectFileEnc)) {
+            System.err.println("Expected file.encoding: " + expectFileEnc);
+            System.err.println("Actual file.encoding: " + fileEnc);
+            failed = true;
+        }
+        if (jnuEnc == null || !jnuEnc.equals(expectSunJnuEnc)) {
+            System.err.println("Expected sun.jnu.encoding: " + expectSunJnuEnc);
+            System.err.println("Actual sun.jnu.encoding: " + jnuEnc);
+            failed = true;
+        }
+        if (failed) {
+            throw new RuntimeException("Test Failed");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/System/MacJNUEncoding/MacJNUEncoding.sh	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,96 @@
+#!/bin/sh
+
+#
+# Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+
+# @test
+# @bug 8003228
+# @summary Test the value of sun.jnu.encoding on Mac
+# @author Brent Christian
+#
+# @run shell MacJNUEncoding.sh
+
+# Only run test on Mac
+OS=`uname -s`
+case "$OS" in
+  Darwin )  ;;
+  * )
+    exit 0
+    ;;
+esac
+
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+JAVAC="${TESTJAVA}"/bin/javac
+JAVA="${TESTJAVA}"/bin/java
+
+echo "Building test classes..."
+"$JAVAC" -d "${TESTCLASSES}" "${TESTSRC}"/ExpectedEncoding.java 
+
+echo ""
+echo "Running test for C locale"
+export LANG=C
+export LC_ALL=C
+"${JAVA}" ${TESTVMOPTS} -classpath "${TESTCLASSES}" ExpectedEncoding US-ASCII UTF-8
+result1=$?
+
+echo ""
+echo "Running test for en_US.UTF-8 locale"
+export LANG=en_US.UTF-8
+export LC_ALL=en_US.UTF-8
+"${JAVA}" ${TESTVMOPTS} -classpath "${TESTCLASSES}" ExpectedEncoding UTF-8 UTF-8
+result2=$?
+
+echo ""
+echo "Cleanup"
+rm ${TESTCLASSES}/ExpectedEncoding.class
+
+if [ ${result1} -ne 0 ] ; then
+    echo "Test failed for C locale"
+    echo "  LANG=\"${LANG}\""
+    echo "  LC_ALL=\"${LC_ALL}\""
+    exit ${result1}
+fi
+if [ ${result2} -ne 0 ] ; then
+    echo "Test failed for en_US.UTF-8 locale"
+    echo "  LANG=\"${LANG}\""
+    echo "  LC_ALL=\"${LC_ALL}\""
+    exit ${result2}
+fi
+exit 0
+
--- a/jdk/test/java/lang/Throwable/LegacyChainedExceptionSerialization.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/Throwable/LegacyChainedExceptionSerialization.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
 
 /**
  * @test
- * @bug     4385429
+ * @bug     4385429 8004928
  * @summary Certain legacy chained exceptions throw IllegalArgumentException
  *          upon deserialization if "causative exception" is null.
  * @author  Josh Bloch
@@ -36,8 +36,7 @@
         new ExceptionInInitializerError(),
         new java.lang.reflect.UndeclaredThrowableException(null),
         new java.lang.reflect.InvocationTargetException(null),
-        new java.security.PrivilegedActionException(null),
-        new java.awt.print.PrinterIOException(null)
+        new java.security.PrivilegedActionException(null)
     };
 
     public static void main(String[] args) throws Exception {
--- a/jdk/test/java/lang/invoke/remote/RemoteExample.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/invoke/remote/RemoteExample.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,12 +1,12 @@
 /*
- * Copyright 2009-2010 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Sun designates this
+ * published by the Free Software Foundation.  Oracle designates this
  * particular file as subject to the "Classpath" exception as provided
- * by Sun in the LICENSE file that accompanied this code.
+ * by Oracle in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
@@ -18,9 +18,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
  */
 package test.java.lang.invoke.remote;
 
--- a/jdk/test/java/lang/management/CompilationMXBean/Basic.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/management/CompilationMXBean/Basic.java	Tue Jan 22 11:54:16 2013 -0800
@@ -23,10 +23,10 @@
 
 /*
  * @test
- * @bug 5011189
+ * @bug 5011189 8004928
  * @summary Unit test for java.lang.management.CompilationMXBean
  *
- * @run main/othervm -Xcomp -Xbatch -Djava.awt.headless=true Basic
+ * @run main/othervm -Xcomp -Xbatch Basic
  */
 import java.lang.management.*;
 
@@ -65,8 +65,6 @@
 
         java.util.Locale.getAvailableLocales();
         java.security.Security.getProviders();
-        java.awt.Toolkit.getDefaultToolkit();
-        javax.swing.UIManager.getInstalledLookAndFeels();
         java.nio.channels.spi.SelectorProvider.provider();
 
         time = mb.getTotalCompilationTime();
--- a/jdk/test/java/lang/reflect/Generics/Probe.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/reflect/Generics/Probe.java	Tue Jan 22 11:54:16 2013 -0800
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 5003916 6704655 6873951 6476261
+ * @bug 5003916 6704655 6873951 6476261 8004928
  * @summary Testing parsing of signatures attributes of nested classes
  * @author Joseph D. Darcy
  */
@@ -52,8 +52,7 @@
           "java.util.HashMap$ValueIterator",
           "java.util.LinkedHashMap$EntryIterator",
           "java.util.LinkedHashMap$KeyIterator",
-          "java.util.LinkedHashMap$ValueIterator",
-          "javax.swing.JComboBox$AccessibleJComboBox"})
+          "java.util.LinkedHashMap$ValueIterator"})
 public class Probe {
     public static void main (String... args) throws Throwable {
         Classes classesAnnotation = (Probe.class).getAnnotation(Classes.class);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Method/IsDefaultTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8005042
+ * @summary Check behavior of Method.isDefault
+ * @author Joseph D. Darcy
+ */
+
+import java.lang.reflect.*;
+import java.lang.annotation.*;
+import java.util.*;
+
+public class IsDefaultTest {
+    public static void main(String... argv) throws Exception {
+        int failures = 0;
+        int visitationCount = 0;
+
+        List<Class<?>> classList = new ArrayList<>();
+        classList.add(TestType1.class);
+        classList.add(TestType2.class);
+        classList.add(TestType3.class);
+        classList.add(TestType4.class);
+
+        for(Class<?> clazz: classList) {
+            for(Method method: clazz.getDeclaredMethods()) {
+                ExpectedIsDefault expectedIsDefault = method.getAnnotation(ExpectedIsDefault.class);
+                if (expectedIsDefault != null) {
+                    visitationCount++;
+                    boolean expected = expectedIsDefault.value();
+                    boolean actual   = method.isDefault();
+
+                    if (actual != expected) {
+                        failures++;
+                        System.err.printf("ERROR: On %s expected isDefault of ''%s''; got ''%s''.\n",
+                                          method.toString(), expected, actual);
+                    }
+                }
+            }
+        }
+
+        if (visitationCount == 0) {
+            System.err.println("Test failed because no methods checked.");
+            throw new RuntimeException();
+        }
+
+        if (failures > 0) {
+            System.err.println("Test failed.");
+            throw new RuntimeException();
+        }
+    }
+}
+
+interface TestType1 {
+    @ExpectedIsDefault(false)
+    void foo();
+
+    @ExpectedIsDefault(true)
+    default void bar() {}; // Default method
+}
+
+class TestType2 {
+    @ExpectedIsDefault(false)
+    void bar() {};
+}
+
+class TestType3 implements TestType1 {
+    @ExpectedIsDefault(false)
+    public void foo(){}
+
+    @ExpectedIsDefault(false)
+    @Override
+    public void bar() {};
+}
+
+@interface TestType4 {
+    @ExpectedIsDefault(false)
+    String value();
+
+    @ExpectedIsDefault(false)
+    String anotherValue() default "";
+}
+
+@Retention(RetentionPolicy.RUNTIME)
+@interface ExpectedIsDefault {
+    boolean value();
+}
--- a/jdk/test/java/lang/reflect/Proxy/ClassRestrictions.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/lang/reflect/Proxy/ClassRestrictions.java	Tue Jan 22 11:54:16 2013 -0800
@@ -22,7 +22,7 @@
  */
 
 /* @test
- * @bug 4227192
+ * @bug 4227192 8004928
  * @summary This is a test of the restrictions on the parameters that may
  * be passed to the Proxy.getProxyClass method.
  * @author Peter Jones
@@ -31,6 +31,7 @@
  * @run main ClassRestrictions
  */
 
+import java.lang.reflect.Modifier;
 import java.lang.reflect.Proxy;
 import java.net.URLClassLoader;
 
@@ -48,6 +49,8 @@
         void foo();
     }
 
+    public static final String nonPublicIntrfaceName = "java.util.zip.ZipConstants";
+
     public static void main(String[] args) {
 
         System.err.println(
@@ -65,7 +68,7 @@
             try {
                 interfaces = new Class<?>[] { Object.class };
                 proxyClass = Proxy.getProxyClass(loader, interfaces);
-                throw new RuntimeException(
+                throw new Error(
                     "proxy class created with java.lang.Object as interface");
             } catch (IllegalArgumentException e) {
                 e.printStackTrace();
@@ -75,7 +78,7 @@
             try {
                 interfaces = new Class<?>[] { Integer.TYPE };
                 proxyClass = Proxy.getProxyClass(loader, interfaces);
-                throw new RuntimeException(
+                throw new Error(
                     "proxy class created with int.class as interface");
             } catch (IllegalArgumentException e) {
                 e.printStackTrace();
@@ -90,7 +93,7 @@
             try {
                 interfaces = new Class<?>[] { Bar.class, Bar.class };
                 proxyClass = Proxy.getProxyClass(loader, interfaces);
-                throw new RuntimeException(
+                throw new Error(
                     "proxy class created with repeated interfaces");
             } catch (IllegalArgumentException e) {
                 e.printStackTrace();
@@ -109,7 +112,7 @@
             try {
                 interfaces = new Class<?>[] { altBarClass };
                 proxyClass = Proxy.getProxyClass(loader, interfaces);
-                throw new RuntimeException(
+                throw new Error(
                     "proxy class created with interface " +
                     "not visible to class loader");
             } catch (IllegalArgumentException e) {
@@ -122,34 +125,16 @@
              * All non-public interfaces must be in the same package.
              */
             Class<?> nonPublic1 = Bashful.class;
-            Class<?> nonPublic2 = null;
-            String[] nonPublicInterfaces = new String[] {
-                "java.awt.Conditional",
-                "java.util.zip.ZipConstants",
-                "javax.swing.GraphicsWrapper",
-                "javax.swing.JPopupMenu$Popup",
-                "javax.swing.JTable$Resizable2",
-                "javax.swing.JTable$Resizable3",
-                "javax.swing.ToolTipManager$Popup",
-                "sun.audio.Format",
-                "sun.audio.HaePlayable",
-                "sun.tools.agent.StepConstants",
-            };
-            for (int i = 0; i < nonPublicInterfaces.length; i++) {
-                try {
-                    nonPublic2 = Class.forName(nonPublicInterfaces[i]);
-                    break;
-                } catch (ClassNotFoundException e) {
-                }
-            }
-            if (nonPublic2 == null) {
-                throw new RuntimeException(
-                    "no second non-public interface found for test");
+            Class<?> nonPublic2 = Class.forName(nonPublicIntrfaceName);
+            if (Modifier.isPublic(nonPublic2.getModifiers())) {
+                throw new Error(
+                    "Interface " + nonPublicIntrfaceName +
+                    " is public and need to be changed!");
             }
             try {
                 interfaces = new Class<?>[] { nonPublic1, nonPublic2 };
                 proxyClass = Proxy.getProxyClass(loader, interfaces);
-                throw new RuntimeException(
+                throw new Error(
                     "proxy class created with two non-public interfaces " +
                     "in different packages");
             } catch (IllegalArgumentException e) {
@@ -165,7 +150,7 @@
             try {
                 interfaces = new Class<?>[] { Bar.class, Baz.class };
                 proxyClass = Proxy.getProxyClass(loader, interfaces);
-                throw new RuntimeException(
+                throw new Error(
                     "proxy class created with conflicting methods");
             } catch (IllegalArgumentException e) {
                 e.printStackTrace();
@@ -178,10 +163,10 @@
              */
             System.err.println("\nTEST PASSED");
 
-        } catch (Exception e) {
+        } catch (Throwable e) {
             System.err.println("\nTEST FAILED:");
             e.printStackTrace();
-            throw new RuntimeException("TEST FAILED: " + e.toString());
+            throw new Error("TEST FAILED: ", e);
         }
     }
 }
--- a/jdk/test/java/math/BigDecimal/FloatDoubleValueTests.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/math/BigDecimal/FloatDoubleValueTests.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/math/BigDecimal/StrippingZerosTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/math/BigDecimal/StrippingZerosTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/net/Inet4Address/PingThis.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/net/Inet4Address/PingThis.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/net/ProxySelector/MultiThreadedSystemProxies.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/net/ProxySelector/MultiThreadedSystemProxies.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/net/Socks/SocksV4Test.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/net/Socks/SocksV4Test.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,6 +26,7 @@
  * @bug 4727547
  * @summary SocksSocketImpl throws NullPointerException
  * @build SocksServer
+ * @run main SocksV4Test
  */
 
 import java.net.*;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/nio/channels/Pipe/PipeInterrupt.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8002306
+ * @summary Ensure that a Pipe can open even if its thread has already
+ *          been interrupted.
+ * @author Dan Xu
+ */
+
+import java.io.IOException;
+import java.nio.channels.Pipe;
+
+
+public class PipeInterrupt {
+
+    private Exception exc = null;
+
+    public static void main(String[] args) throws Exception {
+        PipeInterrupt instance = new PipeInterrupt();
+        instance.test();
+    }
+
+    public void test() throws Exception {
+
+        Thread tester = new Thread("PipeTester") {
+            private Pipe testPipe = null;
+
+            @Override
+            public void run() {
+                for (;;) {
+                    boolean interrupted = this.isInterrupted();
+                    try {
+                        testPipe = Pipe.open();
+                        close();
+                        if (interrupted) {
+                            if (!this.isInterrupted())
+                               exc = new RuntimeException("interrupt status reset");
+                            break;
+                        }
+                    } catch (IOException ioe) {
+                        exc = ioe;
+                    }
+                }
+            }
+
+            private void close() throws IOException {
+                if (testPipe != null) {
+                    testPipe.sink().close();
+                    testPipe.source().close();
+                }
+            }
+        };
+
+        tester.start();
+        Thread.sleep(200);
+        tester.interrupt();
+        tester.join();
+
+        if (exc != null)
+            throw exc;
+    }
+}
--- a/jdk/test/java/rmi/activation/Activatable/shutdownGracefully/ShutdownGracefully.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/rmi/activation/Activatable/shutdownGracefully/ShutdownGracefully.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -168,7 +168,7 @@
             registering = null;
 
             // Need to make sure that rmid goes away by itself
-            Process rmidProcess = rmid.getVM();
+            JavaVM rmidProcess = rmid;
             if (rmidProcess != null) {
                 try {
                     Runnable waitThread =
@@ -205,9 +205,9 @@
      * class that waits for rmid to exit
      */
     private static class ShutdownDetectThread implements Runnable {
-        private Process rmidProcess = null;
+        private JavaVM rmidProcess = null;
 
-        ShutdownDetectThread(Process rmidProcess) {
+        ShutdownDetectThread(JavaVM rmidProcess) {
             this.rmidProcess = rmidProcess;
         }
         public void run() {
--- a/jdk/test/java/rmi/activation/checkusage/CheckUsage.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/rmi/activation/checkusage/CheckUsage.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,6 +23,7 @@
 
 /* @test
  * @bug 4259564
+ * @summary RMID's usage message is incomplete and inconsistent with other tools
  *
  * @library ../../testlibrary
  * @build TestLibrary JavaVM
@@ -37,23 +38,16 @@
  */
 public class CheckUsage {
     public static void main(String[] args) {
-
-        System.err.println("\nregression test for 4259564\n");
-
-        JavaVM rmidVM = null;
-
         try {
-            // make sure the registry exits with a proper usage statement
             ByteArrayOutputStream berr = new ByteArrayOutputStream();
 
-            // run a VM to start the registry
-            rmidVM = new JavaVM("sun.rmi.server.Activation", "", "foo",
-                                    System.out, berr);
+            // create rmid with incorrect command line args
+            JavaVM rmidVM = new JavaVM("sun.rmi.server.Activation", "", "foo",
+                                       System.out, berr);
             System.err.println("starting rmid");
-            rmidVM.start();
 
-            // wait for registry exit
-            int rmidVMExitStatus = rmidVM.getVM().waitFor();
+            // run the subprocess and wait for it to exit
+            int rmidVMExitStatus = rmidVM.execute();
             System.err.println("rmid exited with status: " +
                                rmidVMExitStatus);
 
@@ -66,12 +60,8 @@
             } else {
                 System.err.println("test passed");
             }
-
         } catch (Exception e) {
             TestLibrary.bomb(e);
-        } finally {
-            rmidVM.destroy();
-            rmidVM = null;
         }
     }
 }
--- a/jdk/test/java/rmi/registry/altSecurityManager/AltSecurityManager.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/rmi/registry/altSecurityManager/AltSecurityManager.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, 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
@@ -76,8 +76,7 @@
             }
 
             System.err.println("starting " + utilityToStart);
-            vm.start();
-            vm.getVM().waitFor();
+            vm.execute();
 
         } catch (Exception e) {
             TestLibrary.bomb(e);
--- a/jdk/test/java/rmi/registry/checkusage/CheckUsage.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/rmi/registry/checkusage/CheckUsage.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,34 +35,21 @@
 
 /**
  * Make sure that the rmiregistry prints out a correct usage statement
- * when run with an incorrect command line; test written to conform to
- * new tighter bug fix/regression test guidelines.
+ * when run with an incorrect command line.
  */
 public class CheckUsage {
     public static void main(String[] args) {
 
-        System.err.println("\nregression test for 4151966\n");
-
-        JavaVM registryVM = null;
-
         try {
-            // make sure the registry exits with a proper usage statement
             ByteArrayOutputStream berr = new ByteArrayOutputStream();
 
             // run a VM to start the registry
-            registryVM = new JavaVM("sun.rmi.registry.RegistryImpl",
-                                    "", "foo",
-                                    System.out, berr);
+            JavaVM registryVM = new JavaVM("sun.rmi.registry.RegistryImpl",
+                                           "", "foo",
+                                           System.out, berr);
             System.err.println("starting registry");
-            registryVM.start();
-
-            // wait for registry exit
             System.err.println(" registry exited with status: " +
-                               registryVM.getVM().waitFor());
-            try {
-                Thread.sleep(7000);
-            } catch (InterruptedException ie) {
-            }
+                               registryVM.execute());
 
             String usage = new String(berr.toByteArray());
 
@@ -75,9 +62,6 @@
             }
         } catch (Exception e) {
             TestLibrary.bomb(e);
-        } finally {
-            registryVM.destroy();
-            registryVM = null;
         }
     }
 }
--- a/jdk/test/java/rmi/registry/reexport/Reexport.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/rmi/registry/reexport/Reexport.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, 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
@@ -122,8 +122,7 @@
         try {
             JavaVM jvm = new JavaVM("RegistryRunner", "", Integer.toString(p));
             jvm.start();
-            Reexport.subreg = jvm.getVM();
-
+            Reexport.subreg = jvm;
         } catch (IOException e) {
             // one of these is summarily dropped, can't remember which one
             System.out.println ("Test setup failed - cannot run rmiregistry");
@@ -135,7 +134,8 @@
         } catch (Exception whatever) {
         }
     }
-    private static Process subreg = null;
+
+    private static JavaVM subreg = null;
 
     public static void killRegistry(int port) {
         if (Reexport.subreg != null) {
--- a/jdk/test/java/rmi/testlibrary/JavaVM.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/rmi/testlibrary/JavaVM.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -21,13 +21,10 @@
  * questions.
  */
 
-/**
- *
- */
-
-import java.io.*;
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
 import java.util.Arrays;
-import java.util.Properties;
 import java.util.StringTokenizer;
 
 /**
@@ -44,10 +41,8 @@
     private OutputStream outputStream = System.out;
     private OutputStream errorStream = System.err;
     private String policyFileName = null;
-
-    // This is used to shorten waiting time at startup.
-    private volatile boolean started = false;
-    private boolean forcesOutput = true; // default behavior
+    private StreamPipe outPipe;
+    private StreamPipe errPipe;
 
     private static void mesg(Object mesg) {
         System.err.println("JAVAVM: " + mesg.toString());
@@ -82,24 +77,6 @@
         this.errorStream = err;
     }
 
-    /* This constructor will instantiate a JavaVM object for which caller
-     * can ask for forcing initial version output on child vm process
-     * (if forcesVersionOutput is true), or letting the started vm behave freely
-     * (when forcesVersionOutput is false).
-     */
-    public JavaVM(String classname,
-                  String options, String args,
-                  OutputStream out, OutputStream err,
-                  boolean forcesVersionOutput) {
-        this(classname, options, args, out, err);
-        this.forcesOutput = forcesVersionOutput;
-    }
-
-
-    public void setStarted() {
-        started = true;
-    }
-
     // Prepends passed opts array to current options
     public void addOptions(String[] opts) {
         String newOpts = "";
@@ -139,7 +116,8 @@
      */
     public void start() throws IOException {
 
-        if (vm != null) return;
+        if (vm != null)
+            throw new IllegalStateException("JavaVM already started");
 
         /*
          * If specified, add option for policy file
@@ -151,18 +129,6 @@
 
         addOptions(new String[] { getCodeCoverageOptions() });
 
-        /*
-         * If forcesOutput is true :
-         *  We force the new starting vm to output something so that we can know
-         *  when it is effectively started by redirecting standard output through
-         *  the next StreamPipe call (the vm is considered started when a first
-         *  output has been streamed out).
-         *  We do this by prepnding a "-showversion" option in the command line.
-         */
-        if (forcesOutput) {
-            addOptions(new String[] {"-showversion"});
-        }
-
         StringTokenizer optionsTokenizer = new StringTokenizer(options);
         StringTokenizer argsTokenizer = new StringTokenizer(args);
         int optionsCount = optionsTokenizer.countTokens();
@@ -181,48 +147,12 @@
         }
 
         mesg("command = " + Arrays.asList(javaCommand).toString());
-        System.err.println("");
 
         vm = Runtime.getRuntime().exec(javaCommand);
 
         /* output from the execed process may optionally be captured. */
-        StreamPipe.plugTogether(this, vm.getInputStream(), this.outputStream);
-        StreamPipe.plugTogether(this, vm.getErrorStream(), this.errorStream);
-
-        try {
-            if (forcesOutput) {
-                // Wait distant vm to start, by using waiting time slices of 100 ms.
-                // Wait at most for 2secs, after it considers the vm to be started.
-                final long vmStartSleepTime = 100;
-                final int maxTrials = 20;
-                int numTrials = 0;
-                while (!started && numTrials < maxTrials) {
-                    numTrials++;
-                    Thread.sleep(vmStartSleepTime);
-                }
-
-                // Outputs running status of distant vm
-                String message =
-                    "after " + (numTrials * vmStartSleepTime) + " milliseconds";
-                if (started) {
-                    mesg("distant vm process running, " + message);
-                }
-                else {
-                    mesg("unknown running status of distant vm process, " + message);
-                }
-            }
-            else {
-                // Since we have no way to know if the distant vm is started,
-                // we just consider the vm to be started after a 2secs waiting time.
-                Thread.sleep(2000);
-                mesg("distant vm considered to be started after a waiting time of 2 secs");
-            }
-        } catch (InterruptedException e) {
-            Thread.currentThread().interrupt();
-            mesg("Thread interrupted while checking if distant vm is started. Giving up check.");
-            mesg("Distant vm state unknown");
-            return;
-        }
+        outPipe = StreamPipe.plugTogether(vm.getInputStream(), this.outputStream);
+        errPipe = StreamPipe.plugTogether(vm.getErrorStream(), this.errorStream);
     }
 
     public void destroy() {
@@ -232,7 +162,25 @@
         vm = null;
     }
 
-    protected Process getVM() {
-        return vm;
+    /**
+     * Waits for the subprocess to exit, joins the pipe threads to ensure that
+     * all output is collected, and returns its exit status.
+     */
+    public int waitFor() throws InterruptedException {
+        if (vm == null)
+            throw new IllegalStateException("can't wait for JavaVM that hasn't started");
+
+        int status = vm.waitFor();
+        outPipe.join();
+        errPipe.join();
+        return status;
+    }
+
+    /**
+     * Starts the subprocess, waits for it to exit, and returns its exit status.
+     */
+    public int execute() throws IOException, InterruptedException {
+        start();
+        return waitFor();
     }
 }
--- a/jdk/test/java/rmi/testlibrary/RMID.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/rmi/testlibrary/RMID.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -202,8 +202,6 @@
 
     public void start(long waitTime) throws IOException {
 
-        if (getVM() != null) return;
-
         // if rmid is already running, then the test will fail with
         // a well recognized exception (port already in use...).
 
--- a/jdk/test/java/rmi/testlibrary/StreamPipe.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/rmi/testlibrary/StreamPipe.java	Tue Jan 22 11:54:16 2013 -0800
@@ -21,11 +21,10 @@
  * questions.
  */
 
-/**
- *
- */
-
-import java.io.*;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.io.IOException;
+import java.io.OutputStream;
 
 /**
  * Pipe output of one stream into input of another.
@@ -34,84 +33,46 @@
 
     private InputStream in;
     private OutputStream out;
-    private String preamble;
-    private JavaVM javaVM;
-    private static Object lock = new Object();
+
+    private static Object countLock = new Object();
     private static int count = 0;
 
-
-    /* StreamPipe constructor : should only be called by plugTogether() method !!
-     * If passed vm is not null :
-     * -  This is StreamPipe usage when streams to pipe come from a given
-     *    vm (JavaVM) process (the vm process must be started with a prefixed
-     *    "-showversion" option to be able to determine as soon as possible when
-     *    the vm process is started through the redirection of the streams).
-     *    There must be a close connection between the StreamPipe instance and
-     *    the JavaVM object on which a start() call has been done.
-     *    run() method will flag distant JavaVM as started.
-     * If passed vm is null :
-     * -  We don't have control on the process which we want to redirect the passed
-     *    streams.
-     *    run() method will ignore distant process.
+    /**
+     * StreamPipe constructor : should only be called by plugTogether() method.
      */
-    private StreamPipe(JavaVM vm, InputStream in, OutputStream out, String name) {
+    private StreamPipe(InputStream in, OutputStream out, String name) {
         super(name);
         this.in  = in;
         this.out = out;
-        this.preamble = "# ";
-        this.javaVM = vm;
     }
 
-    // Install redirection of passed InputStream and OutputStream from passed JavaVM
-    // to this vm standard output and input streams.
-    public static void plugTogether(JavaVM vm, InputStream in, OutputStream out) {
-        String name = null;
+    /**
+     * Creates a StreamPipe thread that copies in to out and returns
+     * the created instance.
+     */
+    public static StreamPipe plugTogether(InputStream in, OutputStream out) {
+        String name;
 
-        synchronized (lock) {
-            name = "TestLibrary: StreamPipe-" + (count ++ );
+        synchronized (countLock) {
+            name = "java.rmi.testlibrary.StreamPipe-" + (count++);
         }
 
-        Thread pipe = new StreamPipe(vm, in, out, name);
+        StreamPipe pipe = new StreamPipe(in, out, name);
         pipe.setDaemon(true);
         pipe.start();
-    }
-
-    /* Redirects the InputStream and OutputStream passed by caller to this
-     * vm standard output and input streams.
-     * (we just have to use fully parametered plugTogether() call with a null
-     *  JavaVM input to do this).
-     */
-    public static void plugTogether(InputStream in, OutputStream out) {
-        plugTogether(null, in, out);
+        return pipe;
     }
 
     // Starts redirection of streams.
     public void run() {
-        BufferedReader r = new BufferedReader(new InputStreamReader(in), 1);
-        BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out));
-        byte[] buf = new byte[256];
-
         try {
-            String line;
+            byte[] buf = new byte[1024];
 
-            /* This is to check that the distant vm has started,
-             * if such a vm has been provided at construction :
-             * - As soon as we can read something from r BufferedReader,
-             *   that means the distant vm is already started.
-             * Thus we signal associated JavaVM object that it is now started.
-             */
-            if (((line = r.readLine()) != null) &&
-                (javaVM != null)) {
-                javaVM.setStarted();
-            }
-
-            // Redirects r on w.
-            while (line != null) {
-                w.write(preamble);
-                w.write(line);
-                w.newLine();
-                w.flush();
-                line = r.readLine();
+            while (true) {
+                int nr = in.read(buf);
+                if (nr == -1)
+                    break;
+                out.write(buf, 0, nr);
             }
         } catch (InterruptedIOException iioe) {
             // Thread interrupted during IO operation. Terminate StreamPipe.
@@ -121,5 +82,4 @@
             e.printStackTrace();
         }
     }
-
 }
--- a/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -114,6 +114,7 @@
                 equal = "=";
             }
 
+            // create a client to tell checkFQDN what its rmi name is.
             JavaVM jvm = new JavaVM("CheckFQDNClient",
                                     propOption + property +
                                     equal +
@@ -125,10 +126,7 @@
             propertyBeingTested=property;
             propertyBeingTestedValue=propertyValue;
 
-            // create a client to tell checkFQDN what its rmi name is. */
-            jvm.start();
-
-            if (jvm.getVM().waitFor() != 0 ) {
+            if (jvm.execute() != 0) {
                 TestLibrary.bomb("Test failed, error in client.");
             }
 
--- a/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -102,9 +102,8 @@
                                         " -Drmi.registry.port=" +
                                         registryPort,
                                         "");
-                jvm.start();
 
-                if (jvm.getVM().waitFor() == 1 ) {
+                if (jvm.execute() != 0) {
                     TestLibrary.bomb("Client process failed");
                 }
             }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/security/Principal/Implies.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 7019834
+ * @summary test default implementation of Principal.implies
+ */
+
+import java.security.Principal;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import javax.security.auth.Subject;
+import javax.security.auth.kerberos.KerberosPrincipal;
+import javax.security.auth.x500.X500Principal;
+
+public class Implies {
+    public static void main(String[] args) throws Exception {
+        X500Principal duke = new X500Principal("CN=Duke");
+        // should not throw NullPointerException
+        testImplies(duke, (Subject)null, false);
+
+        Set<Principal> principals = new HashSet<>();
+        principals.add(duke);
+        testImplies(duke, principals, true);
+
+        X500Principal tux = new X500Principal("CN=Tux");
+        principals.add(tux);
+        testImplies(duke, principals, true);
+
+        principals.add(new KerberosPrincipal("duke@java.com"));
+        testImplies(duke, principals, true);
+
+        principals.clear();
+        principals.add(tux);
+        testImplies(duke, principals, false);
+
+        System.out.println("test passed");
+    }
+
+    private static void testImplies(Principal principal,
+                                    Set<? extends Principal> principals,
+                                    boolean result)
+        throws SecurityException
+    {
+        Subject subject = new Subject(true, principals, Collections.emptySet(),
+                                      Collections.emptySet());
+        testImplies(principal, subject, result);
+    }
+
+    private static void testImplies(Principal principal,
+                                    Subject subject, boolean result)
+        throws SecurityException
+    {
+        if (principal.implies(subject) != result) {
+            throw new SecurityException("test failed");
+        }
+    }
+}
--- a/jdk/test/java/security/Signature/VerifyRangeCheckOverflow.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/security/Signature/VerifyRangeCheckOverflow.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/security/cert/CertPathBuilder/targetConstraints/BuildEEBasicConstraints.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/security/cert/CertPathBuilder/targetConstraints/BuildEEBasicConstraints.java	Tue Jan 22 11:54:16 2013 -0800
@@ -21,18 +21,22 @@
  * questions.
  */
 
+// This test case relies on updated static security property, no way to re-use
+// security property in samevm/agentvm mode.
+
 /**
  * @test
  * @bug 6714842
  * @library ../../../testlibrary
  * @build CertUtils
- * @run main BuildEEBasicConstraints
+ * @run main/othervm BuildEEBasicConstraints
  * @summary make sure a PKIX CertPathBuilder builds a path to an
  *      end entity certificate when the setBasicConstraints method of the
  *      X509CertSelector of the targetConstraints PKIXBuilderParameters
  *      parameter is set to -2.
  */
 
+import java.security.Security;
 import java.security.cert.Certificate;
 import java.security.cert.CertPath;
 import java.security.cert.CertStore;
@@ -49,6 +53,9 @@
 public final class BuildEEBasicConstraints {
 
     public static void main(String[] args) throws Exception {
+        // reset the security property to make sure that the algorithms
+        // and keys used in this test are not disabled.
+        Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
 
         X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
         TrustAnchor anchor = new TrustAnchor
--- a/jdk/test/java/security/cert/pkix/policyChanges/TestPolicy.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/security/cert/pkix/policyChanges/TestPolicy.java	Tue Jan 22 11:54:16 2013 -0800
@@ -21,16 +21,22 @@
  * questions.
  */
 
+// This test case relies on updated static security property, no way to re-use
+// security property in samevm/agentvm mode.
+
 /**
  * @test
  * @bug 4684793
- * @summary verify that the RFC3280 policy processing changes are implemented correctly
+ * @summary verify that the RFC3280 policy processing changes are
+ *          implemented correctly
+ * @run main/othervm TestPolicy
  * @author Andreas Sterbenz
  */
 
 import java.io.*;
 import java.util.*;
 
+import java.security.Security;
 import java.security.cert.*;
 
 public class TestPolicy {
@@ -72,6 +78,10 @@
     };
 
     public static void main(String[] args) throws Exception {
+        // reset the security property to make sure that the algorithms
+        // and keys used in this test are not disabled.
+        Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
+
         factory = CertificateFactory.getInstance("X.509");
 
         X509Certificate anchor = loadCertificate("anchor.cer");
--- a/jdk/test/java/text/Bidi/BidiConformance.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/text/Bidi/BidiConformance.java	Tue Jan 22 11:54:16 2013 -0800
@@ -656,7 +656,6 @@
                        baseIsLTR4Constructor1[textNo][testNo],
                        isLTR_isRTL4Constructor1[textNo][0][testNo],
                        isLTR_isRTL4Constructor1[textNo][1][testNo]);
-System.out.println(bidi.toString());
     }
 
     private void callTestEachMethod4Constructor2(int textNo,
@@ -668,7 +667,6 @@
                        baseIsLTR4Constructor2[textNo][flagNo],
                        isLTR_isRTL4Constructor2[textNo][0][flagNo],
                        isLTR_isRTL4Constructor2[textNo][1][flagNo]);
-System.out.println(bidi.toString());
     }
 
     private void callTestEachMethod4Constructor3(int textNo,
@@ -680,7 +678,6 @@
                        baseIsLTR4Constructor3[textNo][dataNo],
                        isLTR_isRTL4Constructor3[textNo][0][dataNo],
                        isLTR_isRTL4Constructor3[textNo][1][dataNo]);
-System.out.println(bidi.toString());
     }
 
     private StringBuilder sb = new StringBuilder();
@@ -934,59 +931,145 @@
         System.out.println("*** Test getRunLevel()");
 
         String str = "ABC 123";
-        int length = str.length();
         Bidi bidi = new Bidi(str, Bidi.DIRECTION_LEFT_TO_RIGHT);
-
         try {
-            if (bidi.getRunLevel(-1) != 0 ||  // runCount - 2
+            if (bidi.getRunLevel(-1) != 0 ||  // runCount - 2 (out of range)
                 bidi.getRunLevel(0) != 0 ||   // runCount - 1
-                bidi.getRunLevel(1) != 0 ||   // runCount
-                bidi.getRunLevel(2) != 0) {   // runCount + 1
-                errorHandling("getRunLevel() should return 0" +
-                    " when getRunCount() is 1.");
+                bidi.getRunLevel(1) != 0 ||   // runCount     (out of range)
+                bidi.getRunLevel(2) != 0) {   // runCount + 1 (out of range)
+                errorHandling("Incorrect getRunLevel() value(s).");
             }
         }
         catch (Exception e) {
-            errorHandling("getRunLevel() should not throw an exception " +
-                "when getRunCount() is 1.");
+            errorHandling("getRunLevel() should not throw an exception: " + e);
         }
 
         str = "ABC " + HebrewABC + " 123";
-        length = str.length();
         bidi = new Bidi(str, Bidi.DIRECTION_LEFT_TO_RIGHT);
+        try {
+            if (bidi.getRunLevel(-1) != 0 ||  // runCount - 4 (out of range)
+                bidi.getRunLevel(0) != 0 ||   // runCount - 3
+                bidi.getRunLevel(1) != 1 ||   // runCount - 2
+                bidi.getRunLevel(2) != 2 ||   // runCount - 1
+                bidi.getRunLevel(3) != 0 ||   // runCount     (out of range)
+                bidi.getRunLevel(4) != 0) {   // runCount + 1 (out of range)
+                errorHandling("Incorrect getRunLevel() value(s).");
+            }
+        }
+        catch (Exception e) {
+            errorHandling("getRunLevel() should not throw an exception: " + e);
+        }
 
+        str = "ABC";
+        bidi = new Bidi(str, Bidi.DIRECTION_LEFT_TO_RIGHT);
         try {
-            bidi.getRunLevel(-1);
-            errorHandling("getRunLevel() should throw an AIOoBE " +
-                "when run is -1(too small).");
+            if (bidi.getRunLevel(-1) != 0 ||  // runCount - 2 (out of range)
+                bidi.getRunLevel(0) != 0 ||   // runCount - 1
+                bidi.getRunLevel(1) != 0 ||   // runCount     (out of range)
+                bidi.getRunLevel(2) != 0) {   // runCount + 1 (out of range)
+                errorHandling("Incorrect getRunLevel() value(s).");
+            }
+        }
+        catch (Exception e) {
+            errorHandling("getRunLevel() should not throw an exception: " + e);
         }
-        catch (ArrayIndexOutOfBoundsException e) {
+
+        str = "ABC";
+        bidi = new Bidi(str, Bidi.DIRECTION_RIGHT_TO_LEFT);
+        try {
+            if (bidi.getRunLevel(-1) != 1 ||  // runCount - 2 (out of range)
+                bidi.getRunLevel(0) != 2 ||   // runCount - 1
+                bidi.getRunLevel(1) != 1 ||   // runCount     (out of range)
+                bidi.getRunLevel(2) != 1) {   // runCount + 1 (out of range)
+                errorHandling("Incorrect getRunLevel() value(s).");
+            }
+        }
+        catch (Exception e) {
+            errorHandling("getRunLevel() should not throw an exception: " + e);
         }
-        catch (IllegalArgumentException e) {
-            errorHandling("getRunLevel() should not throw an IAE " +
-                "but an AIOoBE when run is -1(too small).");
+
+        str = "ABC";
+        bidi = new Bidi(str, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
+        try {
+            if (bidi.getRunLevel(-1) != 0 ||  // runCount - 2 (out of range)
+                bidi.getRunLevel(0) != 0 ||   // runCount - 1
+                bidi.getRunLevel(1) != 0 ||   // runCount     (out of range)
+                bidi.getRunLevel(2) != 0) {   // runCount + 1 (out of range)
+                errorHandling("Incorrect getRunLevel() value(s).");
+            }
+        }
+        catch (Exception e) {
+            errorHandling("getRunLevel() should not throw an exception: " + e);
         }
 
+        str = "ABC";
+        bidi = new Bidi(str, Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT);
         try {
-            bidi.getRunLevel(0);
-            bidi.getRunLevel(1);
-            bidi.getRunLevel(2);
+            if (bidi.getRunLevel(-1) != 0 ||  // runCount - 2 (out of range)
+                bidi.getRunLevel(0) != 0 ||   // runCount - 1
+                bidi.getRunLevel(1) != 0 ||   // runCount     (out of range)
+                bidi.getRunLevel(2) != 0) {   // runCount + 1 (out of range)
+                errorHandling("Incorrect getRunLevel() value(s).");
+            }
         }
         catch (Exception e) {
-            errorHandling("getRunLevel() should not throw an exception" +
-                " when run is from 0 to 2(runCount-1).");
+            errorHandling("getRunLevel() should not throw an exception: " + e);
+        }
+
+        str = HebrewABC;
+        bidi = new Bidi(str, Bidi.DIRECTION_LEFT_TO_RIGHT);
+        try {
+            if (bidi.getRunLevel(-1) != 0 ||  // runCount - 2 (out of range)
+                bidi.getRunLevel(0) != 1 ||   // runCount - 1
+                bidi.getRunLevel(1) != 0 ||   // runCount     (out of range)
+                bidi.getRunLevel(2) != 0) {   // runCount + 1 (out of range)
+                errorHandling("Incorrect getRunLevel() value(s).");
+            }
+        }
+        catch (Exception e) {
+            errorHandling("getRunLevel() should not throw an exception: " + e);
         }
 
+        str = HebrewABC;
+        bidi = new Bidi(str, Bidi.DIRECTION_RIGHT_TO_LEFT);
         try {
-            bidi.getRunLevel(3);
-            errorHandling("getRunLevel() should throw an AIOoBE" +
-                " when run is 3(same as runCount).");
+            if (bidi.getRunLevel(-1) != 1 ||  // runCount - 2 (out of range)
+                bidi.getRunLevel(0) != 1 ||   // runCount - 1
+                bidi.getRunLevel(1) != 1 ||   // runCount     (out of range)
+                bidi.getRunLevel(2) != 1) {   // runCount + 1 (out of range)
+                errorHandling("Incorrect getRunLevel() value(s).");
+            }
+        }
+        catch (Exception e) {
+            errorHandling("getRunLevel() should not throw an exception: " + e);
         }
-        catch (ArrayIndexOutOfBoundsException e) {
+
+        str = HebrewABC;
+        bidi = new Bidi(str, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
+        try {
+            if (bidi.getRunLevel(-1) != 1 ||  // runCount - 2 (out of range)
+                bidi.getRunLevel(0) != 1 ||   // runCount - 1
+                bidi.getRunLevel(1) != 1 ||   // runCount     (out of range)
+                bidi.getRunLevel(2) != 1) {   // runCount + 1 (out of range)
+                errorHandling("Incorrect getRunLevel() value(s).");
+            }
+        }
+        catch (Exception e) {
+            errorHandling("getRunLevel() should not throw an exception: " + e);
         }
-        catch (IllegalArgumentException e) {
-            errorHandling("getRunLevel() should not throw an IAE " +
-                "but an AIOoBE when run is 3(same as runCount).");
+
+        str = HebrewABC;
+        bidi = new Bidi(str, Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT);
+        try {
+            if (bidi.getRunLevel(-1) != 1 ||  // runCount - 2 (out of range)
+                bidi.getRunLevel(0) != 1 ||   // runCount - 1
+                bidi.getRunLevel(1) != 1 ||   // runCount     (out of range)
+                bidi.getRunLevel(2) != 1) {   // runCount + 1 (out of range)
+                errorHandling("Incorrect getRunLevel() value(s).");
+            }
+        }
+        catch (Exception e) {
+            errorHandling("getRunLevel() should not throw an exception: " + e);
         }
     }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/text/Bidi/Bug8005277.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8005277
+ * @summary verify that Bidi.getRunLevel() returns a corect level.
+ */
+import java.text.Bidi;
+
+public class Bug8005277 {
+
+    public static void main(String[] args) {
+        boolean err = false;
+        String string = "\u05D0\u05D1\u05D2";
+        Bidi bidi = new Bidi(string, Bidi.DIRECTION_LEFT_TO_RIGHT);
+
+        int result = bidi.getRunCount();
+        if (result != 1) {
+            System.err.println("Incorrect run count: " + result);
+            err = true;
+        }
+
+        result = bidi.getRunStart(0);
+        if (result != 0) {
+            System.err.println("Incorrect run start: " + result);
+            err = true;
+        }
+
+        result = bidi.getRunLimit(0);
+        if (result != 3) {
+            System.err.println("Incorrect run limit: " + result);
+            err = true;
+        }
+
+        result = bidi.getRunLevel(0);
+        if (result != 1) {
+            System.err.println("Incorrect run level: " + result);
+            err = true;
+        }
+
+        if (err) {
+            throw new RuntimeException("Failed.");
+        }
+    }
+
+}
--- a/jdk/test/java/util/AbstractCollection/ToArrayTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/AbstractCollection/ToArrayTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Arrays/ParallelSorting.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,2067 @@
+/*
+ * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* Adapted from test/java/util/Arrays/Sorting.java
+ *
+ * Where that test checks Arrays.sort against manual quicksort routines,
+ * this test checks parallelSort against either Arrays.sort or manual
+ * quicksort routines.
+ */
+
+/*
+ * @test
+ * @bug 8003981
+ * @run main ParallelSorting -shortrun
+ * @summary Exercise Arrays.parallelSort (adapted from test Sorting)
+ *
+ * @author Vladimir Yaroslavskiy
+ * @author Jon Bentley
+ * @author Josh Bloch
+ */
+
+import java.util.Arrays;
+import java.util.Random;
+import java.io.PrintStream;
+import java.util.Comparator;
+
+public class ParallelSorting {
+    private static final PrintStream out = System.out;
+    private static final PrintStream err = System.err;
+
+    // Array lengths used in a long run (default)
+    private static final int[] LONG_RUN_LENGTHS = {
+        1, 2, 3, 5, 8, 13, 21, 34, 55, 100, 1000, 10000, 100000, 1000000 };
+
+    // Array lengths used in a short run
+    private static final int[] SHORT_RUN_LENGTHS = {
+        1, 2, 3, 21, 55, 1000, 10000 };
+
+    // Random initial values used in a long run (default)
+    private static final long[] LONG_RUN_RANDOMS = { 666, 0xC0FFEE, 999 };
+
+    // Random initial values used in a short run
+    private static final long[] SHORT_RUN_RANDOMS = { 666 };
+
+    public static void main(String[] args) {
+        boolean shortRun = args.length > 0 && args[0].equals("-shortrun");
+        long start = System.currentTimeMillis();
+
+        if (shortRun) {
+            testAndCheck(SHORT_RUN_LENGTHS, SHORT_RUN_RANDOMS);
+        } else {
+            testAndCheck(LONG_RUN_LENGTHS, LONG_RUN_RANDOMS);
+        }
+        long end = System.currentTimeMillis();
+
+        out.format("PASSED in %d sec.\n", Math.round((end - start) / 1E3));
+    }
+
+    private static void testAndCheck(int[] lengths, long[] randoms) {
+        testEmptyAndNullIntArray();
+        testEmptyAndNullLongArray();
+        testEmptyAndNullShortArray();
+        testEmptyAndNullCharArray();
+        testEmptyAndNullByteArray();
+        testEmptyAndNullFloatArray();
+        testEmptyAndNullDoubleArray();
+
+        for (int length : lengths) {
+            testMergeSort(length);
+            testAndCheckRange(length);
+            testAndCheckSubArray(length);
+        }
+        for (long seed : randoms) {
+            for (int length : lengths) {
+                testAndCheckWithInsertionSort(length, new MyRandom(seed));
+                testAndCheckWithCheckSum(length, new MyRandom(seed));
+                testAndCheckWithScrambling(length, new MyRandom(seed));
+                testAndCheckFloat(length, new MyRandom(seed));
+                testAndCheckDouble(length, new MyRandom(seed));
+                testStable(length, new MyRandom(seed));
+            }
+        }
+    }
+
+    private static void testEmptyAndNullIntArray() {
+        ourDescription = "Check empty and null array";
+        Arrays.parallelSort(new int[]{});
+        Arrays.parallelSort(new int[]{}, 0, 0);
+
+        try {
+            Arrays.parallelSort((int[]) null);
+        } catch (NullPointerException expected) {
+            try {
+                Arrays.parallelSort((int[]) null, 0, 0);
+            } catch (NullPointerException expected2) {
+                return;
+            }
+            failed("Arrays.parallelSort(int[],fromIndex,toIndex) shouldn't " +
+                "catch null array");
+        }
+        failed("Arrays.parallelSort(int[]) shouldn't catch null array");
+    }
+
+    private static void testEmptyAndNullLongArray() {
+        ourDescription = "Check empty and null array";
+        Arrays.parallelSort(new long[]{});
+        Arrays.parallelSort(new long[]{}, 0, 0);
+
+        try {
+            Arrays.parallelSort((long[]) null);
+        } catch (NullPointerException expected) {
+            try {
+                Arrays.parallelSort((long[]) null, 0, 0);
+            } catch (NullPointerException expected2) {
+                return;
+            }
+            failed("Arrays.parallelSort(long[],fromIndex,toIndex) shouldn't " +
+                "catch null array");
+        }
+        failed("Arrays.parallelSort(long[]) shouldn't catch null array");
+    }
+
+    private static void testEmptyAndNullShortArray() {
+        ourDescription = "Check empty and null array";
+        Arrays.parallelSort(new short[]{});
+        Arrays.parallelSort(new short[]{}, 0, 0);
+
+        try {
+            Arrays.parallelSort((short[]) null);
+        } catch (NullPointerException expected) {
+            try {
+                Arrays.parallelSort((short[]) null, 0, 0);
+            } catch (NullPointerException expected2) {
+                return;
+            }
+            failed("Arrays.parallelSort(short[],fromIndex,toIndex) shouldn't " +
+                "catch null array");
+        }
+        failed("Arrays.parallelSort(short[]) shouldn't catch null array");
+    }
+
+    private static void testEmptyAndNullCharArray() {
+        ourDescription = "Check empty and null array";
+        Arrays.parallelSort(new char[]{});
+        Arrays.parallelSort(new char[]{}, 0, 0);
+
+        try {
+            Arrays.parallelSort((char[]) null);
+        } catch (NullPointerException expected) {
+            try {
+                Arrays.parallelSort((char[]) null, 0, 0);
+            } catch (NullPointerException expected2) {
+                return;
+            }
+            failed("Arrays.parallelSort(char[],fromIndex,toIndex) shouldn't " +
+                "catch null array");
+        }
+        failed("Arrays.parallelSort(char[]) shouldn't catch null array");
+    }
+
+    private static void testEmptyAndNullByteArray() {
+        ourDescription = "Check empty and null array";
+        Arrays.parallelSort(new byte[]{});
+        Arrays.parallelSort(new byte[]{}, 0, 0);
+
+        try {
+            Arrays.parallelSort((byte[]) null);
+        } catch (NullPointerException expected) {
+            try {
+                Arrays.parallelSort((byte[]) null, 0, 0);
+            } catch (NullPointerException expected2) {
+                return;
+            }
+            failed("Arrays.parallelSort(byte[],fromIndex,toIndex) shouldn't " +
+                "catch null array");
+        }
+        failed("Arrays.parallelSort(byte[]) shouldn't catch null array");
+    }
+
+    private static void testEmptyAndNullFloatArray() {
+        ourDescription = "Check empty and null array";
+        Arrays.parallelSort(new float[]{});
+        Arrays.parallelSort(new float[]{}, 0, 0);
+
+        try {
+            Arrays.parallelSort((float[]) null);
+        } catch (NullPointerException expected) {
+            try {
+                Arrays.parallelSort((float[]) null, 0, 0);
+            } catch (NullPointerException expected2) {
+                return;
+            }
+            failed("Arrays.parallelSort(float[],fromIndex,toIndex) shouldn't " +
+                "catch null array");
+        }
+        failed("Arrays.parallelSort(float[]) shouldn't catch null array");
+    }
+
+    private static void testEmptyAndNullDoubleArray() {
+        ourDescription = "Check empty and null array";
+        Arrays.parallelSort(new double[]{});
+        Arrays.parallelSort(new double[]{}, 0, 0);
+
+        try {
+            Arrays.parallelSort((double[]) null);
+        } catch (NullPointerException expected) {
+            try {
+                Arrays.parallelSort((double[]) null, 0, 0);
+            } catch (NullPointerException expected2) {
+                return;
+            }
+            failed("Arrays.parallelSort(double[],fromIndex,toIndex) shouldn't " +
+                "catch null array");
+        }
+        failed("Arrays.parallelSort(double[]) shouldn't catch null array");
+    }
+
+    private static void testAndCheckSubArray(int length) {
+        ourDescription = "Check sorting of subarray";
+        int[] golden = new int[length];
+        boolean newLine = false;
+
+        for (int m = 1; m < length / 2; m *= 2) {
+            newLine = true;
+            int fromIndex = m;
+            int toIndex = length - m;
+
+            prepareSubArray(golden, fromIndex, toIndex, m);
+            int[] test = golden.clone();
+
+            for (TypeConverter converter : TypeConverter.values()) {
+                out.println("Test 'subarray': " + converter +
+                   " length = " + length + ", m = " + m);
+                Object convertedGolden = converter.convert(golden);
+                Object convertedTest = converter.convert(test);
+                sortSubArray(convertedTest, fromIndex, toIndex);
+                checkSubArray(convertedTest, fromIndex, toIndex, m);
+            }
+        }
+        if (newLine) {
+            out.println();
+        }
+    }
+
+    private static void testAndCheckRange(int length) {
+        ourDescription = "Check range check";
+        int[] golden = new int[length];
+
+        for (int m = 1; m < 2 * length; m *= 2) {
+            for (int i = 1; i <= length; i++) {
+                golden[i - 1] = i % m + m % i;
+            }
+            for (TypeConverter converter : TypeConverter.values()) {
+                out.println("Test 'range': " + converter +
+                   ", length = " + length + ", m = " + m);
+                Object convertedGolden = converter.convert(golden);
+                checkRange(convertedGolden, m);
+            }
+        }
+        out.println();
+    }
+
+    private static void testStable(int length, MyRandom random) {
+        ourDescription = "Check if sorting is stable";
+        Pair[] a = build(length, random);
+
+        out.println("Test 'stable': " + "random = " + random.getSeed() +
+            ", length = " + length);
+        Arrays.parallelSort(a);
+        checkSorted(a);
+        checkStable(a);
+        out.println();
+
+        a = build(length, random);
+
+        out.println("Test 'stable' comparator: " + "random = " + random.getSeed() +
+            ", length = " + length);
+        Arrays.parallelSort(a, pairCmp);
+        checkSorted(a);
+        checkStable(a);
+        out.println();
+
+    }
+
+    private static void checkSorted(Pair[] a) {
+        for (int i = 0; i < a.length - 1; i++) {
+            if (a[i].getKey() > a[i + 1].getKey()) {
+                failedSort(i, "" + a[i].getKey(), "" + a[i + 1].getKey());
+            }
+        }
+    }
+
+    private static void checkStable(Pair[] a) {
+        for (int i = 0; i < a.length / 4; ) {
+            int key1 = a[i].getKey();
+            int value1 = a[i++].getValue();
+            int key2 = a[i].getKey();
+            int value2 = a[i++].getValue();
+            int key3 = a[i].getKey();
+            int value3 = a[i++].getValue();
+            int key4 = a[i].getKey();
+            int value4 = a[i++].getValue();
+
+            if (!(key1 == key2 && key2 == key3 && key3 == key4)) {
+                failed("On position " + i + " keys are different " +
+                    key1 + ", " + key2 + ", " + key3 + ", " + key4);
+            }
+            if (!(value1 < value2 && value2 < value3 && value3 < value4)) {
+                failed("Sorting is not stable at position " + i +
+                    ". Second values have been changed: " +  value1 + ", " +
+                    value2 + ", " + value3 + ", " + value4);
+            }
+        }
+    }
+
+    private static Pair[] build(int length, Random random) {
+        Pair[] a = new Pair[length * 4];
+
+        for (int i = 0; i < a.length; ) {
+            int key = random.nextInt();
+            a[i++] = new Pair(key, 1);
+            a[i++] = new Pair(key, 2);
+            a[i++] = new Pair(key, 3);
+            a[i++] = new Pair(key, 4);
+        }
+        return a;
+    }
+
+    private static Comparator<Pair> pairCmp = new Comparator<Pair>() {
+        public int compare(Pair p1, Pair p2) {
+            return p1.compareTo(p2);
+        }
+    };
+
+    private static final class Pair implements Comparable<Pair> {
+        Pair(int key, int value) {
+            myKey = key;
+            myValue = value;
+        }
+
+        int getKey() {
+            return myKey;
+        }
+
+        int getValue() {
+            return myValue;
+        }
+
+        public int compareTo(Pair pair) {
+            if (myKey < pair.myKey) {
+                return -1;
+            }
+            if (myKey > pair.myKey) {
+                return 1;
+            }
+            return 0;
+        }
+
+        @Override
+        public String toString() {
+            return "(" + myKey + ", " + myValue + ")";
+        }
+
+        private int myKey;
+        private int myValue;
+    }
+
+
+    private static void testAndCheckWithInsertionSort(int length, MyRandom random) {
+        if (length > 1000) {
+            return;
+        }
+        ourDescription = "Check sorting with insertion sort";
+        int[] golden = new int[length];
+
+        for (int m = 1; m < 2 * length; m *= 2) {
+            for (UnsortedBuilder builder : UnsortedBuilder.values()) {
+                builder.build(golden, m, random);
+                int[] test = golden.clone();
+
+                for (TypeConverter converter : TypeConverter.values()) {
+                    out.println("Test 'insertion sort': " + converter +
+                        " " + builder + "random = " + random.getSeed() +
+                        ", length = " + length + ", m = " + m);
+                    Object convertedGolden = converter.convert(golden);
+                    Object convertedTest1 = converter.convert(test);
+                    Object convertedTest2 = converter.convert(test);
+                    sort(convertedTest1);
+                    sortByInsertionSort(convertedTest2);
+                    compare(convertedTest1, convertedTest2);
+                }
+            }
+        }
+        out.println();
+    }
+
+    private static void testMergeSort(int length) {
+        if (length < 1000) {
+            return;
+        }
+        ourDescription = "Check merge sorting";
+        int[] golden = new int[length];
+        int period = 67; // java.util.DualPivotQuicksort.MAX_RUN_COUNT
+
+        for (int m = period - 2; m <= period + 2; m++) {
+            for (MergeBuilder builder : MergeBuilder.values()) {
+                builder.build(golden, m);
+                int[] test = golden.clone();
+
+                for (TypeConverter converter : TypeConverter.values()) {
+                    out.println("Test 'merge sort': " + converter + " " +
+                        builder + "length = " + length + ", m = " + m);
+                    Object convertedGolden = converter.convert(golden);
+                    sort(convertedGolden);
+                    checkSorted(convertedGolden);
+                }
+            }
+        }
+        out.println();
+    }
+
+    private static void testAndCheckWithCheckSum(int length, MyRandom random) {
+        ourDescription = "Check sorting with check sum";
+        int[] golden = new int[length];
+
+        for (int m = 1; m < 2 * length; m *= 2) {
+            for (UnsortedBuilder builder : UnsortedBuilder.values()) {
+                builder.build(golden, m, random);
+                int[] test = golden.clone();
+
+                for (TypeConverter converter : TypeConverter.values()) {
+                    out.println("Test 'check sum': " + converter +
+                        " " + builder + "random = " + random.getSeed() +
+                        ", length = " + length + ", m = " + m);
+                    Object convertedGolden = converter.convert(golden);
+                    Object convertedTest = converter.convert(test);
+                    sort(convertedTest);
+                    checkWithCheckSum(convertedTest, convertedGolden);
+                }
+            }
+        }
+        out.println();
+    }
+
+    private static void testAndCheckWithScrambling(int length, MyRandom random) {
+        ourDescription = "Check sorting with scrambling";
+        int[] golden = new int[length];
+
+        for (int m = 1; m <= 7; m++) {
+            if (m > length) {
+                break;
+            }
+            for (SortedBuilder builder : SortedBuilder.values()) {
+                builder.build(golden, m);
+                int[] test = golden.clone();
+                scramble(test, random);
+
+                for (TypeConverter converter : TypeConverter.values()) {
+                    out.println("Test 'scrambling': " + converter +
+                       " " + builder + "random = " + random.getSeed() +
+                       ", length = " + length + ", m = " + m);
+                    Object convertedGolden = converter.convert(golden);
+                    Object convertedTest = converter.convert(test);
+                    sort(convertedTest);
+                    compare(convertedTest, convertedGolden);
+                }
+            }
+        }
+        out.println();
+    }
+
+    private static void testAndCheckFloat(int length, MyRandom random) {
+        ourDescription = "Check float sorting";
+        float[] golden = new float[length];
+        final int MAX = 10;
+        boolean newLine = false;
+
+        for (int a = 0; a <= MAX; a++) {
+            for (int g = 0; g <= MAX; g++) {
+                for (int z = 0; z <= MAX; z++) {
+                    for (int n = 0; n <= MAX; n++) {
+                        for (int p = 0; p <= MAX; p++) {
+                            if (a + g + z + n + p > length) {
+                                continue;
+                            }
+                            if (a + g + z + n + p < length) {
+                                continue;
+                            }
+                            for (FloatBuilder builder : FloatBuilder.values()) {
+                                out.println("Test 'float': random = " + random.getSeed() +
+                                   ", length = " + length + ", a = " + a + ", g = " +
+                                   g + ", z = " + z + ", n = " + n + ", p = " + p);
+                                builder.build(golden, a, g, z, n, p, random);
+                                float[] test = golden.clone();
+                                scramble(test, random);
+                                sort(test);
+                                compare(test, golden, a, n, g);
+                            }
+                            newLine = true;
+                        }
+                    }
+                }
+            }
+        }
+        if (newLine) {
+            out.println();
+        }
+    }
+
+    private static void testAndCheckDouble(int length, MyRandom random) {
+        ourDescription = "Check double sorting";
+        double[] golden = new double[length];
+        final int MAX = 10;
+        boolean newLine = false;
+
+        for (int a = 0; a <= MAX; a++) {
+            for (int g = 0; g <= MAX; g++) {
+                for (int z = 0; z <= MAX; z++) {
+                    for (int n = 0; n <= MAX; n++) {
+                        for (int p = 0; p <= MAX; p++) {
+                            if (a + g + z + n + p > length) {
+                                continue;
+                            }
+                            if (a + g + z + n + p < length) {
+                                continue;
+                            }
+                            for (DoubleBuilder builder : DoubleBuilder.values()) {
+                                out.println("Test 'double': random = " + random.getSeed() +
+                                   ", length = " + length + ", a = " + a + ", g = " +
+                                   g + ", z = " + z + ", n = " + n + ", p = " + p);
+                                builder.build(golden, a, g, z, n, p, random);
+                                double[] test = golden.clone();
+                                scramble(test, random);
+                                sort(test);
+                                compare(test, golden, a, n, g);
+                            }
+                            newLine = true;
+                        }
+                    }
+                }
+            }
+        }
+        if (newLine) {
+            out.println();
+        }
+    }
+
+    private static void prepareSubArray(int[] a, int fromIndex, int toIndex, int m) {
+        for (int i = 0; i < fromIndex; i++) {
+            a[i] = 0xDEDA;
+        }
+        int middle = (fromIndex + toIndex) >>> 1;
+        int k = 0;
+
+        for (int i = fromIndex; i < middle; i++) {
+            a[i] = k++;
+        }
+        for (int i = middle; i < toIndex; i++) {
+            a[i] = k--;
+        }
+        for (int i = toIndex; i < a.length; i++) {
+            a[i] = 0xBABA;
+        }
+    }
+
+    private static void scramble(int[] a, Random random) {
+        for (int i = 0; i < a.length * 7; i++) {
+            swap(a, random.nextInt(a.length), random.nextInt(a.length));
+        }
+    }
+
+    private static void scramble(float[] a, Random random) {
+        for (int i = 0; i < a.length * 7; i++) {
+            swap(a, random.nextInt(a.length), random.nextInt(a.length));
+        }
+    }
+
+    private static void scramble(double[] a, Random random) {
+        for (int i = 0; i < a.length * 7; i++) {
+            swap(a, random.nextInt(a.length), random.nextInt(a.length));
+        }
+    }
+
+    private static void swap(int[] a, int i, int j) {
+        int t = a[i];
+        a[i] = a[j];
+        a[j] = t;
+    }
+
+    private static void swap(float[] a, int i, int j) {
+        float t = a[i];
+        a[i] = a[j];
+        a[j] = t;
+    }
+
+    private static void swap(double[] a, int i, int j) {
+        double t = a[i];
+        a[i] = a[j];
+        a[j] = t;
+    }
+
+    private static enum TypeConverter {
+        INT {
+            Object convert(int[] a) {
+                return a.clone();
+            }
+        },
+        LONG {
+            Object convert(int[] a) {
+                long[] b = new long[a.length];
+
+                for (int i = 0; i < a.length; i++) {
+                    b[i] = (long) a[i];
+                }
+                return b;
+            }
+        },
+        BYTE {
+            Object convert(int[] a) {
+                byte[] b = new byte[a.length];
+
+                for (int i = 0; i < a.length; i++) {
+                    b[i] = (byte) a[i];
+                }
+                return b;
+            }
+        },
+        SHORT {
+            Object convert(int[] a) {
+                short[] b = new short[a.length];
+
+                for (int i = 0; i < a.length; i++) {
+                    b[i] = (short) a[i];
+                }
+                return b;
+            }
+        },
+        CHAR {
+            Object convert(int[] a) {
+                char[] b = new char[a.length];
+
+                for (int i = 0; i < a.length; i++) {
+                    b[i] = (char) a[i];
+                }
+                return b;
+            }
+        },
+        FLOAT {
+            Object convert(int[] a) {
+                float[] b = new float[a.length];
+
+                for (int i = 0; i < a.length; i++) {
+                    b[i] = (float) a[i];
+                }
+                return b;
+            }
+        },
+        DOUBLE {
+            Object convert(int[] a) {
+                double[] b = new double[a.length];
+
+                for (int i = 0; i < a.length; i++) {
+                    b[i] = (double) a[i];
+                }
+                return b;
+            }
+        },
+        INTEGER {
+            Object convert(int[] a) {
+                Integer[] b = new Integer[a.length];
+
+                for (int i = 0; i < a.length; i++) {
+                    b[i] = new Integer(a[i]);
+                }
+                return b;
+            }
+        };
+
+        abstract Object convert(int[] a);
+
+        @Override public String toString() {
+            String name = name();
+
+            for (int i = name.length(); i < 9; i++) {
+                name += " ";
+            }
+            return name;
+        }
+    }
+
+    private static enum FloatBuilder {
+        SIMPLE {
+            void build(float[] x, int a, int g, int z, int n, int p, Random random) {
+                int fromIndex = 0;
+                float negativeValue = -random.nextFloat();
+                float positiveValue =  random.nextFloat();
+
+                writeValue(x, negativeValue, fromIndex, n);
+                fromIndex += n;
+
+                writeValue(x, -0.0f, fromIndex, g);
+                fromIndex += g;
+
+                writeValue(x, 0.0f, fromIndex, z);
+                fromIndex += z;
+
+                writeValue(x, positiveValue, fromIndex, p);
+                fromIndex += p;
+
+                writeValue(x, Float.NaN, fromIndex, a);
+            }
+        };
+
+        abstract void build(float[] x, int a, int g, int z, int n, int p, Random random);
+    }
+
+    private static enum DoubleBuilder {
+        SIMPLE {
+            void build(double[] x, int a, int g, int z, int n, int p, Random random) {
+                int fromIndex = 0;
+                double negativeValue = -random.nextFloat();
+                double positiveValue =  random.nextFloat();
+
+                writeValue(x, negativeValue, fromIndex, n);
+                fromIndex += n;
+
+                writeValue(x, -0.0d, fromIndex, g);
+                fromIndex += g;
+
+                writeValue(x, 0.0d, fromIndex, z);
+                fromIndex += z;
+
+                writeValue(x, positiveValue, fromIndex, p);
+                fromIndex += p;
+
+                writeValue(x, Double.NaN, fromIndex, a);
+            }
+        };
+
+        abstract void build(double[] x, int a, int g, int z, int n, int p, Random random);
+    }
+
+    private static void writeValue(float[] a, float value, int fromIndex, int count) {
+        for (int i = fromIndex; i < fromIndex + count; i++) {
+            a[i] = value;
+        }
+    }
+
+    private static void compare(float[] a, float[] b, int numNaN, int numNeg, int numNegZero) {
+        for (int i = a.length - numNaN; i < a.length; i++) {
+            if (a[i] == a[i]) {
+                failed("On position " + i + " must be NaN instead of " + a[i]);
+            }
+        }
+        final int NEGATIVE_ZERO = Float.floatToIntBits(-0.0f);
+
+        for (int i = numNeg; i < numNeg + numNegZero; i++) {
+            if (NEGATIVE_ZERO != Float.floatToIntBits(a[i])) {
+                failed("On position " + i + " must be -0.0 instead of " + a[i]);
+            }
+        }
+        for (int i = 0; i < a.length - numNaN; i++) {
+            if (a[i] != b[i]) {
+                failedCompare(i, "" + a[i], "" + b[i]);
+            }
+        }
+    }
+
+    private static void writeValue(double[] a, double value, int fromIndex, int count) {
+        for (int i = fromIndex; i < fromIndex + count; i++) {
+            a[i] = value;
+        }
+    }
+
+    private static void compare(double[] a, double[] b, int numNaN, int numNeg, int numNegZero) {
+        for (int i = a.length - numNaN; i < a.length; i++) {
+            if (a[i] == a[i]) {
+                failed("On position " + i + " must be NaN instead of " + a[i]);
+            }
+        }
+        final long NEGATIVE_ZERO = Double.doubleToLongBits(-0.0d);
+
+        for (int i = numNeg; i < numNeg + numNegZero; i++) {
+            if (NEGATIVE_ZERO != Double.doubleToLongBits(a[i])) {
+                failed("On position " + i + " must be -0.0 instead of " + a[i]);
+            }
+        }
+        for (int i = 0; i < a.length - numNaN; i++) {
+            if (a[i] != b[i]) {
+                failedCompare(i, "" + a[i], "" + b[i]);
+            }
+        }
+    }
+
+    private static enum SortedBuilder {
+        REPEATED {
+            void build(int[] a, int m) {
+                int period = a.length / m;
+                int i = 0;
+                int k = 0;
+
+                while (true) {
+                    for (int t = 1; t <= period; t++) {
+                        if (i >= a.length) {
+                            return;
+                        }
+                        a[i++] = k;
+                    }
+                    if (i >= a.length) {
+                        return;
+                    }
+                    k++;
+                }
+            }
+        },
+        ORGAN_PIPES {
+            void build(int[] a, int m) {
+                int i = 0;
+                int k = m;
+
+                while (true) {
+                    for (int t = 1; t <= m; t++) {
+                        if (i >= a.length) {
+                            return;
+                        }
+                        a[i++] = k;
+                    }
+                }
+            }
+        };
+
+        abstract void build(int[] a, int m);
+
+        @Override public String toString() {
+            String name = name();
+
+            for (int i = name.length(); i < 12; i++) {
+                name += " ";
+            }
+            return name;
+        }
+    }
+
+    private static enum MergeBuilder {
+        ASCENDING {
+            void build(int[] a, int m) {
+                int period = a.length / m;
+                int v = 1, i = 0;
+
+                for (int k = 0; k < m; k++) {
+                    v = 1;
+                    for (int p = 0; p < period; p++) {
+                        a[i++] = v++;
+                    }
+                }
+                for (int j = i; j < a.length - 1; j++) {
+                    a[j] = v++;
+                }
+                a[a.length - 1] = 0;
+            }
+        },
+        DESCENDING {
+            void build(int[] a, int m) {
+                int period = a.length / m;
+                int v = -1, i = 0;
+
+                for (int k = 0; k < m; k++) {
+                    v = -1;
+                    for (int p = 0; p < period; p++) {
+                        a[i++] = v--;
+                    }
+                }
+                for (int j = i; j < a.length - 1; j++) {
+                    a[j] = v--;
+                }
+                a[a.length - 1] = 0;
+            }
+        };
+
+        abstract void build(int[] a, int m);
+
+        @Override public String toString() {
+            String name = name();
+
+            for (int i = name.length(); i < 12; i++) {
+                name += " ";
+            }
+            return name;
+        }
+    }
+
+    private static enum UnsortedBuilder {
+        RANDOM {
+            void build(int[] a, int m, Random random) {
+                for (int i = 0; i < a.length; i++) {
+                    a[i] = random.nextInt();
+                }
+            }
+        },
+        ASCENDING {
+            void build(int[] a, int m, Random random) {
+                for (int i = 0; i < a.length; i++) {
+                    a[i] = m + i;
+                }
+            }
+        },
+        DESCENDING {
+            void build(int[] a, int m, Random random) {
+                for (int i = 0; i < a.length; i++) {
+                    a[i] = a.length - m - i;
+                }
+            }
+        },
+        ALL_EQUAL {
+            void build(int[] a, int m, Random random) {
+                for (int i = 0; i < a.length; i++) {
+                    a[i] = m;
+                }
+            }
+        },
+        SAW {
+            void build(int[] a, int m, Random random) {
+                int incCount = 1;
+                int decCount = a.length;
+                int i = 0;
+                int period = m--;
+
+                while (true) {
+                    for (int k = 1; k <= period; k++) {
+                        if (i >= a.length) {
+                            return;
+                        }
+                        a[i++] = incCount++;
+                    }
+                    period += m;
+
+                    for (int k = 1; k <= period; k++) {
+                        if (i >= a.length) {
+                            return;
+                        }
+                        a[i++] = decCount--;
+                    }
+                    period += m;
+                }
+            }
+        },
+        REPEATED {
+            void build(int[] a, int m, Random random) {
+                for (int i = 0; i < a.length; i++) {
+                    a[i] = i % m;
+                }
+            }
+        },
+        DUPLICATED {
+            void build(int[] a, int m, Random random) {
+                for (int i = 0; i < a.length; i++) {
+                    a[i] = random.nextInt(m);
+                }
+            }
+        },
+        ORGAN_PIPES {
+            void build(int[] a, int m, Random random) {
+                int middle = a.length / (m + 1);
+
+                for (int i = 0; i < middle; i++) {
+                    a[i] = i;
+                }
+                for (int i = middle; i < a.length; i++) {
+                    a[i] = a.length - i - 1;
+                }
+            }
+        },
+        STAGGER {
+            void build(int[] a, int m, Random random) {
+                for (int i = 0; i < a.length; i++) {
+                    a[i] = (i * m + i) % a.length;
+                }
+            }
+        },
+        PLATEAU {
+            void build(int[] a, int m, Random random) {
+                for (int i = 0; i < a.length; i++) {
+                    a[i] = Math.min(i, m);
+                }
+            }
+        },
+        SHUFFLE {
+            void build(int[] a, int m, Random random) {
+                int x = 0, y = 0;
+                for (int i = 0; i < a.length; i++) {
+                    a[i] = random.nextBoolean() ? (x += 2) : (y += 2);
+                }
+            }
+        };
+
+        abstract void build(int[] a, int m, Random random);
+
+        @Override public String toString() {
+            String name = name();
+
+            for (int i = name.length(); i < 12; i++) {
+                name += " ";
+            }
+            return name;
+        }
+    }
+
+    private static void checkWithCheckSum(Object test, Object golden) {
+        checkSorted(test);
+        checkCheckSum(test, golden);
+    }
+
+    private static void failed(String message) {
+        err.format("\n*** TEST FAILED - %s.\n\n%s.\n\n", ourDescription, message);
+        throw new RuntimeException("Test failed - see log file for details");
+    }
+
+    private static void failedSort(int index, String value1, String value2) {
+        failed("Array is not sorted at " + index + "-th position: " +
+            value1 + " and " + value2);
+    }
+
+    private static void failedCompare(int index, String value1, String value2) {
+        failed("On position " + index + " must be " + value2 + " instead of " + value1);
+    }
+
+    private static void compare(Object test, Object golden) {
+        if (test instanceof int[]) {
+            compare((int[]) test, (int[]) golden);
+        } else if (test instanceof long[]) {
+            compare((long[]) test, (long[]) golden);
+        } else if (test instanceof short[]) {
+            compare((short[]) test, (short[]) golden);
+        } else if (test instanceof byte[]) {
+            compare((byte[]) test, (byte[]) golden);
+        } else if (test instanceof char[]) {
+            compare((char[]) test, (char[]) golden);
+        } else if (test instanceof float[]) {
+            compare((float[]) test, (float[]) golden);
+        } else if (test instanceof double[]) {
+            compare((double[]) test, (double[]) golden);
+        } else if (test instanceof Integer[]) {
+            compare((Integer[]) test, (Integer[]) golden);
+        } else {
+            failed("Unknow type of array: " + test + " of class " +
+                test.getClass().getName());
+        }
+    }
+
+    private static void compare(int[] a, int[] b) {
+        for (int i = 0; i < a.length; i++) {
+            if (a[i] != b[i]) {
+                failedCompare(i, "" + a[i], "" + b[i]);
+            }
+        }
+    }
+
+    private static void compare(long[] a, long[] b) {
+        for (int i = 0; i < a.length; i++) {
+            if (a[i] != b[i]) {
+                failedCompare(i, "" + a[i], "" + b[i]);
+            }
+        }
+    }
+
+    private static void compare(short[] a, short[] b) {
+        for (int i = 0; i < a.length; i++) {
+            if (a[i] != b[i]) {
+                failedCompare(i, "" + a[i], "" + b[i]);
+            }
+        }
+    }
+
+    private static void compare(byte[] a, byte[] b) {
+        for (int i = 0; i < a.length; i++) {
+            if (a[i] != b[i]) {
+                failedCompare(i, "" + a[i], "" + b[i]);
+            }
+        }
+    }
+
+    private static void compare(char[] a, char[] b) {
+        for (int i = 0; i < a.length; i++) {
+            if (a[i] != b[i]) {
+                failedCompare(i, "" + a[i], "" + b[i]);
+            }
+        }
+    }
+
+    private static void compare(float[] a, float[] b) {
+        for (int i = 0; i < a.length; i++) {
+            if (a[i] != b[i]) {
+                failedCompare(i, "" + a[i], "" + b[i]);
+            }
+        }
+    }
+
+    private static void compare(double[] a, double[] b) {
+        for (int i = 0; i < a.length; i++) {
+            if (a[i] != b[i]) {
+                failedCompare(i, "" + a[i], "" + b[i]);
+            }
+        }
+    }
+
+    private static void compare(Integer[] a, Integer[] b) {
+        for (int i = 0; i < a.length; i++) {
+            if (a[i].compareTo(b[i]) != 0) {
+                failedCompare(i, "" + a[i], "" + b[i]);
+            }
+        }
+    }
+
+    private static void checkSorted(Object object) {
+        if (object instanceof int[]) {
+            checkSorted((int[]) object);
+        } else if (object instanceof long[]) {
+            checkSorted((long[]) object);
+        } else if (object instanceof short[]) {
+            checkSorted((short[]) object);
+        } else if (object instanceof byte[]) {
+            checkSorted((byte[]) object);
+        } else if (object instanceof char[]) {
+            checkSorted((char[]) object);
+        } else if (object instanceof float[]) {
+            checkSorted((float[]) object);
+        } else if (object instanceof double[]) {
+            checkSorted((double[]) object);
+        } else if (object instanceof Integer[]) {
+            checkSorted((Integer[]) object);
+        } else {
+            failed("Unknow type of array: " + object + " of class " +
+                object.getClass().getName());
+        }
+    }
+
+    private static void checkSorted(int[] a) {
+        for (int i = 0; i < a.length - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+    }
+
+    private static void checkSorted(long[] a) {
+        for (int i = 0; i < a.length - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+    }
+
+    private static void checkSorted(short[] a) {
+        for (int i = 0; i < a.length - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+    }
+
+    private static void checkSorted(byte[] a) {
+        for (int i = 0; i < a.length - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+    }
+
+    private static void checkSorted(char[] a) {
+        for (int i = 0; i < a.length - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+    }
+
+    private static void checkSorted(float[] a) {
+        for (int i = 0; i < a.length - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+    }
+
+    private static void checkSorted(double[] a) {
+        for (int i = 0; i < a.length - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+    }
+
+    private static void checkSorted(Integer[] a) {
+        for (int i = 0; i < a.length - 1; i++) {
+            if (a[i].intValue() > a[i + 1].intValue()) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+    }
+
+    private static void checkCheckSum(Object test, Object golden) {
+        if (checkSumXor(test) != checkSumXor(golden)) {
+            failed("Original and sorted arrays are not identical [xor]");
+        }
+        if (checkSumPlus(test) != checkSumPlus(golden)) {
+            failed("Original and sorted arrays are not identical [plus]");
+        }
+    }
+
+    private static int checkSumXor(Object object) {
+        if (object instanceof int[]) {
+            return checkSumXor((int[]) object);
+        } else if (object instanceof long[]) {
+            return checkSumXor((long[]) object);
+        } else if (object instanceof short[]) {
+            return checkSumXor((short[]) object);
+        } else if (object instanceof byte[]) {
+            return checkSumXor((byte[]) object);
+        } else if (object instanceof char[]) {
+            return checkSumXor((char[]) object);
+        } else if (object instanceof float[]) {
+            return checkSumXor((float[]) object);
+        } else if (object instanceof double[]) {
+            return checkSumXor((double[]) object);
+        } else if (object instanceof Integer[]) {
+            return checkSumXor((Integer[]) object);
+        } else {
+            failed("Unknow type of array: " + object + " of class " +
+                object.getClass().getName());
+            return -1;
+        }
+    }
+
+    private static int checkSumXor(Integer[] a) {
+        int checkSum = 0;
+
+        for (Integer e : a) {
+            checkSum ^= e.intValue();
+        }
+        return checkSum;
+    }
+
+    private static int checkSumXor(int[] a) {
+        int checkSum = 0;
+
+        for (int e : a) {
+            checkSum ^= e;
+        }
+        return checkSum;
+    }
+
+    private static int checkSumXor(long[] a) {
+        long checkSum = 0;
+
+        for (long e : a) {
+            checkSum ^= e;
+        }
+        return (int) checkSum;
+    }
+
+    private static int checkSumXor(short[] a) {
+        short checkSum = 0;
+
+        for (short e : a) {
+            checkSum ^= e;
+        }
+        return (int) checkSum;
+    }
+
+    private static int checkSumXor(byte[] a) {
+        byte checkSum = 0;
+
+        for (byte e : a) {
+            checkSum ^= e;
+        }
+        return (int) checkSum;
+    }
+
+    private static int checkSumXor(char[] a) {
+        char checkSum = 0;
+
+        for (char e : a) {
+            checkSum ^= e;
+        }
+        return (int) checkSum;
+    }
+
+    private static int checkSumXor(float[] a) {
+        int checkSum = 0;
+
+        for (float e : a) {
+            checkSum ^= (int) e;
+        }
+        return checkSum;
+    }
+
+    private static int checkSumXor(double[] a) {
+        int checkSum = 0;
+
+        for (double e : a) {
+            checkSum ^= (int) e;
+        }
+        return checkSum;
+    }
+
+    private static int checkSumPlus(Object object) {
+        if (object instanceof int[]) {
+            return checkSumPlus((int[]) object);
+        } else if (object instanceof long[]) {
+            return checkSumPlus((long[]) object);
+        } else if (object instanceof short[]) {
+            return checkSumPlus((short[]) object);
+        } else if (object instanceof byte[]) {
+            return checkSumPlus((byte[]) object);
+        } else if (object instanceof char[]) {
+            return checkSumPlus((char[]) object);
+        } else if (object instanceof float[]) {
+            return checkSumPlus((float[]) object);
+        } else if (object instanceof double[]) {
+            return checkSumPlus((double[]) object);
+        } else if (object instanceof Integer[]) {
+            return checkSumPlus((Integer[]) object);
+        } else {
+            failed("Unknow type of array: " + object + " of class " +
+                object.getClass().getName());
+            return -1;
+        }
+    }
+
+    private static int checkSumPlus(int[] a) {
+        int checkSum = 0;
+
+        for (int e : a) {
+            checkSum += e;
+        }
+        return checkSum;
+    }
+
+    private static int checkSumPlus(long[] a) {
+        long checkSum = 0;
+
+        for (long e : a) {
+            checkSum += e;
+        }
+        return (int) checkSum;
+    }
+
+    private static int checkSumPlus(short[] a) {
+        short checkSum = 0;
+
+        for (short e : a) {
+            checkSum += e;
+        }
+        return (int) checkSum;
+    }
+
+    private static int checkSumPlus(byte[] a) {
+        byte checkSum = 0;
+
+        for (byte e : a) {
+            checkSum += e;
+        }
+        return (int) checkSum;
+    }
+
+    private static int checkSumPlus(char[] a) {
+        char checkSum = 0;
+
+        for (char e : a) {
+            checkSum += e;
+        }
+        return (int) checkSum;
+    }
+
+    private static int checkSumPlus(float[] a) {
+        int checkSum = 0;
+
+        for (float e : a) {
+            checkSum += (int) e;
+        }
+        return checkSum;
+    }
+
+    private static int checkSumPlus(double[] a) {
+        int checkSum = 0;
+
+        for (double e : a) {
+            checkSum += (int) e;
+        }
+        return checkSum;
+    }
+
+    private static int checkSumPlus(Integer[] a) {
+        int checkSum = 0;
+
+        for (Integer e : a) {
+            checkSum += e.intValue();
+        }
+        return checkSum;
+    }
+
+    private static void sortByInsertionSort(Object object) {
+        if (object instanceof int[]) {
+            sortByInsertionSort((int[]) object);
+        } else if (object instanceof long[]) {
+            sortByInsertionSort((long[]) object);
+        } else if (object instanceof short[]) {
+            sortByInsertionSort((short[]) object);
+        } else if (object instanceof byte[]) {
+            sortByInsertionSort((byte[]) object);
+        } else if (object instanceof char[]) {
+            sortByInsertionSort((char[]) object);
+        } else if (object instanceof float[]) {
+            sortByInsertionSort((float[]) object);
+        } else if (object instanceof double[]) {
+            sortByInsertionSort((double[]) object);
+        } else if (object instanceof Integer[]) {
+            sortByInsertionSort((Integer[]) object);
+        } else {
+            failed("Unknow type of array: " + object + " of class " +
+                object.getClass().getName());
+        }
+    }
+
+    private static void sortByInsertionSort(int[] a) {
+        for (int j, i = 1; i < a.length; i++) {
+            int ai = a[i];
+            for (j = i - 1; j >= 0 && ai < a[j]; j--) {
+                a[j + 1] = a[j];
+            }
+            a[j + 1] = ai;
+        }
+    }
+
+    private static void sortByInsertionSort(long[] a) {
+        for (int j, i = 1; i < a.length; i++) {
+            long ai = a[i];
+            for (j = i - 1; j >= 0 && ai < a[j]; j--) {
+                a[j + 1] = a[j];
+            }
+            a[j + 1] = ai;
+        }
+    }
+
+    private static void sortByInsertionSort(short[] a) {
+        for (int j, i = 1; i < a.length; i++) {
+            short ai = a[i];
+            for (j = i - 1; j >= 0 && ai < a[j]; j--) {
+                a[j + 1] = a[j];
+            }
+            a[j + 1] = ai;
+        }
+    }
+
+    private static void sortByInsertionSort(byte[] a) {
+        for (int j, i = 1; i < a.length; i++) {
+            byte ai = a[i];
+            for (j = i - 1; j >= 0 && ai < a[j]; j--) {
+                a[j + 1] = a[j];
+            }
+            a[j + 1] = ai;
+        }
+    }
+
+    private static void sortByInsertionSort(char[] a) {
+        for (int j, i = 1; i < a.length; i++) {
+            char ai = a[i];
+            for (j = i - 1; j >= 0 && ai < a[j]; j--) {
+                a[j + 1] = a[j];
+            }
+            a[j + 1] = ai;
+        }
+    }
+
+    private static void sortByInsertionSort(float[] a) {
+        for (int j, i = 1; i < a.length; i++) {
+            float ai = a[i];
+            for (j = i - 1; j >= 0 && ai < a[j]; j--) {
+                a[j + 1] = a[j];
+            }
+            a[j + 1] = ai;
+        }
+    }
+
+    private static void sortByInsertionSort(double[] a) {
+        for (int j, i = 1; i < a.length; i++) {
+            double ai = a[i];
+            for (j = i - 1; j >= 0 && ai < a[j]; j--) {
+                a[j + 1] = a[j];
+            }
+            a[j + 1] = ai;
+        }
+    }
+
+    private static void sortByInsertionSort(Integer[] a) {
+        for (int j, i = 1; i < a.length; i++) {
+            Integer ai = a[i];
+            for (j = i - 1; j >= 0 && ai < a[j]; j--) {
+                a[j + 1] = a[j];
+            }
+            a[j + 1] = ai;
+        }
+    }
+
+    private static void sort(Object object) {
+        if (object instanceof int[]) {
+            Arrays.parallelSort((int[]) object);
+        } else if (object instanceof long[]) {
+            Arrays.parallelSort((long[]) object);
+        } else if (object instanceof short[]) {
+            Arrays.parallelSort((short[]) object);
+        } else if (object instanceof byte[]) {
+            Arrays.parallelSort((byte[]) object);
+        } else if (object instanceof char[]) {
+            Arrays.parallelSort((char[]) object);
+        } else if (object instanceof float[]) {
+            Arrays.parallelSort((float[]) object);
+        } else if (object instanceof double[]) {
+            Arrays.parallelSort((double[]) object);
+        } else if (object instanceof Integer[]) {
+            Arrays.parallelSort((Integer[]) object);
+        } else {
+            failed("Unknow type of array: " + object + " of class " +
+                object.getClass().getName());
+        }
+    }
+
+    private static void sortSubArray(Object object, int fromIndex, int toIndex) {
+        if (object instanceof int[]) {
+            Arrays.parallelSort((int[]) object, fromIndex, toIndex);
+        } else if (object instanceof long[]) {
+            Arrays.parallelSort((long[]) object, fromIndex, toIndex);
+        } else if (object instanceof short[]) {
+            Arrays.parallelSort((short[]) object, fromIndex, toIndex);
+        } else if (object instanceof byte[]) {
+            Arrays.parallelSort((byte[]) object, fromIndex, toIndex);
+        } else if (object instanceof char[]) {
+            Arrays.parallelSort((char[]) object, fromIndex, toIndex);
+        } else if (object instanceof float[]) {
+            Arrays.parallelSort((float[]) object, fromIndex, toIndex);
+        } else if (object instanceof double[]) {
+            Arrays.parallelSort((double[]) object, fromIndex, toIndex);
+        } else if (object instanceof Integer[]) {
+            Arrays.parallelSort((Integer[]) object, fromIndex, toIndex);
+        } else {
+            failed("Unknow type of array: " + object + " of class " +
+                object.getClass().getName());
+        }
+    }
+
+    private static void checkSubArray(Object object, int fromIndex, int toIndex, int m) {
+        if (object instanceof int[]) {
+            checkSubArray((int[]) object, fromIndex, toIndex, m);
+        } else if (object instanceof long[]) {
+            checkSubArray((long[]) object, fromIndex, toIndex, m);
+        } else if (object instanceof short[]) {
+            checkSubArray((short[]) object, fromIndex, toIndex, m);
+        } else if (object instanceof byte[]) {
+            checkSubArray((byte[]) object, fromIndex, toIndex, m);
+        } else if (object instanceof char[]) {
+            checkSubArray((char[]) object, fromIndex, toIndex, m);
+        } else if (object instanceof float[]) {
+            checkSubArray((float[]) object, fromIndex, toIndex, m);
+        } else if (object instanceof double[]) {
+            checkSubArray((double[]) object, fromIndex, toIndex, m);
+        } else if (object instanceof Integer[]) {
+            checkSubArray((Integer[]) object, fromIndex, toIndex, m);
+        } else {
+            failed("Unknow type of array: " + object + " of class " +
+                object.getClass().getName());
+        }
+    }
+
+    private static void checkSubArray(Integer[] a, int fromIndex, int toIndex, int m) {
+        for (int i = 0; i < fromIndex; i++) {
+            if (a[i].intValue() != 0xDEDA) {
+                failed("Range sort changes left element on position " + i +
+                    ": " + a[i] + ", must be " + 0xDEDA);
+            }
+        }
+
+        for (int i = fromIndex; i < toIndex - 1; i++) {
+            if (a[i].intValue() > a[i + 1].intValue()) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+
+        for (int i = toIndex; i < a.length; i++) {
+            if (a[i].intValue() != 0xBABA) {
+                failed("Range sort changes right element on position " + i +
+                    ": " + a[i] + ", must be " + 0xBABA);
+            }
+        }
+    }
+
+    private static void checkSubArray(int[] a, int fromIndex, int toIndex, int m) {
+        for (int i = 0; i < fromIndex; i++) {
+            if (a[i] != 0xDEDA) {
+                failed("Range sort changes left element on position " + i +
+                    ": " + a[i] + ", must be " + 0xDEDA);
+            }
+        }
+
+        for (int i = fromIndex; i < toIndex - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+
+        for (int i = toIndex; i < a.length; i++) {
+            if (a[i] != 0xBABA) {
+                failed("Range sort changes right element on position " + i +
+                    ": " + a[i] + ", must be " + 0xBABA);
+            }
+        }
+    }
+
+    private static void checkSubArray(byte[] a, int fromIndex, int toIndex, int m) {
+        for (int i = 0; i < fromIndex; i++) {
+            if (a[i] != (byte) 0xDEDA) {
+                failed("Range sort changes left element on position " + i +
+                    ": " + a[i] + ", must be " + 0xDEDA);
+            }
+        }
+
+        for (int i = fromIndex; i < toIndex - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+
+        for (int i = toIndex; i < a.length; i++) {
+            if (a[i] != (byte) 0xBABA) {
+                failed("Range sort changes right element on position " + i +
+                    ": " + a[i] + ", must be " + 0xBABA);
+            }
+        }
+    }
+
+    private static void checkSubArray(long[] a, int fromIndex, int toIndex, int m) {
+        for (int i = 0; i < fromIndex; i++) {
+            if (a[i] != (long) 0xDEDA) {
+                failed("Range sort changes left element on position " + i +
+                    ": " + a[i] + ", must be " + 0xDEDA);
+            }
+        }
+
+        for (int i = fromIndex; i < toIndex - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+
+        for (int i = toIndex; i < a.length; i++) {
+            if (a[i] != (long) 0xBABA) {
+                failed("Range sort changes right element on position " + i +
+                    ": " + a[i] + ", must be " + 0xBABA);
+            }
+        }
+    }
+
+    private static void checkSubArray(char[] a, int fromIndex, int toIndex, int m) {
+        for (int i = 0; i < fromIndex; i++) {
+            if (a[i] != (char) 0xDEDA) {
+                failed("Range sort changes left element on position " + i +
+                    ": " + a[i] + ", must be " + 0xDEDA);
+            }
+        }
+
+        for (int i = fromIndex; i < toIndex - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+
+        for (int i = toIndex; i < a.length; i++) {
+            if (a[i] != (char) 0xBABA) {
+                failed("Range sort changes right element on position " + i +
+                    ": " + a[i] + ", must be " + 0xBABA);
+            }
+        }
+    }
+
+    private static void checkSubArray(short[] a, int fromIndex, int toIndex, int m) {
+        for (int i = 0; i < fromIndex; i++) {
+            if (a[i] != (short) 0xDEDA) {
+                failed("Range sort changes left element on position " + i +
+                    ": " + a[i] + ", must be " + 0xDEDA);
+            }
+        }
+
+        for (int i = fromIndex; i < toIndex - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+
+        for (int i = toIndex; i < a.length; i++) {
+            if (a[i] != (short) 0xBABA) {
+                failed("Range sort changes right element on position " + i +
+                    ": " + a[i] + ", must be " + 0xBABA);
+            }
+        }
+    }
+
+    private static void checkSubArray(float[] a, int fromIndex, int toIndex, int m) {
+        for (int i = 0; i < fromIndex; i++) {
+            if (a[i] != (float) 0xDEDA) {
+                failed("Range sort changes left element on position " + i +
+                    ": " + a[i] + ", must be " + 0xDEDA);
+            }
+        }
+
+        for (int i = fromIndex; i < toIndex - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+
+        for (int i = toIndex; i < a.length; i++) {
+            if (a[i] != (float) 0xBABA) {
+                failed("Range sort changes right element on position " + i +
+                    ": " + a[i] + ", must be " + 0xBABA);
+            }
+        }
+    }
+
+    private static void checkSubArray(double[] a, int fromIndex, int toIndex, int m) {
+        for (int i = 0; i < fromIndex; i++) {
+            if (a[i] != (double) 0xDEDA) {
+                failed("Range sort changes left element on position " + i +
+                    ": " + a[i] + ", must be " + 0xDEDA);
+            }
+        }
+
+        for (int i = fromIndex; i < toIndex - 1; i++) {
+            if (a[i] > a[i + 1]) {
+                failedSort(i, "" + a[i], "" + a[i + 1]);
+            }
+        }
+
+        for (int i = toIndex; i < a.length; i++) {
+            if (a[i] != (double) 0xBABA) {
+                failed("Range sort changes right element on position " + i +
+                    ": " + a[i] + ", must be " + 0xBABA);
+            }
+        }
+    }
+
+    private static void checkRange(Object object, int m) {
+        if (object instanceof int[]) {
+            checkRange((int[]) object, m);
+        } else if (object instanceof long[]) {
+            checkRange((long[]) object, m);
+        } else if (object instanceof short[]) {
+            checkRange((short[]) object, m);
+        } else if (object instanceof byte[]) {
+            checkRange((byte[]) object, m);
+        } else if (object instanceof char[]) {
+            checkRange((char[]) object, m);
+        } else if (object instanceof float[]) {
+            checkRange((float[]) object, m);
+        } else if (object instanceof double[]) {
+            checkRange((double[]) object, m);
+        } else if (object instanceof Integer[]) {
+            checkRange((Integer[]) object, m);
+        } else {
+            failed("Unknow type of array: " + object + " of class " +
+                object.getClass().getName());
+        }
+    }
+
+    private static void checkRange(Integer[] a, int m) {
+        try {
+            Arrays.parallelSort(a, m + 1, m);
+
+            failed("ParallelSort does not throw IllegalArgumentException " +
+                " as expected: fromIndex = " + (m + 1) +
+                " toIndex = " + m);
+        }
+        catch (IllegalArgumentException iae) {
+            try {
+                Arrays.parallelSort(a, -m, a.length);
+
+                failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                    " as expected: fromIndex = " + (-m));
+            }
+            catch (ArrayIndexOutOfBoundsException aoe) {
+                try {
+                    Arrays.parallelSort(a, 0, a.length + m);
+
+                    failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                        " as expected: toIndex = " + (a.length + m));
+                }
+                catch (ArrayIndexOutOfBoundsException aie) {
+                    return;
+                }
+            }
+        }
+    }
+
+    private static void checkRange(int[] a, int m) {
+        try {
+            Arrays.parallelSort(a, m + 1, m);
+
+            failed("ParallelSort does not throw IllegalArgumentException " +
+                " as expected: fromIndex = " + (m + 1) +
+                " toIndex = " + m);
+        }
+        catch (IllegalArgumentException iae) {
+            try {
+                Arrays.parallelSort(a, -m, a.length);
+
+                failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                    " as expected: fromIndex = " + (-m));
+            }
+            catch (ArrayIndexOutOfBoundsException aoe) {
+                try {
+                    Arrays.parallelSort(a, 0, a.length + m);
+
+                    failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                        " as expected: toIndex = " + (a.length + m));
+                }
+                catch (ArrayIndexOutOfBoundsException aie) {
+                    return;
+                }
+            }
+        }
+    }
+
+    private static void checkRange(long[] a, int m) {
+        try {
+            Arrays.parallelSort(a, m + 1, m);
+
+            failed("ParallelSort does not throw IllegalArgumentException " +
+                " as expected: fromIndex = " + (m + 1) +
+                " toIndex = " + m);
+        }
+        catch (IllegalArgumentException iae) {
+            try {
+                Arrays.parallelSort(a, -m, a.length);
+
+                failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                    " as expected: fromIndex = " + (-m));
+            }
+            catch (ArrayIndexOutOfBoundsException aoe) {
+                try {
+                    Arrays.parallelSort(a, 0, a.length + m);
+
+                    failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                        " as expected: toIndex = " + (a.length + m));
+                }
+                catch (ArrayIndexOutOfBoundsException aie) {
+                    return;
+                }
+            }
+        }
+    }
+
+    private static void checkRange(byte[] a, int m) {
+        try {
+            Arrays.parallelSort(a, m + 1, m);
+
+            failed("ParallelSort does not throw IllegalArgumentException " +
+                " as expected: fromIndex = " + (m + 1) +
+                " toIndex = " + m);
+        }
+        catch (IllegalArgumentException iae) {
+            try {
+                Arrays.parallelSort(a, -m, a.length);
+
+                failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                    " as expected: fromIndex = " + (-m));
+            }
+            catch (ArrayIndexOutOfBoundsException aoe) {
+                try {
+                    Arrays.parallelSort(a, 0, a.length + m);
+
+                    failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                        " as expected: toIndex = " + (a.length + m));
+                }
+                catch (ArrayIndexOutOfBoundsException aie) {
+                    return;
+                }
+            }
+        }
+    }
+
+    private static void checkRange(short[] a, int m) {
+        try {
+            Arrays.parallelSort(a, m + 1, m);
+
+            failed("ParallelSort does not throw IllegalArgumentException " +
+                " as expected: fromIndex = " + (m + 1) +
+                " toIndex = " + m);
+        }
+        catch (IllegalArgumentException iae) {
+            try {
+                Arrays.parallelSort(a, -m, a.length);
+
+                failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                    " as expected: fromIndex = " + (-m));
+            }
+            catch (ArrayIndexOutOfBoundsException aoe) {
+                try {
+                    Arrays.parallelSort(a, 0, a.length + m);
+
+                    failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                        " as expected: toIndex = " + (a.length + m));
+                }
+                catch (ArrayIndexOutOfBoundsException aie) {
+                    return;
+                }
+            }
+        }
+    }
+
+    private static void checkRange(char[] a, int m) {
+        try {
+            Arrays.parallelSort(a, m + 1, m);
+
+            failed("ParallelSort does not throw IllegalArgumentException " +
+                " as expected: fromIndex = " + (m + 1) +
+                " toIndex = " + m);
+        }
+        catch (IllegalArgumentException iae) {
+            try {
+                Arrays.parallelSort(a, -m, a.length);
+
+                failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                    " as expected: fromIndex = " + (-m));
+            }
+            catch (ArrayIndexOutOfBoundsException aoe) {
+                try {
+                    Arrays.parallelSort(a, 0, a.length + m);
+
+                    failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                        " as expected: toIndex = " + (a.length + m));
+                }
+                catch (ArrayIndexOutOfBoundsException aie) {
+                    return;
+                }
+            }
+        }
+    }
+
+    private static void checkRange(float[] a, int m) {
+        try {
+            Arrays.parallelSort(a, m + 1, m);
+
+            failed("ParallelSort does not throw IllegalArgumentException " +
+                " as expected: fromIndex = " + (m + 1) +
+                " toIndex = " + m);
+        }
+        catch (IllegalArgumentException iae) {
+            try {
+                Arrays.parallelSort(a, -m, a.length);
+
+                failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                    " as expected: fromIndex = " + (-m));
+            }
+            catch (ArrayIndexOutOfBoundsException aoe) {
+                try {
+                    Arrays.parallelSort(a, 0, a.length + m);
+
+                    failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                        " as expected: toIndex = " + (a.length + m));
+                }
+                catch (ArrayIndexOutOfBoundsException aie) {
+                    return;
+                }
+            }
+        }
+    }
+
+    private static void checkRange(double[] a, int m) {
+        try {
+            Arrays.parallelSort(a, m + 1, m);
+
+            failed("ParallelSort does not throw IllegalArgumentException " +
+                " as expected: fromIndex = " + (m + 1) +
+                " toIndex = " + m);
+        }
+        catch (IllegalArgumentException iae) {
+            try {
+                Arrays.parallelSort(a, -m, a.length);
+
+                failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                    " as expected: fromIndex = " + (-m));
+            }
+            catch (ArrayIndexOutOfBoundsException aoe) {
+                try {
+                    Arrays.parallelSort(a, 0, a.length + m);
+
+                    failed("ParallelSort does not throw ArrayIndexOutOfBoundsException " +
+                        " as expected: toIndex = " + (a.length + m));
+                }
+                catch (ArrayIndexOutOfBoundsException aie) {
+                    return;
+                }
+            }
+        }
+    }
+
+    private static void outArray(Object[] a) {
+        for (int i = 0; i < a.length; i++) {
+            out.print(a[i] + " ");
+        }
+        out.println();
+    }
+
+    private static void outArray(int[] a) {
+        for (int i = 0; i < a.length; i++) {
+            out.print(a[i] + " ");
+        }
+        out.println();
+    }
+
+    private static void outArray(float[] a) {
+        for (int i = 0; i < a.length; i++) {
+            out.print(a[i] + " ");
+        }
+        out.println();
+    }
+
+    private static void outArray(double[] a) {
+        for (int i = 0; i < a.length; i++) {
+            out.print(a[i] + " ");
+        }
+        out.println();
+    }
+
+    private static class MyRandom extends Random {
+        MyRandom(long seed) {
+            super(seed);
+            mySeed = seed;
+        }
+
+        long getSeed() {
+            return mySeed;
+        }
+
+        private long mySeed;
+    }
+
+    private static String ourDescription;
+}
--- a/jdk/test/java/util/Collections/EmptyIterator.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/Collections/EmptyIterator.java	Tue Jan 22 11:54:16 2013 -0800
@@ -23,12 +23,12 @@
 
 /*
  * @test
- * @bug 5017904 6356890
+ * @bug 5017904 6356890 8004928
  * @summary Test empty iterators, enumerations, and collections
  */
 
+import static java.util.Collections.*;
 import java.util.*;
-import static java.util.Collections.*;
 
 public class EmptyIterator {
 
@@ -45,10 +45,13 @@
         testEmptyIterator(emptyTable.values().iterator());
         testEmptyIterator(emptyTable.entrySet().iterator());
 
-        testEmptyEnumeration(javax.swing.tree.DefaultMutableTreeNode
-                             .EMPTY_ENUMERATION);
-        testEmptyEnumeration(javax.swing.text.SimpleAttributeSet
-                             .EMPTY.getAttributeNames());
+        final Enumeration<EmptyIterator> finalEmptyTyped =
+            Collections.emptyEnumeration();
+        testEmptyEnumeration(finalEmptyTyped);
+
+        final Enumeration finalEmptyAbstract =
+            Collections.emptyEnumeration();
+        testEmptyEnumeration(finalEmptyAbstract);
 
         @SuppressWarnings("unchecked") Iterator<?> x =
             new sun.tools.java.MethodSet()
--- a/jdk/test/java/util/Currency/ValidateISO4217.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/Currency/ValidateISO4217.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,7 +22,7 @@
  */
 /*
  * @test
- * @bug 4691089 4819436 4942982 5104960 6544471 6627549 7066203
+ * @bug 4691089 4819436 4942982 5104960 6544471 6627549 7066203 7195759
  * @summary Validate ISO 4217 data for Currency class.
  */
 
@@ -92,7 +92,7 @@
 
     /* Codes that are obsolete, do not have related country */
     static final String otherCodes =
-        "ADP-AFA-ATS-AYM-AZM-BEF-BGL-BOV-BYB-CLF-CUC-CYP-DEM-EEK-ESP-FIM-FRF-GHC-GRD-GWP-IEP-ITL-LUF-MGF-MTL-MXV-MZM-NLG-PTE-ROL-RUR-SDD-SIT-SKK-SRG-TMM-TPE-TRL-VEF-USN-USS-VEB-XAG-XAU-XBA-XBB-XBC-XBD-XDR-XFO-XFU-XPD-XPT-XSU-XTS-XUA-XXX-YUM-ZWD-ZWN-ZWR";
+        "ADP-AFA-ATS-AYM-AZM-BEF-BGL-BOV-BYB-CLF-CUC-CYP-DEM-EEK-ESP-FIM-FRF-GHC-GRD-GWP-IEP-ITL-LUF-MGF-MTL-MXV-MZM-NLG-PTE-ROL-RUR-SDD-SIT-SKK-SRG-TMM-TPE-TRL-VEF-USN-USS-VEB-XAG-XAU-XBA-XBB-XBC-XBD-XDR-XFO-XFU-XPD-XPT-XSU-XTS-XUA-XXX-YUM-ZMK-ZWD-ZWN-ZWR";
 
     static boolean err = false;
 
--- a/jdk/test/java/util/Currency/tablea1.txt	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/Currency/tablea1.txt	Tue Jan 22 11:54:16 2013 -0800
@@ -1,12 +1,12 @@
 #
 #
-# Amendments up until ISO 4217 AMENDMENT NUMBER 153
-#   (As of 12 January 2012)
+# Amendments up until ISO 4217 AMENDMENT NUMBER 154
+#   (As of 31 August 2012)
 #
 
 # Version
 FILEVERSION=1
-DATAVERSION=153
+DATAVERSION=154
 
 # ISO 4217 currency data
 AF	AFN	971	2
@@ -274,7 +274,7 @@
 WF	XPF	953	0
 EH	MAD	504	2
 YE	YER	886	2
-ZM	ZMK	894	2
+ZM	ZMW	967	2
 ZW	ZWL	932	2
 #XAU	XAU	959
 #XBA	XBA	955
--- a/jdk/test/java/util/Map/EntryHashCode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/Map/EntryHashCode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/Compatibility.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd" 
+ [<!ENTITY intEnt 'value3'> ]>
+<?PITarget PIContent?>
+<properties>
+<comment>Property With Other Encoding</comment>
+<entry key="Key1">value1</entry>
+<entry key="Key2"><![CDATA[<value2>]]></entry>
+<entry key="Key3">&intEnt;</entry>
+</properties>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/CompatibilityTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8005280 8004371
+ * @summary Compatibility test
+ * @run main CompatibilityTest
+ * @run main/othervm -Dsun.util.spi.XmlPropertiesProvider=jdk.internal.util.xml.BasicXmlPropertiesProvider CompatibilityTest
+ */
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+/**
+ * This is a behavior compatibility test.
+ * Although not defined by the properties.dtd, the constructs
+ * in Compatibility.xml are supported by the regular JDK XML
+ * Provider.
+ *
+ * @author: Joe Wang
+ */
+public class CompatibilityTest {
+
+    public static void main(String[] args) {
+        testInternalDTD();
+    }
+
+    /*
+     * Not in the spec, but the constructs work with the current JDK
+     */
+    static void testInternalDTD() {
+        String src = System.getProperty("test.src");
+        if (src == null) {
+            src = ".";
+        }
+        loadPropertyFile(src + "/Compatibility.xml");
+    }
+
+    /*
+     * 'Store' the populated 'Property' with the specified 'Encoding Type' as an
+     * XML file. Retrieve the same XML file and 'load' onto a new 'Property' object.
+     */
+    static void loadPropertyFile(String filename) {
+        try (InputStream in = new FileInputStream(filename)) {
+            Properties prop = new Properties();
+            prop.loadFromXML(in);
+            verifyProperites(prop);
+        } catch (IOException ex) {
+            fail(ex.getMessage());
+        }
+    }
+
+    /*
+     * This method verifies the first key-value with the original string.
+     */
+    static void verifyProperites(Properties prop) {
+        try {
+            for (String key : prop.stringPropertyNames()) {
+                String val = prop.getProperty(key);
+                if (key.equals("Key1")) {
+                    if (!val.equals("value1")) {
+                        fail("Key:" + key + "'s value: \nExpected: value1\nFound: " + val);
+                    }
+                } else if (key.equals("Key2")) {
+                    if (!val.equals("<value2>")) {
+                        fail("Key:" + key + "'s value: \nExpected: <value2>\nFound: " + val);
+                    }
+                } else if (key.equals("Key3")) {
+                    if (!val.equals("value3")) {
+                        fail("Key:" + key + "'s value: \nExpected: value3\nFound: " + val);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            fail(e.getMessage());
+        }
+
+    }
+
+    static void fail(String err) {
+        throw new RuntimeException(err);
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/ConcurrentLoadAndStoreXML.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8005281
+ * @summary Test that the Properties storeToXML and loadFromXML methods are
+ *   thread safe
+ * @run main ConcurrentLoadAndStoreXML
+ * @run main/othervm -Dsun.util.spi.XmlPropertiesProvider=jdk.internal.util.xml.BasicXmlPropertiesProvider ConcurrentLoadAndStoreXML
+
+ */
+
+import java.io.*;
+import java.util.Properties;
+import java.util.Random;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+
+public class ConcurrentLoadAndStoreXML {
+
+    static final Random RAND = new Random();
+
+    static volatile boolean done;
+
+    /**
+     * Simple task that bashes on storeToXML and loadFromXML until the "done"
+     * flag is set.
+     */
+    static class Basher implements Callable<Void> {
+        final Properties props;
+
+        Basher(Properties props) {
+            this.props = props;
+        }
+
+        public Void call() throws IOException {
+            while (!done) {
+
+                // store as XML format
+                ByteArrayOutputStream out = new ByteArrayOutputStream();
+                props.storeToXML(out, null, "UTF-8");
+
+                // load from XML format
+                Properties p = new Properties();
+                ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
+                p.loadFromXML(in);
+
+                // check that the properties are as expected
+                if (!p.equals(props))
+                    throw new RuntimeException("Properties not equal");
+            }
+            return null;
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        final int NTASKS = 4 + RAND.nextInt(4);
+
+        // create Bashers with Properties of random keys and values
+        Basher[] basher = new Basher[NTASKS];
+        for (int i=0; i<NTASKS; i++) {
+            Properties props = new Properties();
+            for (int j=0; j<RAND.nextInt(100); j++) {
+                String key = "k" + RAND.nextInt(1000);
+                String value = "v" + RAND.nextInt(1000);
+                props.put(key, value);
+            }
+            basher[i] = new Basher(props);
+        }
+
+        ExecutorService pool = Executors.newFixedThreadPool(NTASKS);
+        try {
+            // kick off the bashers
+            Future<Void>[] task = new Future[NTASKS];
+            for (int i=0; i<NTASKS; i++) {
+                task[i] = pool.submit(basher[i]);
+            }
+
+            // give them time to interfere with each each
+            Thread.sleep(2000);
+            done = true;
+
+            // check the result
+            for (int i=0; i<NTASKS; i++) {
+                task[i].get();
+            }
+        } finally {
+            done = true;
+            pool.shutdown();
+        }
+
+    }
+}
--- a/jdk/test/java/util/Properties/LoadAndStoreXML.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/Properties/LoadAndStoreXML.java	Tue Jan 22 11:54:16 2013 -0800
@@ -23,13 +23,16 @@
 
 /*
  * @test
- * @bug 8000354 8000685
+ * @bug 8000354 8000685 8004371
  * @summary Basic test of storeToXML and loadToXML
+ * @run main LoadAndStoreXML
+ * @run main/othervm -Dsun.util.spi.XmlPropertiesProvider=jdk.internal.util.xml.BasicXmlPropertiesProvider LoadAndStoreXML
  */
 
 import java.io.*;
 import java.util.*;
 import java.security.*;
+import java.nio.file.*;
 
 public class LoadAndStoreXML {
 
@@ -67,9 +70,14 @@
      * read with Properties#loadFromXML.
      */
     static void testLoadAndStore(String encoding) throws IOException {
+        System.out.println("testLoadAndStore, encoding=" + encoding);
+
         Properties props = new Properties();
         props.put("k1", "foo");
         props.put("k2", "bar");
+        props.put("k3", "\\u0020\\u0391\\u0392\\u0393\\u0394\\u0395\\u0396\\u0397");
+        props.put("k4", "\u7532\u9aa8\u6587");
+        props.put("k5", "<java.home>/lib/jaxp.properties");
 
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         props.storeToXML(out, null, encoding);
@@ -89,6 +97,8 @@
      * Test loadFromXML with a document that does not have an encoding declaration
      */
     static void testLoadWithoutEncoding() throws IOException {
+        System.out.println("testLoadWithoutEncoding");
+
         Properties expected = new Properties();
         expected.put("foo", "bar");
 
@@ -107,10 +117,11 @@
         }
     }
 
-     /**
-      * Test loadFromXML with unsupported encoding
-      */
-     static void testLoadWithBadEncoding() throws IOException {
+    /**
+     * Test loadFromXML with unsupported encoding
+     */
+    static void testLoadWithBadEncoding() throws IOException {
+        System.out.println("testLoadWithBadEncoding");
         String s = "<?xml version=\"1.0\" encoding=\"BAD\"?>" +
                    "<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">" +
                    "<properties>" +
@@ -128,6 +139,7 @@
      * Test storeToXML with unsupported encoding
      */
     static void testStoreWithBadEncoding() throws IOException {
+        System.out.println("testStoreWithBadEncoding");
         Properties props = new Properties();
         props.put("foo", "bar");
         ByteArrayOutputStream out = new ByteArrayOutputStream();
@@ -137,6 +149,26 @@
         } catch (UnsupportedEncodingException expected) { }
     }
 
+    /**
+     * Test loadFromXML with malformed documents
+     */
+    static void testLoadWithMalformedDoc(Path dir) throws IOException {
+        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.xml")) {
+            for (Path file: stream) {
+                System.out.println("testLoadWithMalformedDoc, file=" + file.getFileName());
+                try (InputStream in = Files.newInputStream(file)) {
+                    Properties props = new Properties();
+                    try {
+                        props.loadFromXML(in);
+                        throw new RuntimeException("InvalidPropertiesFormatException not thrown");
+                    } catch (InvalidPropertiesFormatException x) {
+                        System.out.println(x);
+                    }
+                }
+            }
+        }
+    }
+
     public static void main(String[] args) throws IOException {
 
         testLoadAndStore("UTF-8");
@@ -145,6 +177,12 @@
         testLoadWithBadEncoding();
         testStoreWithBadEncoding();
 
+        // malformed documents
+        String src = System.getProperty("test.src");
+        String subdir = "invalidxml";
+        Path dir = (src == null) ? Paths.get(subdir) : Paths.get(src, subdir);
+        testLoadWithMalformedDoc(dir);
+
         // re-run sanity test with security manager
         Policy orig = Policy.getPolicy();
         Policy p = new SimplePolicy(new RuntimePermission("setSecurityManager"),
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/invalidxml/BadCase.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
+
+<!-- XML tags are case sensitve, opening and closing tags must use same case -->
+
+<properties>
+<entry key="foo">bar</entry>
+<entry key="gus">baz</entry>
+</PROPERTIES>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/invalidxml/BadDocType.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE namevaluepairs SYSTEM "http://java.sun.com/dtd/properties.dtd">
+
+<!-- The root element for a XML properties document is properties -->
+
+<properties>
+<entry key="foo">bar</entry>
+<entry key="gus">baz</entry>
+</properties>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/invalidxml/DTDRootNotMatch.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf8" standalone="no"?>
+<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
+
+<!-- XML tags are case sensitve, the root element should have been in lower case -->
+
+<Properties>
+<comment>comment</comment>
+<entry key="firstKey">value of the first key</entry>
+</Properties>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/invalidxml/IllegalComment.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf8" standalone="no"?>
+<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
+
+<!-- The dtd allows zero or one comment element -->
+
+<properties>
+<comment>comment1</comment>
+<comment>comment2</comment>
+<entry key="firstKey">value of the first key</entry>
+</properties>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/invalidxml/IllegalEntry.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf8" standalone="no"?>
+<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
+
+<!-- The dtd requires 'entry' element, 'Entry' is illegal -->
+
+<properties>
+<comment>comment</comment>
+<Entry key="firstKey">value of the first key</Entry>
+</properties>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/invalidxml/IllegalEntry1.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf8" standalone="no"?>
+<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
+
+<!-- 'entry1' is illegal as per the dtd -->
+
+<properties>
+<comment>comment1</comment>
+
+<entry key="firstkey">value of the first key</entry>
+<entry1 key="secondkey">value of the second key</entry1>
+</properties>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/invalidxml/IllegalKeyAttribute.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf8" standalone="no"?>
+<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
+
+<!-- 'key' attribute is expected. 'key1' is mistyped -->
+
+<properties>
+<comment>comment1</comment>
+<entry key1="typo">value of the first key</entry>
+</properties>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/invalidxml/NoClosingTag.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
+
+<!-- XML elements must having a closing tag -->
+
+<properties>
+<entry key="foo">bar</entry>
+<entry key="gus">baz</entry>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/invalidxml/NoDocType.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+
+<!-- An XML properties document has the DOCTYPE declaration with the properties root element -->
+
+<properties>
+<entry key="foo">bar</entry>
+<entry key="gus">baz</entry>
+</properties>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/invalidxml/NoNamespaceSupport.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf8" standalone="no"?>
+<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
+
+<!-- namespace is not supported -->
+
+<javautil:properties xmlns:javautil="http://java.sun.com/java/util/Properties">
+<javautil:comment>comment1</javautil:comment>
+
+<javautil:entry key="firstkey">value of the first key</javautil:entry>
+<javautil:entry key="secondkey">value of the second key</javautil:entry>
+</javautil:properties>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/invalidxml/NoRoot.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
+
+<!-- XML documents must have a root element -->
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/invalidxml/NotQuoted.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
+
+<!-- XML attribute values must be quoted -->
+
+<properties>
+<entry key=foo>bar</entry>
+<entry key=gus>baz</entry>
+</properties>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/Properties/invalidxml/README.txt	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,5 @@
+
+This directory contains test cases for the LoadAndStoreXML test case. Each file
+in this directory should be a malformed XML document that should cause the
+java.util.Properties loadFromXML method to throw InvalidPropertiesFormatException.
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/TimeZone/CLDRDisplayNamesTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8005471
+ * @run main/othervm -Djava.locale.providers=CLDR CLDRDisplayNamesTest
+ * @summary Make sure that localized time zone names of CLDR are used
+ * if specified.
+ */
+
+import java.util.*;
+import static java.util.TimeZone.*;
+
+public class CLDRDisplayNamesTest {
+    /*
+     * The first element is a language tag. The rest are localized
+     * display names of America/Los_Angeles copied from the CLDR
+     * resources data. If data change in CLDR, test data below will
+     * need to be changed accordingly.
+     *
+     * Generic names are NOT tested (until they are supported by API).
+     */
+    static final String[][] CLDR_DATA = {
+        {
+            "ja-JP",
+            "\u30a2\u30e1\u30ea\u30ab\u592a\u5e73\u6d0b\u6a19\u6e96\u6642",
+            "PST",
+            "\u30a2\u30e1\u30ea\u30ab\u592a\u5e73\u6d0b\u590f\u6642\u9593",
+            "PDT",
+            //"\u30a2\u30e1\u30ea\u30ab\u592a\u5e73\u6d0b\u6642\u9593",
+            //"PT"
+        },
+        {
+            "zh-CN",
+            "\u592a\u5e73\u6d0b\u6807\u51c6\u65f6\u95f4",
+            "PST",
+            "\u592a\u5e73\u6d0b\u590f\u4ee4\u65f6\u95f4",
+            "PDT",
+            //"\u7f8e\u56fd\u592a\u5e73\u6d0b\u65f6\u95f4",
+            //"PT"
+        },
+        {
+            "de-DE",
+            "Nordamerikanische Westk\u00fcsten-Winterzeit",
+            "PST",
+            "Nordamerikanische Westk\u00fcsten-Sommerzeit",
+            "PDT",
+            //"Nordamerikanische Westk\u00fcstenzeit",
+            //"PT"
+        },
+    };
+
+    public static void main(String[] args) {
+        TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
+        int errors = 0;
+        for (String[] data : CLDR_DATA) {
+            Locale locale = Locale.forLanguageTag(data[0]);
+            for (int i = 1; i < data.length; i++) {
+                int style = ((i % 2) == 1) ? LONG : SHORT;
+                boolean daylight = (i == 3 || i == 4);
+                String name = tz.getDisplayName(daylight, style, locale);
+                if (!data[i].equals(name)) {
+                    System.err.printf("error: got '%s' expected '%s' (style=%d, daylight=%s, locale=%s)%n",
+                                      name, data[i], style, daylight, locale);
+                    errors++;
+                }
+            }
+        }
+        if (errors > 0) {
+            throw new RuntimeException("test failed");
+        }
+    }
+}
--- a/jdk/test/java/util/concurrent/FutureTask/DoneTimedGetLoops.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/concurrent/FutureTask/DoneTimedGetLoops.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/util/logging/LoggerResourceBundleRace.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/logging/LoggerResourceBundleRace.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/util/logging/LoggingDeadlock2.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/logging/LoggingDeadlock2.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/util/logging/LoggingDeadlock3.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/logging/LoggingDeadlock3.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/util/logging/LoggingDeadlock4.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/logging/LoggingDeadlock4.java	Tue Jan 22 11:54:16 2013 -0800
@@ -23,11 +23,11 @@
 
 /*
  * @test
- * @bug     6977677
+ * @bug     6977677 8004928
  * @summary Deadlock between LogManager.<clinit> and Logger.getLogger()
  * @author  Daniel D. Daugherty
- * @build LoggingDeadlock4
- * @run main/othervm/timeout=15 -Djava.awt.headless=true LoggingDeadlock4
+ * @compile -XDignore.symbol.file LoggingDeadlock4.java
+ * @run main/othervm/timeout=15 LoggingDeadlock4
  */
 
 import java.util.concurrent.CountDownLatch;
@@ -39,21 +39,16 @@
     private static CountDownLatch lmIsRunning  = new CountDownLatch(1);
     private static CountDownLatch logIsRunning = new CountDownLatch(1);
 
+    // Create a sun.util.logging.PlatformLogger$JavaLogger object
+    // that has to be redirected when the LogManager class
+    // is initialized. This can cause a deadlock between
+    // LogManager.<clinit> and Logger.getLogger().
+    private static final sun.util.logging.PlatformLogger log =
+        sun.util.logging.PlatformLogger.getLogger("java.util.logging");
+
     public static void main(String[] args) {
         System.out.println("main: LoggingDeadlock4 is starting.");
 
-        // Loading the java.awt.Container class will create a
-        // sun.util.logging.PlatformLogger$JavaLogger object
-        // that has to be redirected when the LogManager class
-        // is initialized. This can cause a deadlock between
-        // LogManager.<clinit> and Logger.getLogger().
-        try {
-            Class.forName("java.awt.Container");
-        } catch (ClassNotFoundException cnfe) {
-            throw new RuntimeException("Test failed: could not load"
-                + " java.awt.Container." + cnfe);
-        }
-
         Thread lmThread = new Thread("LogManagerThread") {
             public void run() {
                 // let main know LogManagerThread is running
--- a/jdk/test/java/util/logging/SimpleFormatterFormat.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/logging/SimpleFormatterFormat.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/java/util/prefs/PrefsSpi.sh	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/prefs/PrefsSpi.sh	Tue Jan 22 11:54:16 2013 -0800
@@ -87,17 +87,17 @@
 
 case "`uname`" in Windows*|CYGWIN* ) CPS=';';; *) CPS=':';; esac
 
-Sys "$java" "${TESTVMOPTS}" "-cp" "$TESTCLASSES${CPS}extDir/PrefsSpi.jar" \
+Sys "$java" ${TESTVMOPTS} "-cp" "$TESTCLASSES${CPS}extDir/PrefsSpi.jar" \
     -Djava.util.prefs.PreferencesFactory=StubPreferencesFactory \
     -Djava.util.prefs.userRoot=. \
     PrefsSpi "StubPreferences"
-Sys "$java" "${TESTVMOPTS}" "-cp" "$TESTCLASSES" \
+Sys "$java" ${TESTVMOPTS} "-cp" "$TESTCLASSES" \
     -Djava.util.prefs.userRoot=. \
     PrefsSpi "java.util.prefs.*"
-Sys "$java" "${TESTVMOPTS}" "-cp" "$TESTCLASSES${CPS}extDir/PrefsSpi.jar" \
+Sys "$java" ${TESTVMOPTS} "-cp" "$TESTCLASSES${CPS}extDir/PrefsSpi.jar" \
     -Djava.util.prefs.userRoot=. \
     PrefsSpi "StubPreferences"
-Sys "$java" "${TESTVMOPTS}" "-cp" "$TESTCLASSES" "-Djava.ext.dirs=extDir" \
+Sys "$java" ${TESTVMOPTS} "-cp" "$TESTCLASSES" "-Djava.ext.dirs=extDir" \
     -Djava.util.prefs.userRoot=. \
     PrefsSpi "StubPreferences"
 
--- a/jdk/test/java/util/spi/ResourceBundleControlProvider/providersrc/XmlRB.xml	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/spi/ResourceBundleControlProvider/providersrc/XmlRB.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -5,13 +5,13 @@
  
  This code is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License version 2 only, as
- published by the Free Software Foundation. Oracle designates this
- particular file as subject to the Classpath exception as provided
+ published by the Free Software Foundation.  Oracle designates this
+ particular file as subject to the "Classpath" exception as provided
  by Oracle in the LICENSE file that accompanied this code.
  
  This code is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ 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).
  
--- a/jdk/test/java/util/spi/ResourceBundleControlProvider/providersrc/XmlRB_ja.xml	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/java/util/spi/ResourceBundleControlProvider/providersrc/XmlRB_ja.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -5,13 +5,13 @@
  
  This code is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License version 2 only, as
- published by the Free Software Foundation. Oracle designates this
- particular file as subject to the Classpath exception as provided
+ published by the Free Software Foundation.  Oracle designates this
+ particular file as subject to the "Classpath" exception as provided
  by Oracle in the LICENSE file that accompanied this code.
  
  This code is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ 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).
  
--- a/jdk/test/javax/crypto/Cipher/GCMAPI.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/crypto/Cipher/GCMAPI.java	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -78,6 +78,8 @@
             c.updateAAD(src);
         } catch (UnsupportedOperationException e) {
             // swallow
+        } catch (IllegalStateException ise) {
+            // swallow
         }catch (Exception e) {
             e.printStackTrace();
             failed++;
@@ -99,6 +101,8 @@
             c.updateAAD(src, offset, len);
         } catch (UnsupportedOperationException e) {
             // swallow
+        } catch (IllegalStateException ise) {
+            // swallow
         } catch (Exception e) {
             e.printStackTrace();
             failed++;
@@ -120,6 +124,8 @@
             c.updateAAD(src);
         } catch (UnsupportedOperationException e) {
             // swallow
+        } catch (IllegalStateException ise) {
+            // swallow
         }catch (Exception e) {
             e.printStackTrace();
             failed++;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/management/MBeanInfo/SerializationTest1.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 6783290
+ * @summary Test correct reading of an empty Descriptor.
+ * @author Jaroslav Bachorik
+ * @run clean SerializationTest1
+ * @run build SerializationTest1
+ * @run main SerializationTest1
+ */
+
+import java.io.*;
+import javax.management.*;
+
+public class SerializationTest1 {
+    public static void main(String[] args) throws Exception {
+        MBeanInfo mi1 = new MBeanInfo("",
+                                      "",
+                                      new MBeanAttributeInfo[]{},
+                                      new MBeanConstructorInfo[]{},
+                                      new MBeanOperationInfo[]{},
+                                      new MBeanNotificationInfo[]{},
+                                      ImmutableDescriptor.EMPTY_DESCRIPTOR);
+
+        test(mi1);
+
+        MBeanFeatureInfo mfi2 = new MBeanFeatureInfo("",
+                                                     "",
+                                                     ImmutableDescriptor.EMPTY_DESCRIPTOR);
+
+        test(mfi2);
+    }
+
+    public static void test(Object obj) throws Exception {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        ObjectOutputStream oos = new ObjectOutputStream(baos);
+        oos.writeObject(obj);
+
+        final boolean[] failed = new boolean[]{false};
+        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+        final ObjectInputStream ois = new ObjectInputStream(bais) {
+            protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
+                System.out.println("*** " + desc.getName());
+                if (desc.getName().equals("[Ljava.lang.Object;")) { // javax.management.Descriptor fields
+                    Thread.dumpStack();
+                    for(StackTraceElement e : Thread.currentThread().getStackTrace()) { // checking for the deserialization location
+                        if (e.getMethodName().equals("skipCustomData")) { // indicates the presence of unread values from the custom object serialization
+                            failed[0] = true;
+                        }
+                    }
+                }
+                return super.resolveClass(desc); //To change body of generated methods, choose Tools | Templates.
+            }
+        };
+        Object newObj = ois.readObject();
+
+        if (failed[0]) {
+            throw new RuntimeException("Zero-length descriptor not read back");
+        }
+    }
+}
--- a/jdk/test/javax/management/remote/mandatory/connection/AddressableTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/management/remote/mandatory/connection/AddressableTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -45,19 +45,36 @@
 
     private static final MBeanServer mbs = MBeanServerFactory.createMBeanServer();
 
+    private static boolean isProtocolSupported(String protocol) {
+        if (protocol.equals("rmi"))
+            return true;
+        if (protocol.equals("iiop")) {
+            try {
+                Class.forName("javax.management.remote.rmi._RMIConnectionImpl_Tie");
+                return true;
+            } catch (ClassNotFoundException x) { }
+        }
+        return false;
+    }
+
     public static void main(String[] args) throws Exception {
         System.out.println(">>> test the new interface Addressable.");
         boolean ok = true;
 
         for (int i = 0; i < protocols.length; i++) {
-            try {
-                test(protocols[i], prefixes[i]);
-
-                System.out.println(">>> Test successed for "+protocols[i]);
-            } catch (Exception e) {
-                System.out.println(">>> Test failed for "+protocols[i]);
-                e.printStackTrace(System.out);
-                ok = false;
+            String protocol = protocols[i];
+            if (isProtocolSupported(protocol)) {
+                try {
+                    test(protocol, prefixes[i]);
+                    System.out.println(">>> Test successed for "+protocols[i]);
+                } catch (Exception e) {
+                    System.out.println(">>> Test failed for "+protocols[i]);
+                    e.printStackTrace(System.out);
+                    ok = false;
+                }
+            } else {
+                System.out.format(">>> Test skipped for %s, protocol not supported%n",
+                    protocol);
             }
         }
 
@@ -65,7 +82,7 @@
             System.out.println(">>> All Test passed.");
         } else {
             System.out.println(">>> Some TESTs FAILED");
-            System.exit(1);
+            throw new RuntimeException("See log for details");
         }
     }
 
--- a/jdk/test/javax/management/remote/mandatory/connection/CloseableTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/management/remote/mandatory/connection/CloseableTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -42,7 +42,6 @@
 import javax.management.remote.rmi.RMIIIOPServerImpl;
 import javax.management.remote.rmi.RMIJRMPServerImpl;
 import javax.management.remote.rmi.RMIServerImpl;
-import org.omg.stub.javax.management.remote.rmi._RMIConnection_Stub;
 
 public class CloseableTest {
     private static final Class closeArray[] = {
@@ -51,26 +50,43 @@
         RMIConnection.class,
         RMIConnectionImpl.class,
         RMIConnectionImpl_Stub.class,
-        _RMIConnection_Stub.class,
         RMIServerImpl.class,
         RMIIIOPServerImpl.class,
         RMIJRMPServerImpl.class
     };
+
+    static int error;
+
+    static void test(Class<?> c) {
+        System.out.println("\nTest " + c);
+        if (Closeable.class.isAssignableFrom(c)) {
+            System.out.println("Test passed!");
+        } else {
+            error++;
+            System.out.println("Test failed!");
+        }
+    }
+
+    static void test(String cn) {
+        try {
+            test(Class.forName(cn));
+        } catch (ClassNotFoundException ignore) {
+            System.out.println("\n" + cn + " not tested.");
+        }
+    }
+
     public static void main(String[] args) throws Exception {
         System.out.println("Test that all the JMX Remote API classes that " +
                            "define\nthe method \"void close() throws " +
                            "IOException;\" extend\nor implement the " +
                            "java.io.Closeable interface.");
-        int error = 0;
-        for (Class c : closeArray) {
-            System.out.println("\nTest " + c);
-            if (Closeable.class.isAssignableFrom(c)) {
-                System.out.println("Test passed!");
-            } else {
-                error++;
-                System.out.println("Test failed!");
-            }
+        for (Class<?> c : closeArray) {
+            test(c);
         }
+
+        // Stub classes not present if RMI-IIOP not supported
+        test("org.omg.stub.javax.management.remote.rmi._RMIConnection_Stub");
+
         if (error > 0) {
             final String msg = "\nTest FAILED! Got " + error + " error(s)";
             System.out.println(msg);
--- a/jdk/test/javax/management/remote/mandatory/connection/ConnectionListenerNullTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/management/remote/mandatory/connection/ConnectionListenerNullTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -39,33 +39,22 @@
 import java.util.Map;
 public class ConnectionListenerNullTest {
 
-    static final boolean optionalFlag;
-    static {
-        Class genericClass = null;
+    static boolean isPresent(String cn) {
         try {
-            genericClass =
-            Class.forName("javax.management.remote.generic.GenericConnector");
+            Class.forName(cn);
+            return true;
         } catch (ClassNotFoundException x) {
-            // NO optional package
+            return false;
         }
-        optionalFlag = (genericClass != null);
     }
 
-    final static String[] mandatoryList = {
-        "service:jmx:rmi://", "service:jmx:iiop://"
-    };
-
-    final static String[] optionalList = {
-        "service:jmx:jmxmp://"
-    };
-
-    public static int test(String[] urls) {
+    public static int test(String... urls) {
         int errCount = 0;
         for (int i=0;i<urls.length;i++) {
             try {
                 final JMXServiceURL url = new JMXServiceURL(urls[i]);
                 final JMXConnector c =
-                    JMXConnectorFactory.newJMXConnector(url,(Map)null);
+                    JMXConnectorFactory.newJMXConnector(url,(Map<String,String>)null);
                 final NotificationListener nl = null;
                 final NotificationFilter   nf = null;
                 final Object               h  = null;
@@ -121,12 +110,19 @@
 
     public static void main(String args[]) {
         int errCount = 0;
-        errCount += test(mandatoryList);
-        if (optionalFlag) errCount += test(optionalList);
+
+        // mandatory
+        errCount += test("service:jmx:rmi://");
+
+        // optional
+        if (isPresent("javax.management.remote.rmi._RMIConnectionImpl_Tie"))
+            errCount += test("service:jmx:iiop://");
+        if (isPresent("javax.management.remote.generic.GenericConnector"))
+            errCount += test("service:jmx:jmxmp://");
+
         if (errCount > 0) {
-            System.err.println("ConnectionListenerNullTest failed: " +
-                               errCount + " error(s) reported.");
-            System.exit(1);
+            throw new RuntimeException("ConnectionListenerNullTest failed: " +
+                errCount + " error(s) reported.");
         }
         System.out.println("ConnectionListenerNullTest passed.");
     }
--- a/jdk/test/javax/management/remote/mandatory/connection/IIOPURLTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/management/remote/mandatory/connection/IIOPURLTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -49,17 +49,24 @@
     public static void main(String[] args) throws Exception {
         JMXServiceURL inputAddr =
             new JMXServiceURL("service:jmx:iiop://");
-        JMXConnectorServer s =
-            JMXConnectorServerFactory.newJMXConnectorServer(inputAddr, null,
-                                                            null);
+        JMXConnectorServer s;
+        try {
+            s = JMXConnectorServerFactory.newJMXConnectorServer(inputAddr, null, null);
+        } catch (java.net.MalformedURLException x) {
+            try {
+                Class.forName("javax.management.remote.rmi._RMIConnectionImpl_Tie");
+                throw new RuntimeException("MalformedURLException thrown but iiop appears to be supported");
+            } catch (ClassNotFoundException expected) { }
+            System.out.println("IIOP protocol not supported, test skipped");
+            return;
+        }
         MBeanServer mbs = MBeanServerFactory.createMBeanServer();
         mbs.registerMBean(s, new ObjectName("a:b=c"));
         s.start();
         JMXServiceURL outputAddr = s.getAddress();
         if (!outputAddr.getURLPath().startsWith("/ior/IOR:")) {
-            System.out.println("URL path should start with \"/ior/IOR:\": " +
-                               outputAddr);
-            System.exit(1);
+            throw new RuntimeException("URL path should start with \"/ior/IOR:\": " +
+                                       outputAddr);
         }
         System.out.println("IIOP URL path looks OK: " + outputAddr);
         JMXConnector c = JMXConnectorFactory.connect(outputAddr);
--- a/jdk/test/javax/management/remote/mandatory/connection/IdleTimeoutTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/management/remote/mandatory/connection/IdleTimeoutTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -52,21 +52,27 @@
 import com.sun.jmx.remote.util.EnvHelp;
 
 public class IdleTimeoutTest {
+
+    static boolean isPresent(String cn) {
+        try {
+            Class.forName(cn);
+            return true;
+        } catch (ClassNotFoundException x) {
+            return false;
+        }
+    }
+
     public static void main(String[] args) throws Exception {
         boolean ok = true;
         List protos;
         if (args.length > 0)
             protos = Arrays.asList(args);
         else {
-            protos =
-                new ArrayList(Arrays.asList(new String[] {"rmi", "iiop"}));
-            try {
-                Class.forName("javax.management.remote.jmxmp." +
-                              "JMXMPConnectorServer");
+            protos = new ArrayList(Arrays.asList(new String[] {"rmi"}));
+            if (isPresent("javax.management.remote.rmi._RMIConnectionImpl_Tie"))
+                protos.add("iiop");
+            if (isPresent("javax.management.remote.jmxmp.JMXMPConnectorServer"))
                 protos.add("jmxmp");
-            } catch (ClassNotFoundException e) {
-                // OK: Optional JMXMP support is not present
-            }
         }
         for (Iterator it = protos.iterator(); it.hasNext(); ) {
             String proto = (String) it.next();
@@ -81,13 +87,13 @@
             }
         }
         if (!ok) {
-            System.out.println("SOME TESTS FAILED");
-            System.exit(1);
+            throw new RuntimeException("Some tests failed - see log for details");
         }
     }
 
     private static long getIdleTimeout(MBeanServer mbs, JMXServiceURL url)
-        throws Exception {
+        throws Exception
+    {
         JMXConnectorServer server =
             JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
         server.start();
--- a/jdk/test/javax/management/remote/mandatory/connection/MultiThreadDeadLockTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/management/remote/mandatory/connection/MultiThreadDeadLockTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -253,4 +253,3 @@
         System.out.println("===Leave the method: " + m);
     }
 }
-
--- a/jdk/test/javax/management/remote/mandatory/connectorServer/SetMBeanServerForwarder.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/management/remote/mandatory/connectorServer/SetMBeanServerForwarder.java	Tue Jan 22 11:54:16 2013 -0800
@@ -40,27 +40,16 @@
 
 public class SetMBeanServerForwarder {
 
-    static final boolean optionalFlag;
-    static {
-        Class genericClass = null;
+    static boolean isPresent(String cn) {
         try {
-            genericClass =
-            Class.forName("javax.management.remote.generic.GenericConnector");
+            Class.forName(cn);
+            return true;
         } catch (ClassNotFoundException x) {
-            // NO optional package
+            return false;
         }
-        optionalFlag = (genericClass != null);
     }
 
-    final static String[] mandatoryList = {
-        "service:jmx:rmi://", "service:jmx:iiop://"
-    };
-
-    final static String[] optionalList = {
-        "service:jmx:jmxmp://"
-    };
-
-    public static int test(String[] urls) {
+    public static int test(String... urls) {
         int errorCount = 0;
         for (int i=0;i<urls.length;i++) {
             try {
@@ -241,12 +230,19 @@
 
     public static void main(String args[]) {
         int errCount = 0;
-        errCount += test(mandatoryList);
-        if (optionalFlag) errCount += test(optionalList);
+
+        // mandatory
+        errCount += test("service:jmx:rmi://");
+
+        // optional
+        if (isPresent("javax.management.remote.rmi._RMIConnectionImpl_Tie"))
+            errCount += test("service:jmx:iiop://");
+        if (isPresent("javax.management.remote.generic.GenericConnector"))
+            errCount += test("service:jmx:jmxmp://");
+
         if (errCount > 0) {
-            System.err.println("SetMBeanServerForwarder failed: " +
-                               errCount + " error(s) reported.");
-            System.exit(1);
+            throw new RuntimeException("SetMBeanServerForwarder failed: " +
+                                       errCount + " error(s) reported.");
         }
         System.out.println("SetMBeanServerForwarder passed.");
     }
--- a/jdk/test/javax/management/remote/mandatory/loading/MissingClassTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/management/remote/mandatory/loading/MissingClassTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -70,7 +70,6 @@
 import javax.management.remote.JMXConnectorServerFactory;
 import javax.management.remote.JMXServiceURL;
 import javax.management.remote.rmi.RMIConnectorServer;
-import org.omg.CORBA.MARSHAL;
 
 public class MissingClassTest {
     private static final int NNOTIFS = 50;
@@ -84,6 +83,15 @@
 
     private static final Object unserializableObject = Thread.currentThread();
 
+    private static boolean isInstance(Object o, String cn) {
+        try {
+            Class<?> c = Class.forName(cn);
+            return c.isInstance(o);
+        } catch (ClassNotFoundException x) {
+            return false;
+        }
+    }
+
     public static void main(String[] args) throws Exception {
         System.out.println("Test that the client or server end of a " +
                            "connection does not fail if sent an object " +
@@ -118,8 +126,7 @@
         if (ok)
             System.out.println("Test passed");
         else {
-            System.out.println("TEST FAILED");
-            System.exit(1);
+            throw new RuntimeException("TEST FAILED");
         }
     }
 
@@ -133,7 +140,7 @@
 
         JMXConnectorServer cs;
         JMXServiceURL url = new JMXServiceURL(proto, null, 0);
-        Map serverMap = new HashMap();
+        Map<String,Object> serverMap = new HashMap<>();
         serverMap.put(JMXConnectorServerFactory.DEFAULT_CLASS_LOADER,
                       serverLoader);
 
@@ -151,7 +158,7 @@
         }
         cs.start();
         JMXServiceURL addr = cs.getAddress();
-        Map clientMap = new HashMap();
+        Map<String,Object> clientMap = new HashMap<>();
         clientMap.put(JMXConnectorFactory.DEFAULT_CLASS_LOADER,
                       clientLoader);
 
@@ -174,7 +181,7 @@
             ok = false;
         } catch (IOException e) {
             Throwable cause = e.getCause();
-            if (cause instanceof MARSHAL)  // see CR 4935098
+            if (isInstance(cause, "org.omg.CORBA.MARSHAL"))  // see CR 4935098
                 cause = cause.getCause();
             if (cause instanceof ClassNotFoundException) {
                 System.out.println("Success: got an IOException wrapping " +
@@ -188,7 +195,7 @@
         }
 
         System.out.println("Doing queryNames to ensure connection alive");
-        Set names = mbsc.queryNames(null, null);
+        Set<ObjectName> names = mbsc.queryNames(null, null);
         System.out.println("queryNames returned " + names);
 
         System.out.println("Provoke exception of unknown class");
@@ -198,7 +205,7 @@
             ok = false;
         } catch (IOException e) {
             Throwable wrapped = e.getCause();
-            if (wrapped instanceof MARSHAL)  // see CR 4935098
+            if (isInstance(wrapped, "org.omg.CORBA.MARSHAL"))  // see CR 4935098
                 wrapped = wrapped.getCause();
             if (wrapped instanceof ClassNotFoundException) {
                 System.out.println("Success: got an IOException wrapping " +
@@ -251,7 +258,7 @@
                 ok = false;
             } catch (IOException e) {
                 Throwable cause = e.getCause();
-                if (cause instanceof MARSHAL)  // see CR 4935098
+                if (isInstance(cause, "org.omg.CORBA.MARSHAL"))  // see CR 4935098
                     cause = cause.getCause();
                 if (cause instanceof ClassNotFoundException) {
                     System.out.println("Success: got an IOException " +
@@ -584,15 +591,13 @@
             try {
                 new ObjectOutputStream(new ByteArrayOutputStream())
                     .writeObject(tricky);
-                System.out.println("TEST INCORRECT: tricky notif is " +
-                                   "serializable");
-                System.exit(1);
+                throw new RuntimeException("TEST INCORRECT: tricky notif is " +
+                                           "serializable");
             } catch (NotSerializableException e) {
                 // OK: tricky notif is not serializable
             } catch (IOException e) {
-                System.out.println("TEST INCORRECT: tricky notif " +
-                                   "serialization check failed");
-                System.exit(1);
+                throw new RuntimeException("TEST INCORRECT: tricky notif " +
+                                            "serialization check failed");
             }
 
             /* Now shuffle an imaginary deck of cards where K, U, T, and
@@ -629,12 +634,11 @@
             }
             if (knownCount != 0 || unknownCount != 0
                 || trickyCount != 0 || boringCount != 0) {
-                System.out.println("TEST INCORRECT: Shuffle failed: " +
+                throw new RuntimeException("TEST INCORRECT: Shuffle failed: " +
                                    "known=" + knownCount +" unknown=" +
                                    unknownCount + " tricky=" + trickyCount +
                                    " boring=" + boringCount +
                                    " deal=" + notifList);
-                System.exit(1);
             }
             String notifs = notifList.toString();
             System.out.println("Shuffle: " + notifs);
@@ -646,10 +650,8 @@
                 case 't': n = tricky; break;
                 case 'b': n = boring; break;
                 default:
-                    System.out.println("TEST INCORRECT: Bad shuffle char: " +
-                                       notifs.charAt(i));
-                    System.exit(1);
-                    throw new Error();
+                    throw new RuntimeException("TEST INCORRECT: Bad shuffle char: " +
+                                               notifs.charAt(i));
                 }
                 sendNotification(n);
             }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/management/remote/mandatory/notif/ConcurrentModificationTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 7120365
+ * @summary test on Concurrent Modification
+ * @author Shanliang JIANG
+ * @run main ConcurrentModificationTest
+ */
+
+import java.net.MalformedURLException;
+import java.util.ConcurrentModificationException;
+import javax.management.MBeanServer;
+import javax.management.MBeanServerConnection;
+import javax.management.MBeanServerFactory;
+import javax.management.Notification;
+import javax.management.NotificationListener;
+import javax.management.ObjectName;
+import javax.management.remote.JMXConnector;
+import javax.management.remote.JMXConnectorFactory;
+import javax.management.remote.JMXConnectorServer;
+import javax.management.remote.JMXConnectorServerFactory;
+import javax.management.remote.JMXServiceURL;
+
+/**
+ *
+ */
+public class ConcurrentModificationTest {
+    private static final String[] protocols = {"rmi", "iiop", "jmxmp"};
+    private static int number = 100;
+
+    private static final MBeanServer mbs = MBeanServerFactory.createMBeanServer();
+    private static ObjectName delegateName;
+    private static ObjectName[] timerNames = new ObjectName[number];
+    private static NotificationListener[] listeners = new NotificationListener[number];
+
+    private static Throwable uncaughtException = null;
+
+    public static void main(String[] args) throws Exception {
+        System.out.println(">>> test on Concurrent Modification.");
+
+        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
+            @Override
+            public void uncaughtException(Thread t, Throwable e) {
+                e.printStackTrace();
+                if (e instanceof ConcurrentModificationException) {
+                    uncaughtException = e;
+                }
+            }
+        });
+
+        delegateName = new ObjectName("JMImplementation:type=MBeanServerDelegate");
+        for (int i=0; i<number; i++) {
+            timerNames[i] = new ObjectName("MBean:name=Timer"+i);
+            listeners[i] = new NotificationListener() {
+                @Override
+                public void handleNotification(Notification notification, Object handback) {
+                    // nothing
+                }
+            };
+        }
+        String errors = "";
+
+        for (int i = 0; i < protocols.length; i++) {
+            uncaughtException = null;
+            System.out.println(">>> Test for protocol " + protocols[i]);
+            test(protocols[i]);
+            if (uncaughtException != null) {
+                if ("".equals(errors)) {
+                    errors = "Failed to " + protocols[i] + ": "+uncaughtException;
+                } else {
+                    errors = errors+", failed to " + protocols[i] + ": "+uncaughtException;
+                }
+                System.out.println(">>> FAILED for protocol " + protocols[i]);
+            } else {
+                System.out.println(">>> PASSED for protocol " + protocols[i]);
+            }
+        }
+
+        if ("".equals(errors)) {
+            System.out.println("All Passed!");
+        } else {
+            System.out.println("!!!!!! Failed.");
+
+            throw new RuntimeException(errors);
+        }
+    }
+
+    private static void test(String proto) throws Exception {
+        JMXServiceURL u = new JMXServiceURL(proto, null, 0);
+        JMXConnectorServer server;
+        JMXConnector client;
+
+        try {
+            server =
+                    JMXConnectorServerFactory.newJMXConnectorServer(u, null, mbs);
+            server.start();
+            JMXServiceURL addr = server.getAddress();
+            client = JMXConnectorFactory.connect(addr, null);
+        } catch (MalformedURLException e) {
+            System.out.println(">>> not support: " + proto);
+            return;
+        }
+
+        final MBeanServerConnection mserver = client.getMBeanServerConnection();
+
+        int count = 0;
+        boolean adding = true;
+        while (uncaughtException == null && count++ < 10) {
+            for (int i = 0; i < number; i++) {
+                listenerOp(mserver, listeners[i], adding);
+                mbeanOp(mserver, timerNames[i], adding);
+            }
+            adding = !adding;
+        }
+
+        if (uncaughtException != null) { // clean
+            for (int i = 0; i < number; i++) {
+                try {
+                    mbeanOp(mserver, timerNames[i], false);
+                } catch (Exception e) {
+                }
+            }
+        }
+        client.close();
+        server.stop();
+    }
+
+    private static void mbeanOp(MBeanServerConnection mserver, ObjectName name, boolean adding)
+            throws Exception {
+        if (adding) {
+            mserver.createMBean("javax.management.timer.Timer", name);
+        } else {
+            mserver.unregisterMBean(name);
+        }
+    }
+
+    private static void listenerOp(MBeanServerConnection mserver, NotificationListener listener, boolean adding)
+            throws Exception {
+        if (adding) {
+            mserver.addNotificationListener(delegateName, listener, null, null);
+        } else {
+            mserver.removeNotificationListener(delegateName, listener);
+        }
+    }
+}
\ No newline at end of file
--- a/jdk/test/javax/management/remote/mandatory/provider/ProviderTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/management/remote/mandatory/provider/ProviderTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -49,13 +49,13 @@
 import provider.JMXConnectorProviderImpl;
 import provider.JMXConnectorServerProviderImpl;
 public class ProviderTest {
+
     public static void main(String[] args) throws Exception {
         System.out.println("Starting ProviderTest");
         MBeanServer mbs = MBeanServerFactory.newMBeanServer();
-        //First do the test with a protocol handled by Service providers
-        JMXServiceURL url =
-            new JMXServiceURL("service:jmx:rmi://");
 
+        // First do the test with a protocol handled by Service providers
+        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
         dotest(url, mbs);
 
         boolean clientCalled = provider.JMXConnectorProviderImpl.called();
@@ -66,16 +66,22 @@
                 System.out.println("Client provider not called");
             if (!serverCalled)
                 System.out.println("Server provider not called");
-            System.out.println("Test Failed");
-            System.exit(1);
+            throw new RuntimeException("Test failed - see log for details");
         }
 
-        //The Service Provider doesn't handle IIOP. Default providers MUST
-        //be called.
-        url =
-            new JMXServiceURL("service:jmx:iiop://");
-
-        dotest(url, mbs);
+        // The Service Provider doesn't handle IIOP. Default providers MUST
+        // be called, which may or may not support IIOP.
+        url = new JMXServiceURL("service:jmx:iiop://");
+        try {
+            dotest(url, mbs);
+        } catch (MalformedURLException e) {
+            try {
+                Class.forName("javax.management.remote.rmi._RMIConnectionImpl_Tie");
+                e.printStackTrace(System.out);
+                throw new RuntimeException("MalformedURLException throw but IIOP appears to be supported");
+            } catch (ClassNotFoundException expected) { }
+            System.out.println("MalformedURLException thrown, IIOP transport not supported");
+        }
 
         // Unsupported protocol.
         JMXConnectorServer server = null;
@@ -87,31 +93,19 @@
                 JMXConnectorServerFactory.newJMXConnectorServer(url,
                                                                 null,
                                                                 mbs);
-            System.out.println("Exception not thrown.");
-            System.exit(1);
-        }catch(MalformedURLException e) {
+            throw new RuntimeException("Exception not thrown.");
+        } catch (MalformedURLException e) {
             System.out.println("Expected MalformedURLException thrown.");
         }
-        catch(Exception e) {
-            e.printStackTrace();
-            System.out.println("Exception thrown : " + e);
-            System.exit(1);
-        }
 
         try {
             client =
                 JMXConnectorFactory.newJMXConnector(url,
                                                     null);
-            System.out.println("Exception not thrown.");
-            System.exit(1);
-        }catch(MalformedURLException e) {
+            throw new RuntimeException("Exception not thrown.");
+        } catch (MalformedURLException e) {
             System.out.println("Expected MalformedURLException thrown.");
         }
-        catch(Exception e) {
-            e.printStackTrace();
-            System.out.println("Exception thrown : " + e);
-            System.exit(1);
-        }
 
         //JMXConnectorProviderException
         url =
@@ -121,60 +115,34 @@
                 JMXConnectorServerFactory.newJMXConnectorServer(url,
                                                                 null,
                                                                 mbs);
-            System.out.println("Exception not thrown.");
-            System.exit(1);
-        }catch(JMXProviderException e) {
+            throw new RuntimeException("Exception not thrown.");
+        } catch(JMXProviderException e) {
             System.out.println("Expected JMXProviderException thrown.");
         }
-        catch(Exception e) {
-            e.printStackTrace();
-            System.out.println("Exception thrown : " + e);
-            System.exit(1);
-        }
 
         try {
             client =
                 JMXConnectorFactory.newJMXConnector(url,
                                                     null);
-            System.out.println("Exception not thrown.");
-            System.exit(1);
+            throw new RuntimeException("Exception not thrown.");
         }catch(JMXProviderException e) {
             System.out.println("Expected JMXProviderException thrown.");
         }
-        catch(Exception e) {
-            e.printStackTrace();
-            System.out.println("Exception thrown : " + e);
-            System.exit(1);
-        }
 
         System.out.println("Test OK");
-        return;
     }
 
     private static void dotest(JMXServiceURL url, MBeanServer mbs)
         throws Exception {
         JMXConnectorServer server = null;
         JMXConnector client = null;
-        try {
-            server =
-                JMXConnectorServerFactory.newJMXConnectorServer(url,
-                                                                null,
-                                                                mbs);
-        }catch(IllegalArgumentException e) {
-            e.printStackTrace();
-            System.exit(1);
-        }
+
+        server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
         server.start();
         JMXServiceURL outputAddr = server.getAddress();
         System.out.println("Server started ["+ outputAddr+ "]");
 
-        try {
-            client =
-                JMXConnectorFactory.newJMXConnector(outputAddr, null);
-        }catch(IllegalArgumentException e) {
-            e.printStackTrace();
-            System.exit(1);
-        }
+        client = JMXConnectorFactory.newJMXConnector(outputAddr, null);
 
         client.connect();
         System.out.println("Client connected");
--- a/jdk/test/javax/management/remote/mandatory/serverError/JMXServerErrorTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/management/remote/mandatory/serverError/JMXServerErrorTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -120,7 +120,7 @@
         try {
             cs=JMXConnectorServerFactory.newJMXConnectorServer(jurl,null,kbs);
         } catch (MalformedURLException m) {
-            if ("jmxmp".equals(jurl.getProtocol())) {
+            if ("jmxmp".equals(jurl.getProtocol()) || "iiop".equals(jurl.getProtocol())) {
                 // OK, we may not have this in the classpath...
                 System.out.println("WARNING: Skipping protocol: " + jurl);
                 return;
--- a/jdk/test/javax/swing/AncestorNotifier/7193219/bug7193219.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/swing/AncestorNotifier/7193219/bug7193219.java	Tue Jan 22 11:54:16 2013 -0800
@@ -30,6 +30,7 @@
 import java.io.*;
 
 import javax.swing.*;
+import javax.swing.plaf.metal.*;
 
 public class bug7193219 {
     private static byte[] serializeGUI() {
@@ -73,6 +74,7 @@
     }
 
     public static void main(String[] args) throws Exception {
+        UIManager.setLookAndFeel(new MetalLookAndFeel());
         SwingUtilities.invokeAndWait(new Runnable() {
             @Override
             public void run() {
--- a/jdk/test/javax/swing/JComponent/7154030/bug7154030.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/swing/JComponent/7154030/bug7154030.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JFrame/4962534/bug4962534.html	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,43 @@
+<html>
+<!--
+  Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+
+  This code is free software; you can redistribute it and/or modify it
+  under the terms of the GNU General Public License version 2 only, as
+  published by the Free Software Foundation.
+
+  This code is distributed in the hope that it will be useful, but WITHOUT
+  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+  version 2 for more details (a copy is included in the LICENSE file that
+  accompanied this code).
+
+  You should have received a copy of the GNU General Public License version
+  2 along with this work; if not, write to the Free Software Foundation,
+  Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+
+  Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+  or visit www.oracle.com if you need additional information or have any
+  questions.
+ -->
+
+<!--
+  @test
+  @bug 4962534
+  @summary JFrame dances very badly
+  @author dav@sparc.spb.su area=
+  @run applet bug4962534.html
+  -->
+<head>
+<title>  </title>
+</head>
+<body>
+
+<h1>bug4962534<br>Bug ID: 4962534 </h1>
+
+<p> This is an AUTOMATIC test, simply wait for completion </p>
+
+<APPLET CODE="bug4962534.class" WIDTH=200 HEIGHT=200></APPLET>
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JFrame/4962534/bug4962534.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,235 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ test
+ @bug 4962534 7104594
+ @summary JFrame dances very badly
+ @author dav@sparc.spb.su area=
+ @run applet bug4962534.html
+ */
+import java.applet.Applet;
+import java.awt.*;
+import java.awt.event.*;
+import java.util.Random;
+import javax.swing.*;
+import sun.awt.SunToolkit;
+
+public class bug4962534 extends Applet {
+
+    Robot robot;
+    volatile Point framePosition;
+    volatile Point newFrameLocation;
+    JFrame frame;
+    Rectangle gcBounds;
+    Component titleComponent;
+    JLayeredPane lPane;
+    volatile boolean titleFound = false;
+    SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
+    public static Object LOCK = new Object();
+
+    @Override
+    public void init() {
+        try {
+            SwingUtilities.invokeAndWait(new Runnable() {
+                @Override
+                public void run() {
+                    createAndShowGUI();
+                }
+            });
+        } catch (Exception ex) {
+            throw new RuntimeException("Init failed. " + ex.getMessage());
+        }
+    }//End  init()
+
+    @Override
+    public void start() {
+        validate();
+
+        try {
+            setJLayeredPaneEDT();
+            setTitleComponentEDT();
+        } catch (Exception ex) {
+            ex.printStackTrace();
+            throw new RuntimeException("Test failed. " + ex.getMessage());
+        }
+
+        if (!titleFound) {
+            throw new RuntimeException("Test Failed. Unable to determine title's size.");
+        }
+
+        Random r = new Random();
+
+        for (int iteration = 0; iteration < 10; iteration++) {
+            try {
+                setFramePosEDT();
+            } catch (Exception ex) {
+                ex.printStackTrace();
+                throw new RuntimeException("Test failed.");
+            }
+            try {
+                robot = new Robot();
+                robot.setAutoDelay(70);
+
+                toolkit.realSync();
+
+                robot.mouseMove(framePosition.x + getJFrameWidthEDT() / 2,
+                        framePosition.y + titleComponent.getHeight() / 2);
+                robot.mousePress(InputEvent.BUTTON1_MASK);
+
+                toolkit.realSync();
+
+                gcBounds =
+                        GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getConfigurations()[0].getBounds();
+
+                robot.mouseMove(framePosition.x + getJFrameWidthEDT() / 2,
+                        framePosition.y + titleComponent.getHeight() / 2);
+
+                toolkit.realSync();
+
+                int multier = gcBounds.height / 2 - 10; //we will not go out the borders
+                for (int i = 0; i < 10; i++) {
+                    robot.mouseMove(gcBounds.width / 2 - (int) (r.nextDouble() * multier), gcBounds.height / 2 - (int) (r.nextDouble() * multier));
+                }
+                robot.mouseRelease(InputEvent.BUTTON1_MASK);
+
+                toolkit.realSync();
+
+            } catch (AWTException e) {
+                throw new RuntimeException("Test Failed. AWTException thrown." + e.getMessage());
+            } catch (Exception e) {
+                e.printStackTrace();
+                throw new RuntimeException("Test Failed.");
+            }
+            System.out.println("Mouse  lies in " + MouseInfo.getPointerInfo().getLocation());
+            boolean frameIsOutOfScreen = false;
+            try {
+                setNewFrameLocationEDT();
+                System.out.println("Now Frame lies in " + newFrameLocation);
+                frameIsOutOfScreen = checkFrameIsOutOfScreenEDT();
+            } catch (Exception ex) {
+                ex.printStackTrace();
+                throw new RuntimeException("Test Failed.");
+            }
+
+            if (frameIsOutOfScreen) {
+                throw new RuntimeException("Test failed. JFrame is out of screen.");
+            }
+
+        } //for iteration
+        System.out.println("Test passed.");
+    }// start()
+
+    private void createAndShowGUI() {
+        try {
+            UIManager.setLookAndFeel(
+                    "javax.swing.plaf.metal.MetalLookAndFeel");
+        } catch (Exception ex) {
+            throw new RuntimeException(ex.getMessage());
+        }
+        JFrame.setDefaultLookAndFeelDecorated(true);
+        frame = new JFrame("JFrame Dance Test");
+        frame.pack();
+        frame.setSize(450, 260);
+        frame.setVisible(true);
+    }
+
+    private void setJLayeredPaneEDT() throws Exception {
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                lPane = frame.getLayeredPane();
+                System.out.println("JFrame's LayeredPane " + lPane);
+            }
+        });
+    }
+
+    private void setTitleComponentEDT() throws Exception {
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                for (int j = 0; j < lPane.getComponentsInLayer(JLayeredPane.FRAME_CONTENT_LAYER.intValue()).length; j++) {
+                    titleComponent = lPane.getComponentsInLayer(JLayeredPane.FRAME_CONTENT_LAYER.intValue())[j];
+                    if (titleComponent.getClass().getName().equals("javax.swing.plaf.metal.MetalTitlePane")) {
+                        titleFound = true;
+                        break;
+                    }
+                }
+            }
+        });
+    }
+
+    private void setFramePosEDT() throws Exception {
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                framePosition = frame.getLocationOnScreen();
+            }
+        });
+    }
+
+    private boolean checkFrameIsOutOfScreenEDT() throws Exception {
+
+        final boolean[] result = new boolean[1];
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                if (newFrameLocation.x > gcBounds.width || newFrameLocation.x < 0
+                    || newFrameLocation.y > gcBounds.height || newFrameLocation.y
+                    < 0) {
+                result[0] = true;
+            }
+            }
+        });
+        return result[0];
+    }
+
+    private void setNewFrameLocationEDT() throws Exception {
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                newFrameLocation = new Point(frame.getLocationOnScreen().x
+                        + frame.getWidth() / 2, frame.getLocationOnScreen().y + titleComponent.getHeight() / 2);
+            }
+        });
+    }
+
+    private int getJFrameWidthEDT() throws Exception {
+
+        final int[] result = new int[1];
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                result[0] = frame.getWidth();
+            }
+        });
+
+        return result[0];
+    }
+}// class
--- a/jdk/test/javax/swing/JTabbedPane/4310381/bug4310381.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/swing/JTabbedPane/4310381/bug4310381.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/javax/swing/JTable/4235420/bug4235420.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/swing/JTable/4235420/bug4235420.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/javax/swing/JTable/6788484/bug6788484.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/swing/JTable/6788484/bug6788484.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/javax/swing/JTable/7055065/bug7055065.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/swing/JTable/7055065/bug7055065.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/javax/swing/JTable/7188612/JTableAccessibleGetLocationOnScreen.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/swing/JTable/7188612/JTableAccessibleGetLocationOnScreen.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/JTable/8005019/bug8005019.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8005019
+ * @summary JTable passes row index instead of length when inserts selection interval
+ * @author Alexander Scherbatiy
+ * @run main bug8005019
+ */
+
+import java.util.*;
+import javax.swing.*;
+import javax.swing.table.*;
+
+public class bug8005019 {
+
+    public static void main(String[] args) throws Exception {
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                testSelectionWithFilterTable();
+            }
+        });
+    }
+
+    private static void testSelectionWithFilterTable() {
+        DefaultTableModel model = new DefaultTableModel(0, 1);
+        // a model with 3 elements is the minimum to demonstrate
+        // the bug
+        int last = 2;
+        for (int i = 0; i <= last; i++) {
+            model.addRow(new Object[]{i});
+        }
+        JTable table = new JTable(model);
+        table.setAutoCreateRowSorter(true);
+        // set selection at the end
+        table.setRowSelectionInterval(last, last);
+        // exclude rows based on identifier
+        RowFilter filter = new GeneralFilter(new int[]{0});
+        ((DefaultRowSorter) table.getRowSorter()).setRowFilter(filter);
+        // insertRow _before or at_ selected model index, such that
+        // endIndex (in event) > 1
+        model.insertRow(2, new Object[]{"x"});
+    }
+
+    private static class GeneralFilter extends RowFilter<Object, Object> {
+
+        private int[] columns;
+        List excludes = Arrays.asList(0);
+
+        GeneralFilter(int[] columns) {
+            this.columns = columns;
+        }
+
+        public boolean include(RowFilter.Entry<? extends Object, ? extends Object> value) {
+            int count = value.getValueCount();
+            if (columns.length > 0) {
+                for (int i = columns.length - 1; i >= 0; i--) {
+                    int index = columns[i];
+                    if (index < count) {
+                        if (include(value, index)) {
+                            return true;
+                        }
+                    }
+                }
+            } else {
+                while (--count >= 0) {
+                    if (include(value, count)) {
+                        return true;
+                    }
+                }
+            }
+            return false;
+        }
+
+        protected boolean include(
+                Entry<? extends Object, ? extends Object> entry,
+                int index) {
+            return !excludes.contains(entry.getIdentifier());
+        }
+    }
+}
--- a/jdk/test/javax/swing/JTextArea/7049024/bug7049024.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/swing/JTextArea/7049024/bug7049024.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/javax/swing/border/Test7022041.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/swing/border/Test7022041.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,11 +1,12 @@
 /*
- * Copyright 2012 Red Hat, Inc. All Rights Reserved.
  * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
@@ -16,6 +17,10 @@
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
  */
 
 import java.awt.Color;
--- a/jdk/test/javax/swing/text/DefaultCaret/6938583/bug6938583.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/javax/swing/text/DefaultCaret/6938583/bug6938583.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/java2d/cmm/ColorConvertOp/GrayTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug     7124245
+ * @summary Test verifies that color conversion does not distort
+ *          colors in destination image of standard type.
+ *
+ * @run main GrayTest
+ */
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.color.ColorSpace;
+import java.awt.image.BufferedImage;
+import java.awt.image.ColorConvertOp;
+
+public class GrayTest {
+    public static void main(String[] args) {
+        GrayTest t = new GrayTest();
+
+        t.doTest(BufferedImage.TYPE_INT_RGB);
+        t.doTest(BufferedImage.TYPE_INT_BGR);
+        t.doTest(BufferedImage.TYPE_INT_ARGB);
+        t.doTest(BufferedImage.TYPE_3BYTE_BGR);
+        t.doTest(BufferedImage.TYPE_4BYTE_ABGR);
+        System.out.println("Test passed.");
+    }
+
+    private static final int w = 3;
+    private static final int h = 3;
+
+    private BufferedImage src;
+    private BufferedImage dst;
+
+    private ColorConvertOp op;
+
+    public GrayTest() {
+        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
+        op = new ColorConvertOp(cs, null);
+    }
+
+    private void render(Graphics2D g) {
+        g.setColor(Color.red);
+        g.fillRect(0, 0, w, h);
+    }
+
+    private BufferedImage initImage(int type) {
+        BufferedImage img = new BufferedImage(w, h, type);
+        Graphics2D g = img.createGraphics();
+
+        render(g);
+
+        g.dispose();
+
+        return img;
+    }
+
+    public void doTest(int type) {
+        System.out.println("Test for type: " + type);
+        src = initImage(type);
+
+        dst = initImage(type);
+
+        dst = op.filter(src, dst);
+
+        int pixel = dst.getRGB(1, 1);
+        int r = 0xff & (pixel >> 16);
+        int g = 0xff & (pixel >>  8);
+        int b = 0xff & (pixel      );
+
+        System.out.printf("dst: r:%02x, g: %02x, %02x\n",
+                r, g, b);
+
+        if (r != g || r != b) {
+            String msg = String.format("Invalid pixel: %08x", pixel);
+            throw new RuntimeException(msg);
+        }
+        System.out.println("Done.");
+    }
+}
--- a/jdk/test/sun/management/AgentCMETest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/management/AgentCMETest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/sun/management/jmxremote/startstop/JMXStartStopDoSomething.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/management/jmxremote/startstop/JMXStartStopDoSomething.java	Tue Jan 22 11:54:16 2013 -0800
@@ -41,7 +41,7 @@
                     System.err.println("Lock is too old. Aborting");
                     return;
                 }
-                Thread.sleep(1);
+                Thread.sleep(500);
             }
 
         } catch (Throwable e) {
--- a/jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.sh	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.sh	Tue Jan 22 11:54:16 2013 -0800
@@ -1,6 +1,6 @@
 #!/bin/sh
 
-# Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 # 
 # This code is free software; you can redistribute it and/or modify it
@@ -43,7 +43,7 @@
 
 _compile(){
 
-    if [ ! -e ${_testclasses} ]
+    if [ ! -d ${_testclasses} ]
     then
       mkdir -p ${_testclasses} 
     fi   
@@ -53,7 +53,7 @@
     # Compile testcase
     ${TESTJAVA}/bin/javac -d ${_testclasses} JMXStartStopDoSomething.java JMXStartStopTest.java 
 
-    if [ ! -e ${_testclasses}/JMXStartStopTest.class ]
+    if [ ! -f ${_testclasses}/JMXStartStopTest.class ]
     then
       echo "ERROR: Can't compile"
       exit -1
@@ -63,15 +63,22 @@
 _app_start(){
   ${TESTJAVA}/bin/java ${TESTVMOPTS} $* -cp ${_testclasses} JMXStartStopDoSomething  >> ${_logname} 2>&1 &
 
-  npid=`_get_pid`
-  if [ "${npid}" = "" ]
-  then
-     echo "ERROR: Test app not started"
-     if [ "${_jtreg}" = "yes" ]
+  x=0
+  while [ ! -f ${_lockFileName} ]
+  do
+     if [ $x -gt 20 ]
      then
-       exit -1
-     fi  
-  fi
+        echo "ERROR: Test app not started"
+        if [ "${_jtreg}" = "yes" ]
+        then
+           exit -1
+        fi   
+     fi    
+        
+     echo "Waiting JMXStartStopDoSomething to start: $x"
+     x=`expr $x + 1`
+     sleep 1
+  done
 }
 
 _get_pid(){
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/net/www/http/KeepAliveStream/InfiniteLoop.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8004863
+ * @summary Checks for proper close code in KeepAliveStream
+ */
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import com.sun.net.httpserver.HttpServer;
+import java.io.*;
+import java.net.*;
+import java.util.concurrent.Phaser;
+
+// Racey test, will not always fail, but if it does then we have a problem.
+
+public class InfiniteLoop {
+
+    public static void main(String[] args) throws Exception {
+        HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
+        server.createContext("/test/InfiniteLoop", new RespHandler());
+        server.start();
+        try {
+            InetSocketAddress address = server.getAddress();
+            URL url = new URL("http://localhost:" + address.getPort()
+                              + "/test/InfiniteLoop");
+            final Phaser phaser = new Phaser(2);
+            for (int i=0; i<10; i++) {
+                HttpURLConnection uc = (HttpURLConnection)url.openConnection();
+                final InputStream is = uc.getInputStream();
+                final Thread thread = new Thread() {
+                    public void run() {
+                        try {
+                            phaser.arriveAndAwaitAdvance();
+                            while (is.read() != -1)
+                                Thread.sleep(50);
+                        } catch (Exception x) { x.printStackTrace(); }
+                    }};
+                thread.start();
+                phaser.arriveAndAwaitAdvance();
+                is.close();
+                System.out.println("returned from close");
+                thread.join();
+            }
+        } finally {
+            server.stop(0);
+        }
+    }
+
+    static class RespHandler implements HttpHandler {
+        static final int RESP_LENGTH = 32 * 1024;
+        @Override
+        public void handle(HttpExchange t) throws IOException {
+            InputStream is  = t.getRequestBody();
+            byte[] ba = new byte[8192];
+            while(is.read(ba) != -1);
+
+            t.sendResponseHeaders(200, RESP_LENGTH);
+            try (OutputStream os = t.getResponseBody()) {
+                os.write(new byte[RESP_LENGTH]);
+            }
+            t.close();
+        }
+    }
+}
--- a/jdk/test/sun/nio/ch/SelProvider.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/nio/ch/SelProvider.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/sun/rmi/rmic/classpath/RMICClassPathTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/rmi/rmic/classpath/RMICClassPathTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/sun/rmi/runtime/Log/4504153/Test4504153.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/rmi/runtime/Log/4504153/Test4504153.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -48,8 +48,7 @@
         ByteArrayOutputStream err = new ByteArrayOutputStream();
         JavaVM vm = new JavaVM(StartRegistry.class.getName(),
                                "-Dsun.rmi.transport.logLevel=v", "", out, err);
-        vm.start();
-        vm.getVM().waitFor();
+        vm.execute();
 
         String errString = err.toString();
 
--- a/jdk/test/sun/rmi/runtime/Log/6409194/NoConsoleOutput.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/rmi/runtime/Log/6409194/NoConsoleOutput.java	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -64,9 +64,8 @@
         // (neither on standard output, nor on standard err streams).
         JavaVM vm = new JavaVM(DoRMIStuff.class.getName(),
             "-Djava.util.logging.config.file=" + loggingPropertiesFile,
-                               "", out, err, false);
-        vm.start();
-        vm.getVM().waitFor();
+                               "", out, err);
+        vm.execute();
 
         /*
          * Verify that the subprocess had no System.out or System.err
--- a/jdk/test/sun/rmi/transport/tcp/DeadCachedConnection.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/rmi/transport/tcp/DeadCachedConnection.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -104,7 +104,7 @@
             JavaVM jvm =
                 new JavaVM("sun.rmi.registry.RegistryImpl", "", Integer.toString(p));
             jvm.start();
-            DeadCachedConnection.subreg = jvm.getVM();
+            DeadCachedConnection.subreg = jvm;
 
         } catch (IOException e) {
             // one of these is summarily dropped, can't remember which one
@@ -117,7 +117,7 @@
         } catch (Exception whatever) {
         }
     }
-    private static Process subreg = null;
+    private static JavaVM subreg = null;
 
     public static void killRegistry() {
         if (DeadCachedConnection.subreg != null) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/krb5/ServiceCredsCombination.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+/*
+ * @test
+ * @bug 8005447
+ * @compile -XDignore.symbol.file ServiceCredsCombination.java
+ * @run main ServiceCredsCombination
+ * @summary default principal can act as anyone
+ */
+
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.Objects;
+import javax.security.auth.Subject;
+import javax.security.auth.kerberos.KerberosKey;
+import javax.security.auth.kerberos.KerberosPrincipal;
+import javax.security.auth.kerberos.KeyTab;
+import org.ietf.jgss.GSSCredential;
+import org.ietf.jgss.GSSException;
+import org.ietf.jgss.GSSManager;
+import org.ietf.jgss.GSSName;
+import sun.security.jgss.GSSUtil;
+
+public class ServiceCredsCombination {
+
+    public static void main(String[] args) throws Exception {
+        // pass
+        check("a", "a", princ("a"), key("a"));
+        check(null, "a", princ("a"), key("a"));
+        check("x", "NOCRED", princ("a"), key("a"));
+        // two pass
+        check("a", "a", princ("a"), key("a"), princ("b"), key("b"));
+        check("b", "b", princ("a"), key("a"), princ("b"), key("b"));
+        check(null, null, princ("a"), key("a"), princ("b"), key("b"));
+        check("x", "NOCRED", princ("a"), key("a"), princ("b"), key("b"));
+        // old ktab
+        check("b", "b", princ("b"), oldktab());
+        check("x", "NOCRED", princ("b"), oldktab());
+        check(null, "b", princ("b"), oldktab());
+        // Two old ktab
+        check("a", "a", princ("a"), princ("b"), oldktab(), oldktab());
+        check("b", "b", princ("a"), princ("b"), oldktab(), oldktab());
+        check(null, null, princ("a"), princ("b"), oldktab(), oldktab());
+        check("x", "NOCRED", princ("a"), princ("b"), oldktab(), oldktab());
+        // pass + old ktab
+        check("a", "a", princ("a"), princ("b"), key("a"), oldktab());
+        check("b", "b", princ("a"), princ("b"), key("a"), oldktab());
+        check(null, null, princ("a"), princ("b"), key("a"), oldktab());
+        check("x", "NOCRED", princ("a"), princ("b"), key("a"), oldktab());
+        // Compatibility, automatically add princ for keys
+        check(null, "a", key("a"));
+        check("x", "NOCRED", key("a"));
+        check(null, "a", key("a"), oldktab());
+        check("x", "NOCRED", key("a"), oldktab());
+        // Limitation, "a" has no key, but we don't know oldktab() is for "b"
+        check("a", "a", princ("a"), princ("b"), oldktab());
+    }
+
+    /**
+     * Checks the correct bound
+     * @param a get a creds for this principal, null for default one
+     * @param b expected name, null for still unbound, "NOCRED" for no creds
+     * @param objs princs, keys and keytabs in the subject
+     */
+    private static void check(final String a, String b, Object... objs)
+            throws Exception {
+        Subject subj = new Subject();
+        for (Object obj: objs) {
+            if (obj instanceof KerberosPrincipal) {
+                subj.getPrincipals().add((KerberosPrincipal)obj);
+            } else if (obj instanceof KerberosKey || obj instanceof KeyTab) {
+                subj.getPrivateCredentials().add(obj);
+            }
+        }
+        final GSSManager man = GSSManager.getInstance();
+        try {
+            String result = Subject.doAs(
+                    subj, new PrivilegedExceptionAction<String>() {
+                @Override
+                public String run() throws GSSException {
+                    GSSCredential cred = man.createCredential(
+                            a == null ? null : man.createName(r(a), null),
+                            GSSCredential.INDEFINITE_LIFETIME,
+                            GSSUtil.GSS_KRB5_MECH_OID,
+                            GSSCredential.ACCEPT_ONLY);
+                    GSSName name = cred.getName();
+                    return name == null ? null : name.toString();
+                }
+            });
+            if (!Objects.equals(result, r(b))) {
+                throw new Exception("Check failed: getInstance(" + a
+                        + ") has name " + result + ", not " + b);
+            }
+        } catch (PrivilegedActionException e) {
+            if (!"NOCRED".equals(b)) {
+                throw new Exception("Check failed: getInstance(" + a
+                        + ") is null " + ", but not one with name " + b);
+            }
+        }
+    }
+    private static String r(String s) {
+        return s == null ? null : (s+"@REALM");
+    }
+    private static KerberosPrincipal princ(String s) {
+        return new KerberosPrincipal(r(s));
+    }
+    private static KerberosKey key(String s) {
+        return new KerberosKey(princ(s), new byte[0], 0, 0);
+    }
+    private static KeyTab oldktab() {
+        return KeyTab.getInstance();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/krb5/auto/AcceptPermissions.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 9999999
+ * @summary default principal can act as anyone
+ * @compile -XDignore.symbol.file AcceptPermissions.java
+ * @run main/othervm AcceptPermissions
+ */
+
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
+import java.security.Permission;
+import javax.security.auth.kerberos.ServicePermission;
+import sun.security.jgss.GSSUtil;
+import java.util.*;
+
+public class AcceptPermissions extends SecurityManager {
+
+    private static Map<Permission,String> perms = new HashMap<>();
+    @Override
+    public void checkPermission(Permission perm) {
+        if (!(perm instanceof ServicePermission)) {
+            return;
+        }
+        ServicePermission sp = (ServicePermission)perm;
+        if (!sp.getActions().equals("accept")) {
+            return;
+        }
+        // We only care about accept ServicePermission in this test
+        try {
+            super.checkPermission(sp);
+        } catch (SecurityException se) {
+            if (perms.containsKey(sp)) {
+                perms.put(sp, "checked");
+            } else {
+                throw se;   // We didn't expect this is needed
+            }
+        }
+    }
+
+    // Fills in permissions we are expecting
+    private static void initPerms(String... names) {
+        perms.clear();
+        for (String name: names) {
+            perms.put(new ServicePermission(
+                    name + "@" + OneKDC.REALM, "accept"), "expected");
+        }
+    }
+
+    // Checks if they are all checked
+    private static void checkPerms() {
+        for (Map.Entry<Permission,String> entry: perms.entrySet()) {
+            if (entry.getValue().equals("expected")) {
+                throw new RuntimeException(
+                        "Expected but not used: " + entry.getKey());
+            }
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        System.setSecurityManager(new AcceptPermissions());
+        new OneKDC(null).writeJAASConf();
+        String two = "two {\n"
+                + " com.sun.security.auth.module.Krb5LoginModule required"
+                + "     principal=\"" + OneKDC.SERVER + "\" useKeyTab=true"
+                + "     isInitiator=false storeKey=true;\n"
+                + " com.sun.security.auth.module.Krb5LoginModule required"
+                + "     principal=\"" + OneKDC.BACKEND + "\" useKeyTab=true"
+                + "     isInitiator=false storeKey=true;\n"
+                + "};\n";
+        Files.write(Paths.get(OneKDC.JAAS_CONF), two.getBytes(),
+                StandardOpenOption.APPEND);
+
+        Context c, s;
+
+        // In all cases, a ServicePermission on the acceptor name is needed
+        // for a handshake. For default principal with no predictable name,
+        // permission not needed (yet) for credentials creation.
+
+        // Named principal
+        initPerms(OneKDC.SERVER);
+        c = Context.fromJAAS("client");
+        s = Context.fromJAAS("server");
+        c.startAsClient(OneKDC.SERVER, GSSUtil.GSS_KRB5_MECH_OID);
+        s.startAsServer(OneKDC.SERVER, GSSUtil.GSS_KRB5_MECH_OID);
+        checkPerms();
+        initPerms(OneKDC.SERVER);
+        Context.handshake(c, s);
+        checkPerms();
+
+        // Named principal (even if there are 2 JAAS modules)
+        initPerms(OneKDC.SERVER);
+        c = Context.fromJAAS("client");
+        s = Context.fromJAAS("two");
+        c.startAsClient(OneKDC.SERVER, GSSUtil.GSS_KRB5_MECH_OID);
+        s.startAsServer(OneKDC.SERVER, GSSUtil.GSS_KRB5_MECH_OID);
+        checkPerms();
+        initPerms(OneKDC.SERVER);
+        Context.handshake(c, s);
+        checkPerms();
+
+        // Default principal with a predictable name
+        initPerms(OneKDC.SERVER);
+        c = Context.fromJAAS("client");
+        s = Context.fromJAAS("server");
+        c.startAsClient(OneKDC.SERVER, GSSUtil.GSS_KRB5_MECH_OID);
+        s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
+        checkPerms();
+        initPerms(OneKDC.SERVER);
+        Context.handshake(c, s);
+        checkPerms();
+
+        // Default principal with no predictable name
+        initPerms();    // permission not needed for cred !!!
+        c = Context.fromJAAS("client");
+        s = Context.fromJAAS("two");
+        c.startAsClient(OneKDC.SERVER, GSSUtil.GSS_KRB5_MECH_OID);
+        s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
+        checkPerms();
+        initPerms(OneKDC.SERVER);   // still needed for handshake !!!
+        Context.handshake(c, s);
+        checkPerms();
+    }
+}
--- a/jdk/test/sun/security/krb5/auto/CleanState.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/krb5/auto/CleanState.java	Tue Jan 22 11:54:16 2013 -0800
@@ -24,6 +24,7 @@
 /*
  * @test
  * @bug 6716534
+ * @compile -XDignore.symbol.file CleanState.java
  * @run main/othervm CleanState
  * @summary Krb5LoginModule has not cleaned temp info between authentication attempts
  */
--- a/jdk/test/sun/security/krb5/auto/Context.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/krb5/auto/Context.java	Tue Jan 22 11:54:16 2013 -0800
@@ -131,21 +131,24 @@
         return out;
     }
 
+    /**
+     * Logins with username/password as a new Subject
+     */
     public static Context fromUserPass(
             String user, char[] pass, boolean storeKey) throws Exception {
-        return fromUserPass(null, user, pass, storeKey);
+        return fromUserPass(new Subject(), user, pass, storeKey);
     }
 
     /**
-     * Logins with a username and a password, using Krb5LoginModule directly
-     * @param s existing subject, test multiple princ & creds for single subj
-     * @param storeKey true if key should be saved, used on acceptor side
+     * Logins with username/password as an existing Subject. The
+     * same subject can be used multiple times to simulate multiple logins.
+     * @param s existing subject
      */
     public static Context fromUserPass(Subject s,
             String user, char[] pass, boolean storeKey) throws Exception {
         Context out = new Context();
         out.name = user;
-        out.s = s == null ? new Subject() : s;
+        out.s = s;
         Krb5LoginModule krb5 = new Krb5LoginModule();
         Map<String, String> map = new HashMap<>();
         Map<String, Object> shared = new HashMap<>();
@@ -172,14 +175,23 @@
     }
 
     /**
-     * Logins with a username and a keytab, using Krb5LoginModule directly
-     * @param storeKey true if key should be saved, used on acceptor side
+     * Logins with username/keytab as an existing Subject. The
+     * same subject can be used multiple times to simulate multiple logins.
+     * @param s existing subject
      */
-    public static Context fromUserKtab(String user, String ktab, boolean storeKey)
-            throws Exception {
+    public static Context fromUserKtab(
+            String user, String ktab, boolean storeKey) throws Exception {
+        return fromUserKtab(new Subject(), user, ktab, storeKey);
+    }
+
+    /**
+     * Logins with username/keytab as a new subject,
+     */
+    public static Context fromUserKtab(Subject s,
+            String user, String ktab, boolean storeKey) throws Exception {
         Context out = new Context();
         out.name = user;
-        out.s = new Subject();
+        out.s = s;
         Krb5LoginModule krb5 = new Krb5LoginModule();
         Map<String, String> map = new HashMap<>();
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/krb5/auto/DiffNameSameKey.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8005447
+ * @summary default principal can act as anyone
+ * @compile -XDignore.symbol.file DiffNameSameKey.java
+ * @run main/othervm/fail DiffNameSameKey a
+ * @run main/othervm DiffNameSameKey b
+ */
+
+import sun.security.jgss.GSSUtil;
+import sun.security.krb5.PrincipalName;
+
+/**
+ * This test confirms the compatibility codes described in
+ * ServiceCreds.getEKeys(). If the acceptor starts as x.us.oracle.com
+ * but client requests for x.us, as long as the KDC supports both names
+ * and the keys are the same, the auth should succeed.
+ */
+public class DiffNameSameKey {
+
+    static final String SERVER2 = "x" + OneKDC.SERVER;
+
+    public static void main(String[] args) throws Exception {
+
+        OneKDC kdc = new KDC2();
+        kdc.addPrincipal(SERVER2, "samepass".toCharArray());
+        kdc.addPrincipal(OneKDC.SERVER, "samepass".toCharArray());
+        kdc.writeJAASConf();
+        kdc.writeKtab(OneKDC.KTAB);
+
+        Context c, s;
+        c = Context.fromJAAS("client");
+        s = Context.fromJAAS("server");
+
+        switch (args[0]) {
+            case "a":   // If server starts as another service, should fail
+                c.startAsClient(OneKDC.SERVER, GSSUtil.GSS_SPNEGO_MECH_OID);
+                s.startAsServer(SERVER2.replace('/', '@'),
+                        GSSUtil.GSS_SPNEGO_MECH_OID);
+                break;
+            case "b":   // If client requests another server with the same keys,
+                        // succeed to be compatible
+                c.startAsClient(SERVER2, GSSUtil.GSS_SPNEGO_MECH_OID);
+                s.startAsServer(OneKDC.SERVER.replace('/', '@'),
+                        GSSUtil.GSS_SPNEGO_MECH_OID);
+                break;
+        }
+
+        Context.handshake(c, s);
+
+        s.dispose();
+        c.dispose();
+    }
+
+    /**
+     * This KDC returns the same salt for all principals. This means same
+     * passwords generate same keys.
+     */
+    static class KDC2 extends OneKDC {
+        KDC2() throws Exception {
+            super(null);
+        }
+        @Override
+        public String getSalt(PrincipalName pn) {
+            return "SAME";
+        }
+    }
+}
--- a/jdk/test/sun/security/krb5/auto/DynamicKeytab.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/krb5/auto/DynamicKeytab.java	Tue Jan 22 11:54:16 2013 -0800
@@ -24,6 +24,7 @@
 /*
  * @test
  * @bug 6894072
+ * @compile -XDignore.symbol.file DynamicKeytab.java
  * @run main/othervm DynamicKeytab
  * @summary always refresh keytab
  */
@@ -110,11 +111,13 @@
             throw new Exception("Should not success");
         } catch (GSSException gsse) {
             System.out.println(gsse);
-            KrbException ke = (KrbException)gsse.getCause();
-            if (ke.returnCode() != Krb5.KRB_AP_ERR_BADKEYVER) {
-                throw new Exception("Not expected failure code: " +
-                        ke.returnCode());
-            }
+            // Since 7197159, different kvno is accepted, this return code
+            // will never be thrown out again.
+            //KrbException ke = (KrbException)gsse.getCause();
+            //if (ke.returnCode() != Krb5.KRB_AP_ERR_BADKEYVER) {
+            //    throw new Exception("Not expected failure code: " +
+            //            ke.returnCode());
+            //}
         }
 
         // Test 8: an empty KDC means revoke all
--- a/jdk/test/sun/security/krb5/auto/KDC.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/krb5/auto/KDC.java	Tue Jan 22 11:54:16 2013 -0800
@@ -285,10 +285,12 @@
             if (Character.isDigit(pass[pass.length-1])) {
                 kvno = pass[pass.length-1] - '0';
             }
-            ktab.addEntry(new PrincipalName(name,
-                    name.indexOf('/') < 0 ?
-                        PrincipalName.KRB_NT_UNKNOWN :
-                        PrincipalName.KRB_NT_SRV_HST),
+            PrincipalName pn = new PrincipalName(name,
+                        name.indexOf('/') < 0 ?
+                            PrincipalName.KRB_NT_UNKNOWN :
+                            PrincipalName.KRB_NT_SRV_HST);
+            ktab.addEntry(pn,
+                        getSalt(pn),
                         pass,
                         kvno,
                         true);
@@ -534,7 +536,7 @@
         if (pass == null) {
             throw new KrbException(server?
                 Krb5.KDC_ERR_S_PRINCIPAL_UNKNOWN:
-                Krb5.KDC_ERR_C_PRINCIPAL_UNKNOWN);
+                Krb5.KDC_ERR_C_PRINCIPAL_UNKNOWN, pn.toString());
         }
         return pass;
     }
@@ -544,7 +546,7 @@
      * @param p principal
      * @return the salt
      */
-    private String getSalt(PrincipalName p) {
+    protected String getSalt(PrincipalName p) {
         String pn = p.toString();
         if (p.getRealmString() == null) {
             pn = pn + "@" + getRealm();
--- a/jdk/test/sun/security/krb5/auto/KeyTabCompat.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/krb5/auto/KeyTabCompat.java	Tue Jan 22 11:54:16 2013 -0800
@@ -38,7 +38,7 @@
  *
  * 1. If there is only KerberosKeys in private credential set and no
  *    KerberosPrincipal. JAAS login should go on.
- * 2. Even if KeyTab is used, user can still get KerberosKeys from
+ * 2. If KeyTab is used, user won't get KerberosKeys from
  *    private credentials set.
  */
 public class KeyTabCompat {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/krb5/auto/KvnoNA.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 7197159
+ * @compile -XDignore.symbol.file KvnoNA.java
+ * @run main/othervm KvnoNA
+ * @summary accept different kvno if there no match
+ */
+
+import org.ietf.jgss.GSSException;
+import sun.security.jgss.GSSUtil;
+import sun.security.krb5.KrbException;
+import sun.security.krb5.PrincipalName;
+import sun.security.krb5.internal.ktab.KeyTab;
+import sun.security.krb5.internal.Krb5;
+
+public class KvnoNA {
+
+    public static void main(String[] args)
+            throws Exception {
+
+        OneKDC kdc = new OneKDC(null);
+        kdc.writeJAASConf();
+
+        // In KDC, it's 2
+        char[] pass = "pass2".toCharArray();
+        kdc.addPrincipal(OneKDC.SERVER, pass);
+
+        // In ktab, kvno is 1 or 3, 3 has the same password
+        KeyTab ktab = KeyTab.create(OneKDC.KTAB);
+        PrincipalName p = new PrincipalName(
+            OneKDC.SERVER+"@"+OneKDC.REALM, PrincipalName.KRB_NT_SRV_HST);
+        ktab.addEntry(p, "pass1".toCharArray(), 1, true);
+        ktab.addEntry(p, "pass2".toCharArray(), 3, true);
+        ktab.save();
+
+        Context c, s;
+
+        c = Context.fromUserPass("dummy", "bogus".toCharArray(), false);
+        s = Context.fromJAAS("server");
+
+        c.startAsClient(OneKDC.SERVER, GSSUtil.GSS_KRB5_MECH_OID);
+        s.startAsServer(GSSUtil.GSS_KRB5_MECH_OID);
+
+        Context.handshake(c, s);
+
+        s.dispose();
+        c.dispose();
+    }
+}
--- a/jdk/test/sun/security/krb5/auto/MoreKvno.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/krb5/auto/MoreKvno.java	Tue Jan 22 11:54:16 2013 -0800
@@ -23,8 +23,7 @@
 
 /*
  * @test
- * @bug 6893158
- * @bug 6907425
+ * @bug 6893158 6907425 7197159
  * @run main/othervm MoreKvno
  * @summary AP_REQ check should use key version number
  */
@@ -69,11 +68,13 @@
             go(OneKDC.SERVER, "com.sun.security.jgss.krb5.accept", pass);
             throw new Exception("This test should fail");
         } catch (GSSException gsse) {
-            KrbException ke = (KrbException)gsse.getCause();
-            if (ke.returnCode() != Krb5.KRB_AP_ERR_BADKEYVER) {
-                throw new Exception("Not expected failure code: " +
-                        ke.returnCode());
-            }
+            // Since 7197159, different kvno is accepted, this return code
+            // will never be thrown out again.
+            //KrbException ke = (KrbException)gsse.getCause();
+            //if (ke.returnCode() != Krb5.KRB_AP_ERR_BADKEYVER) {
+            //    throw new Exception("Not expected failure code: " +
+            //            ke.returnCode());
+            //}
         }
     }
 
--- a/jdk/test/sun/security/krb5/auto/ReplayCache.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/krb5/auto/ReplayCache.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright 2012 Sun Microsystems, Inc.  All Rights Reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -16,9 +16,9 @@
  * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * 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.
  */
 
 /*
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/krb5/auto/TwoOrThree.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8005447
+ * @summary default principal can act as anyone
+ * @compile -XDignore.symbol.file TwoOrThree.java
+ * @run main/othervm TwoOrThree first first
+ * @run main/othervm/fail TwoOrThree first second
+ * @run main/othervm TwoOrThree - first
+ * @run main/othervm TwoOrThree - second
+ * @run main/othervm/fail TwoOrThree - third
+ */
+
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
+import javax.security.auth.Subject;
+import sun.security.jgss.GSSUtil;
+
+/*
+ * The JAAS login has two krb5 modules
+ *   1. principal is A
+ *   2. principal is B
+ * A named principal can only accept itself. The default principal can accept
+ * either, but not any other service even if the keytab also include its keys.
+ */
+public class TwoOrThree {
+
+    public static void main(String[] args) throws Exception {
+
+        String server = args[0].equals("-") ? null : args[0];
+        String target = args[1];
+        OneKDC kdc = new OneKDC(null);
+        kdc.addPrincipal("first", "first".toCharArray());
+        kdc.addPrincipal("second", "second".toCharArray());
+        kdc.addPrincipal("third", "third".toCharArray());
+        kdc.writeKtab(OneKDC.KTAB);
+
+        Context c = Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false);
+
+        // Using keytabs
+        Subject sub4s = new Subject();
+        Context.fromUserKtab(sub4s, "first", OneKDC.KTAB, true);
+        Context s = Context.fromUserKtab(sub4s, "second", OneKDC.KTAB, true);
+        c.startAsClient(target, GSSUtil.GSS_KRB5_MECH_OID);
+        s.startAsServer(server, GSSUtil.GSS_KRB5_MECH_OID);
+        Context.handshake(c, s);
+
+        // Using keys
+        sub4s = new Subject();
+        Context.fromUserPass(sub4s, "first", "first".toCharArray(), true);
+        s = Context.fromUserPass(sub4s, "second", "second".toCharArray(), true);
+        c.startAsClient(target, GSSUtil.GSS_KRB5_MECH_OID);
+        s.startAsServer(server, GSSUtil.GSS_KRB5_MECH_OID);
+        Context.handshake(c, s);
+
+        s.dispose();
+        c.dispose();
+    }
+}
--- a/jdk/test/sun/security/provider/PolicyFile/Comparator.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/provider/PolicyFile/Comparator.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -39,7 +39,6 @@
 import javax.security.auth.x500.X500Principal;
 
 import sun.security.provider.PolicyFile;
-import com.sun.security.auth.PrincipalComparator;
 import com.sun.security.auth.UnixPrincipal;
 import com.sun.security.auth.NTUserPrincipal;
 import com.sun.security.auth.SolarisPrincipal;
@@ -90,7 +89,7 @@
     private static final Principal[] badP = new Principal[] {
                                 new SolarisPrincipal("bad") };
 
-    public static class PCompare1 implements PrincipalComparator {
+    public static class PCompare1 implements Principal {
 
         private String name;
 
@@ -98,6 +97,12 @@
             this.name = name;
         }
 
+        @Override
+        public String getName() {
+            return name;
+        }
+
+        @Override
         public boolean implies (Subject subject) {
             if (subject.getPrincipals().contains(p1[0])) {
                 return true;
@@ -106,13 +111,19 @@
         }
     }
 
-    public static class PCompare2 implements PrincipalComparator {
+    public static class PCompare2 implements Principal {
         private String name;
 
         public PCompare2(String name) {
             this.name = name;
         }
 
+        @Override
+        public String getName() {
+            return name;
+        }
+
+        @Override
         public boolean implies (Subject subject) {
             if (subject.getPrincipals().contains(p2[0]) &&
                 subject.getPrincipals().contains(p2[1])) {
@@ -122,13 +133,19 @@
         }
     }
 
-    public static class PCompare3 implements PrincipalComparator {
+    public static class PCompare3 implements Principal {
         private String name;
 
         public PCompare3(String name) {
             this.name = name;
         }
 
+        @Override
+        public String getName() {
+            return name;
+        }
+
+        @Override
         public boolean implies (Subject subject) {
             return false;
         }
--- a/jdk/test/sun/security/provider/certpath/DisabledAlgorithms/CPBuilder.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/provider/certpath/DisabledAlgorithms/CPBuilder.java	Tue Jan 22 11:54:16 2013 -0800
@@ -21,6 +21,9 @@
  * questions.
  */
 
+// This test case relies on updated static security property, no way to re-use
+// security property in samevm/agentvm mode.
+
 /**
  * @test
  *
@@ -392,6 +395,9 @@
     }
 
     public static void main(String args[]) throws Exception {
+        // reset the security property to make sure that the algorithms
+        // and keys used in this test are not disabled.
+        Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
 
         CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
 
--- a/jdk/test/sun/security/provider/certpath/DisabledAlgorithms/CPValidatorEndEntity.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/provider/certpath/DisabledAlgorithms/CPValidatorEndEntity.java	Tue Jan 22 11:54:16 2013 -0800
@@ -21,6 +21,9 @@
  * questions.
  */
 
+// This test case relies on updated static security property, no way to re-use
+// security property in samevm/agentvm mode.
+
 /**
  * @test
  *
@@ -28,7 +31,7 @@
  * @summary Disable MD2 support.
  *          New CertPathValidatorException.BasicReason enum constant for
  *     constrained algorithm.
- *
+ * @run main/othervm CPValidatorEndEntity
  * @author Xuelei Fan
  */
 
@@ -313,6 +316,10 @@
     }
 
     public static void main(String args[]) throws Exception {
+        // reset the security property to make sure that the algorithms
+        // and keys used in this test are not disabled.
+        Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
+
         try {
             validate(endentiry_SHA1withRSA_1024_1024,
                                     intermediate_SHA1withRSA_1024_1024);
--- a/jdk/test/sun/security/provider/certpath/DisabledAlgorithms/CPValidatorIntermediate.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/provider/certpath/DisabledAlgorithms/CPValidatorIntermediate.java	Tue Jan 22 11:54:16 2013 -0800
@@ -21,6 +21,9 @@
  * questions.
  */
 
+// This test case relies on updated static security property, no way to re-use
+// security property in samevm/agentvm mode.
+
 /**
  * @test
  *
@@ -28,7 +31,7 @@
  * @summary Disable MD2 support
  *          new CertPathValidatorException.BasicReason enum constant for
  *     constrained algorithm
- *
+ * @run main/othervm CPValidatorIntermediate
  * @author Xuelei Fan
  */
 
@@ -212,6 +215,10 @@
     }
 
     public static void main(String args[]) throws Exception {
+        // reset the security property to make sure that the algorithms
+        // and keys used in this test are not disabled.
+        Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
+
         try {
             validate(intermediate_SHA1withRSA_1024_1024);
             validate(intermediate_SHA1withRSA_1024_512);
--- a/jdk/test/sun/security/provider/certpath/DisabledAlgorithms/CPValidatorTrustAnchor.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/provider/certpath/DisabledAlgorithms/CPValidatorTrustAnchor.java	Tue Jan 22 11:54:16 2013 -0800
@@ -21,6 +21,9 @@
  * questions.
  */
 
+// This test case relies on updated static security property, no way to re-use
+// security property in samevm/agentvm mode.
+
 /**
  * @test
  *
@@ -28,7 +31,7 @@
  * @summary Disable MD2 support
  *          new CertPathValidatorException.BasicReason enum constant for
  *     constrained algorithm
- *
+ * @run main/othervm CPValidatorTrustAnchor
  * @author Xuelei Fan
  */
 
@@ -133,6 +136,10 @@
     }
 
     public static void main(String args[]) throws Exception {
+        // reset the security property to make sure that the algorithms
+        // and keys used in this test are not disabled.
+        Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
+
         try {
             validate(trustAnchor_SHA1withRSA_1024);
             validate(trustAnchor_SHA1withRSA_512);
--- a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/ClientHandshaker/RSAExport.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/ClientHandshaker/RSAExport.java	Tue Jan 22 11:54:16 2013 -0800
@@ -21,14 +21,14 @@
  * questions.
  */
 
+// SunJSSE does not support dynamic system properties, no way to re-use
+// system properties in samevm/agentvm mode.
+
 /*
  * @test
  * @bug 6690018
  * @summary RSAClientKeyExchange NullPointerException
  * @run main/othervm RSAExport
- *
- *     SunJSSE does not support dynamic system properties, no way to re-use
- *     system properties in samevm/agentvm mode.
  */
 
 /*
@@ -199,6 +199,7 @@
 
 import java.io.*;
 import java.net.*;
+import java.security.Security;
 import java.security.KeyStore;
 import java.security.KeyFactory;
 import java.security.cert.Certificate;
@@ -415,6 +416,10 @@
     volatile Exception clientException = null;
 
     public static void main(String[] args) throws Exception {
+        // reset the security property to make sure that the algorithms
+        // and keys used in this test are not disabled.
+        Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
+
         if (debug)
             System.setProperty("javax.net.debug", "all");
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/ssl/javax/net/ssl/TLSv12/DisabledShortRSAKeys.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,433 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// SunJSSE does not support dynamic system properties, no way to re-use
+// system properties in samevm/agentvm mode.
+
+/*
+ * @test
+ * @bug 7109274
+ * @summary Consider disabling support for X.509 certificates with RSA keys
+ *          less than 1024 bits
+ *
+ * @run main/othervm DisabledShortRSAKeys PKIX TLSv1.2
+ * @run main/othervm DisabledShortRSAKeys SunX509 TLSv1.2
+ * @run main/othervm DisabledShortRSAKeys PKIX TLSv1.1
+ * @run main/othervm DisabledShortRSAKeys SunX509 TLSv1.1
+ * @run main/othervm DisabledShortRSAKeys PKIX TLSv1
+ * @run main/othervm DisabledShortRSAKeys SunX509 TLSv1
+ * @run main/othervm DisabledShortRSAKeys PKIX SSLv3
+ * @run main/othervm DisabledShortRSAKeys SunX509 SSLv3
+ */
+
+import java.net.*;
+import java.util.*;
+import java.io.*;
+import javax.net.ssl.*;
+import java.security.Security;
+import java.security.KeyStore;
+import java.security.KeyFactory;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateFactory;
+import java.security.spec.*;
+import java.security.interfaces.*;
+import sun.misc.BASE64Decoder;
+
+
+public class DisabledShortRSAKeys {
+
+    /*
+     * =============================================================
+     * Set the various variables needed for the tests, then
+     * specify what tests to run on each side.
+     */
+
+    /*
+     * Should we run the client or server in a separate thread?
+     * Both sides can throw exceptions, but do you have a preference
+     * as to which side should be the main thread.
+     */
+    static boolean separateServerThread = true;
+
+    /*
+     * Where do we find the keystores?
+     */
+    // Certificates and key used in the test.
+    static String trustedCertStr =
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" +
+        "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" +
+        "MTEwODE5MDE1MjE5WhcNMzIwNzI5MDE1MjE5WjA7MQswCQYDVQQGEwJVUzENMAsG\n" +
+        "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" +
+        "KoZIhvcNAQEBBQADgY0AMIGJAoGBAM8orG08DtF98TMSscjGsidd1ZoN4jiDpi8U\n" +
+        "ICz+9dMm1qM1d7O2T+KH3/mxyox7Rc2ZVSCaUD0a3CkhPMnlAx8V4u0H+E9sqso6\n" +
+        "iDW3JpOyzMExvZiRgRG/3nvp55RMIUV4vEHOZ1QbhuqG4ebN0Vz2DkRft7+flthf\n" +
+        "vDld6f5JAgMBAAGjgaUwgaIwHQYDVR0OBBYEFLl81dnfp0wDrv0OJ1sxlWzH83Xh\n" +
+        "MGMGA1UdIwRcMFqAFLl81dnfp0wDrv0OJ1sxlWzH83XhoT+kPTA7MQswCQYDVQQG\n" +
+        "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" +
+        "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEE\n" +
+        "BQADgYEALlgaH1gWtoBZ84EW8Hu6YtGLQ/L9zIFmHonUPZwn3Pr//icR9Sqhc3/l\n" +
+        "pVTxOINuFHLRz4BBtEylzRIOPzK3tg8XwuLb1zd0db90x3KBCiAL6E6cklGEPwLe\n" +
+        "XYMHDn9eDsaq861Tzn6ZwzMgw04zotPMoZN0mVd/3Qca8UJFucE=\n" +
+        "-----END CERTIFICATE-----";
+
+    static String targetCertStr =
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIICNDCCAZ2gAwIBAgIBDDANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" +
+        "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" +
+        "MTExMTA3MTM1NTUyWhcNMzEwNzI1MTM1NTUyWjBPMQswCQYDVQQGEwJVUzENMAsG\n" +
+        "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxEjAQBgNV\n" +
+        "BAMTCWxvY2FsaG9zdDBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC3Pb49OSPfOD2G\n" +
+        "HSXFCFx1GJEZfqG9ZUf7xuIi/ra5dLjPGAaoY5QF2QOa8VnOriQCXDfyXHxsuRnE\n" +
+        "OomxL7EVAgMBAAGjeDB2MAsGA1UdDwQEAwID6DAdBgNVHQ4EFgQUXNCJK3/dtCIc\n" +
+        "xb+zlA/JINlvs/MwHwYDVR0jBBgwFoAUuXzV2d+nTAOu/Q4nWzGVbMfzdeEwJwYD\n" +
+        "VR0lBCAwHgYIKwYBBQUHAwEGCCsGAQUFBwMCBggrBgEFBQcDAzANBgkqhkiG9w0B\n" +
+        "AQQFAAOBgQB2qIDUxA2caMPpGtUACZAPRUtrGssCINIfItETXJZCx/cRuZ5sP4D9\n" +
+        "N1acoNDn0hCULe3lhXAeTC9NZ97680yJzregQMV5wATjo1FGsKY30Ma+sc/nfzQW\n" +
+        "+h/7RhYtoG0OTsiaDCvyhI6swkNJzSzrAccPY4+ZgU8HiDLzZTmM3Q==\n" +
+        "-----END CERTIFICATE-----";
+
+    // Private key in the format of PKCS#8, key size is 512 bits.
+    static String targetPrivateKey =
+        "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAtz2+PTkj3zg9hh0l\n" +
+        "xQhcdRiRGX6hvWVH+8biIv62uXS4zxgGqGOUBdkDmvFZzq4kAlw38lx8bLkZxDqJ\n" +
+        "sS+xFQIDAQABAkByx/5Oo2hQ/w2q4L8z+NTRlJ3vdl8iIDtC/4XPnfYfnGptnpG6\n" +
+        "ZThQRvbMZiai0xHQPQMszvAHjZVme1eDl3EBAiEA3aKJHynPVCEJhpfCLWuMwX5J\n" +
+        "1LntwJO7NTOyU5m8rPECIQDTpzn5X44r2rzWBDna/Sx7HW9IWCxNgUD2Eyi2nA7W\n" +
+        "ZQIgJerEorw4aCAuzQPxiGu57PB6GRamAihEAtoRTBQlH0ECIQDN08FgTtnesgCU\n" +
+        "DFYLLcw1CiHvc7fZw4neBDHCrC8NtQIgA8TOUkGnpCZlQ0KaI8KfKWI+vxFcgFnH\n" +
+        "3fnqsTgaUs4=";
+
+    static char passphrase[] = "passphrase".toCharArray();
+
+    /*
+     * Is the server ready to serve?
+     */
+    volatile static boolean serverReady = false;
+
+    /*
+     * Turn on SSL debugging?
+     */
+    static boolean debug = false;
+
+    /*
+     * Define the server side of the test.
+     *
+     * If the server prematurely exits, serverReady will be set to true
+     * to avoid infinite hangs.
+     */
+    void doServerSide() throws Exception {
+        SSLContext context = generateSSLContext(null, targetCertStr,
+                                            targetPrivateKey);
+        SSLServerSocketFactory sslssf = context.getServerSocketFactory();
+        SSLServerSocket sslServerSocket =
+            (SSLServerSocket)sslssf.createServerSocket(serverPort);
+        serverPort = sslServerSocket.getLocalPort();
+
+        /*
+         * Signal Client, we're ready for his connect.
+         */
+        serverReady = true;
+
+        try (SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept()) {
+            InputStream sslIS = sslSocket.getInputStream();
+            OutputStream sslOS = sslSocket.getOutputStream();
+
+            sslIS.read();
+            sslOS.write('A');
+            sslOS.flush();
+
+            throw new Exception(
+                    "RSA keys shorter than 1024 bits should be disabled");
+        } catch (SSLHandshakeException sslhe) {
+            // the expected exception, ignore
+        }
+    }
+
+    /*
+     * Define the client side of the test.
+     *
+     * If the server prematurely exits, serverReady will be set to true
+     * to avoid infinite hangs.
+     */
+    void doClientSide() throws Exception {
+
+        /*
+         * Wait for server to get started.
+         */
+        while (!serverReady) {
+            Thread.sleep(50);
+        }
+
+        SSLContext context = generateSSLContext(trustedCertStr, null, null);
+        SSLSocketFactory sslsf = context.getSocketFactory();
+
+        try (SSLSocket sslSocket =
+            (SSLSocket)sslsf.createSocket("localhost", serverPort)) {
+
+            // only enable the target protocol
+            sslSocket.setEnabledProtocols(new String[] {enabledProtocol});
+
+            // enable a block cipher
+            sslSocket.setEnabledCipherSuites(
+                new String[] {"TLS_DHE_RSA_WITH_AES_128_CBC_SHA"});
+
+            InputStream sslIS = sslSocket.getInputStream();
+            OutputStream sslOS = sslSocket.getOutputStream();
+
+            sslOS.write('B');
+            sslOS.flush();
+            sslIS.read();
+
+            throw new Exception(
+                    "RSA keys shorter than 1024 bits should be disabled");
+        } catch (SSLHandshakeException sslhe) {
+            // the expected exception, ignore
+        }
+    }
+
+    /*
+     * =============================================================
+     * The remainder is just support stuff
+     */
+    private static String tmAlgorithm;        // trust manager
+    private static String enabledProtocol;    // the target protocol
+
+    private static void parseArguments(String[] args) {
+        tmAlgorithm = args[0];
+        enabledProtocol = args[1];
+    }
+
+    private static SSLContext generateSSLContext(String trustedCertStr,
+            String keyCertStr, String keySpecStr) throws Exception {
+
+        // generate certificate from cert string
+        CertificateFactory cf = CertificateFactory.getInstance("X.509");
+
+        // create a key store
+        KeyStore ks = KeyStore.getInstance("JKS");
+        ks.load(null, null);
+
+        // import the trused cert
+        Certificate trusedCert = null;
+        ByteArrayInputStream is = null;
+        if (trustedCertStr != null) {
+            is = new ByteArrayInputStream(trustedCertStr.getBytes());
+            trusedCert = cf.generateCertificate(is);
+            is.close();
+
+            ks.setCertificateEntry("RSA Export Signer", trusedCert);
+        }
+
+        if (keyCertStr != null) {
+            // generate the private key.
+            PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
+                                new BASE64Decoder().decodeBuffer(keySpecStr));
+            KeyFactory kf = KeyFactory.getInstance("RSA");
+            RSAPrivateKey priKey =
+                    (RSAPrivateKey)kf.generatePrivate(priKeySpec);
+
+            // generate certificate chain
+            is = new ByteArrayInputStream(keyCertStr.getBytes());
+            Certificate keyCert = cf.generateCertificate(is);
+            is.close();
+
+            Certificate[] chain = null;
+            if (trusedCert != null) {
+                chain = new Certificate[2];
+                chain[0] = keyCert;
+                chain[1] = trusedCert;
+            } else {
+                chain = new Certificate[1];
+                chain[0] = keyCert;
+            }
+
+            // import the key entry.
+            ks.setKeyEntry("Whatever", priKey, passphrase, chain);
+        }
+
+        // create SSL context
+        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
+        tmf.init(ks);
+
+        SSLContext ctx = SSLContext.getInstance("TLS");
+        if (keyCertStr != null && !keyCertStr.isEmpty()) {
+            KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
+            kmf.init(ks, passphrase);
+
+            ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
+            ks = null;
+        } else {
+            ctx.init(null, tmf.getTrustManagers(), null);
+        }
+
+        return ctx;
+    }
+
+
+    // use any free port by default
+    volatile int serverPort = 0;
+
+    volatile Exception serverException = null;
+    volatile Exception clientException = null;
+
+    public static void main(String[] args) throws Exception {
+        if (debug)
+            System.setProperty("javax.net.debug", "all");
+
+        /*
+         * Get the customized arguments.
+         */
+        parseArguments(args);
+
+        /*
+         * Start the tests.
+         */
+        new DisabledShortRSAKeys();
+    }
+
+    Thread clientThread = null;
+    Thread serverThread = null;
+
+    /*
+     * Primary constructor, used to drive remainder of the test.
+     *
+     * Fork off the other side, then do your work.
+     */
+    DisabledShortRSAKeys() throws Exception {
+        try {
+            if (separateServerThread) {
+                startServer(true);
+                startClient(false);
+            } else {
+                startClient(true);
+                startServer(false);
+            }
+        } catch (Exception e) {
+            // swallow for now.  Show later
+        }
+
+        /*
+         * Wait for other side to close down.
+         */
+        if (separateServerThread) {
+            serverThread.join();
+        } else {
+            clientThread.join();
+        }
+
+        /*
+         * When we get here, the test is pretty much over.
+         * Which side threw the error?
+         */
+        Exception local;
+        Exception remote;
+        String whichRemote;
+
+        if (separateServerThread) {
+            remote = serverException;
+            local = clientException;
+            whichRemote = "server";
+        } else {
+            remote = clientException;
+            local = serverException;
+            whichRemote = "client";
+        }
+
+        /*
+         * If both failed, return the curthread's exception, but also
+         * print the remote side Exception
+         */
+        if ((local != null) && (remote != null)) {
+            System.out.println(whichRemote + " also threw:");
+            remote.printStackTrace();
+            System.out.println();
+            throw local;
+        }
+
+        if (remote != null) {
+            throw remote;
+        }
+
+        if (local != null) {
+            throw local;
+        }
+    }
+
+    void startServer(boolean newThread) throws Exception {
+        if (newThread) {
+            serverThread = new Thread() {
+                public void run() {
+                    try {
+                        doServerSide();
+                    } catch (Exception e) {
+                        /*
+                         * Our server thread just died.
+                         *
+                         * Release the client, if not active already...
+                         */
+                        System.err.println("Server died...");
+                        serverReady = true;
+                        serverException = e;
+                    }
+                }
+            };
+            serverThread.start();
+        } else {
+            try {
+                doServerSide();
+            } catch (Exception e) {
+                serverException = e;
+            } finally {
+                serverReady = true;
+            }
+        }
+    }
+
+    void startClient(boolean newThread) throws Exception {
+        if (newThread) {
+            clientThread = new Thread() {
+                public void run() {
+                    try {
+                        doClientSide();
+                    } catch (Exception e) {
+                        /*
+                         * Our client thread just died.
+                         */
+                        System.err.println("Client died...");
+                        clientException = e;
+                    }
+                }
+            };
+            clientThread.start();
+        } else {
+            try {
+                doClientSide();
+            } catch (Exception e) {
+                clientException = e;
+            }
+        }
+    }
+}
--- a/jdk/test/sun/security/ssl/javax/net/ssl/TLSv12/ShortRSAKey512.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/ssl/javax/net/ssl/TLSv12/ShortRSAKey512.java	Tue Jan 22 11:54:16 2013 -0800
@@ -23,6 +23,9 @@
  * questions.
  */
 
+// This test case relies on updated static security property, no way to re-use
+// security property in samevm/agentvm mode.
+
 /*
  * @test
  * @bug 7106773
@@ -38,6 +41,7 @@
 import java.util.*;
 import java.io.*;
 import javax.net.ssl.*;
+import java.security.Security;
 import java.security.KeyStore;
 import java.security.KeyFactory;
 import java.security.cert.Certificate;
@@ -275,6 +279,10 @@
     volatile Exception clientException = null;
 
     public static void main(String[] args) throws Exception {
+        // reset the security property to make sure that the algorithms
+        // and keys used in this test are not disabled.
+        Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
+
         if (debug)
             System.setProperty("javax.net.debug", "all");
 
--- a/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/HttpsProxyStackOverflow.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/HttpsProxyStackOverflow.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/sun/security/tools/jarsigner/concise_jarsigner.sh	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/security/tools/jarsigner/concise_jarsigner.sh	Tue Jan 22 11:54:16 2013 -0800
@@ -44,10 +44,10 @@
     ;;
 esac
 
-# Choose 512-bit RSA to make sure it runs fine and fast on all platforms. In fact,
-# every keyalg/keysize combination is OK for this test.
+# Choose 1024-bit RSA to make sure it runs fine and fast on all platforms. In
+# fact, every keyalg/keysize combination is OK for this test.
 
-KT="$TESTJAVA${FS}bin${FS}keytool -storepass changeit -keypass changeit -keystore js.jks -keyalg rsa -keysize 512"
+KT="$TESTJAVA${FS}bin${FS}keytool -storepass changeit -keypass changeit -keystore js.jks -keyalg rsa -keysize 1024"
 JAR=$TESTJAVA${FS}bin${FS}jar
 JARSIGNER=$TESTJAVA${FS}bin${FS}jarsigner
 JAVAC=$TESTJAVA${FS}bin${FS}javac
--- a/jdk/test/sun/text/resources/LocaleData	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/text/resources/LocaleData	Tue Jan 22 11:54:16 2013 -0800
@@ -7657,3 +7657,9 @@
 FormatData/zh/DayNarrows/4=\u56db
 FormatData/zh/DayNarrows/5=\u4e94
 FormatData/zh/DayNarrows/6=\u516d
+
+# bug 7195759
+CurrencyNames//ZMW=ZMW
+
+# bug 7114053
+LocaleNames/sq/sq=shqip
--- a/jdk/test/sun/text/resources/LocaleDataTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/text/resources/LocaleDataTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -34,7 +34,7 @@
  *      6509039 6609737 6610748 6645271 6507067 6873931 6450945 6645268 6646611
  *      6645405 6650730 6910489 6573250 6870908 6585666 6716626 6914413 6916787
  *      6919624 6998391 7019267 7020960 7025837 7020583 7036905 7066203 7101495
- *      7003124 7085757 7028073 7171028 7189611 8000983
+ *      7003124 7085757 7028073 7171028 7189611 8000983 7195759 7114053
  * @summary Verify locale data
  *
  */
--- a/jdk/test/sun/tools/jps/jps-V_2.sh	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/tools/jps/jps-V_2.sh	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2004, 2011,Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/sun/tools/jrunscript/common.sh	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/sun/tools/jrunscript/common.sh	Tue Jan 22 11:54:16 2013 -0800
@@ -63,8 +63,4 @@
     JRUNSCRIPT="${TESTJAVA}/bin/jrunscript"
     JAVAC="${TESTJAVA}/bin/javac"
     JAVA="${TESTJAVA}/bin/java"
-    # needed to get full headless behavior on Mac
-    if [ "$OS" = "Darwin" ]; then
-        export AWT_TOOLKIT=XToolkit
-    fi
 }
--- a/jdk/test/tools/jar/JarBackSlash.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/tools/jar/JarBackSlash.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/tools/launcher/FXLauncherTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/tools/launcher/FXLauncherTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8001533
+ * @bug 8001533 8004547
  * @summary Test launching FX application with java -jar
  * Test uses main method and blank main method, a jfx app class and an incorrest
  * jfx app class, a main-class for the manifest, a bogus one and none.
@@ -47,6 +47,8 @@
 
     /* standard main class can be used as java main for fx app class */
     static final String StdMainClass = "helloworld.HelloWorld";
+    static final String ExtMainClass = "helloworld.ExtHello";
+    static final String NonFXMainClass = "helloworld.HelloJava";
     static int testcount = 0;
 
     /* a main method and a blank. */
@@ -107,9 +109,7 @@
     }
 
     /*
-     * Create class to extend fx java file for test application
-     * TODO: make test to create java file and this extension of the java file
-     *      and jar them together an run app via this java class.
+     * Create class that extends HelloWorld instead of Application
      */
     static void createExtJavaFile(String mainmethod) {
         try {
@@ -125,16 +125,48 @@
             compile("-cp", ".", "-d", ".", mainClass + JAVA_FILE_EXT);
         } catch (java.io.IOException ioe) {
             ioe.printStackTrace();
-            throw new RuntimeException("Failed creating HelloWorld.");
+            throw new RuntimeException("Failed creating ExtHello.");
+        }
+    }
+
+    /*
+     * Create non-JavaFX class for testing if jfxrt.jar is being loaded
+     * when it shouldn't be
+     */
+    static void createNonFXJavaFile() {
+        try {
+            String mainClass = "HelloJava";
+            List<String> contents = new ArrayList<>();
+            contents.add("package helloworld;");
+            contents.add("public class HelloJava {");
+            contents.add("    public static void main(String[] args) {");
+            contents.add("        for(String aa : args)");
+            contents.add("            System.out.println(\"arg: \" + aa);" );
+            contents.add("    }");
+            contents.add("}");
+            // Create and compile java source.
+            MainJavaFile = new File(mainClass + JAVA_FILE_EXT);
+            createFile(MainJavaFile, contents);
+            compile("-cp", ".", "-d", ".", mainClass + JAVA_FILE_EXT);
+        } catch (java.io.IOException ioe) {
+            ioe.printStackTrace();
+            throw new RuntimeException("Failed creating HelloJava.");
         }
     }
 
     // Create manifest for test fx application
-    static List<String> createManifestContents(String mainclassentry) {
+    static List<String> createManifestContents(String mainClassEntry, String fxMainEntry) {
         List<String> mcontents = new ArrayList<>();
         mcontents.add("Manifest-Version: 1.0");
         mcontents.add("Created-By: FXLauncherTest");
-        mcontents.add("Main-Class: " + mainclassentry);
+        if (mainClassEntry != null) {
+            mcontents.add("Main-Class: " + mainClassEntry);
+            System.out.println("Main-Class: " + mainClassEntry);
+        }
+        if (fxMainEntry != null) {
+            mcontents.add("JavaFX-Application-Class: " + fxMainEntry);
+            System.out.println("JavaFX-Application-Class: " + fxMainEntry);
+        }
         return mcontents;
     }
 
@@ -175,31 +207,41 @@
 
     /*
      * Set Main-Class and iterate main_methods.
-     * Try launching with both -jar and -cp methods.
+     * Try launching with both -jar and -cp methods, with and without FX main
+     * class manifest entry.
      * All cases should run.
+     *
+     * See sun.launcher.LauncherHelper$FXHelper for more details on how JavaFX
+     * applications are launched.
      */
     @Test
     static void testBasicFXApp() throws Exception {
-        testBasicFXApp(true);
-        testBasicFXApp(false);
+        testBasicFXApp(true, false);    // -cp, no JAC
+        testBasicFXApp(false, true);    // -jar, with JAC
+        testBasicFXApp(false, false);   // -jar, no JAC
     }
 
-    static void testBasicFXApp(boolean useCP) throws Exception {
+    static void testBasicFXApp(boolean useCP, boolean setFXMainClass) throws Exception {
         String testname = "testBasicFXApp";
+        if (useCP) {
+            testname = testname.concat("_useCP");
+        }
+        String fxMC = StdMainClass;
+        if (!setFXMainClass) {
+            testname = testname.concat("_noJAC");
+            fxMC = null;
+        }
         for (String mm : MAIN_METHODS) {
             testcount++;
             line();
-            System.out.println("test# " + testcount +
-                "-  Main method: " + mm +
-                 ";  MF main class: " + StdMainClass);
+            System.out.println("test# " + testcount + "-  Main method: " + mm);
             createJavaFile(mm);
-            createFile(ManifestFile, createManifestContents(StdMainClass));
+            createFile(ManifestFile, createManifestContents(StdMainClass, fxMC));
             createJar(FXtestJar, ManifestFile);
             String sTestJar = FXtestJar.getAbsolutePath();
             TestResult tr;
             if (useCP) {
                 tr = doExec(javaCmd, "-cp", sTestJar, StdMainClass, APP_PARMS[0], APP_PARMS[1]);
-                testname = testname.concat("_useCP");
             } else {
                 tr = doExec(javaCmd, "-jar", sTestJar, APP_PARMS[0], APP_PARMS[1]);
             }
@@ -224,26 +266,33 @@
      */
     @Test
     static void testExtendFXApp() throws Exception {
-        testExtendFXApp(true);
-        testExtendFXApp(false);
+        testExtendFXApp(true, false);   // -cp, no JAC
+        testExtendFXApp(false, true);   // -jar, with JAC
+        testExtendFXApp(false, false);  // -jar, no JAC
     }
 
-    static void testExtendFXApp(boolean useCP) throws Exception {
+    static void testExtendFXApp(boolean useCP, boolean setFXMainClass) throws Exception {
         String testname = "testExtendFXApp";
+        if (useCP) {
+            testname = testname.concat("_useCP");
+        }
+        String fxMC = ExtMainClass;
+        if (!setFXMainClass) {
+            testname = testname.concat("_noJAC");
+            fxMC = null;
+        }
         for (String mm : MAIN_METHODS) {
             testcount++;
             line();
-            System.out.println("test# " + testcount +
-                "-  Main method: " + mm + ";  MF main class: " + StdMainClass);
+            System.out.println("test# " + testcount + "-  Main method: " + mm);
             createJavaFile(mm);
             createExtJavaFile(mm);
-            createFile(ManifestFile, createManifestContents(StdMainClass));
+            createFile(ManifestFile, createManifestContents(ExtMainClass, fxMC));
             createJar(FXtestJar, ManifestFile);
             String sTestJar = FXtestJar.getAbsolutePath();
             TestResult tr;
             if (useCP) {
-                tr = doExec(javaCmd, "-cp", sTestJar, StdMainClass, APP_PARMS[0], APP_PARMS[1]);
-                testname = testname.concat("_useCP");
+                tr = doExec(javaCmd, "-cp", sTestJar, ExtMainClass, APP_PARMS[0], APP_PARMS[1]);
             } else {
                 tr = doExec(javaCmd, "-jar", sTestJar, APP_PARMS[0], APP_PARMS[1]);
             }
@@ -256,27 +305,82 @@
                     }
                 }
             }
-            checkStatus(tr, testname, testcount, StdMainClass);
+            checkStatus(tr, testname, testcount, ExtMainClass);
         }
     }
 
     /*
+     * Ensure we can NOT launch a FX app jar with no Main-Class manifest entry
+     */
+    @Test
+    static void testMissingMC() throws Exception {
+        String testname = "testMissingMC";
+        testcount++;
+        line();
+        System.out.println("test# " + testcount + ": abort on missing Main-Class");
+        createJavaFile(" "); // no main() needed
+        createFile(ManifestFile, createManifestContents(null, StdMainClass)); // No MC, but supply JAC
+        createJar(FXtestJar, ManifestFile);
+        String sTestJar = FXtestJar.getAbsolutePath();
+        TestResult tr = doExec(javaCmd, "-jar", sTestJar, APP_PARMS[0], APP_PARMS[1]);
+        tr.checkNegative(); // should abort if no Main-Class
+        if (tr.testStatus) {
+            if (!tr.contains("no main manifest attribute")) {
+                System.err.println("ERROR: launcher did not abort properly");
+            }
+        } else {
+            System.err.println("ERROR: jar executed with no Main-Class!");
+        }
+        checkStatus(tr, testname, testcount, StdMainClass);
+    }
+
+    /*
      * test to ensure that we don't load any extraneous fx jars when
      * launching a standard java application
+     * Test both -cp and -jar methods since they use different code paths.
+     * Neither case should cause jfxrt.jar to be loaded.
      */
     @Test
-    static void testExtraneousJars()throws Exception {
+    static void testExtraneousJars() throws Exception {
+        testExtraneousJars(true);
+        testExtraneousJars(false);
+    }
+
+    static void testExtraneousJars(boolean useCP) throws Exception {
         String testname = "testExtraneousJars";
+        if (useCP) {
+            testname = testname.concat("_useCP");
+        }
         testcount++;
         line();
-        System.out.println("test# " + testcount);
-        TestResult tr = doExec(javacCmd, "-J-verbose:class", "-version");
-        if (!tr.notContains("jfxrt.jar")) {
-            System.out.println("testing for extraneous jfxrt jar");
-            System.out.println(tr);
-            throw new Exception("jfxrt.jar is being loaded by javac!!!");
+        System.out.println("test# " + testcount
+                + ": test for erroneous jfxrt.jar loading");
+        createNonFXJavaFile();
+        createFile(ManifestFile, createManifestContents(NonFXMainClass, null));
+        createJar(FXtestJar, ManifestFile);
+        String sTestJar = FXtestJar.getAbsolutePath();
+        TestResult tr;
+
+        if (useCP) {
+            tr = doExec(javaCmd, "-verbose:class", "-cp", sTestJar, NonFXMainClass, APP_PARMS[0], APP_PARMS[1]);
+        } else {
+            tr = doExec(javaCmd, "-verbose:class", "-jar", sTestJar, APP_PARMS[0], APP_PARMS[1]);
         }
-        checkStatus(tr, testname, testcount, StdMainClass);
+        tr.checkPositive();
+        if (tr.testStatus) {
+            if (!tr.notContains("jfxrt.jar")) {
+                System.out.println("testing for extraneous jfxrt jar");
+                System.out.println(tr);
+                throw new Exception("jfxrt.jar is being loaded, it should not be!");
+            }
+            for (String p : APP_PARMS) {
+                if (!tr.contains(p)) {
+                    System.err.println("ERROR: Did not find "
+                            + p + " in output!");
+                }
+            }
+        }
+        checkStatus(tr, testname, testcount, NonFXMainClass);
     }
 
     public static void main(String... args) throws Exception {
--- a/jdk/test/tools/launcher/UnicodeTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/tools/launcher/UnicodeTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2012, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/jdk/test/tools/launcher/VersionCheck.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/jdk/test/tools/launcher/VersionCheck.java	Tue Jan 22 11:54:16 2013 -0800
@@ -68,6 +68,7 @@
         "jcmd",
         "jconsole",
         "jcontrol",
+        "jdeps",
         "jinfo",
         "jmap",
         "jps",
--- a/langtools/.hgtags	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/.hgtags	Tue Jan 22 11:54:16 2013 -0800
@@ -190,3 +190,8 @@
 20230f8b0eef92a57043735fc2ca00fea7e510a0 jdk8-b66
 303b09787a69136cd2019f9edfed3f308572e9fc jdk8-b67
 014a6a11dfe5ddc23ec8c76bb42ac998dbf49acb jdk8-b68
+d7360bf35ee1f40ff78c2e83a22b5446ee464346 jdk8-b69
+47f71d7c124f24c2fe2dfc49865b332345b458ed jdk8-b70
+467e4d9281bcf119eaec42af1423c96bd401871c jdk8-b71
+6f0986ed9b7e11d6eb06618f27e20b18f19fb797 jdk8-b72
+8d0baee36c7184d55c80354b45704c37d6b7ac79 jdk8-b73
--- a/langtools/make/Makefile-classic	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/make/Makefile-classic	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2007, 2012 Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
--- a/langtools/make/build.properties	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/make/build.properties	Tue Jan 22 11:54:16 2013 -0800
@@ -68,7 +68,7 @@
 # set the following to -version to verify the versions of javac being used
 javac.version.opt =
 # in time, there should be no exceptions to -Xlint:all
-javac.lint.opts = -Xlint:all,-deprecation -Werror
+javac.lint.opts = -Xlint:all -Werror
 
 # options for the <javadoc> task for javac
 #javadoc.jls3.url=http://java.sun.com/docs/books/jls/
@@ -117,7 +117,8 @@
         javax/lang/model/ \
         javax/tools/ \
         com/sun/source/ \
-        com/sun/tools/javac/
+        com/sun/tools/javac/ \
+        com/sun/tools/doclint/
 
 javac.tests = \
         tools/javac
@@ -152,6 +153,7 @@
 javap.includes = \
         com/sun/tools/classfile/ \
         com/sun/tools/javap/ \
+        com/sun/tools/jdeps/ \
         sun/tools/javap/
 
 javap.tests = \
--- a/langtools/makefiles/BuildLangtools.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/makefiles/BuildLangtools.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -75,6 +75,7 @@
 	printf "jdk=$(JDK_VERSION)\nfull=$(FULL_VERSION)\nrelease=$(RELEASE)\n" > $(LANGTOOLS_OUTPUTDIR)/gensrc/com/sun/tools/javah/resources/version.properties
 	printf "jdk=$(JDK_VERSION)\nfull=$(FULL_VERSION)\nrelease=$(RELEASE)\n" > $(LANGTOOLS_OUTPUTDIR)/gensrc/com/sun/tools/javap/resources/version.properties
 	printf "jdk=$(JDK_VERSION)\nfull=$(FULL_VERSION)\nrelease=$(RELEASE)\n" > $(LANGTOOLS_OUTPUTDIR)/gensrc/com/sun/tools/javac/resources/version.properties
+	printf "jdk=$(JDK_VERSION)\nfull=$(FULL_VERSION)\nrelease=$(RELEASE)\n" > $(LANGTOOLS_OUTPUTDIR)/gensrc/com/sun/tools/jdeps/resources/version.properties
 	echo Compiling $(words $(PROPSOURCES) v1 v2 v3) properties into resource bundles
 	$(TOOL_COMPILEPROPS_CMD) $(PROPCMDLINE) \
 		-compile 	$(LANGTOOLS_OUTPUTDIR)/gensrc/com/sun/tools/javah/resources/version.properties \
@@ -85,6 +86,9 @@
 				java.util.ListResourceBundle \
 		-compile	$(LANGTOOLS_OUTPUTDIR)/gensrc/com/sun/tools/javac/resources/version.properties \
 				$(LANGTOOLS_OUTPUTDIR)/gensrc/com/sun/tools/javac/resources/version.java \
+				java.util.ListResourceBundle \
+		-compile	$(LANGTOOLS_OUTPUTDIR)/gensrc/com/sun/tools/jdeps/resources/version.properties \
+				$(LANGTOOLS_OUTPUTDIR)/gensrc/com/sun/tools/jdeps/resources/version.java \
 				java.util.ListResourceBundle
 	echo PROPS_ARE_CREATED=yes > $@
 
--- a/langtools/src/share/classes/com/sun/javadoc/AnnotationDesc.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/javadoc/AnnotationDesc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -52,6 +52,12 @@
      */
     ElementValuePair[] elementValues();
 
+    /**
+     * Check for the synthesized bit on the annotation.
+     *
+     * @return true if the annotation is synthesized.
+     */
+    boolean isSynthesized();
 
     /**
      * Represents an association between an annotation type element
--- a/langtools/src/share/classes/com/sun/javadoc/ClassDoc.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/javadoc/ClassDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -66,6 +66,12 @@
     boolean isExternalizable();
 
     /**
+     * Return true if this class can be used as a target type of a lambda expression
+     * or method reference.
+     */
+    boolean isFunctionalInterface();
+
+    /**
      * Return the serialization methods for this class or
      * interface.
      *
--- a/langtools/src/share/classes/com/sun/javadoc/MethodDoc.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/javadoc/MethodDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -39,6 +39,11 @@
     boolean isAbstract();
 
     /**
+     * Return true if this method is default
+     */
+    boolean isDefault();
+
+    /**
      * Get return type.
      *
      * @return the return type of this method, null if it
--- a/langtools/src/share/classes/com/sun/source/util/DocTrees.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/source/util/DocTrees.java	Tue Jan 22 11:54:16 2013 -0800
@@ -45,9 +45,7 @@
      * @throws IllegalArgumentException if the task does not support the Trees API.
      */
     public static DocTrees instance(CompilationTask task) {
-        if (!task.getClass().getName().equals("com.sun.tools.javac.api.JavacTaskImpl"))
-            throw new IllegalArgumentException();
-        return (DocTrees) getJavacTrees(CompilationTask.class, task);
+        return (DocTrees) Trees.instance(task);
     }
 
     /**
--- a/langtools/src/share/classes/com/sun/source/util/JavacTask.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/source/util/JavacTask.java	Tue Jan 22 11:54:16 2013 -0800
@@ -139,6 +139,7 @@
      * @see com.sun.source.util.Trees#getTypeMirror
      */
     public abstract TypeMirror getTypeMirror(Iterable<? extends Tree> path);
+
     /**
      * Get a utility object for dealing with program elements.
      */
--- a/langtools/src/share/classes/com/sun/source/util/Plugin.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/source/util/Plugin.java	Tue Jan 22 11:54:16 2013 -0800
@@ -56,9 +56,9 @@
     String getName();
 
     /**
-     * Invoke the plug-in for a given compilation task.
+     * Initialize the plug-in for a given compilation task.
      * @param task The compilation task that has just been started
      * @param args Arguments, if any, for the plug-in
      */
-    void call(JavacTask task, String... args);
+    void init(JavacTask task, String... args);
 }
--- a/langtools/src/share/classes/com/sun/source/util/TreePath.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/source/util/TreePath.java	Tue Jan 22 11:54:16 2013 -0800
@@ -60,14 +60,20 @@
                 this.path = path;
             }
         }
+
         class PathFinder extends TreePathScanner<TreePath,Tree> {
             public TreePath scan(Tree tree, Tree target) {
-                if (tree == target)
+                if (tree == target) {
                     throw new Result(new TreePath(getCurrentPath(), target));
+                }
                 return super.scan(tree, target);
             }
         }
 
+        if (path.getLeaf() == target) {
+            return path;
+        }
+
         try {
             new PathFinder().scan(path, target);
         } catch (Result result) {
--- a/langtools/src/share/classes/com/sun/tools/classfile/Attribute.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/classfile/Attribute.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,6 +51,7 @@
     public static final String LineNumberTable          = "LineNumberTable";
     public static final String LocalVariableTable       = "LocalVariableTable";
     public static final String LocalVariableTypeTable   = "LocalVariableTypeTable";
+    public static final String MethodParameters         = "MethodParameters";
     public static final String RuntimeVisibleAnnotations = "RuntimeVisibleAnnotations";
     public static final String RuntimeInvisibleAnnotations = "RuntimeInvisibleAnnotations";
     public static final String RuntimeVisibleParameterAnnotations = "RuntimeVisibleParameterAnnotations";
@@ -113,6 +114,7 @@
             standardAttributes.put(LocalVariableTypeTable, LocalVariableTypeTable_attribute.class);
 
             if (!compat) { // old javap does not recognize recent attributes
+                standardAttributes.put(MethodParameters, MethodParameters_attribute.class);
                 standardAttributes.put(CompilationID, CompilationID_attribute.class);
                 standardAttributes.put(RuntimeInvisibleAnnotations, RuntimeInvisibleAnnotations_attribute.class);
                 standardAttributes.put(RuntimeInvisibleParameterAnnotations, RuntimeInvisibleParameterAnnotations_attribute.class);
@@ -171,6 +173,7 @@
         R visitLineNumberTable(LineNumberTable_attribute attr, P p);
         R visitLocalVariableTable(LocalVariableTable_attribute attr, P p);
         R visitLocalVariableTypeTable(LocalVariableTypeTable_attribute attr, P p);
+        R visitMethodParameters(MethodParameters_attribute attr, P p);
         R visitRuntimeVisibleAnnotations(RuntimeVisibleAnnotations_attribute attr, P p);
         R visitRuntimeInvisibleAnnotations(RuntimeInvisibleAnnotations_attribute attr, P p);
         R visitRuntimeVisibleParameterAnnotations(RuntimeVisibleParameterAnnotations_attribute attr, P p);
--- a/langtools/src/share/classes/com/sun/tools/classfile/ClassWriter.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/classfile/ClassWriter.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,6 +1,6 @@
 
 /*
- * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -479,6 +479,15 @@
             out.writeShort(entry.index);
         }
 
+        public Void visitMethodParameters(MethodParameters_attribute attr, ClassOutputStream out) {
+            out.writeByte(attr.method_parameter_table.length);
+            for (MethodParameters_attribute.Entry e : attr.method_parameter_table) {
+                out.writeShort(e.name_index);
+                out.writeInt(e.flags);
+            }
+            return null;
+        }
+
         public Void visitRuntimeVisibleAnnotations(RuntimeVisibleAnnotations_attribute attr, ClassOutputStream out) {
             annotationWriter.write(attr.annotations, out);
             return null;
--- a/langtools/src/share/classes/com/sun/tools/classfile/Dependencies.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/classfile/Dependencies.java	Tue Jan 22 11:54:16 2013 -0800
@@ -142,6 +142,15 @@
     }
 
     /**
+     * Get a finder to do class dependency analysis.
+     *
+     * @return a Class dependency finder
+     */
+    public static Finder getClassDependencyFinder() {
+        return new ClassDependencyFinder();
+    }
+
+    /**
      * Get the finder used to locate the dependencies for a class.
      * @return the finder
      */
@@ -246,8 +255,6 @@
         return results;
     }
 
-
-
     /**
      * Find the dependencies of a class, using the current
      * {@link Dependencies#getFinder finder} and
@@ -306,38 +313,44 @@
      * A location identifying a class.
      */
     static class SimpleLocation implements Location {
-        public SimpleLocation(String className) {
-            this.className = className;
+        public SimpleLocation(String name) {
+            this.name = name;
+            this.className = name.replace('/', '.').replace('$', '.');
         }
 
-        /**
-         * Get the name of the class being depended on. This name will be used to
-         * locate the class file for transitive dependency analysis.
-         * @return the name of the class being depended on
-         */
+        public String getName() {
+            return name;
+        }
+
         public String getClassName() {
             return className;
         }
 
+        public String getPackageName() {
+            int i = name.lastIndexOf('/');
+            return (i > 0) ? name.substring(0, i).replace('/', '.') : "";
+        }
+
         @Override
         public boolean equals(Object other) {
             if (this == other)
                 return true;
             if (!(other instanceof SimpleLocation))
                 return false;
-            return (className.equals(((SimpleLocation) other).className));
+            return (name.equals(((SimpleLocation) other).name));
         }
 
         @Override
         public int hashCode() {
-            return className.hashCode();
+            return name.hashCode();
         }
 
         @Override
         public String toString() {
-            return className;
+            return name;
         }
 
+        private String name;
         private String className;
     }
 
@@ -431,9 +444,7 @@
         }
 
         public boolean accepts(Dependency dependency) {
-            String cn = dependency.getTarget().getClassName();
-            int lastSep = cn.lastIndexOf("/");
-            String pn = (lastSep == -1 ? "" : cn.substring(0, lastSep));
+            String pn = dependency.getTarget().getPackageName();
             if (packageNames.contains(pn))
                 return true;
 
@@ -451,8 +462,6 @@
         private final boolean matchSubpackages;
     }
 
-
-
     /**
      * This class identifies class names directly or indirectly in the constant pool.
      */
@@ -462,6 +471,26 @@
             for (CPInfo cpInfo: classfile.constant_pool.entries()) {
                 v.scan(cpInfo);
             }
+            try {
+                v.addClass(classfile.super_class);
+                v.addClasses(classfile.interfaces);
+                v.scan(classfile.attributes);
+
+                for (Field f : classfile.fields) {
+                    v.scan(f.descriptor, f.attributes);
+                }
+                for (Method m : classfile.methods) {
+                    v.scan(m.descriptor, m.attributes);
+                    Exceptions_attribute e =
+                        (Exceptions_attribute)m.attributes.get(Attribute.Exceptions);
+                    if (e != null) {
+                        v.addClasses(e.exception_index_table);
+                    }
+                }
+            } catch (ConstantPoolException e) {
+                throw new ClassFileError(e);
+            }
+
             return v.deps;
         }
     }
@@ -558,9 +587,7 @@
             void scan(Descriptor d, Attributes attrs) {
                 try {
                     scan(new Signature(d.index).getType(constant_pool));
-                    Signature_attribute sa = (Signature_attribute) attrs.get(Attribute.Signature);
-                    if (sa != null)
-                        scan(new Signature(sa.signature_index).getType(constant_pool));
+                    scan(attrs);
                 } catch (ConstantPoolException e) {
                     throw new ClassFileError(e);
                 }
@@ -574,6 +601,43 @@
                 t.accept(this, null);
             }
 
+            void scan(Attributes attrs) {
+                try {
+                    Signature_attribute sa = (Signature_attribute)attrs.get(Attribute.Signature);
+                    if (sa != null)
+                        scan(sa.getParsedSignature().getType(constant_pool));
+
+                    scan((RuntimeVisibleAnnotations_attribute)
+                            attrs.get(Attribute.RuntimeVisibleAnnotations));
+                    scan((RuntimeVisibleParameterAnnotations_attribute)
+                            attrs.get(Attribute.RuntimeVisibleParameterAnnotations));
+                } catch (ConstantPoolException e) {
+                    throw new ClassFileError(e);
+                }
+            }
+
+            private void scan(RuntimeAnnotations_attribute attr) throws ConstantPoolException {
+                if (attr == null) {
+                    return;
+                }
+                for (int i = 0; i < attr.annotations.length; i++) {
+                    int index = attr.annotations[i].type_index;
+                    scan(new Signature(index).getType(constant_pool));
+                }
+            }
+
+            private void scan(RuntimeParameterAnnotations_attribute attr) throws ConstantPoolException {
+                if (attr == null) {
+                    return;
+                }
+                for (int param = 0; param < attr.parameter_annotations.length; param++) {
+                    for (int i = 0; i < attr.parameter_annotations[param].length; i++) {
+                        int index = attr.parameter_annotations[param][i].type_index;
+                        scan(new Signature(index).getType(constant_pool));
+                    }
+                }
+            }
+
             void addClass(int index) throws ConstantPoolException {
                 if (index != 0) {
                     String name = constant_pool.getClassInfo(index).getBaseName();
@@ -698,6 +762,7 @@
                 findDependencies(type.paramTypes);
                 findDependencies(type.returnType);
                 findDependencies(type.throwsTypes);
+                findDependencies(type.typeParamTypes);
                 return null;
             }
 
@@ -709,7 +774,7 @@
 
             public Void visitClassType(ClassType type, Void p) {
                 findDependencies(type.outerType);
-                addDependency(type.name);
+                addDependency(type.getBinaryName());
                 findDependencies(type.typeArgs);
                 return null;
             }
--- a/langtools/src/share/classes/com/sun/tools/classfile/Dependency.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/classfile/Dependency.java	Tue Jan 22 11:54:16 2013 -0800
@@ -71,7 +71,19 @@
          * dependency analysis.
          * @return the name of the class containing the location.
          */
+        String getName();
+
+        /**
+         * Get the fully-qualified name of the class containing the location.
+         * @return the fully-qualified name of the class containing the location.
+         */
         String getClassName();
+
+        /**
+         * Get the package name of the class containing the location.
+         * @return the package name of the class containing the location.
+         */
+        String getPackageName();
     }
 
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/classfile/MethodParameters_attribute.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.tools.classfile;
+
+import java.io.IOException;
+
+/**
+ * See JVMS, section 4.8.13.
+ *
+ *  <p><b>This is NOT part of any supported API.
+ *  If you write code that depends on this, you do so at your own risk.
+ *  This code and its internal interfaces are subject to change or
+ *  deletion without notice.</b>
+ */
+public class MethodParameters_attribute extends Attribute {
+
+    public final int method_parameter_table_length;
+    public final Entry[] method_parameter_table;
+
+    MethodParameters_attribute(ClassReader cr,
+                              int name_index,
+                              int length)
+        throws IOException {
+        super(name_index, length);
+
+        method_parameter_table_length = cr.readUnsignedByte();
+        method_parameter_table = new Entry[method_parameter_table_length];
+        for (int i = 0; i < method_parameter_table_length; i++)
+            method_parameter_table[i] = new Entry(cr);
+    }
+
+    public MethodParameters_attribute(ConstantPool constant_pool,
+                                      Entry[] method_parameter_table)
+        throws ConstantPoolException {
+        this(constant_pool.getUTF8Index(Attribute.MethodParameters),
+             method_parameter_table);
+    }
+
+    public MethodParameters_attribute(int name_index,
+                                      Entry[] method_parameter_table) {
+        super(name_index, 1 + method_parameter_table.length * Entry.length());
+        this.method_parameter_table_length = method_parameter_table.length;
+        this.method_parameter_table = method_parameter_table;
+    }
+
+    public <R, D> R accept(Visitor<R, D> visitor, D data) {
+        return visitor.visitMethodParameters(this, data);
+    }
+
+    public static class Entry {
+        Entry(ClassReader cr) throws IOException {
+            name_index = cr.readUnsignedShort();
+            flags = cr.readInt();
+        }
+
+        public static int length() {
+            return 6;
+        }
+
+        public final int name_index;
+        public final int flags;
+    }
+
+}
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AbstractMemberWriter.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/AbstractMemberWriter.java	Tue Jan 22 11:54:16 2013 -0800
@@ -239,7 +239,14 @@
         if ((member.isField() || member.isMethod()) &&
             writer instanceof ClassWriterImpl &&
             ((ClassWriterImpl) writer).getClassDoc().isInterface()) {
-            mod = Util.replaceText(mod, "public", "").trim();
+            // This check for isDefault() and the default modifier needs to be
+            // added for it to appear on the method details section. Once the
+            // default modifier is added to the Modifier list on DocEnv and once
+            // it is updated to use the javax.lang.model.element.Modifier, we
+            // will need to remove this.
+            mod = (member.isMethod() && ((MethodDoc)member).isDefault()) ?
+                    Util.replaceText(mod, "public", "default").trim() :
+                    Util.replaceText(mod, "public", "").trim();
         }
         if(mod.length() > 0) {
             htmltree.addContent(mod);
@@ -313,8 +320,19 @@
             code.addContent(configuration.getText("doclet.Package_private"));
             code.addContent(" ");
         }
-        if (member.isMethod() && ((MethodDoc)member).isAbstract()) {
-            code.addContent("abstract ");
+        if (member.isMethod()) {
+            if (!(member.containingClass().isInterface()) &&
+                    ((MethodDoc)member).isAbstract()) {
+                code.addContent("abstract ");
+            }
+            // This check for isDefault() and the default modifier needs to be
+            // added for it to appear on the "Modifier and Type" column in the
+            // method summary section. Once the default modifier is added
+            // to the Modifier list on DocEnv and once it is updated to use the
+            // javax.lang.model.element.Modifier, we will need to remove this.
+            if (((MethodDoc)member).isDefault()) {
+                code.addContent("default ");
+            }
         }
         if (member.isStatic()) {
             code.addContent("static ");
@@ -544,9 +562,15 @@
         if (member instanceof MethodDoc && !member.isAnnotationTypeElement()) {
             int methodType = (member.isStatic()) ? MethodTypes.STATIC.value() :
                     MethodTypes.INSTANCE.value();
-            methodType = (classdoc.isInterface() || ((MethodDoc)member).isAbstract()) ?
-                    methodType | MethodTypes.ABSTRACT.value() :
-                    methodType | MethodTypes.CONCRETE.value();
+            if (member.containingClass().isInterface()) {
+                methodType = (((MethodDoc) member).isAbstract())
+                        ? methodType | MethodTypes.ABSTRACT.value()
+                        : methodType | MethodTypes.DEFAULT.value();
+            } else {
+                methodType = (((MethodDoc) member).isAbstract())
+                        ? methodType | MethodTypes.ABSTRACT.value()
+                        : methodType | MethodTypes.CONCRETE.value();
+            }
             if (Util.isDeprecated(member) || Util.isDeprecated(classdoc)) {
                 methodType = methodType | MethodTypes.DEPRECATED.value();
             }
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ClassWriterImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ClassWriterImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -516,6 +516,20 @@
     /**
      * {@inheritDoc}
      */
+    public void addFunctionalInterfaceInfo (Content classInfoTree) {
+        if (classDoc.isFunctionalInterface()) {
+            Content dt = HtmlTree.DT(getResource("doclet.Functional_Interface"));
+            Content dl = HtmlTree.DL(dt);
+            Content dd = new HtmlTree(HtmlTag.DD);
+            dd.addContent(getResource("doclet.Functional_Interface_Message"));
+            dl.addContent(dd);
+            classInfoTree.addContent(dl);
+        }
+    }
+
+    /**
+     * {@inheritDoc}
+     */
     public void addClassDeprecationInfo(Content classInfoTree) {
         Content hr = new HtmlTree(HtmlTag.HR);
         classInfoTree.addContent(hr);
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java	Tue Jan 22 11:54:16 2013 -0800
@@ -90,6 +90,16 @@
     protected boolean printedAnnotationHeading = false;
 
     /**
+     * To check whether the repeated annotations is documented or not.
+     */
+    private boolean isAnnotationDocumented = false;
+
+    /**
+     * To check whether the container annotations is documented or not.
+     */
+    private boolean isContainerDocumented = false;
+
+    /**
      * Constructor to construct the HtmlStandardWriter object.
      *
      * @param path File to be generated.
@@ -1793,50 +1803,66 @@
         StringBuilder annotation;
         for (int i = 0; i < descList.length; i++) {
             AnnotationTypeDoc annotationDoc = descList[i].annotationType();
-            if (! Util.isDocumentedAnnotation(annotationDoc)){
+            // If an annotation is not documented, do not add it to the list. If
+            // the annotation is of a repeatable type, and if it is not documented
+            // and also if its container annotation is not documented, do not add it
+            // to the list. If an annotation of a repeatable type is not documented
+            // but its container is documented, it will be added to the list.
+            if (! Util.isDocumentedAnnotation(annotationDoc) &&
+                    (!isAnnotationDocumented && !isContainerDocumented)) {
                 continue;
             }
             annotation = new StringBuilder();
+            isAnnotationDocumented = false;
             LinkInfoImpl linkInfo = new LinkInfoImpl(configuration,
                 LinkInfoImpl.CONTEXT_ANNOTATION, annotationDoc);
-            linkInfo.label = "@" + annotationDoc.name();
-            annotation.append(getLink(linkInfo));
             AnnotationDesc.ElementValuePair[] pairs = descList[i].elementValues();
-            if (pairs.length > 0) {
-                annotation.append('(');
+            // If the annotation is synthesized, do not print the container.
+            if (descList[i].isSynthesized()) {
                 for (int j = 0; j < pairs.length; j++) {
-                    if (j > 0) {
-                        annotation.append(",");
-                        if (linkBreak) {
-                            annotation.append(DocletConstants.NL);
-                            int spaces = annotationDoc.name().length() + 2;
-                            for (int k = 0; k < (spaces + indent); k++) {
-                                annotation.append(' ');
-                            }
-                        }
-                    }
-                    annotation.append(getDocLink(LinkInfoImpl.CONTEXT_ANNOTATION,
-                        pairs[j].element(), pairs[j].element().name(), false));
-                    annotation.append('=');
                     AnnotationValue annotationValue = pairs[j].value();
                     List<AnnotationValue> annotationTypeValues = new ArrayList<AnnotationValue>();
                     if (annotationValue.value() instanceof AnnotationValue[]) {
                         AnnotationValue[] annotationArray =
-                            (AnnotationValue[]) annotationValue.value();
-                        for (int k = 0; k < annotationArray.length; k++) {
-                            annotationTypeValues.add(annotationArray[k]);
-                        }
+                                (AnnotationValue[]) annotationValue.value();
+                        annotationTypeValues.addAll(Arrays.asList(annotationArray));
                     } else {
                         annotationTypeValues.add(annotationValue);
                     }
-                    annotation.append(annotationTypeValues.size() == 1 ? "" : "{");
-                    for (Iterator<AnnotationValue> iter = annotationTypeValues.iterator(); iter.hasNext(); ) {
-                        annotation.append(annotationValueToString(iter.next()));
-                        annotation.append(iter.hasNext() ? "," : "");
+                    String sep = "";
+                    for (AnnotationValue av : annotationTypeValues) {
+                        annotation.append(sep);
+                        annotation.append(annotationValueToString(av));
+                        sep = " ";
                     }
-                    annotation.append(annotationTypeValues.size() == 1 ? "" : "}");
                 }
-                annotation.append(")");
+            }
+            else if (isAnnotationArray(pairs)) {
+                // If the container has 1 or more value defined and if the
+                // repeatable type annotation is not documented, do not print
+                // the container.
+                if (pairs.length == 1 && isAnnotationDocumented) {
+                    AnnotationValue[] annotationArray =
+                            (AnnotationValue[]) (pairs[0].value()).value();
+                    List<AnnotationValue> annotationTypeValues = new ArrayList<AnnotationValue>();
+                    annotationTypeValues.addAll(Arrays.asList(annotationArray));
+                    String sep = "";
+                    for (AnnotationValue av : annotationTypeValues) {
+                        annotation.append(sep);
+                        annotation.append(annotationValueToString(av));
+                        sep = " ";
+                    }
+                }
+                // If the container has 1 or more value defined and if the
+                // repeatable type annotation is not documented, print the container.
+                else {
+                    addAnnotations(annotationDoc, linkInfo, annotation, pairs,
+                        indent, false);
+                }
+            }
+            else {
+                addAnnotations(annotationDoc, linkInfo, annotation, pairs,
+                        indent, linkBreak);
             }
             annotation.append(linkBreak ? DocletConstants.NL : "");
             results.add(annotation.toString());
@@ -1844,6 +1870,91 @@
         return results;
     }
 
+    /**
+     * Add annotation to the annotation string.
+     *
+     * @param annotationDoc the annotation being documented
+     * @param linkInfo the information about the link
+     * @param annotation the annotation string to which the annotation will be added
+     * @param pairs annotation type element and value pairs
+     * @param indent the number of extra spaces to indent the annotations.
+     * @param linkBreak if true, add new line between each member value
+     */
+    private void addAnnotations(AnnotationTypeDoc annotationDoc, LinkInfoImpl linkInfo,
+            StringBuilder annotation, AnnotationDesc.ElementValuePair[] pairs,
+            int indent, boolean linkBreak) {
+        linkInfo.label = "@" + annotationDoc.name();
+        annotation.append(getLink(linkInfo));
+        if (pairs.length > 0) {
+            annotation.append('(');
+            for (int j = 0; j < pairs.length; j++) {
+                if (j > 0) {
+                    annotation.append(",");
+                    if (linkBreak) {
+                        annotation.append(DocletConstants.NL);
+                        int spaces = annotationDoc.name().length() + 2;
+                        for (int k = 0; k < (spaces + indent); k++) {
+                            annotation.append(' ');
+                        }
+                    }
+                }
+                annotation.append(getDocLink(LinkInfoImpl.CONTEXT_ANNOTATION,
+                        pairs[j].element(), pairs[j].element().name(), false));
+                annotation.append('=');
+                AnnotationValue annotationValue = pairs[j].value();
+                List<AnnotationValue> annotationTypeValues = new ArrayList<AnnotationValue>();
+                if (annotationValue.value() instanceof AnnotationValue[]) {
+                    AnnotationValue[] annotationArray =
+                            (AnnotationValue[]) annotationValue.value();
+                    annotationTypeValues.addAll(Arrays.asList(annotationArray));
+                } else {
+                    annotationTypeValues.add(annotationValue);
+                }
+                annotation.append(annotationTypeValues.size() == 1 ? "" : "{");
+                String sep = "";
+                for (AnnotationValue av : annotationTypeValues) {
+                    annotation.append(sep);
+                    annotation.append(annotationValueToString(av));
+                    sep = ",";
+                }
+                annotation.append(annotationTypeValues.size() == 1 ? "" : "}");
+                isContainerDocumented = false;
+            }
+            annotation.append(")");
+        }
+    }
+
+    /**
+     * Check if the annotation contains an array of annotation as a value. This
+     * check is to verify if a repeatable type annotation is present or not.
+     *
+     * @param pairs annotation type element and value pairs
+     *
+     * @return true if the annotation contains an array of annotation as a value.
+     */
+    private boolean isAnnotationArray(AnnotationDesc.ElementValuePair[] pairs) {
+        AnnotationValue annotationValue;
+        for (int j = 0; j < pairs.length; j++) {
+            annotationValue = pairs[j].value();
+            if (annotationValue.value() instanceof AnnotationValue[]) {
+                AnnotationValue[] annotationArray =
+                        (AnnotationValue[]) annotationValue.value();
+                if (annotationArray.length > 1) {
+                    if (annotationArray[0].value() instanceof AnnotationDesc) {
+                        AnnotationTypeDoc annotationDoc =
+                                ((AnnotationDesc) annotationArray[0].value()).annotationType();
+                        isContainerDocumented = true;
+                        if (Util.isDocumentedAnnotation(annotationDoc)) {
+                            isAnnotationDocumented = true;
+                        }
+                        return true;
+                    }
+                }
+            }
+        }
+        return false;
+    }
+
     private String annotationValueToString(AnnotationValue annotationValue) {
         if (annotationValue.value() instanceof Type) {
             Type type = (Type) annotationValue.value();
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/resources/standard.properties	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/resources/standard.properties	Tue Jan 22 11:54:16 2013 -0800
@@ -90,6 +90,8 @@
 doclet.Subclasses=Direct Known Subclasses:
 doclet.Subinterfaces=All Known Subinterfaces:
 doclet.Implementing_Classes=All Known Implementing Classes:
+doclet.Functional_Interface=Functional Interface:
+doclet.Functional_Interface_Message=This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. 
 doclet.also=also
 doclet.Frames=Frames
 doclet.No_Frames=No Frames
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/ClassWriter.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/ClassWriter.java	Tue Jan 22 11:54:16 2013 -0800
@@ -117,6 +117,13 @@
     public void addInterfaceUsageInfo(Content classInfoTree);
 
     /**
+     * If this is an functional interface, display appropriate message.
+     *
+     * @param classInfoTree content tree to which the documentation will be added
+     */
+    public void addFunctionalInterfaceInfo(Content classInfoTree);
+
+    /**
      * If this is an inner class or interface, add the enclosing class or
      * interface.
      *
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/ClassBuilder.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/ClassBuilder.java	Tue Jan 22 11:54:16 2013 -0800
@@ -236,6 +236,16 @@
     }
 
     /**
+     * If this is an functional interface, display appropriate message.
+     *
+     * @param node the XML element that specifies which components to document
+     * @param classInfoTree the content tree to which the documentation will be added
+     */
+    public void buildFunctionalInterfaceInfo(XMLNode node, Content classInfoTree) {
+        writer.addFunctionalInterfaceInfo(classInfoTree);
+    }
+
+    /**
      * If this class is deprecated, build the appropriate information.
      *
      * @param node the XML element that specifies which components to document
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/resources/doclet.xml	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/resources/doclet.xml	Tue Jan 22 11:54:16 2013 -0800
@@ -85,6 +85,7 @@
             <SubInterfacesInfo/>
             <InterfaceUsageInfo/>
             <NestedClassInfo/>
+            <FunctionalInterfaceInfo/>
             <DeprecationInfo/>
             <ClassSignature/>
             <ClassDescription/>
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/MethodTypes.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/MethodTypes.java	Tue Jan 22 11:54:16 2013 -0800
@@ -36,7 +36,8 @@
     INSTANCE(0x2, "Instance Methods", "t2", false),
     ABSTRACT(0x4, "Abstract Methods", "t3", false),
     CONCRETE(0x8, "Concrete Methods", "t4", false),
-    DEPRECATED(0x10, "Deprecated Methods", "t5", false);
+    DEFAULT(0x10, "Default Methods", "t5", false),
+    DEPRECATED(0x20, "Deprecated Methods", "t6", false);
 
     private final int value;
     private final String text;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/doclint/Checker.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,754 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.tools.doclint;
+
+import java.util.regex.Matcher;
+import com.sun.source.doctree.LinkTree;
+import java.net.URI;
+import java.util.regex.Pattern;
+import java.io.IOException;
+import com.sun.tools.javac.tree.DocPretty;
+import java.io.StringWriter;
+import java.util.Deque;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.tools.Diagnostic.Kind;
+
+import com.sun.source.doctree.AttributeTree;
+import com.sun.source.doctree.AuthorTree;
+import com.sun.source.doctree.DocCommentTree;
+import com.sun.source.doctree.DocTree;
+import com.sun.source.doctree.EndElementTree;
+import com.sun.source.doctree.EntityTree;
+import com.sun.source.doctree.ErroneousTree;
+import com.sun.source.doctree.IdentifierTree;
+import com.sun.source.doctree.InheritDocTree;
+import com.sun.source.doctree.ParamTree;
+import com.sun.source.doctree.ReferenceTree;
+import com.sun.source.doctree.ReturnTree;
+import com.sun.source.doctree.SerialDataTree;
+import com.sun.source.doctree.SerialFieldTree;
+import com.sun.source.doctree.SinceTree;
+import com.sun.source.doctree.StartElementTree;
+import com.sun.source.doctree.TextTree;
+import com.sun.source.doctree.ThrowsTree;
+import com.sun.source.doctree.VersionTree;
+import com.sun.source.util.DocTreeScanner;
+import com.sun.source.util.TreePath;
+import com.sun.tools.doclint.HtmlTag.AttrKind;
+import java.net.URISyntaxException;
+import static com.sun.tools.doclint.Messages.Group.*;
+
+
+/**
+ * Validate a doc comment.
+ *
+ * <p><b>This is NOT part of any supported API.
+ * If you write code that depends on this, you do so at your own
+ * risk.  This code and its internal interfaces are subject to change
+ * or deletion without notice.</b></p>
+ */
+public class Checker extends DocTreeScanner<Void, Void> {
+    final Env env;
+
+    Set<Element> foundParams = new HashSet<Element>();
+    Set<TypeMirror> foundThrows = new HashSet<TypeMirror>();
+    Set<String> foundAnchors = new HashSet<String>();
+    boolean foundInheritDoc = false;
+    boolean foundReturn = false;
+
+    enum Flag {
+        TABLE_HAS_CAPTION,
+        HAS_ELEMENT,
+        HAS_TEXT
+    }
+
+    static class TagStackItem {
+        final DocTree tree; // typically, but not always, StartElementTree
+        final HtmlTag tag;
+        final Set<HtmlTag.Attr> attrs;
+        final Set<Flag> flags;
+        TagStackItem(DocTree tree, HtmlTag tag) {
+            this.tree = tree;
+            this.tag = tag;
+            attrs = EnumSet.noneOf(HtmlTag.Attr.class);
+            flags = EnumSet.noneOf(Flag.class);
+        }
+        @Override
+        public String toString() {
+            return String.valueOf(tag);
+        }
+    }
+
+    private Deque<TagStackItem> tagStack; // TODO: maybe want to record starting tree as well
+    private HtmlTag currHeaderTag;
+
+    // <editor-fold defaultstate="collapsed" desc="Top level">
+
+    Checker(Env env) {
+        env.getClass();
+        this.env = env;
+        tagStack = new LinkedList<TagStackItem>();
+    }
+
+    public Void scan(DocCommentTree tree, TreePath p) {
+        env.setCurrent(p, tree);
+
+        boolean isOverridingMethod = !env.currOverriddenMethods.isEmpty();
+
+        if (tree == null) {
+            if (!isSynthetic() && !isOverridingMethod)
+                reportMissing("dc.missing.comment");
+            return null;
+        }
+
+        tagStack.clear();
+        currHeaderTag = null;
+
+        foundParams.clear();
+        foundThrows.clear();
+        foundInheritDoc = false;
+        foundReturn = false;
+
+        scan(tree, (Void) null);
+
+        if (!isOverridingMethod) {
+            switch (env.currElement.getKind()) {
+                case METHOD:
+                case CONSTRUCTOR: {
+                    ExecutableElement ee = (ExecutableElement) env.currElement;
+                    checkParamsDocumented(ee.getTypeParameters());
+                    checkParamsDocumented(ee.getParameters());
+                    switch (ee.getReturnType().getKind()) {
+                        case VOID:
+                        case NONE:
+                            break;
+                        default:
+                            if (!foundReturn
+                                    && !foundInheritDoc
+                                    && !env.types.isSameType(ee.getReturnType(), env.java_lang_Void)) {
+                                reportMissing("dc.missing.return");
+                            }
+                    }
+                    checkThrowsDocumented(ee.getThrownTypes());
+                }
+            }
+        }
+
+        return null;
+    }
+
+    private void reportMissing(String code, Object... args) {
+        env.messages.report(MISSING, Kind.WARNING, env.currPath.getLeaf(), code, args);
+    }
+
+    @Override
+    public Void visitDocComment(DocCommentTree tree, Void ignore) {
+        super.visitDocComment(tree, ignore);
+        for (TagStackItem tsi: tagStack) {
+            if (tsi.tree.getKind() == DocTree.Kind.START_ELEMENT
+                    && tsi.tag.endKind == HtmlTag.EndKind.REQUIRED) {
+                StartElementTree t = (StartElementTree) tsi.tree;
+                env.messages.error(HTML, t, "dc.tag.not.closed", t.getName());
+            }
+        }
+        return null;
+    }
+    // </editor-fold>
+
+    // <editor-fold defaultstate="collapsed" desc="Text and entities.">
+
+    @Override
+    public Void visitText(TextTree tree, Void ignore) {
+        if (!tree.getBody().trim().isEmpty()) {
+            markEnclosingTag(Flag.HAS_TEXT);
+        }
+        return null;
+    }
+
+    @Override
+    public Void visitEntity(EntityTree tree, Void ignore) {
+        markEnclosingTag(Flag.HAS_TEXT);
+        String name = tree.getName().toString();
+        if (name.startsWith("#")) {
+            int v = name.toLowerCase().startsWith("#x")
+                    ? Integer.parseInt(name.substring(2), 16)
+                    : Integer.parseInt(name.substring(1), 10);
+            if (!Entity.isValid(v)) {
+                env.messages.error(HTML, tree, "dc.entity.invalid", name);
+            }
+        } else if (!Entity.isValid(name)) {
+            env.messages.error(HTML, tree, "dc.entity.invalid", name);
+        }
+        return null;
+    }
+
+    // </editor-fold>
+
+    // <editor-fold defaultstate="collapsed" desc="HTML elements">
+
+    @Override
+    public Void visitStartElement(StartElementTree tree, Void ignore) {
+        markEnclosingTag(Flag.HAS_ELEMENT);
+        final Name treeName = tree.getName();
+        final HtmlTag t = HtmlTag.get(treeName);
+        if (t == null) {
+            env.messages.error(HTML, tree, "dc.tag.unknown", treeName);
+        } else {
+            // tag specific checks
+            switch (t) {
+                // check for out of sequence headers, such as <h1>...</h1>  <h3>...</h3>
+                case H1: case H2: case H3: case H4: case H5: case H6:
+                    checkHeader(tree, t);
+                    break;
+                // <p> inside <pre>
+                case P:
+                    TagStackItem top = tagStack.peek();
+                    if (top != null && top.tag == HtmlTag.PRE)
+                        env.messages.warning(HTML, tree, "dc.tag.p.in.pre");
+                    break;
+            }
+
+            // check that only block tags and inline tags are used,
+            // and that blocks tags are not used within inline tags
+            switch (t.blockType) {
+                case INLINE:
+                    break;
+                case BLOCK:
+                    TagStackItem top = tagStack.peek();
+                    if (top != null && top.tag != null && top.tag.blockType == HtmlTag.BlockType.INLINE) {
+                        switch (top.tree.getKind()) {
+                            case START_ELEMENT: {
+                                Name name = ((StartElementTree) top.tree).getName();
+                                env.messages.error(HTML, tree, "dc.tag.not.allowed.inline.element",
+                                        treeName, name);
+                                break;
+                            }
+                            case LINK:
+                            case LINK_PLAIN: {
+                                String name = top.tree.getKind().tagName;
+                                env.messages.error(HTML, tree, "dc.tag.not.allowed.inline.tag",
+                                        treeName, name);
+                                break;
+                            }
+                            default:
+                                env.messages.error(HTML, tree, "dc.tag.not.allowed.inline.other",
+                                        treeName);
+                        }
+                    }
+                    break;
+                case OTHER:
+                    env.messages.error(HTML, tree, "dc.tag.not.allowed", treeName);
+                    break;
+                default:
+                    throw new AssertionError();
+            }
+
+            if (t.flags.contains(HtmlTag.Flag.NO_NEST)) {
+                for (TagStackItem i: tagStack) {
+                    if (t == i.tag) {
+                        env.messages.warning(HTML, tree, "dc.tag.nested.not.allowed", treeName);
+                        break;
+                    }
+                }
+            }
+        }
+
+        // check for self closing tags, such as <a id="name"/>
+        if (tree.isSelfClosing()) {
+            env.messages.error(HTML, tree, "dc.tag.self.closing", treeName);
+        }
+
+        try {
+            TagStackItem parent = tagStack.peek();
+            TagStackItem top = new TagStackItem(tree, t);
+            tagStack.push(top);
+
+            super.visitStartElement(tree, ignore);
+
+            // handle attributes that may or may not have been found in start element
+            if (t != null) {
+                switch (t) {
+                    case CAPTION:
+                        if (parent != null && parent.tag == HtmlTag.TABLE)
+                            parent.flags.add(Flag.TABLE_HAS_CAPTION);
+                        break;
+
+                    case IMG:
+                        if (!top.attrs.contains(HtmlTag.Attr.ALT))
+                            env.messages.error(ACCESSIBILITY, tree, "dc.no.alt.attr.for.image");
+                        break;
+                }
+            }
+
+            return null;
+        } finally {
+
+            if (t == null || t.endKind == HtmlTag.EndKind.NONE)
+                tagStack.pop();
+        }
+    }
+
+    private void checkHeader(StartElementTree tree, HtmlTag tag) {
+        // verify the new tag
+        if (getHeaderLevel(tag) > getHeaderLevel(currHeaderTag) + 1) {
+            if (currHeaderTag == null) {
+                env.messages.error(ACCESSIBILITY, tree, "dc.tag.header.sequence.1", tag);
+            } else {
+                env.messages.error(ACCESSIBILITY, tree, "dc.tag.header.sequence.2",
+                    tag, currHeaderTag);
+            }
+        }
+
+        currHeaderTag = tag;
+    }
+
+    private int getHeaderLevel(HtmlTag tag) {
+        if (tag == null)
+            return 0;
+        switch (tag) {
+            case H1: return 1;
+            case H2: return 2;
+            case H3: return 3;
+            case H4: return 4;
+            case H5: return 5;
+            case H6: return 6;
+            default: throw new IllegalArgumentException();
+        }
+    }
+
+    @Override
+    public Void visitEndElement(EndElementTree tree, Void ignore) {
+        final Name treeName = tree.getName();
+        final HtmlTag t = HtmlTag.get(treeName);
+        if (t == null) {
+            env.messages.error(HTML, tree, "dc.tag.unknown", treeName);
+        } else if (t.endKind == HtmlTag.EndKind.NONE) {
+            env.messages.error(HTML, tree, "dc.tag.end.not.permitted", treeName);
+        } else if (tagStack.isEmpty()) {
+            env.messages.error(HTML, tree, "dc.tag.end.unexpected", treeName);
+        } else {
+            while (!tagStack.isEmpty()) {
+                TagStackItem top = tagStack.peek();
+                if (t == top.tag) {
+                    switch (t) {
+                        case TABLE:
+                            if (!top.attrs.contains(HtmlTag.Attr.SUMMARY)
+                                    && !top.flags.contains(Flag.TABLE_HAS_CAPTION)) {
+                                env.messages.error(ACCESSIBILITY, tree,
+                                        "dc.no.summary.or.caption.for.table");
+                            }
+                    }
+                    if (t.flags.contains(HtmlTag.Flag.EXPECT_CONTENT)
+                            && !top.flags.contains(Flag.HAS_TEXT)
+                            && !top.flags.contains(Flag.HAS_ELEMENT)) {
+                        env.messages.warning(HTML, tree, "dc.tag.empty", treeName);
+                    }
+                    if (t.flags.contains(HtmlTag.Flag.NO_TEXT)
+                            && top.flags.contains(Flag.HAS_TEXT)) {
+                        env.messages.error(HTML, tree, "dc.text.not.allowed", treeName);
+                    }
+                    tagStack.pop();
+                    break;
+                } else if (top.tag == null || top.tag.endKind != HtmlTag.EndKind.REQUIRED) {
+                    tagStack.pop();
+                } else {
+                    boolean found = false;
+                    for (TagStackItem si: tagStack) {
+                        if (si.tag == t) {
+                            found = true;
+                            break;
+                        }
+                    }
+                    if (found && top.tree.getKind() == DocTree.Kind.START_ELEMENT) {
+                        env.messages.error(HTML, top.tree, "dc.tag.start.unmatched",
+                                ((StartElementTree) top.tree).getName());
+                        tagStack.pop();
+                    } else {
+                        env.messages.error(HTML, tree, "dc.tag.end.unexpected", treeName);
+                        break;
+                    }
+                }
+            }
+        }
+
+        return super.visitEndElement(tree, ignore);
+    }
+    // </editor-fold>
+
+    // <editor-fold defaultstate="collapsed" desc="HTML attributes">
+
+    @Override @SuppressWarnings("fallthrough")
+    public Void visitAttribute(AttributeTree tree, Void ignore) {
+        HtmlTag currTag = tagStack.peek().tag;
+        if (currTag != null) {
+            Name name = tree.getName();
+            HtmlTag.Attr attr = currTag.getAttr(name);
+            if (attr != null) {
+                boolean first = tagStack.peek().attrs.add(attr);
+                if (!first)
+                    env.messages.error(HTML, tree, "dc.attr.repeated", name);
+            }
+            AttrKind k = currTag.getAttrKind(name);
+            switch (k) {
+                case OK:
+                    break;
+
+                case INVALID:
+                    env.messages.error(HTML, tree, "dc.attr.unknown", name);
+                    break;
+
+                case OBSOLETE:
+                    env.messages.warning(ACCESSIBILITY, tree, "dc.attr.obsolete", name);
+                    break;
+
+                case USE_CSS:
+                    env.messages.warning(ACCESSIBILITY, tree, "dc.attr.obsolete.use.css", name);
+                    break;
+            }
+
+            if (attr != null) {
+                switch (attr) {
+                    case NAME:
+                        if (currTag != HtmlTag.A) {
+                            break;
+                        }
+                    // fallthrough
+                    case ID:
+                        String value = getAttrValue(tree);
+                        if (!validName.matcher(value).matches()) {
+                            env.messages.error(HTML, tree, "dc.invalid.anchor", value);
+                        }
+                        if (!foundAnchors.add(value)) {
+                            env.messages.error(HTML, tree, "dc.anchor.already.defined", value);
+                        }
+                        break;
+
+                    case HREF:
+                        if (currTag == HtmlTag.A) {
+                            String v = getAttrValue(tree);
+                            if (v == null || v.isEmpty()) {
+                                env.messages.error(HTML, tree, "dc.attr.lacks.value");
+                            } else {
+                                Matcher m = docRoot.matcher(v);
+                                if (m.matches()) {
+                                    String rest = m.group(2);
+                                    if (!rest.isEmpty())
+                                        checkURI(tree, rest);
+                                } else {
+                                    checkURI(tree, v);
+                                }
+                            }
+                        }
+                        break;
+                }
+            }
+        }
+
+        // TODO: basic check on value
+
+        return super.visitAttribute(tree, ignore);
+    }
+
+    // http://www.w3.org/TR/html401/types.html#type-name
+    private static final Pattern validName = Pattern.compile("[A-Za-z][A-Za-z0-9-_:.]*");
+
+    // pattern to remove leading {@docRoot}/?
+    private static final Pattern docRoot = Pattern.compile("(?i)(\\{@docRoot *\\}/?)?(.*)");
+
+    private String getAttrValue(AttributeTree tree) {
+        if (tree.getValue() == null)
+            return null;
+
+        StringWriter sw = new StringWriter();
+        try {
+            new DocPretty(sw).print(tree.getValue());
+        } catch (IOException e) {
+            // cannot happen
+        }
+        // ignore potential use of entities for now
+        return sw.toString();
+    }
+
+    private void checkURI(AttributeTree tree, String uri) {
+        try {
+            URI u = new URI(uri);
+        } catch (URISyntaxException e) {
+            env.messages.error(HTML, tree, "dc.invalid.uri", uri);
+        }
+    }
+    // </editor-fold>
+
+    // <editor-fold defaultstate="collapsed" desc="javadoc tags">
+
+    @Override
+    public Void visitAuthor(AuthorTree tree, Void ignore) {
+        warnIfEmpty(tree, tree.getName());
+        return super.visitAuthor(tree, ignore);
+    }
+
+    @Override
+    public Void visitInheritDoc(InheritDocTree tree, Void ignore) {
+        // TODO: verify on overridden method
+        foundInheritDoc = true;
+        return super.visitInheritDoc(tree, ignore);
+    }
+
+    @Override
+    public Void visitLink(LinkTree tree, Void ignore) {
+        // simulate inline context on tag stack
+        HtmlTag t = (tree.getKind() == DocTree.Kind.LINK)
+                ? HtmlTag.CODE : HtmlTag.SPAN;
+        tagStack.push(new TagStackItem(tree, t));
+        try {
+            return super.visitLink(tree, ignore);
+        } finally {
+            tagStack.pop();
+        }
+    }
+
+    @Override
+    public Void visitParam(ParamTree tree, Void ignore) {
+        boolean typaram = tree.isTypeParameter();
+        IdentifierTree nameTree = tree.getName();
+        Element e = env.currElement;
+        switch (e.getKind()) {
+            case METHOD: case CONSTRUCTOR: {
+                ExecutableElement ee = (ExecutableElement) e;
+                checkParamDeclared(nameTree, typaram ? ee.getTypeParameters() : ee.getParameters());
+                break;
+            }
+
+            case CLASS: case INTERFACE: {
+                TypeElement te = (TypeElement) e;
+                if (typaram) {
+                    checkParamDeclared(nameTree, te.getTypeParameters());
+                } else {
+                    env.messages.error(REFERENCE, tree, "dc.invalid.param");
+                }
+                break;
+            }
+
+            default:
+                env.messages.error(REFERENCE, tree, "dc.invalid.param");
+                break;
+        }
+        warnIfEmpty(tree, tree.getDescription());
+        return super.visitParam(tree, ignore);
+    }
+    // where
+    private void checkParamDeclared(IdentifierTree nameTree, List<? extends Element> list) {
+        Name name = nameTree.getName();
+        boolean found = false;
+        for (Element e: list) {
+            if (name.equals(e.getSimpleName())) {
+                foundParams.add(e);
+                found = true;
+            }
+        }
+        if (!found)
+            env.messages.error(REFERENCE, nameTree, "dc.param.name.not.found");
+    }
+
+    private void checkParamsDocumented(List<? extends Element> list) {
+        if (foundInheritDoc)
+            return;
+
+        for (Element e: list) {
+            if (!foundParams.contains(e)) {
+                CharSequence paramName = (e.getKind() == ElementKind.TYPE_PARAMETER)
+                        ? "<" + e.getSimpleName() + ">"
+                        : e.getSimpleName();
+                reportMissing("dc.missing.param", paramName);
+            }
+        }
+    }
+
+    @Override
+    public Void visitReference(ReferenceTree tree, Void ignore) {
+        Element e = env.trees.getElement(env.currPath, tree);
+        if (e == null)
+            env.messages.error(REFERENCE, tree, "dc.ref.not.found");
+        return super.visitReference(tree, ignore);
+    }
+
+    @Override
+    public Void visitReturn(ReturnTree tree, Void ignore) {
+        Element e = env.trees.getElement(env.currPath);
+        if (e.getKind() != ElementKind.METHOD
+                || ((ExecutableElement) e).getReturnType().getKind() == TypeKind.VOID)
+            env.messages.error(REFERENCE, tree, "dc.invalid.return");
+        foundReturn = true;
+        warnIfEmpty(tree, tree.getDescription());
+        return super.visitReturn(tree, ignore);
+    }
+
+    @Override
+    public Void visitSerialData(SerialDataTree tree, Void ignore) {
+        warnIfEmpty(tree, tree.getDescription());
+        return super.visitSerialData(tree, ignore);
+    }
+
+    @Override
+    public Void visitSerialField(SerialFieldTree tree, Void ignore) {
+        warnIfEmpty(tree, tree.getDescription());
+        return super.visitSerialField(tree, ignore);
+    }
+
+    @Override
+    public Void visitSince(SinceTree tree, Void ignore) {
+        warnIfEmpty(tree, tree.getBody());
+        return super.visitSince(tree, ignore);
+    }
+
+    @Override
+    public Void visitThrows(ThrowsTree tree, Void ignore) {
+        ReferenceTree exName = tree.getExceptionName();
+        Element ex = env.trees.getElement(env.currPath, exName);
+        if (ex == null) {
+            env.messages.error(REFERENCE, tree, "dc.ref.not.found");
+        } else if (ex.asType().getKind() == TypeKind.DECLARED
+                && env.types.isAssignable(ex.asType(), env.java_lang_Throwable)) {
+            switch (env.currElement.getKind()) {
+                case CONSTRUCTOR:
+                case METHOD:
+                    if (isCheckedException(ex.asType())) {
+                        ExecutableElement ee = (ExecutableElement) env.currElement;
+                        checkThrowsDeclared(exName, ex.asType(), ee.getThrownTypes());
+                    }
+                    break;
+                default:
+                    env.messages.error(REFERENCE, tree, "dc.invalid.throws");
+            }
+        } else {
+            env.messages.error(REFERENCE, tree, "dc.invalid.throws");
+        }
+        warnIfEmpty(tree, tree.getDescription());
+        return scan(tree.getDescription(), ignore);
+    }
+
+    private void checkThrowsDeclared(ReferenceTree tree, TypeMirror t, List<? extends TypeMirror> list) {
+        boolean found = false;
+        for (TypeMirror tl : list) {
+            if (env.types.isAssignable(t, tl)) {
+                foundThrows.add(tl);
+                found = true;
+            }
+        }
+        if (!found)
+            env.messages.error(REFERENCE, tree, "dc.exception.not.thrown", t);
+    }
+
+    private void checkThrowsDocumented(List<? extends TypeMirror> list) {
+        if (foundInheritDoc)
+            return;
+
+        for (TypeMirror tl: list) {
+            if (isCheckedException(tl) && !foundThrows.contains(tl))
+                reportMissing("dc.missing.throws", tl);
+        }
+    }
+
+    @Override
+    public Void visitVersion(VersionTree tree, Void ignore) {
+        warnIfEmpty(tree, tree.getBody());
+        return super.visitVersion(tree, ignore);
+    }
+
+    @Override
+    public Void visitErroneous(ErroneousTree tree, Void ignore) {
+        env.messages.error(SYNTAX, tree, null, tree.getDiagnostic().getMessage(null));
+        return null;
+    }
+    // </editor-fold>
+
+    // <editor-fold defaultstate="collapsed" desc="Utility methods">
+
+    private boolean isCheckedException(TypeMirror t) {
+        return !(env.types.isAssignable(t, env.java_lang_Error)
+                || env.types.isAssignable(t, env.java_lang_RuntimeException));
+    }
+
+    private boolean isSynthetic() {
+        switch (env.currElement.getKind()) {
+            case CONSTRUCTOR:
+                // A synthetic default constructor has the same pos as the
+                // enclosing class
+                TreePath p = env.currPath;
+                return env.getPos(p) == env.getPos(p.getParentPath());
+        }
+        return false;
+    }
+
+    void markEnclosingTag(Flag flag) {
+        TagStackItem top = tagStack.peek();
+        if (top != null)
+            top.flags.add(flag);
+    }
+
+    String toString(TreePath p) {
+        StringBuilder sb = new StringBuilder("TreePath[");
+        toString(p, sb);
+        sb.append("]");
+        return sb.toString();
+    }
+
+    void toString(TreePath p, StringBuilder sb) {
+        TreePath parent = p.getParentPath();
+        if (parent != null) {
+            toString(parent, sb);
+            sb.append(",");
+        }
+       sb.append(p.getLeaf().getKind()).append(":").append(env.getPos(p)).append(":S").append(env.getStartPos(p));
+    }
+
+    void warnIfEmpty(DocTree tree, List<? extends DocTree> list) {
+        for (DocTree d: list) {
+            switch (d.getKind()) {
+                case TEXT:
+                    if (!((TextTree) d).getBody().trim().isEmpty())
+                        return;
+                    break;
+                default:
+                    return;
+            }
+        }
+        env.messages.warning(SYNTAX, tree, "dc.empty", tree.getKind().tagName);
+    }
+    // </editor-fold>
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/doclint/DocLint.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,376 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.tools.doclint;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.lang.model.element.Name;
+import javax.tools.StandardLocation;
+
+import com.sun.source.doctree.DocCommentTree;
+import com.sun.source.tree.ClassTree;
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.tree.MethodTree;
+import com.sun.source.tree.Tree;
+import com.sun.source.tree.VariableTree;
+import com.sun.source.util.JavacTask;
+import com.sun.source.util.Plugin;
+import com.sun.source.util.TaskEvent;
+import com.sun.source.util.TaskListener;
+import com.sun.source.util.TreePath;
+import com.sun.source.util.TreePathScanner;
+import com.sun.tools.javac.api.JavacTaskImpl;
+import com.sun.tools.javac.api.JavacTool;
+import com.sun.tools.javac.file.JavacFileManager;
+import com.sun.tools.javac.main.JavaCompiler;
+import com.sun.tools.javac.util.Context;
+
+/**
+ * Multi-function entry point for the doc check utility.
+ *
+ * This class can be invoked in the following ways:
+ * <ul>
+ * <li>From the command line
+ * <li>From javac, as a plugin
+ * <li>Directly, via a simple API
+ * </ul>
+ *
+ * <p><b>This is NOT part of any supported API.
+ * If you write code that depends on this, you do so at your own
+ * risk.  This code and its internal interfaces are subject to change
+ * or deletion without notice.</b></p>
+ */
+public class DocLint implements Plugin {
+
+    public static final String XMSGS_OPTION = "-Xmsgs";
+    public static final String XMSGS_CUSTOM_PREFIX = "-Xmsgs:";
+    private static final String STATS = "-stats";
+
+    // <editor-fold defaultstate="collapsed" desc="Command-line entry point">
+    public static void main(String... args) {
+        try {
+            new DocLint().run(args);
+        } catch (BadArgs e) {
+            System.err.println(e.getMessage());
+            System.exit(1);
+        } catch (IOException e) {
+            System.err.println(e);
+            System.exit(2);
+        }
+    }
+
+    // </editor-fold>
+
+    // <editor-fold defaultstate="collapsed" desc="Simple API">
+
+    public static class BadArgs extends Exception {
+        private static final long serialVersionUID = 0;
+        BadArgs(String code, Object... args) {
+            this.code = code;
+            this.args = args;
+        }
+
+        final String code;
+        final Object[] args;
+    }
+
+    /**
+     * Simple API entry point.
+     */
+    public void run(String... args) throws BadArgs, IOException {
+        PrintWriter out = new PrintWriter(System.out);
+        try {
+            run(out, args);
+        } finally {
+            out.flush();
+        }
+    }
+
+    public void run(PrintWriter out, String... args) throws BadArgs, IOException {
+        env = new Env();
+        processArgs(args);
+
+        if (needHelp)
+            showHelp(out);
+
+        if (javacFiles.isEmpty()) {
+            if (!needHelp)
+                System.out.println("no files given");
+        }
+
+        JavacTool tool = JavacTool.create();
+
+        JavacFileManager fm = new JavacFileManager(new Context(), false, null);
+        fm.setSymbolFileEnabled(false);
+        fm.setLocation(StandardLocation.PLATFORM_CLASS_PATH, javacBootClassPath);
+        fm.setLocation(StandardLocation.CLASS_PATH, javacClassPath);
+        fm.setLocation(StandardLocation.SOURCE_PATH, javacSourcePath);
+
+        JavacTask task = tool.getTask(out, fm, null, javacOpts, null,
+                fm.getJavaFileObjectsFromFiles(javacFiles));
+        Iterable<? extends CompilationUnitTree> units = task.parse();
+        ((JavacTaskImpl) task).enter();
+
+        env.init(task);
+        checker = new Checker(env);
+
+        DeclScanner ds = new DeclScanner() {
+            @Override
+            void visitDecl(Tree tree, Name name) {
+                TreePath p = getCurrentPath();
+                DocCommentTree dc = env.trees.getDocCommentTree(p);
+
+                checker.scan(dc, p);
+            }
+        };
+
+        ds.scan(units, null);
+
+        reportStats(out);
+
+        Context ctx = ((JavacTaskImpl) task).getContext();
+        JavaCompiler c = JavaCompiler.instance(ctx);
+        c.printCount("error", c.errorCount());
+        c.printCount("warn", c.warningCount());
+    }
+
+    void processArgs(String... args) throws BadArgs {
+        javacOpts = new ArrayList<String>();
+        javacFiles = new ArrayList<File>();
+
+        if (args.length == 0)
+            needHelp = true;
+
+        for (int i = 0; i < args.length; i++) {
+            String arg = args[i];
+            if (arg.matches("-Xmax(errs|warns)") && i + 1 < args.length) {
+                if (args[++i].matches("[0-9]+")) {
+                    javacOpts.add(arg);
+                    javacOpts.add(args[i]);
+                } else {
+                    throw new BadArgs("dc.bad.value.for.option", arg, args[i]);
+                }
+            } else if (arg.equals(STATS)) {
+                env.messages.setStatsEnabled(true);
+            } else if (arg.matches("-bootclasspath") && i + 1 < args.length) {
+                javacBootClassPath = splitPath(args[++i]);
+            } else if (arg.matches("-classpath") && i + 1 < args.length) {
+                javacClassPath = splitPath(args[++i]);
+            } else if (arg.matches("-sourcepath") && i + 1 < args.length) {
+                javacSourcePath = splitPath(args[++i]);
+            } else if (arg.equals(XMSGS_OPTION)) {
+                env.messages.setOptions(null);
+            } else if (arg.startsWith(XMSGS_CUSTOM_PREFIX)) {
+                env.messages.setOptions(arg.substring(arg.indexOf(":") + 1));
+            } else if (arg.equals("-h") || arg.equals("-help") || arg.equals("--help")
+                    || arg.equals("-?") || arg.equals("-usage")) {
+                needHelp = true;
+            } else if (arg.startsWith("-")) {
+                throw new BadArgs("dc.bad.option", arg);
+            } else {
+                while (i < args.length)
+                    javacFiles.add(new File(args[i++]));
+            }
+        }
+    }
+
+    void showHelp(PrintWriter out) {
+        out.println("Usage:");
+        out.println("    doclint [options] source-files...");
+        out.println("");
+        out.println("Options:");
+        out.println("  -Xmsgs  ");
+        out.println("    Same as -Xmsgs:all");
+        out.println("  -Xmsgs:values");
+        out.println("    Specify categories of issues to be checked, where 'values'");
+        out.println("    is a comma-separated list of any of the following:");
+        out.println("      reference      show places where comments contain incorrect");
+        out.println("                     references to Java source code elements");
+        out.println("      syntax         show basic syntax errors within comments");
+        out.println("      html           show issues with HTML tags and attributes");
+        out.println("      accessibility  show issues for accessibility");
+        out.println("      missing        show issues with missing documentation");
+        out.println("      all            all of the above");
+        out.println("    Precede a value with '-' to negate it");
+        out.println("    Categories may be qualified by one of:");
+        out.println("      /public /protected /package /private");
+        out.println("    For positive categories (not beginning with '-')");
+        out.println("    the qualifier applies to that access level and above.");
+        out.println("    For negative categories (beginning with '-')");
+        out.println("    the qualifier applies to that access level and below.");
+        out.println("    If a qualifier is missing, the category applies to");
+        out.println("    all access levels.");
+        out.println("    For example, -Xmsgs:all,-syntax/private");
+        out.println("    This will enable all messages, except syntax errors");
+        out.println("    in the doc comments of private methods.");
+        out.println("    If no -Xmsgs options are provided, the default is");
+        out.println("    equivalent to -Xmsgs:all/protected, meaning that");
+        out.println("    all messages are reported for protected and public");
+        out.println("    declarations only. ");
+        out.println("  -h -help --help -usage -?");
+        out.println("    Show this message.");
+        out.println("");
+        out.println("The following javac options are also supported");
+        out.println("  -bootclasspath, -classpath, -sourcepath, -Xmaxerrs, -Xmaxwarns");
+        out.println("");
+        out.println("To run doclint on part of a project, put the compiled classes for your");
+        out.println("project on the classpath (or bootclasspath), then specify the source files");
+        out.println("to be checked on the command line.");
+    }
+
+    List<File> splitPath(String path) {
+        List<File> files = new ArrayList<File>();
+        for (String f: path.split(File.separator)) {
+            if (f.length() > 0)
+                files.add(new File(f));
+        }
+        return files;
+    }
+
+    List<File> javacBootClassPath;
+    List<File> javacClassPath;
+    List<File> javacSourcePath;
+    List<String> javacOpts;
+    List<File> javacFiles;
+    boolean needHelp = false;
+
+    // </editor-fold>
+
+    // <editor-fold defaultstate="collapsed" desc="javac Plugin">
+
+    @Override
+    public String getName() {
+        return "doclint";
+    }
+
+    @Override
+    public void init(JavacTask task, String... args) {
+        init(task, args, true);
+    }
+
+    // </editor-fold>
+
+    // <editor-fold defaultstate="collapsed" desc="Embedding API">
+
+    public void init(JavacTask task, String[] args, boolean addTaskListener) {
+        env = new Env();
+        for (int i = 0; i < args.length; i++) {
+            String arg = args[i];
+            if (arg.equals(XMSGS_OPTION)) {
+                env.messages.setOptions(null);
+            } else if (arg.startsWith(XMSGS_CUSTOM_PREFIX)) {
+                env.messages.setOptions(arg.substring(arg.indexOf(":") + 1));
+            } else
+                throw new IllegalArgumentException(arg);
+        }
+        env.init(task);
+
+        checker = new Checker(env);
+
+        if (addTaskListener) {
+            final DeclScanner ds = new DeclScanner() {
+                @Override
+                void visitDecl(Tree tree, Name name) {
+                    TreePath p = getCurrentPath();
+                    DocCommentTree dc = env.trees.getDocCommentTree(p);
+
+                    checker.scan(dc, p);
+                }
+            };
+
+            TaskListener tl = new TaskListener() {
+                @Override
+                public void started(TaskEvent e) {
+                    return;
+                }
+
+                @Override
+                public void finished(TaskEvent e) {
+                    switch (e.getKind()) {
+                        case ENTER:
+                            ds.scan(e.getCompilationUnit(), null);
+                    }
+                }
+            };
+
+            task.addTaskListener(tl);
+        }
+    }
+
+    public void scan(TreePath p) {
+        DocCommentTree dc = env.trees.getDocCommentTree(p);
+        checker.scan(dc, p);
+    }
+
+    public void reportStats(PrintWriter out) {
+        env.messages.reportStats(out);
+    }
+
+    // </editor-fold>
+
+    Env env;
+    Checker checker;
+
+    public static boolean isValidOption(String opt) {
+        if (opt.equals(XMSGS_OPTION))
+           return true;
+        if (opt.startsWith(XMSGS_CUSTOM_PREFIX))
+           return Messages.Options.isValidOptions(opt.substring(XMSGS_CUSTOM_PREFIX.length()));
+        return false;
+    }
+
+    // <editor-fold defaultstate="collapsed" desc="DeclScanner">
+
+    static abstract class DeclScanner extends TreePathScanner<Void, Void> {
+        abstract void visitDecl(Tree tree, Name name);
+
+        @Override
+        public Void visitClass(ClassTree tree, Void ignore) {
+            visitDecl(tree, tree.getSimpleName());
+            return super.visitClass(tree, ignore);
+        }
+
+        @Override
+        public Void visitMethod(MethodTree tree, Void ignore) {
+            visitDecl(tree, tree.getName());
+            //return super.visitMethod(tree, ignore);
+            return null;
+        }
+
+        @Override
+        public Void visitVariable(VariableTree tree, Void ignore) {
+            visitDecl(tree, tree.getName());
+            return super.visitVariable(tree, ignore);
+        }
+    }
+
+    // </editor-fold>
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/doclint/Entity.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,326 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.tools.doclint;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Table of entities defined in HTML 4.01.
+ *
+ * <p> Derived from
+ * <a href="http://www.w3.org/TR/html4/sgml/entities.html">Character entity references in HTML 4</a>.
+ *
+ * The name of the member follows the name of the entity,
+ * except when it clashes with a keyword, in which case
+ * it is prefixed by '_'.
+ *
+ * <p><b>This is NOT part of any supported API.
+ * If you write code that depends on this, you do so at your own
+ * risk.  This code and its internal interfaces are subject to change
+ * or deletion without notice.</b></p>
+ */
+enum Entity {
+    nbsp(160),
+    iexcl(161),
+    cent(162),
+    pound(163),
+    curren(164),
+    yen(165),
+    brvbar(166),
+    sect(167),
+    uml(168),
+    copy(169),
+    ordf(170),
+    laquo(171),
+    not(172),
+    shy(173),
+    reg(174),
+    macr(175),
+    deg(176),
+    plusmn(177),
+    sup2(178),
+    sup3(179),
+    acute(180),
+    micro(181),
+    para(182),
+    middot(183),
+    cedil(184),
+    sup1(185),
+    ordm(186),
+    raquo(187),
+    frac14(188),
+    frac12(189),
+    frac34(190),
+    iquest(191),
+    Agrave(192),
+    Aacute(193),
+    Acirc(194),
+    Atilde(195),
+    Auml(196),
+    Aring(197),
+    AElig(198),
+    Ccedil(199),
+    Egrave(200),
+    Eacute(201),
+    Ecirc(202),
+    Euml(203),
+    Igrave(204),
+    Iacute(205),
+    Icirc(206),
+    Iuml(207),
+    ETH(208),
+    Ntilde(209),
+    Ograve(210),
+    Oacute(211),
+    Ocirc(212),
+    Otilde(213),
+    Ouml(214),
+    times(215),
+    Oslash(216),
+    Ugrave(217),
+    Uacute(218),
+    Ucirc(219),
+    Uuml(220),
+    Yacute(221),
+    THORN(222),
+    szlig(223),
+    agrave(224),
+    aacute(225),
+    acirc(226),
+    atilde(227),
+    auml(228),
+    aring(229),
+    aelig(230),
+    ccedil(231),
+    egrave(232),
+    eacute(233),
+    ecirc(234),
+    euml(235),
+    igrave(236),
+    iacute(237),
+    icirc(238),
+    iuml(239),
+    eth(240),
+    ntilde(241),
+    ograve(242),
+    oacute(243),
+    ocirc(244),
+    otilde(245),
+    ouml(246),
+    divide(247),
+    oslash(248),
+    ugrave(249),
+    uacute(250),
+    ucirc(251),
+    uuml(252),
+    yacute(253),
+    thorn(254),
+    yuml(255),
+    fnof(402),
+    Alpha(913),
+    Beta(914),
+    Gamma(915),
+    Delta(916),
+    Epsilon(917),
+    Zeta(918),
+    Eta(919),
+    Theta(920),
+    Iota(921),
+    Kappa(922),
+    Lambda(923),
+    Mu(924),
+    Nu(925),
+    Xi(926),
+    Omicron(927),
+    Pi(928),
+    Rho(929),
+    Sigma(931),
+    Tau(932),
+    Upsilon(933),
+    Phi(934),
+    Chi(935),
+    Psi(936),
+    Omega(937),
+    alpha(945),
+    beta(946),
+    gamma(947),
+    delta(948),
+    epsilon(949),
+    zeta(950),
+    eta(951),
+    theta(952),
+    iota(953),
+    kappa(954),
+    lambda(955),
+    mu(956),
+    nu(957),
+    xi(958),
+    omicron(959),
+    pi(960),
+    rho(961),
+    sigmaf(962),
+    sigma(963),
+    tau(964),
+    upsilon(965),
+    phi(966),
+    chi(967),
+    psi(968),
+    omega(969),
+    thetasym(977),
+    upsih(978),
+    piv(982),
+    bull(8226),
+    hellip(8230),
+    prime(8242),
+    Prime(8243),
+    oline(8254),
+    frasl(8260),
+    weierp(8472),
+    image(8465),
+    real(8476),
+    trade(8482),
+    alefsym(8501),
+    larr(8592),
+    uarr(8593),
+    rarr(8594),
+    darr(8595),
+    harr(8596),
+    crarr(8629),
+    lArr(8656),
+    uArr(8657),
+    rArr(8658),
+    dArr(8659),
+    hArr(8660),
+    forall(8704),
+    part(8706),
+    exist(8707),
+    empty(8709),
+    nabla(8711),
+    isin(8712),
+    notin(8713),
+    ni(8715),
+    prod(8719),
+    sum(8721),
+    minus(8722),
+    lowast(8727),
+    radic(8730),
+    prop(8733),
+    infin(8734),
+    ang(8736),
+    and(8743),
+    or(8744),
+    cap(8745),
+    cup(8746),
+    _int(8747),
+    there4(8756),
+    sim(8764),
+    cong(8773),
+    asymp(8776),
+    ne(8800),
+    equiv(8801),
+    le(8804),
+    ge(8805),
+    sub(8834),
+    sup(8835),
+    nsub(8836),
+    sube(8838),
+    supe(8839),
+    oplus(8853),
+    otimes(8855),
+    perp(8869),
+    sdot(8901),
+    lceil(8968),
+    rceil(8969),
+    lfloor(8970),
+    rfloor(8971),
+    lang(9001),
+    rang(9002),
+    loz(9674),
+    spades(9824),
+    clubs(9827),
+    hearts(9829),
+    diams(9830),
+    quot(34),
+    amp(38),
+    lt(60),
+    gt(62),
+    OElig(338),
+    oelig(339),
+    Scaron(352),
+    scaron(353),
+    Yuml(376),
+    circ(710),
+    tilde(732),
+    ensp(8194),
+    emsp(8195),
+    thinsp(8201),
+    zwnj(8204),
+    zwj(8205),
+    lrm(8206),
+    rlm(8207),
+    ndash(8211),
+    mdash(8212),
+    lsquo(8216),
+    rsquo(8217),
+    sbquo(8218),
+    ldquo(8220),
+    rdquo(8221),
+    bdquo(8222),
+    dagger(8224),
+    Dagger(8225),
+    permil(8240),
+    lsaquo(8249),
+    rsaquo(8250),
+    euro(8364);
+
+    int code;
+
+    private Entity(int code) {
+        this.code = code;
+    }
+
+    static boolean isValid(String name) {
+        return names.containsKey(name);
+    }
+
+    static boolean isValid(int code) {
+        // allow numeric codes for standard ANSI characters
+        return codes.containsKey(code) || ( 32 <= code && code < 2127);
+    }
+
+    private static final Map<String,Entity> names = new HashMap<String,Entity>();
+    private static final Map<Integer,Entity> codes = new HashMap<Integer,Entity>();
+    static {
+        for (Entity e: values()) {
+            String name = e.name();
+            int code = e.code;
+            if (name.startsWith("_")) name = name.substring(1);
+            names.put(name, e);
+            codes.put(code, e);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/doclint/Env.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.tools.doclint;
+
+
+import java.util.Set;
+
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.util.Elements;
+import javax.lang.model.util.Types;
+
+import com.sun.source.doctree.DocCommentTree;
+import com.sun.source.util.DocTrees;
+import com.sun.source.util.JavacTask;
+import com.sun.source.util.SourcePositions;
+import com.sun.source.util.TreePath;
+import com.sun.tools.javac.model.JavacTypes;
+import com.sun.tools.javac.tree.JCTree;
+
+/**
+ * Utility container for current execution environment,
+ * providing the current declaration and its doc comment.
+ *
+ * <p><b>This is NOT part of any supported API.
+ * If you write code that depends on this, you do so at your own
+ * risk.  This code and its internal interfaces are subject to change
+ * or deletion without notice.</b></p>
+ */
+public class Env {
+    /**
+     * Access kinds for declarations.
+     */
+    public enum AccessKind {
+        PRIVATE,
+        PACKAGE,
+        PROTECTED,
+        PUBLIC;
+
+        static boolean accepts(String opt) {
+            for (AccessKind g: values())
+                if (opt.equals(g.name().toLowerCase())) return true;
+            return false;
+        }
+
+        static AccessKind of(Set<Modifier> mods) {
+            if (mods.contains(Modifier.PUBLIC))
+                return AccessKind.PUBLIC;
+            else if (mods.contains(Modifier.PROTECTED))
+                return AccessKind.PROTECTED;
+            else if (mods.contains(Modifier.PRIVATE))
+                return AccessKind.PRIVATE;
+            else
+                return AccessKind.PACKAGE;
+        }
+    };
+
+    /** Message handler. */
+    final Messages messages;
+
+    // Utility classes
+    DocTrees trees;
+    Elements elements;
+    Types types;
+
+    // Types used when analysing doc comments.
+    TypeMirror java_lang_Error;
+    TypeMirror java_lang_RuntimeException;
+    TypeMirror java_lang_Throwable;
+    TypeMirror java_lang_Void;
+
+    /** The path for the declaration containing the comment currently being analyzed. */
+    TreePath currPath;
+    /** The element for the declaration containing the comment currently being analyzed. */
+    Element currElement;
+    /** The comment current being analyzed. */
+    DocCommentTree currDocComment;
+    /**
+     * The access kind of the declaration containing the comment currently being analyzed.
+     * This is the minimum (most restrictive) access kind of the declaration iteself
+     * and that of its containers. For example, a public method in a private class is
+     * noted as private.
+     */
+    AccessKind currAccess;
+    /** The set of methods, if any, that the current declaration overrides. */
+    Set<? extends ExecutableElement> currOverriddenMethods;
+
+    Env() {
+        messages = new Messages(this);
+    }
+
+    void init(JavacTask task) {
+        init(DocTrees.instance(task), task.getElements(), task.getTypes());
+    }
+
+    void init(DocTrees trees, Elements elements, Types types) {
+        this.trees = trees;
+        this.elements = elements;
+        this.types = types;
+        java_lang_Error = elements.getTypeElement("java.lang.Error").asType();
+        java_lang_RuntimeException = elements.getTypeElement("java.lang.RuntimeException").asType();
+        java_lang_Throwable = elements.getTypeElement("java.lang.Throwable").asType();
+        java_lang_Void = elements.getTypeElement("java.lang.Void").asType();
+    }
+
+    /** Set the current declaration and its doc comment. */
+    void setCurrent(TreePath path, DocCommentTree comment) {
+        currPath = path;
+        currDocComment = comment;
+        currElement = trees.getElement(currPath);
+        currOverriddenMethods = ((JavacTypes) types).getOverriddenMethods(currElement);
+
+        AccessKind ak = null;
+        for (TreePath p = path; p != null; p = p.getParentPath()) {
+            Element e = trees.getElement(p);
+            if (e != null) {
+                ak = min(ak, AccessKind.of(e.getModifiers()));
+            }
+        }
+        currAccess = ak;
+    }
+
+    AccessKind getAccessKind() {
+        return currAccess;
+    }
+
+    long getPos(TreePath p) {
+        return ((JCTree) p.getLeaf()).pos;
+    }
+
+    long getStartPos(TreePath p) {
+        SourcePositions sp = trees.getSourcePositions();
+        return sp.getStartPosition(p.getCompilationUnit(), p.getLeaf());
+    }
+
+    private <T extends Comparable<T>> T min(T item1, T item2) {
+        return (item1 == null) ? item2
+                : (item2 == null) ? item1
+                : item1.compareTo(item2) <= 0 ? item1 : item2;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/doclint/HtmlTag.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,356 @@
+/*
+ * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.tools.doclint;
+
+import java.util.Set;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.lang.model.element.Name;
+
+import static com.sun.tools.doclint.HtmlTag.Attr.*;
+
+/**
+ * Enum representing HTML tags.
+ *
+ * The intent of this class is to embody the semantics of W3C HTML 4.01
+ * to the extent supported/used by javadoc.
+ *
+ * This is derivative of com.sun.tools.doclets.formats.html.markup.HtmlTag.
+ * Eventually, these two should be merged back together, and possibly made
+ * public.
+ *
+ * @see <a href="http://www.w3.org/TR/REC-html40/">HTML 4.01 Specification</a>
+ * @author Bhavesh Patel
+ * @author Jonathan Gibbons (revised)
+ */
+public enum HtmlTag {
+    A(BlockType.INLINE, EndKind.REQUIRED,
+            attrs(AttrKind.OK, HREF, TARGET, NAME)),
+
+    B(BlockType.INLINE, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT, Flag.NO_NEST)),
+
+    BLOCKQUOTE,
+
+    BODY(BlockType.OTHER, EndKind.REQUIRED),
+
+    BR(BlockType.INLINE, EndKind.NONE,
+            attrs(AttrKind.USE_CSS, CLEAR)),
+
+    CAPTION(EnumSet.of(Flag.EXPECT_CONTENT)),
+
+    CENTER,
+
+    CITE(BlockType.INLINE, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT, Flag.NO_NEST)),
+
+    CODE(BlockType.INLINE, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT, Flag.NO_NEST)),
+
+    DD(BlockType.BLOCK, EndKind.OPTIONAL,
+            EnumSet.of(Flag.EXPECT_CONTENT)),
+
+    DIV,
+
+    DL(BlockType.BLOCK, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT, Flag.NO_TEXT),
+            attrs(AttrKind.USE_CSS, COMPACT)),
+
+    DT(BlockType.BLOCK, EndKind.OPTIONAL,
+            EnumSet.of(Flag.EXPECT_CONTENT)),
+
+    EM(BlockType.INLINE, EndKind.REQUIRED,
+            EnumSet.of(Flag.NO_NEST)),
+
+    FONT(BlockType.INLINE, EndKind.REQUIRED, // tag itself is deprecated
+            EnumSet.of(Flag.EXPECT_CONTENT),
+            attrs(AttrKind.USE_CSS, SIZE, COLOR, FACE)),
+
+    FRAME(BlockType.OTHER, EndKind.NONE),
+
+    FRAMESET(BlockType.OTHER, EndKind.REQUIRED),
+
+    H1,
+    H2,
+    H3,
+    H4,
+    H5,
+    H6,
+
+    HEAD(BlockType.OTHER, EndKind.REQUIRED),
+
+    HR(BlockType.BLOCK, EndKind.NONE),
+
+    HTML(BlockType.OTHER, EndKind.REQUIRED),
+
+    I(BlockType.INLINE, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT, Flag.NO_NEST)),
+
+    IMG(BlockType.INLINE, EndKind.NONE,
+            attrs(AttrKind.OK, SRC, ALT, HEIGHT, WIDTH),
+            attrs(AttrKind.OBSOLETE, NAME),
+            attrs(AttrKind.USE_CSS, ALIGN, HSPACE, VSPACE, BORDER)),
+
+    LI(BlockType.BLOCK, EndKind.OPTIONAL),
+
+    LINK(BlockType.OTHER, EndKind.NONE),
+
+    MENU,
+
+    META(BlockType.OTHER, EndKind.NONE),
+
+    NOFRAMES(BlockType.OTHER, EndKind.REQUIRED),
+
+    NOSCRIPT(BlockType.OTHER, EndKind.REQUIRED),
+
+    OL(BlockType.BLOCK, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT, Flag.NO_TEXT),
+            attrs(AttrKind.USE_CSS, START, TYPE)),
+
+    P(BlockType.BLOCK, EndKind.OPTIONAL,
+            EnumSet.of(Flag.EXPECT_CONTENT),
+            attrs(AttrKind.USE_CSS, ALIGN)),
+
+    PRE(EnumSet.of(Flag.EXPECT_CONTENT)),
+
+    SCRIPT(BlockType.OTHER, EndKind.REQUIRED),
+
+    SMALL(BlockType.INLINE, EndKind.REQUIRED),
+
+    SPAN(BlockType.INLINE, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT)),
+
+    STRONG(BlockType.INLINE, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT)),
+
+    SUB(BlockType.INLINE, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT, Flag.NO_NEST)),
+
+    SUP(BlockType.INLINE, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT, Flag.NO_NEST)),
+
+    TABLE(BlockType.BLOCK, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT, Flag.NO_TEXT),
+            attrs(AttrKind.OK, SUMMARY, Attr.FRAME, RULES, BORDER,
+                CELLPADDING, CELLSPACING),
+            attrs(AttrKind.USE_CSS, ALIGN, WIDTH, BGCOLOR)),
+
+    TBODY(BlockType.BLOCK, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT, Flag.NO_TEXT),
+            attrs(AttrKind.OK, ALIGN, CHAR, CHAROFF, VALIGN)),
+
+    TD(BlockType.BLOCK, EndKind.OPTIONAL,
+            attrs(AttrKind.OK, COLSPAN, ROWSPAN, HEADERS, SCOPE, ABBR, AXIS,
+                ALIGN, CHAR, CHAROFF, VALIGN),
+            attrs(AttrKind.USE_CSS, WIDTH, BGCOLOR, HEIGHT, NOWRAP)),
+
+    TFOOT(BlockType.BLOCK, EndKind.REQUIRED,
+            attrs(AttrKind.OK, ALIGN, CHAR, CHAROFF, VALIGN)),
+
+    TH(BlockType.BLOCK, EndKind.OPTIONAL,
+            attrs(AttrKind.OK, COLSPAN, ROWSPAN, HEADERS, SCOPE, ABBR, AXIS,
+                ALIGN, CHAR, CHAROFF, VALIGN),
+            attrs(AttrKind.USE_CSS, WIDTH, BGCOLOR, HEIGHT, NOWRAP)),
+
+    THEAD(BlockType.BLOCK, EndKind.REQUIRED,
+            attrs(AttrKind.OK, ALIGN, CHAR, CHAROFF, VALIGN)),
+
+    TITLE(BlockType.OTHER, EndKind.REQUIRED),
+
+    TR(BlockType.BLOCK, EndKind.OPTIONAL,
+            EnumSet.of(Flag.NO_TEXT),
+            attrs(AttrKind.OK, ALIGN, CHAR, CHAROFF, VALIGN),
+            attrs(AttrKind.USE_CSS, BGCOLOR)),
+
+    TT(BlockType.INLINE, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT, Flag.NO_NEST)),
+
+    U(BlockType.INLINE, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT, Flag.NO_NEST)),
+
+    UL(BlockType.BLOCK, EndKind.REQUIRED,
+            EnumSet.of(Flag.EXPECT_CONTENT, Flag.NO_TEXT),
+            attrs(AttrKind.USE_CSS, COMPACT, TYPE)),
+
+    VAR(BlockType.INLINE, EndKind.REQUIRED);
+
+    /**
+     * Enum representing the type of HTML element.
+     */
+    public static enum BlockType {
+        BLOCK,
+        INLINE,
+        OTHER;
+    }
+
+    /**
+     * Enum representing HTML end tag requirement.
+     */
+    public static enum EndKind {
+        NONE,
+        OPTIONAL,
+        REQUIRED;
+    }
+
+    public static enum Flag {
+        EXPECT_CONTENT,
+        NO_NEST,
+        NO_TEXT
+    }
+
+    public static enum Attr {
+        ABBR,
+        ALIGN,
+        ALT,
+        AXIS,
+        BGCOLOR,
+        BORDER,
+        CELLSPACING,
+        CELLPADDING,
+        CHAR,
+        CHAROFF,
+        CLEAR,
+        CLASS,
+        COLOR,
+        COLSPAN,
+        COMPACT,
+        FACE,
+        FRAME,
+        HEADERS,
+        HEIGHT,
+        HREF,
+        HSPACE,
+        ID,
+        NAME,
+        NOWRAP,
+        REVERSED,
+        ROWSPAN,
+        RULES,
+        SCOPE,
+        SIZE,
+        SPACE,
+        SRC,
+        START,
+        STYLE,
+        SUMMARY,
+        TARGET,
+        TYPE,
+        VALIGN,
+        VSPACE,
+        WIDTH;
+
+        public String getText() {
+            return name().toLowerCase();
+        }
+
+        static final Map<String,Attr> index = new HashMap<String,Attr>();
+        static {
+            for (Attr t: values()) {
+                index.put(t.name().toLowerCase(), t);
+            }
+        }
+    }
+
+    public static enum AttrKind {
+        INVALID,
+        OBSOLETE,
+        USE_CSS,
+        OK
+    }
+
+    // This class exists to avoid warnings from using parameterized vararg type
+    // Map<Attr,AttrKind> in signature of HtmlTag constructor.
+    private static class AttrMap extends EnumMap<Attr,AttrKind>  {
+        private static final long serialVersionUID = 0;
+        AttrMap() {
+            super(Attr.class);
+        }
+    }
+
+
+    public final BlockType blockType;
+    public final EndKind endKind;
+    public final Set<Flag> flags;
+    private final Map<Attr,AttrKind> attrs;
+
+
+    HtmlTag() {
+        this(BlockType.BLOCK, EndKind.REQUIRED);
+    }
+
+    HtmlTag(Set<Flag> flags) {
+        this(BlockType.BLOCK, EndKind.REQUIRED, flags);
+    }
+
+    HtmlTag(BlockType blockType, EndKind endKind, AttrMap... attrMaps) {
+        this(blockType, endKind, Collections.<Flag>emptySet(), attrMaps);
+    }
+
+    HtmlTag(BlockType blockType, EndKind endKind, Set<Flag> flags, AttrMap... attrMaps) {
+        this.blockType = blockType;
+        this.endKind = endKind;this.flags = flags;
+        this.attrs = new EnumMap<Attr,AttrKind>(Attr.class);
+        for (Map<Attr,AttrKind> m: attrMaps)
+            this.attrs.putAll(m);
+        attrs.put(Attr.CLASS, AttrKind.OK);
+        attrs.put(Attr.ID, AttrKind.OK);
+        attrs.put(Attr.STYLE, AttrKind.OK);
+    }
+
+    public String getText() {
+        return name().toLowerCase();
+    }
+
+    public Attr getAttr(Name attrName) {
+        return Attr.index.get(attrName.toString().toLowerCase());
+    }
+
+    public AttrKind getAttrKind(Name attrName) {
+        AttrKind k = attrs.get(getAttr(attrName)); // null-safe
+        return (k == null) ? AttrKind.INVALID : k;
+    }
+
+    private static AttrMap attrs(AttrKind k, Attr... attrs) {
+        AttrMap map = new AttrMap();
+        for (Attr a: attrs) map.put(a, k);
+        return map;
+    }
+
+    private static final Map<String,HtmlTag> index = new HashMap<String,HtmlTag>();
+    static {
+        for (HtmlTag t: values()) {
+            index.put(t.name().toLowerCase(), t);
+        }
+    }
+
+    static HtmlTag get(Name tagName) {
+        return index.get(tagName.toString().toLowerCase());
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/doclint/Messages.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,348 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.tools.doclint;
+
+import java.io.PrintWriter;
+import java.text.MessageFormat;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import javax.tools.Diagnostic;
+
+import com.sun.source.doctree.DocTree;
+import com.sun.source.tree.Tree;
+import com.sun.tools.doclint.Env.AccessKind;
+
+/**
+ * Message reporting for DocLint.
+ *
+ * Options are used to filter out messages based on group and access level.
+ * Support can be enabled for accumulating statistics of different kinds of
+ * messages.
+ *
+ * <p><b>This is NOT part of any supported API.
+ * If you write code that depends on this, you do so at your own
+ * risk.  This code and its internal interfaces are subject to change
+ * or deletion without notice.</b></p>
+ */
+public class Messages {
+    /**
+     * Groups used to categorize messages, so that messages in each group
+     * can be enabled or disabled via options.
+     */
+    public enum Group {
+        ACCESSIBILITY,
+        HTML,
+        MISSING,
+        SYNTAX,
+        REFERENCE;
+
+        String optName() { return name().toLowerCase(); }
+        String notOptName() { return "-" + optName(); }
+
+        static boolean accepts(String opt) {
+            for (Group g: values())
+                if (opt.equals(g.optName())) return true;
+            return false;
+        }
+    };
+
+    private final Options options;
+    private final Stats stats;
+
+    ResourceBundle bundle;
+    Env env;
+
+    Messages(Env env) {
+        this.env = env;
+        String name = getClass().getPackage().getName() + ".resources.doclint";
+        bundle = ResourceBundle.getBundle(name, Locale.ENGLISH);
+
+        stats = new Stats(bundle);
+        options = new Options(stats);
+    }
+
+    void error(Group group, DocTree tree, String code, Object... args) {
+        report(group, Diagnostic.Kind.ERROR, tree, code, args);
+    }
+
+    void warning(Group group, DocTree tree, String code, Object... args) {
+        report(group, Diagnostic.Kind.WARNING, tree, code, args);
+    }
+
+    void setOptions(String opts) {
+        options.setOptions(opts);
+    }
+
+    void setStatsEnabled(boolean b) {
+        stats.setEnabled(b);
+    }
+
+    void reportStats(PrintWriter out) {
+        stats.report(out);
+    }
+
+    protected void report(Group group, Diagnostic.Kind dkind, DocTree tree, String code, Object... args) {
+        if (options.isEnabled(group, env.currAccess)) {
+            String msg = (code == null) ? (String) args[0] : localize(code, args);
+            env.trees.printMessage(dkind, msg, tree,
+                    env.currDocComment, env.currPath.getCompilationUnit());
+
+            stats.record(group, dkind, code);
+        }
+    }
+
+    protected void report(Group group, Diagnostic.Kind dkind, Tree tree, String code, Object... args) {
+        if (options.isEnabled(group, env.currAccess)) {
+            String msg = localize(code, args);
+            env.trees.printMessage(dkind, msg, tree, env.currPath.getCompilationUnit());
+
+            stats.record(group, dkind, code);
+        }
+    }
+
+    String localize(String code, Object... args) {
+        String msg = bundle.getString(code);
+        if (msg == null) {
+            StringBuilder sb = new StringBuilder();
+            sb.append("message file broken: code=").append(code);
+            if (args.length > 0) {
+                sb.append(" arguments={0}");
+                for (int i = 1; i < args.length; i++) {
+                    sb.append(", {").append(i).append("}");
+                }
+            }
+            msg = sb.toString();
+        }
+        return MessageFormat.format(msg, args);
+    }
+
+    // <editor-fold defaultstate="collapsed" desc="Options">
+
+    /**
+     * Handler for (sub)options specific to message handling.
+     */
+    static class Options {
+        Map<String, Env.AccessKind> map = new HashMap<String, Env.AccessKind>();
+        private final Stats stats;
+
+        static boolean isValidOptions(String opts) {
+            for (String opt: opts.split(",")) {
+                if (!isValidOption(opt.trim().toLowerCase()))
+                    return false;
+            }
+            return true;
+        }
+
+        private static boolean isValidOption(String opt) {
+            if (opt.equals("none") || opt.equals(Stats.OPT))
+                return true;
+
+            int begin = opt.startsWith("-") ? 1 : 0;
+            int sep = opt.indexOf("/");
+            String grp = opt.substring(begin, (sep != -1) ? sep : opt.length());
+            return ((begin == 0 && grp.equals("all")) || Group.accepts(grp))
+                    && ((sep == -1) || AccessKind.accepts(opt.substring(sep + 1)));
+        }
+
+        Options(Stats stats) {
+            this.stats = stats;
+        }
+
+        /** Determine if a message group is enabled for a particular access level. */
+        boolean isEnabled(Group g, Env.AccessKind access) {
+            if (map.isEmpty())
+                map.put("all", Env.AccessKind.PROTECTED);
+
+            Env.AccessKind ak = map.get(g.optName());
+            if (ak != null && access.compareTo(ak) >= 0)
+                return true;
+
+            ak = map.get(ALL);
+            if (ak != null && access.compareTo(ak) >= 0) {
+                ak = map.get(g.notOptName());
+                if (ak == null || access.compareTo(ak) > 0) // note >, not >=
+                    return true;
+            }
+
+            return false;
+        }
+
+        void setOptions(String opts) {
+            if (opts == null)
+                setOption(ALL, Env.AccessKind.PRIVATE);
+            else {
+                for (String opt: opts.split(","))
+                    setOption(opt.trim().toLowerCase());
+            }
+        }
+
+        private void setOption(String arg) throws IllegalArgumentException {
+            if (arg.equals(Stats.OPT)) {
+                stats.setEnabled(true);
+                return;
+            }
+
+            int sep = arg.indexOf("/");
+            if (sep > 0) {
+                Env.AccessKind ak = Env.AccessKind.valueOf(arg.substring(sep + 1).toUpperCase());
+                setOption(arg.substring(0, sep), ak);
+            } else {
+                setOption(arg, null);
+            }
+        }
+
+        private void setOption(String opt, Env.AccessKind ak) {
+            map.put(opt, (ak != null) ? ak
+                    : opt.startsWith("-") ? Env.AccessKind.PUBLIC : Env.AccessKind.PRIVATE);
+        }
+
+        private static final String ALL = "all";
+    }
+
+    // </editor-fold>
+
+    // <editor-fold defaultstate="collapsed" desc="Statistics">
+
+    /**
+     * Optionally record statistics of different kinds of message.
+     */
+    static class Stats {
+        public static final String OPT = "stats";
+        public static final String NO_CODE = "";
+        final ResourceBundle bundle;
+
+        // tables only initialized if enabled
+        int[] groupCounts;
+        int[] dkindCounts;
+        Map<String, Integer> codeCounts;
+
+        Stats(ResourceBundle bundle) {
+            this.bundle = bundle;
+        }
+
+        void setEnabled(boolean b) {
+            if (b) {
+                groupCounts = new int[Messages.Group.values().length];
+                dkindCounts = new int[Diagnostic.Kind.values().length];
+                codeCounts = new HashMap<String, Integer>();
+            } else {
+                groupCounts = null;
+                dkindCounts = null;
+                codeCounts = null;
+            }
+        }
+
+        void record(Messages.Group g, Diagnostic.Kind dkind, String code) {
+            if (codeCounts == null) {
+                return;
+            }
+            groupCounts[g.ordinal()]++;
+            dkindCounts[dkind.ordinal()]++;
+            if (code == null) {
+                code = NO_CODE;
+            }
+            Integer i = codeCounts.get(code);
+            codeCounts.put(code, (i == null) ? 1 : i + 1);
+        }
+
+        void report(PrintWriter out) {
+            if (codeCounts == null) {
+                return;
+            }
+            out.println("By group...");
+            Table groupTable = new Table();
+            for (Messages.Group g : Messages.Group.values()) {
+                groupTable.put(g.optName(), groupCounts[g.ordinal()]);
+            }
+            groupTable.print(out);
+            out.println();
+            out.println("By diagnostic kind...");
+            Table dkindTable = new Table();
+            for (Diagnostic.Kind k : Diagnostic.Kind.values()) {
+                dkindTable.put(k.toString().toLowerCase(), dkindCounts[k.ordinal()]);
+            }
+            dkindTable.print(out);
+            out.println();
+            out.println("By message kind...");
+            Table codeTable = new Table();
+            for (Map.Entry<String, Integer> e : codeCounts.entrySet()) {
+                String code = e.getKey();
+                String msg;
+                try {
+                    msg = code.equals(NO_CODE) ? "OTHER" : bundle.getString(code);
+                } catch (MissingResourceException ex) {
+                    msg = code;
+                }
+                codeTable.put(msg, e.getValue());
+            }
+            codeTable.print(out);
+        }
+
+        /**
+         * A table of (int, String) sorted by decreasing int.
+         */
+        private static class Table {
+
+            private static final Comparator<Integer> DECREASING = new Comparator<Integer>() {
+
+                public int compare(Integer o1, Integer o2) {
+                    return o2.compareTo(o1);
+                }
+            };
+            private final TreeMap<Integer, Set<String>> map = new TreeMap<Integer, Set<String>>(DECREASING);
+
+            void put(String label, int n) {
+                if (n == 0) {
+                    return;
+                }
+                Set<String> labels = map.get(n);
+                if (labels == null) {
+                    map.put(n, labels = new TreeSet<String>());
+                }
+                labels.add(label);
+            }
+
+            void print(PrintWriter out) {
+                for (Map.Entry<Integer, Set<String>> e : map.entrySet()) {
+                    int count = e.getKey();
+                    Set<String> labels = e.getValue();
+                    for (String label : labels) {
+                        out.println(String.format("%6d: %s", count, label));
+                    }
+                }
+            }
+        }
+    }
+    // </editor-fold>
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/doclint/resources/doclint.properties	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,65 @@
+#
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+dc.anchor.already.defined = anchor already defined: {0}
+dc.attr.lacks.value = attribute lacks value
+dc.attr.obsolete = attribute obsolete: {0}
+dc.attr.obsolete.use.css = attribute obsolete, use CSS instead: {0}
+dc.attr.repeated = repeated attribute: {0}
+dc.attr.unknown = unknown attribute: {0}
+dc.bad.option = bad option: {0}
+dc.bad.value.for.option = bad value for option: {0} {1}
+dc.empty = no description for @{0}
+dc.entity.invalid = invalid entity &{0};
+dc.exception.not.thrown = exception not thrown: {0}
+dc.invalid.anchor = invalid name for anchor: "{0}"
+dc.invalid.param = invalid use of @param
+dc.invalid.return = invalid use of @return
+dc.invalid.throws = invalid use of @throws
+dc.invalid.uri = invalid uri: "{0}"
+dc.missing.comment = no comment
+dc.missing.param = no @param for {0}
+dc.missing.return = no @return
+dc.missing.throws = no @throws for {0}
+dc.no.alt.attr.for.image = no "alt" attribute for image
+dc.no.summary.or.caption.for.table=no summary or caption for table
+dc.param.name.not.found = @param name not found
+dc.ref.not.found = reference not found
+dc.tag.empty = empty <{0}> tag
+dc.tag.end.not.permitted = invalid end tag: </{0}>
+dc.tag.end.unexpected = unexpected end tag: </{0}>
+dc.tag.header.sequence.1 = header used out of sequence: <{0}>
+dc.tag.header.sequence.2 = header used out of sequence: <{0}>
+dc.tag.nested.not.allowed=nested tag not allowed: <{0}>
+dc.tag.not.allowed = element not allowed in documentation comments: <{0}>
+dc.tag.not.allowed.inline.element = block element not allowed within inline element <{1}>: {0}
+dc.tag.not.allowed.inline.tag = block element not allowed within @{1}: {0}
+dc.tag.not.allowed.inline.other = block element not allowed here: {0}
+dc.tag.not.closed= element not closed: {0}
+dc.tag.p.in.pre= unexpected use of <p> inside <pre> element
+dc.tag.self.closing = self-closing element not allowed
+dc.tag.start.unmatched = end tag missing: </{0}>
+dc.tag.unknown = unknown tag: {0}
+dc.text.not.allowed = text not allowed in <{0}> element
--- a/langtools/src/share/classes/com/sun/tools/javac/api/BasicJavacTask.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/api/BasicJavacTask.java	Tue Jan 22 11:54:16 2013 -0800
@@ -57,6 +57,13 @@
     protected Context context;
     private TaskListener taskListener;
 
+    public static JavacTask instance(Context context) {
+        JavacTask instance = context.get(JavacTask.class);
+        if (instance == null)
+            instance = new BasicJavacTask(context, true);
+        return instance;
+    }
+
     public BasicJavacTask(Context c, boolean register) {
         context = c;
         if (register)
--- a/langtools/src/share/classes/com/sun/tools/javac/api/JavacTaskImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/api/JavacTaskImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -65,7 +65,6 @@
  * @author Jonathan Gibbons
  */
 public class JavacTaskImpl extends BasicJavacTask {
-    private ClientCodeWrapper ccw;
     private Main compilerMain;
     private JavaCompiler compiler;
     private Locale locale;
@@ -85,7 +84,6 @@
                 Context context,
                 List<JavaFileObject> fileObjects) {
         super(null, false);
-        this.ccw = ClientCodeWrapper.instance(context);
         this.compilerMain = compilerMain;
         this.args = args;
         this.classNames = classNames;
--- a/langtools/src/share/classes/com/sun/tools/javac/api/JavacTool.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/api/JavacTool.java	Tue Jan 22 11:54:16 2013 -0800
@@ -159,7 +159,7 @@
         }
     }
 
-    private static void processOptions(Context context,
+    public static void processOptions(Context context,
                                        JavaFileManager fileManager,
                                        Iterable<String> options)
     {
--- a/langtools/src/share/classes/com/sun/tools/javac/api/JavacTrees.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/api/JavacTrees.java	Tue Jan 22 11:54:16 2013 -0800
@@ -84,6 +84,7 @@
 import com.sun.tools.javac.tree.TreeCopier;
 import com.sun.tools.javac.tree.TreeInfo;
 import com.sun.tools.javac.tree.TreeMaker;
+import com.sun.tools.javac.util.Abort;
 import com.sun.tools.javac.util.Assert;
 import com.sun.tools.javac.util.Context;
 import com.sun.tools.javac.util.JCDiagnostic;
@@ -236,19 +237,26 @@
     public Element getElement(TreePath path) {
         JCTree tree = (JCTree) path.getLeaf();
         Symbol sym = TreeInfo.symbolFor(tree);
-        if (sym == null && TreeInfo.isDeclaration(tree)) {
-            for (TreePath p = path; p != null; p = p.getParentPath()) {
-                JCTree t = (JCTree) p.getLeaf();
-                if (t.hasTag(JCTree.Tag.CLASSDEF)) {
-                    JCClassDecl ct = (JCClassDecl) t;
-                    if (ct.sym != null) {
-                        if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
-                            attr.attribClass(ct.pos(), ct.sym);
-                            sym = TreeInfo.symbolFor(tree);
+        if (sym == null) {
+            if (TreeInfo.isDeclaration(tree)) {
+                for (TreePath p = path; p != null; p = p.getParentPath()) {
+                    JCTree t = (JCTree) p.getLeaf();
+                    if (t.hasTag(JCTree.Tag.CLASSDEF)) {
+                        JCClassDecl ct = (JCClassDecl) t;
+                        if (ct.sym != null) {
+                            if ((ct.sym.flags_field & Flags.UNATTRIBUTED) != 0) {
+                                attr.attribClass(ct.pos(), ct.sym);
+                                sym = TreeInfo.symbolFor(tree);
+                            }
+                            break;
                         }
-                        break;
                     }
                 }
+            } else if (tree.hasTag(Tag.TOPLEVEL)) {
+                JCCompilationUnit cu = (JCCompilationUnit) tree;
+                if (cu.sourcefile.isNameCompatible("package-info", JavaFileObject.Kind.SOURCE)) {
+                    sym = cu.packge;
+                }
             }
         }
         return sym;
@@ -332,6 +340,8 @@
             } else {
                 return msym;
             }
+        } catch (Abort e) { // may be thrown by Check.completionError in case of bad class file
+            return null;
         } finally {
             log.popDiagnosticHandler(deferredDiagnosticHandler);
         }
--- a/langtools/src/share/classes/com/sun/tools/javac/code/Attribute.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/code/Attribute.java	Tue Jan 22 11:54:16 2013 -0800
@@ -60,6 +60,9 @@
         throw new UnsupportedOperationException();
     }
 
+    public boolean isSynthesized() {
+        return false;
+    }
 
     /** The value for an annotation element of primitive type or String. */
     public static class Constant extends Attribute {
@@ -136,6 +139,18 @@
          *  access this attribute.
          */
         public final List<Pair<MethodSymbol,Attribute>> values;
+
+        private boolean synthesized = false;
+
+        @Override
+        public boolean isSynthesized() {
+            return synthesized;
+        }
+
+        public void setSynthesized(boolean synthesized) {
+            this.synthesized = synthesized;
+        }
+
         public Compound(Type type,
                         List<Pair<MethodSymbol,Attribute>> values) {
             super(type);
--- a/langtools/src/share/classes/com/sun/tools/javac/code/Symbol.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/code/Symbol.java	Tue Jan 22 11:54:16 2013 -0800
@@ -83,13 +83,13 @@
      *  Attributes of class symbols should be accessed through the accessor
      *  method to make sure that the class symbol is loaded.
      */
-    public List<Attribute.Compound> getAnnotationMirrors() {
-        return Assert.checkNonNull(annotations.getAttributes());
+    public List<Attribute.Compound> getRawAttributes() {
+        return annotations.getAttributes();
     }
 
     /** Fetch a particular annotation from a symbol. */
     public Attribute.Compound attribute(Symbol anno) {
-        for (Attribute.Compound a : getAnnotationMirrors()) {
+        for (Attribute.Compound a : getRawAttributes()) {
             if (a.type.tsym == anno) return a;
         }
         return null;
@@ -447,6 +447,14 @@
     }
 
     /**
+     * This is the implementation for {@code
+     * javax.lang.model.element.Element.getAnnotationMirrors()}.
+     */
+    public final List<Attribute.Compound> getAnnotationMirrors() {
+        return getRawAttributes();
+    }
+
+    /**
      * @deprecated this method should never be used by javac internally.
      */
     @Deprecated
@@ -662,15 +670,21 @@
             return flags_field;
         }
 
-        public List<Attribute.Compound> getAnnotationMirrors() {
+        @Override
+        public List<Attribute.Compound> getRawAttributes() {
             if (completer != null) complete();
             if (package_info != null && package_info.completer != null) {
                 package_info.complete();
-                if (annotations.isEmpty()) {
-                    annotations.setAttributes(package_info.annotations);
+                mergeAttributes();
             }
+            return super.getRawAttributes();
+        }
+
+        private void mergeAttributes() {
+            if (annotations.isEmpty() &&
+                !package_info.annotations.isEmpty()) {
+                annotations.setAttributes(package_info.annotations);
             }
-            return Assert.checkNonNull(annotations.getAttributes());
         }
 
         /** A package "exists" if a type or package that exists has
@@ -770,9 +784,10 @@
             return members_field;
         }
 
-        public List<Attribute.Compound> getAnnotationMirrors() {
+        @Override
+        public List<Attribute.Compound> getRawAttributes() {
             if (completer != null) complete();
-            return Assert.checkNonNull(annotations.getAttributes());
+            return super.getRawAttributes();
         }
 
         public Type erasure(Types types) {
@@ -1268,8 +1283,9 @@
                 List<Name> paramNames = savedParameterNames;
                 savedParameterNames = null;
                 // discard the provided names if the list of names is the wrong size.
-                if (paramNames == null || paramNames.size() != type.getParameterTypes().size())
+                if (paramNames == null || paramNames.size() != type.getParameterTypes().size()) {
                     paramNames = List.nil();
+                }
                 ListBuffer<VarSymbol> buf = new ListBuffer<VarSymbol>();
                 List<Name> remaining = paramNames;
                 // assert: remaining and paramNames are both empty or both
@@ -1353,7 +1369,7 @@
             return defaultValue;
         }
 
-        public List<VarSymbol> getParameters() {
+         public List<VarSymbol> getParameters() {
             return params();
         }
 
@@ -1361,6 +1377,10 @@
             return (flags() & VARARGS) != 0;
         }
 
+        public boolean isDefault() {
+            return (flags() & DEFAULT) != 0;
+        }
+
         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
             return v.visitExecutable(this, p);
         }
--- a/langtools/src/share/classes/com/sun/tools/javac/code/Type.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/code/Type.java	Tue Jan 22 11:54:16 2013 -0800
@@ -302,10 +302,12 @@
      * never complete classes. Where isSameType would complete a
      * class, equals assumes that the two types are different.
      */
+    @Override
     public boolean equals(Object t) {
         return super.equals(t);
     }
 
+    @Override
     public int hashCode() {
         return super.hashCode();
     }
@@ -996,34 +998,6 @@
             return "(" + argtypes + ")" + restype;
         }
 
-        public boolean equals(Object obj) {
-            if (this == obj)
-                return true;
-            if (!(obj instanceof MethodType))
-                return false;
-            MethodType m = (MethodType)obj;
-            List<Type> args1 = argtypes;
-            List<Type> args2 = m.argtypes;
-            while (!args1.isEmpty() && !args2.isEmpty()) {
-                if (!args1.head.equals(args2.head))
-                    return false;
-                args1 = args1.tail;
-                args2 = args2.tail;
-            }
-            if (!args1.isEmpty() || !args2.isEmpty())
-                return false;
-            return restype.equals(m.restype);
-        }
-
-        public int hashCode() {
-            int h = METHOD.ordinal();
-            for (List<Type> thisargs = this.argtypes;
-                 thisargs.tail != null; /*inlined: thisargs.nonEmpty()*/
-                 thisargs = thisargs.tail)
-                h = (h << 5) + thisargs.head.hashCode();
-            return (h << 5) + this.restype.hashCode();
-        }
-
         public List<Type>        getParameterTypes() { return argtypes; }
         public Type              getReturnType()     { return restype; }
         public List<Type>        getThrownTypes()    { return thrown; }
--- a/langtools/src/share/classes/com/sun/tools/javac/code/Types.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/code/Types.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1007,11 +1007,11 @@
                     if (!visit(supertype(t), supertype(s)))
                         return false;
 
-                    HashSet<SingletonType> set = new HashSet<SingletonType>();
+                    HashSet<UniqueType> set = new HashSet<UniqueType>();
                     for (Type x : interfaces(t))
-                        set.add(new SingletonType(x));
+                        set.add(new UniqueType(x, Types.this));
                     for (Type x : interfaces(s)) {
-                        if (!set.remove(new SingletonType(x)))
+                        if (!set.remove(new UniqueType(x, Types.this)))
                             return false;
                     }
                     return (set.isEmpty());
@@ -3137,7 +3137,7 @@
             }
             @Override
             public int hashCode() {
-                return 127 * Types.hashCode(t1) + Types.hashCode(t2);
+                return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
             }
             @Override
             public boolean equals(Object obj) {
@@ -3400,7 +3400,7 @@
     /**
      * Compute a hash code on a type.
      */
-    public static int hashCode(Type t) {
+    public int hashCode(Type t) {
         return hashCode.visit(t);
     }
     // where
@@ -3423,6 +3423,16 @@
             }
 
             @Override
+            public Integer visitMethodType(MethodType t, Void ignored) {
+                int h = METHOD.ordinal();
+                for (List<Type> thisargs = t.argtypes;
+                     thisargs.tail != null;
+                     thisargs = thisargs.tail)
+                    h = (h << 5) + visit(thisargs.head);
+                return (h << 5) + visit(t.restype);
+            }
+
+            @Override
             public Integer visitWildcardType(WildcardType t, Void ignored) {
                 int result = t.kind.hashCode();
                 if (t.type != null) {
@@ -4082,21 +4092,28 @@
     /**
      * A wrapper for a type that allows use in sets.
      */
-    class SingletonType {
-        final Type t;
-        SingletonType(Type t) {
-            this.t = t;
-        }
-        public int hashCode() {
-            return Types.hashCode(t);
+    public static class UniqueType {
+        public final Type type;
+        final Types types;
+
+        public UniqueType(Type type, Types types) {
+            this.type = type;
+            this.types = types;
         }
-        public boolean equals(Object obj) {
-            return (obj instanceof SingletonType) &&
-                isSameType(t, ((SingletonType)obj).t);
+
+        public int hashCode() {
+            return types.hashCode(type);
         }
+
+        public boolean equals(Object obj) {
+            return (obj instanceof UniqueType) &&
+                types.isSameType(type, ((UniqueType)obj).type);
+        }
+
         public String toString() {
-            return t.toString();
+            return type.toString();
         }
+
     }
     // </editor-fold>
 
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Annotate.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Annotate.java	Tue Jan 22 11:54:16 2013 -0800
@@ -400,6 +400,7 @@
             Attribute.Compound c = enterAnnotation(annoTree,
                                                    targetContainerType,
                                                    ctx.env);
+            c.setSynthesized(true);
             return c;
         } else {
             return null; // errors should have been reported elsewhere
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1405,7 +1405,8 @@
         Type owntype = standaloneConditional ? condType(tree, truetype, falsetype) : pt();
         if (condtype.constValue() != null &&
                 truetype.constValue() != null &&
-                falsetype.constValue() != null) {
+                falsetype.constValue() != null &&
+                !owntype.hasTag(NONE)) {
             //constant folding
             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
         }
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/DeferredAttr.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/DeferredAttr.java	Tue Jan 22 11:54:16 2013 -0800
@@ -38,6 +38,7 @@
 import javax.tools.JavaFileObject;
 
 import java.util.ArrayList;
+import java.util.EnumSet;
 import java.util.LinkedHashSet;
 import java.util.Map;
 import java.util.Queue;
@@ -177,29 +178,19 @@
          * attribution round must follow one or more speculative rounds.
          */
         Type check(ResultInfo resultInfo) {
+            return check(resultInfo, stuckVars(tree, env, resultInfo), basicCompleter);
+        }
+
+        Type check(ResultInfo resultInfo, List<Type> stuckVars, DeferredTypeCompleter deferredTypeCompleter) {
             DeferredAttrContext deferredAttrContext =
                     resultInfo.checkContext.deferredAttrContext();
             Assert.check(deferredAttrContext != emptyDeferredAttrContext);
-            List<Type> stuckVars = stuckVars(tree, env, resultInfo);
             if (stuckVars.nonEmpty()) {
                 deferredAttrContext.addDeferredAttrNode(this, resultInfo, stuckVars);
                 return Type.noType;
             } else {
                 try {
-                    switch (deferredAttrContext.mode) {
-                        case SPECULATIVE:
-                            Assert.check(mode == null ||
-                                    (mode == AttrMode.SPECULATIVE &&
-                                    speculativeType(deferredAttrContext.msym, deferredAttrContext.phase).hasTag(NONE)));
-                            JCTree speculativeTree = attribSpeculative(tree, env, resultInfo);
-                            speculativeCache.put(deferredAttrContext.msym, speculativeTree, deferredAttrContext.phase);
-                            return speculativeTree.type;
-                        case CHECK:
-                            Assert.check(mode == AttrMode.SPECULATIVE);
-                            return attr.attribTree(tree, env, resultInfo);
-                    }
-                    Assert.error();
-                    return null;
+                    return deferredTypeCompleter.complete(this, resultInfo, deferredAttrContext);
                 } finally {
                     mode = deferredAttrContext.mode;
                 }
@@ -208,6 +199,43 @@
     }
 
     /**
+     * A completer for deferred types. Defines an entry point for type-checking
+     * a deferred type.
+     */
+    interface DeferredTypeCompleter {
+        /**
+         * Entry point for type-checking a deferred type. Depending on the
+         * circumstances, type-checking could amount to full attribution
+         * or partial structural check (aka potential applicability).
+         */
+        Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext);
+    }
+
+    /**
+     * A basic completer for deferred types. This completer type-checks a deferred type
+     * using attribution; depending on the attribution mode, this could be either standard
+     * or speculative attribution.
+     */
+    DeferredTypeCompleter basicCompleter = new DeferredTypeCompleter() {
+        public Type complete(DeferredType dt, ResultInfo resultInfo, DeferredAttrContext deferredAttrContext) {
+            switch (deferredAttrContext.mode) {
+                case SPECULATIVE:
+                    Assert.check(dt.mode == null ||
+                            (dt.mode == AttrMode.SPECULATIVE &&
+                            dt.speculativeType(deferredAttrContext.msym, deferredAttrContext.phase).hasTag(NONE)));
+                    JCTree speculativeTree = attribSpeculative(dt.tree, dt.env, resultInfo);
+                    dt.speculativeCache.put(deferredAttrContext.msym, speculativeTree, deferredAttrContext.phase);
+                    return speculativeTree.type;
+                case CHECK:
+                    Assert.check(dt.mode == AttrMode.SPECULATIVE);
+                    return attr.attribTree(dt.tree, dt.env, resultInfo);
+            }
+            Assert.error();
+            return null;
+        }
+    };
+
+    /**
      * The 'mode' in which the deferred type is to be type-checked
      */
     public enum AttrMode {
@@ -498,10 +526,80 @@
                 if (resultInfo.pt.hasTag(NONE) || resultInfo.pt.isErroneous()) {
             return List.nil();
         } else {
-            StuckChecker sc = new StuckChecker(resultInfo, env);
+            return stuckVarsInternal(tree, resultInfo.pt, resultInfo.checkContext.inferenceContext());
+        }
+    }
+    //where
+        private List<Type> stuckVarsInternal(JCTree tree, Type pt, Infer.InferenceContext inferenceContext) {
+            StuckChecker sc = new StuckChecker(pt, inferenceContext);
             sc.scan(tree);
             return List.from(sc.stuckVars);
         }
+
+    /**
+     * A special tree scanner that would only visit portions of a given tree.
+     * The set of nodes visited by the scanner can be customized at construction-time.
+     */
+    abstract static class FilterScanner extends TreeScanner {
+
+        final Filter<JCTree> treeFilter;
+
+        FilterScanner(final Set<JCTree.Tag> validTags) {
+            this.treeFilter = new Filter<JCTree>() {
+                public boolean accepts(JCTree t) {
+                    return validTags.contains(t.getTag());
+                }
+            };
+        }
+
+        @Override
+        public void scan(JCTree tree) {
+            if (tree != null) {
+                if (treeFilter.accepts(tree)) {
+                    super.scan(tree);
+                } else {
+                    skip(tree);
+                }
+            }
+        }
+
+        /**
+         * handler that is executed when a node has been discarded
+         */
+        abstract void skip(JCTree tree);
+    }
+
+    /**
+     * A tree scanner suitable for visiting the target-type dependent nodes of
+     * a given argument expression.
+     */
+    static class PolyScanner extends FilterScanner {
+
+        PolyScanner() {
+            super(EnumSet.of(CONDEXPR, PARENS, LAMBDA, REFERENCE));
+        }
+
+        @Override
+        void skip(JCTree tree) {
+            //do nothing
+        }
+    }
+
+    /**
+     * A tree scanner suitable for visiting the target-type dependent nodes nested
+     * within a lambda expression body.
+     */
+    static class LambdaReturnScanner extends FilterScanner {
+
+        LambdaReturnScanner() {
+            super(EnumSet.of(BLOCK, CASE, CATCH, DOLOOP, FOREACHLOOP,
+                    FORLOOP, RETURN, SYNCHRONIZED, SWITCH, TRY, WHILELOOP));
+        }
+
+        @Override
+        void skip(JCTree tree) {
+            //do nothing
+        }
     }
 
     /**
@@ -510,83 +608,32 @@
      * inferring types that make some of the nested expressions incompatible
      * with their corresponding instantiated target
      */
-    class StuckChecker extends TreeScanner {
+    class StuckChecker extends PolyScanner {
 
         Type pt;
-        Filter<JCTree> treeFilter;
         Infer.InferenceContext inferenceContext;
         Set<Type> stuckVars = new LinkedHashSet<Type>();
-        Env<AttrContext> env;
 
-        final Filter<JCTree> argsFilter = new Filter<JCTree>() {
-            public boolean accepts(JCTree t) {
-                switch (t.getTag()) {
-                    case CONDEXPR:
-                    case LAMBDA:
-                    case PARENS:
-                    case REFERENCE:
-                        return true;
-                    default:
-                        return false;
-                }
-            }
-        };
-
-        final Filter<JCTree> lambdaBodyFilter = new Filter<JCTree>() {
-            public boolean accepts(JCTree t) {
-                switch (t.getTag()) {
-                    case BLOCK: case CASE: case CATCH: case DOLOOP:
-                    case FOREACHLOOP: case FORLOOP: case RETURN:
-                    case SYNCHRONIZED: case SWITCH: case TRY: case WHILELOOP:
-                        return true;
-                    default:
-                        return false;
-                }
-            }
-        };
-
-        StuckChecker(ResultInfo resultInfo, Env<AttrContext> env) {
-            this.pt = resultInfo.pt;
-            this.inferenceContext = resultInfo.checkContext.inferenceContext();
-            this.treeFilter = argsFilter;
-            this.env = env;
-        }
-
-        @Override
-        public void scan(JCTree tree) {
-            if (tree != null && treeFilter.accepts(tree)) {
-                super.scan(tree);
-            }
+        StuckChecker(Type pt, Infer.InferenceContext inferenceContext) {
+            this.pt = pt;
+            this.inferenceContext = inferenceContext;
         }
 
         @Override
         public void visitLambda(JCLambda tree) {
-            Type prevPt = pt;
-            Filter<JCTree> prevFilter = treeFilter;
-            try {
-                if (inferenceContext.inferenceVars().contains(pt)) {
-                    stuckVars.add(pt);
-                }
-                if (!types.isFunctionalInterface(pt.tsym)) {
-                    return;
-                }
-                Type descType = types.findDescriptorType(pt);
-                List<Type> freeArgVars = inferenceContext.freeVarsIn(descType.getParameterTypes());
-                if (!TreeInfo.isExplicitLambda(tree) &&
-                        freeArgVars.nonEmpty()) {
-                    stuckVars.addAll(freeArgVars);
-                }
-                pt = descType.getReturnType();
-                if (tree.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
-                    scan(tree.getBody());
-                } else {
-                    treeFilter = lambdaBodyFilter;
-                    super.visitLambda(tree);
-                }
-            } finally {
-                pt = prevPt;
-                treeFilter = prevFilter;
+            if (inferenceContext.inferenceVars().contains(pt)) {
+                stuckVars.add(pt);
+            }
+            if (!types.isFunctionalInterface(pt.tsym)) {
+                return;
             }
+            Type descType = types.findDescriptorType(pt);
+            List<Type> freeArgVars = inferenceContext.freeVarsIn(descType.getParameterTypes());
+            if (!TreeInfo.isExplicitLambda(tree) &&
+                    freeArgVars.nonEmpty()) {
+                stuckVars.addAll(freeArgVars);
+            }
+            scanLambdaBody(tree, descType.getReturnType());
         }
 
         @Override
@@ -605,16 +652,19 @@
             stuckVars.addAll(freeArgVars);
         }
 
-        @Override
-        public void visitReturn(JCReturn tree) {
-            Filter<JCTree> prevFilter = treeFilter;
-            try {
-                treeFilter = argsFilter;
-                if (tree.expr != null) {
-                    scan(tree.expr);
-                }
-            } finally {
-                treeFilter = prevFilter;
+        void scanLambdaBody(JCLambda lambda, final Type pt) {
+            if (lambda.getBodyKind() == JCTree.JCLambda.BodyKind.EXPRESSION) {
+                stuckVars.addAll(stuckVarsInternal(lambda.body, pt, inferenceContext));
+            } else {
+                LambdaReturnScanner lambdaScanner = new LambdaReturnScanner() {
+                    @Override
+                    public void visitReturn(JCReturn tree) {
+                        if (tree.expr != null) {
+                            stuckVars.addAll(stuckVarsInternal(tree.expr, pt, inferenceContext));
+                        }
+                    }
+                };
+                lambdaScanner.scan(lambda.body);
             }
         }
     }
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java	Tue Jan 22 11:54:16 2013 -0800
@@ -114,7 +114,7 @@
         }
     }
 
-    private final InferenceException inferenceException;
+    final InferenceException inferenceException;
 
 /***************************************************************************
  * Mini/Maximization of UndetVars
@@ -271,15 +271,19 @@
                                   boolean allowBoxing,
                                   boolean useVarargs,
                                   Resolve.MethodResolutionContext resolveContext,
+                                  Resolve.MethodCheck methodCheck,
                                   Warner warn) throws InferenceException {
         //-System.err.println("instantiateMethod(" + tvars + ", " + mt + ", " + argtypes + ")"); //DEBUG
         final InferenceContext inferenceContext = new InferenceContext(tvars, this, true);
         inferenceException.clear();
 
+        DeferredAttr.DeferredAttrContext deferredAttrContext =
+                resolveContext.deferredAttrContext(msym, inferenceContext);
+
         try {
-            rs.checkRawArgumentsAcceptable(env, msym, resolveContext.attrMode(), inferenceContext,
-                    argtypes, mt.getParameterTypes(), allowBoxing, useVarargs, warn,
-                    new InferenceCheckHandler(inferenceContext));
+            methodCheck.argumentsAcceptable(env, deferredAttrContext, argtypes, mt.getParameterTypes(), warn);
+
+            deferredAttrContext.complete();
 
             // minimize as yet undetermined type variables
             for (Type t : inferenceContext.undetvars) {
@@ -309,32 +313,6 @@
             inferenceContext.notifyChange(types);
         }
     }
-    //where
-
-        /** inference check handler **/
-        class InferenceCheckHandler implements Resolve.MethodCheckHandler {
-
-            InferenceContext inferenceContext;
-
-            public InferenceCheckHandler(InferenceContext inferenceContext) {
-                this.inferenceContext = inferenceContext;
-            }
-
-            public InapplicableMethodException arityMismatch() {
-                return inferenceException.setMessage("infer.arg.length.mismatch", inferenceContext.inferenceVars());
-            }
-            public InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details) {
-                String key = varargs ?
-                        "infer.varargs.argument.mismatch" :
-                        "infer.no.conforming.assignment.exists";
-                return inferenceException.setMessage(key,
-                        inferenceContext.inferenceVars(), details);
-            }
-            public InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected) {
-                return inferenceException.setMessage("inaccessible.varargs.type",
-                        expected, Kinds.kindName(location), location);
-            }
-        }
 
     /** check that type parameters are within their bounds.
      */
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java	Tue Jan 22 11:54:16 2013 -0800
@@ -692,8 +692,9 @@
         //determine the static bsm args
         Type mtype = makeFunctionalDescriptorType(targetType, true);
         List<Object> staticArgs = List.<Object>of(
-                new Pool.MethodHandle(ClassFile.REF_invokeInterface, types.findDescriptorSymbol(targetType.tsym)),
-                new Pool.MethodHandle(refKind, refSym),
+                new Pool.MethodHandle(ClassFile.REF_invokeInterface,
+                    types.findDescriptorSymbol(targetType.tsym), types),
+                new Pool.MethodHandle(refKind, refSym, types),
                 new MethodType(mtype.getParameterTypes(),
                         mtype.getReturnType(),
                         mtype.getThrownTypes(),
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java	Tue Jan 22 11:54:16 2013 -0800
@@ -506,6 +506,7 @@
                         List<Type> typeargtypes,
                         boolean allowBoxing,
                         boolean useVarargs,
+                        MethodCheck methodCheck,
                         Warner warn) throws Infer.InferenceException {
 
         Type mt = types.memberType(site, m);
@@ -558,10 +559,11 @@
                                     allowBoxing,
                                     useVarargs,
                                     currentResolutionContext,
+                                    methodCheck,
                                     warn);
 
-        checkRawArgumentsAcceptable(env, m, argtypes, mt.getParameterTypes(),
-                                allowBoxing, useVarargs, warn);
+        methodCheck.argumentsAcceptable(env, currentResolutionContext.deferredAttrContext(m, infer.emptyContext),
+                                argtypes, mt.getParameterTypes(), warn);
         return mt;
     }
 
@@ -578,7 +580,7 @@
             currentResolutionContext.attrMode = DeferredAttr.AttrMode.CHECK;
             MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
-                    step.isBoxingRequired(), step.isVarargsRequired(), warn);
+                    step.isBoxingRequired(), step.isVarargsRequired(), resolveMethodCheck, warn);
         }
         finally {
             currentResolutionContext = prevContext;
@@ -595,80 +597,65 @@
                      List<Type> typeargtypes,
                      boolean allowBoxing,
                      boolean useVarargs,
+                     MethodCheck methodCheck,
                      Warner warn) {
         try {
             return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
-                                  allowBoxing, useVarargs, warn);
+                                  allowBoxing, useVarargs, methodCheck, warn);
         } catch (InapplicableMethodException ex) {
             return null;
         }
     }
 
-    /** Check if a parameter list accepts a list of args.
+    /**
+     * This interface defines an entry point that should be used to perform a
+     * method check. A method check usually consist in determining as to whether
+     * a set of types (actuals) is compatible with another set of types (formals).
+     * Since the notion of compatibility can vary depending on the circumstances,
+     * this interfaces allows to easily add new pluggable method check routines.
      */
-    boolean argumentsAcceptable(Env<AttrContext> env,
-                                Symbol msym,
+    interface MethodCheck {
+        /**
+         * Main method check routine. A method check usually consist in determining
+         * as to whether a set of types (actuals) is compatible with another set of
+         * types (formals). If an incompatibility is found, an unchecked exception
+         * is assumed to be thrown.
+         */
+        void argumentsAcceptable(Env<AttrContext> env,
+                                DeferredAttrContext deferredAttrContext,
                                 List<Type> argtypes,
                                 List<Type> formals,
-                                boolean allowBoxing,
-                                boolean useVarargs,
-                                Warner warn) {
-        try {
-            checkRawArgumentsAcceptable(env, msym, argtypes, formals, allowBoxing, useVarargs, warn);
-            return true;
-        } catch (InapplicableMethodException ex) {
-            return false;
-        }
-    }
-    /**
-     * A check handler is used by the main method applicability routine in order
-     * to handle specific method applicability failures. It is assumed that a class
-     * implementing this interface should throw exceptions that are a subtype of
-     * InapplicableMethodException (see below). Such exception will terminate the
-     * method applicability check and propagate important info outwards (for the
-     * purpose of generating better diagnostics).
-     */
-    interface MethodCheckHandler {
-        /* The number of actuals and formals differ */
-        InapplicableMethodException arityMismatch();
-        /* An actual argument type does not conform to the corresponding formal type */
-        InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details);
-        /* The element type of a varargs is not accessible in the current context */
-        InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected);
+                                Warner warn);
     }
 
     /**
-     * Basic method check handler used within Resolve - all methods end up
-     * throwing InapplicableMethodException; a diagnostic fragment that describes
-     * the cause as to why the method is not applicable is set on the exception
-     * before it is thrown.
+     * Helper enum defining all method check diagnostics (used by resolveMethodCheck).
      */
-    MethodCheckHandler resolveHandler = new MethodCheckHandler() {
-            public InapplicableMethodException arityMismatch() {
-                return inapplicableMethodException.setMessage("arg.length.mismatch");
-            }
-            public InapplicableMethodException argumentMismatch(boolean varargs, JCDiagnostic details) {
-                String key = varargs ?
-                        "varargs.argument.mismatch" :
-                        "no.conforming.assignment.exists";
-                return inapplicableMethodException.setMessage(key,
-                        details);
-            }
-            public InapplicableMethodException inaccessibleVarargs(Symbol location, Type expected) {
-                return inapplicableMethodException.setMessage("inaccessible.varargs.type",
-                        expected, Kinds.kindName(location), location);
-            }
-    };
-
-    void checkRawArgumentsAcceptable(Env<AttrContext> env,
-                                Symbol msym,
-                                List<Type> argtypes,
-                                List<Type> formals,
-                                boolean allowBoxing,
-                                boolean useVarargs,
-                                Warner warn) {
-        checkRawArgumentsAcceptable(env, msym, currentResolutionContext.attrMode(), infer.emptyContext, argtypes, formals,
-                allowBoxing, useVarargs, warn, resolveHandler);
+    enum MethodCheckDiag {
+        /**
+         * Actuals and formals differs in length.
+         */
+        ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
+        /**
+         * An actual is incompatible with a formal.
+         */
+        ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
+        /**
+         * An actual is incompatible with the varargs element type.
+         */
+        VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
+        /**
+         * The varargs element type is inaccessible.
+         */
+        INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
+
+        final String basicKey;
+        final String inferKey;
+
+        MethodCheckDiag(String basicKey, String inferKey) {
+            this.basicKey = basicKey;
+            this.inferKey = inferKey;
+        }
     }
 
     /**
@@ -689,68 +676,94 @@
      *
      * A method check handler (see above) is used in order to report errors.
      */
-    void checkRawArgumentsAcceptable(final Env<AttrContext> env,
-                                Symbol msym,
-                                DeferredAttr.AttrMode mode,
-                                final Infer.InferenceContext inferenceContext,
-                                List<Type> argtypes,
-                                List<Type> formals,
-                                boolean allowBoxing,
-                                boolean useVarargs,
-                                Warner warn,
-                                final MethodCheckHandler handler) {
-        Type varargsFormal = useVarargs ? formals.last() : null;
-
-        if (varargsFormal == null &&
-                argtypes.size() != formals.size()) {
-            throw handler.arityMismatch(); // not enough args
-        }
-
-        DeferredAttr.DeferredAttrContext deferredAttrContext =
-                deferredAttr.new DeferredAttrContext(mode, msym, currentResolutionContext.step, inferenceContext);
-
-        while (argtypes.nonEmpty() && formals.head != varargsFormal) {
-            ResultInfo mresult = methodCheckResult(formals.head, allowBoxing, false, inferenceContext, deferredAttrContext, handler, warn);
-            mresult.check(null, argtypes.head);
-            argtypes = argtypes.tail;
-            formals = formals.tail;
-        }
-
-        if (formals.head != varargsFormal) {
-            throw handler.arityMismatch(); // not enough args
-        }
-
-        if (useVarargs) {
-            //note: if applicability check is triggered by most specific test,
-            //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
-            final Type elt = types.elemtype(varargsFormal);
-            ResultInfo mresult = methodCheckResult(elt, allowBoxing, true, inferenceContext, deferredAttrContext, handler, warn);
-            while (argtypes.nonEmpty()) {
+    MethodCheck resolveMethodCheck = new MethodCheck() {
+        @Override
+        public void argumentsAcceptable(final Env<AttrContext> env,
+                                    DeferredAttrContext deferredAttrContext,
+                                    List<Type> argtypes,
+                                    List<Type> formals,
+                                    Warner warn) {
+            //should we expand formals?
+            boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
+
+            //inference context used during this method check
+            InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
+
+            Type varargsFormal = useVarargs ? formals.last() : null;
+
+            if (varargsFormal == null &&
+                    argtypes.size() != formals.size()) {
+                report(MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
+            }
+
+            while (argtypes.nonEmpty() && formals.head != varargsFormal) {
+                ResultInfo mresult = methodCheckResult(false, formals.head, deferredAttrContext, warn);
                 mresult.check(null, argtypes.head);
                 argtypes = argtypes.tail;
+                formals = formals.tail;
             }
-            //check varargs element type accessibility
-            varargsAccessible(env, elt, handler, inferenceContext);
-        }
-
-        deferredAttrContext.complete();
-    }
-
-    void varargsAccessible(final Env<AttrContext> env, final Type t, final Resolve.MethodCheckHandler handler, final InferenceContext inferenceContext) {
-        if (inferenceContext.free(t)) {
-            inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
-                @Override
-                public void typesInferred(InferenceContext inferenceContext) {
-                    varargsAccessible(env, inferenceContext.asInstType(t, types), handler, inferenceContext);
+
+            if (formals.head != varargsFormal) {
+                report(MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
+            }
+
+            if (useVarargs) {
+                //note: if applicability check is triggered by most specific test,
+                //the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
+                final Type elt = types.elemtype(varargsFormal);
+                ResultInfo mresult = methodCheckResult(true, elt, deferredAttrContext, warn);
+                while (argtypes.nonEmpty()) {
+                    mresult.check(null, argtypes.head);
+                    argtypes = argtypes.tail;
                 }
-            });
-        } else {
-            if (!isAccessible(env, t)) {
-                Symbol location = env.enclClass.sym;
-                throw handler.inaccessibleVarargs(location, t);
+                //check varargs element type accessibility
+                varargsAccessible(env, elt, inferenceContext);
             }
         }
-    }
+
+        private void report(MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
+            boolean inferDiag = inferenceContext != infer.emptyContext;
+            InapplicableMethodException ex = inferDiag ?
+                    infer.inferenceException : inapplicableMethodException;
+            if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
+                Object[] args2 = new Object[args.length + 1];
+                System.arraycopy(args, 0, args2, 1, args.length);
+                args2[0] = inferenceContext.inferenceVars();
+                args = args2;
+            }
+            throw ex.setMessage(inferDiag ? diag.inferKey : diag.basicKey, args);
+        }
+
+        private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
+            if (inferenceContext.free(t)) {
+                inferenceContext.addFreeTypeListener(List.of(t), new FreeTypeListener() {
+                    @Override
+                    public void typesInferred(InferenceContext inferenceContext) {
+                        varargsAccessible(env, inferenceContext.asInstType(t, types), inferenceContext);
+                    }
+                });
+            } else {
+                if (!isAccessible(env, t)) {
+                    Symbol location = env.enclClass.sym;
+                    report(MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
+                }
+            }
+        }
+
+        private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
+                final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
+            CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
+                MethodCheckDiag methodDiag = varargsCheck ?
+                                 MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
+
+                @Override
+                public void report(DiagnosticPosition pos, JCDiagnostic details) {
+                    report(methodDiag, deferredAttrContext.inferenceContext, details);
+                }
+            };
+            return new MethodResultInfo(to, checkContext);
+        }
+    };
 
     /**
      * Check context to be used during method applicability checks. A method check
@@ -758,23 +771,24 @@
      */
     abstract class MethodCheckContext implements CheckContext {
 
-        MethodCheckHandler handler;
-        boolean useVarargs;
-        Infer.InferenceContext inferenceContext;
+        boolean strict;
         DeferredAttrContext deferredAttrContext;
         Warner rsWarner;
 
-        public MethodCheckContext(MethodCheckHandler handler, boolean useVarargs,
-                Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
-            this.handler = handler;
-            this.useVarargs = useVarargs;
-            this.inferenceContext = inferenceContext;
-            this.deferredAttrContext = deferredAttrContext;
-            this.rsWarner = rsWarner;
+        public MethodCheckContext(boolean strict, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
+           this.strict = strict;
+           this.deferredAttrContext = deferredAttrContext;
+           this.rsWarner = rsWarner;
+        }
+
+        public boolean compatible(Type found, Type req, Warner warn) {
+            return strict ?
+                    types.isSubtypeUnchecked(found, deferredAttrContext.inferenceContext.asFree(req, types), warn) :
+                    types.isConvertible(found, deferredAttrContext.inferenceContext.asFree(req, types), warn);
         }
 
         public void report(DiagnosticPosition pos, JCDiagnostic details) {
-            throw handler.argumentMismatch(useVarargs, details);
+            throw inapplicableMethodException.setMessage(details);
         }
 
         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
@@ -782,7 +796,7 @@
         }
 
         public InferenceContext inferenceContext() {
-            return inferenceContext;
+            return deferredAttrContext.inferenceContext;
         }
 
         public DeferredAttrContext deferredAttrContext() {
@@ -791,56 +805,13 @@
     }
 
     /**
-     * Subclass of method check context class that implements strict method conversion.
-     * Strict method conversion checks compatibility between types using subtyping tests.
-     */
-    class StrictMethodContext extends MethodCheckContext {
-
-        public StrictMethodContext(MethodCheckHandler handler, boolean useVarargs,
-                Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
-            super(handler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
-        }
-
-        public boolean compatible(Type found, Type req, Warner warn) {
-            return types.isSubtypeUnchecked(found, inferenceContext.asFree(req, types), warn);
-        }
-    }
-
-    /**
-     * Subclass of method check context class that implements loose method conversion.
-     * Loose method conversion checks compatibility between types using method conversion tests.
+     * ResultInfo class to be used during method applicability checks. Check
+     * for deferred types goes through special path.
      */
-    class LooseMethodContext extends MethodCheckContext {
-
-        public LooseMethodContext(MethodCheckHandler handler, boolean useVarargs,
-                Infer.InferenceContext inferenceContext, DeferredAttrContext deferredAttrContext, Warner rsWarner) {
-            super(handler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
-        }
-
-        public boolean compatible(Type found, Type req, Warner warn) {
-            return types.isConvertible(found, inferenceContext.asFree(req, types), warn);
-        }
-    }
-
-    /**
-     * Create a method check context to be used during method applicability check
-     */
-    ResultInfo methodCheckResult(Type to, boolean allowBoxing, boolean useVarargs,
-            Infer.InferenceContext inferenceContext, DeferredAttr.DeferredAttrContext deferredAttrContext,
-            MethodCheckHandler methodHandler, Warner rsWarner) {
-        MethodCheckContext checkContext = allowBoxing ?
-                new LooseMethodContext(methodHandler, useVarargs, inferenceContext, deferredAttrContext, rsWarner) :
-                new StrictMethodContext(methodHandler, useVarargs, inferenceContext, deferredAttrContext, rsWarner);
-        return new MethodResultInfo(to, checkContext, deferredAttrContext);
-    }
-
     class MethodResultInfo extends ResultInfo {
 
-        DeferredAttr.DeferredAttrContext deferredAttrContext;
-
-        public MethodResultInfo(Type pt, CheckContext checkContext, DeferredAttr.DeferredAttrContext deferredAttrContext) {
+        public MethodResultInfo(Type pt, CheckContext checkContext) {
             attr.super(VAL, pt, checkContext);
-            this.deferredAttrContext = deferredAttrContext;
         }
 
         @Override
@@ -855,12 +826,12 @@
 
         @Override
         protected MethodResultInfo dup(Type newPt) {
-            return new MethodResultInfo(newPt, checkContext, deferredAttrContext);
+            return new MethodResultInfo(newPt, checkContext);
         }
 
         @Override
         protected ResultInfo dup(CheckContext newContext) {
-            return new MethodResultInfo(pt, newContext, deferredAttrContext);
+            return new MethodResultInfo(pt, newContext);
         }
     }
 
@@ -1071,7 +1042,7 @@
         Assert.check(sym.kind < AMBIGUOUS);
         try {
             Type mt = rawInstantiate(env, site, sym, null, argtypes, typeargtypes,
-                               allowBoxing, useVarargs, types.noWarnings);
+                               allowBoxing, useVarargs, resolveMethodCheck, types.noWarnings);
             if (!operator)
                 currentResolutionContext.addApplicableCandidate(sym, mt);
         } catch (InapplicableMethodException ex) {
@@ -1151,52 +1122,20 @@
                 if (m1Abstract && !m2Abstract) return m2;
                 if (m2Abstract && !m1Abstract) return m1;
                 // both abstract or both concrete
-                if (!m1Abstract && !m2Abstract)
-                    return ambiguityError(m1, m2);
-                // check that both signatures have the same erasure
-                if (!types.isSameTypes(m1.erasure(types).getParameterTypes(),
-                                       m2.erasure(types).getParameterTypes()))
-                    return ambiguityError(m1, m2);
-                // both abstract, neither overridden; merge throws clause and result type
-                Type mst = mostSpecificReturnType(mt1, mt2);
-                if (mst == null) {
-                    // Theoretically, this can't happen, but it is possible
-                    // due to error recovery or mixing incompatible class files
-                    return ambiguityError(m1, m2);
-                }
-                Symbol mostSpecific = mst == mt1 ? m1 : m2;
-                List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
-                Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
-                MethodSymbol result = new MethodSymbol(
-                        mostSpecific.flags(),
-                        mostSpecific.name,
-                        newSig,
-                        mostSpecific.owner) {
-                    @Override
-                    public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
-                        if (origin == site.tsym)
-                            return this;
-                        else
-                            return super.implementation(origin, types, checkResult);
-                        }
-                    };
-                return result;
+                return ambiguityError(m1, m2);
             }
             if (m1SignatureMoreSpecific) return m1;
             if (m2SignatureMoreSpecific) return m2;
             return ambiguityError(m1, m2);
         case AMBIGUOUS:
+            //check if m1 is more specific than all ambiguous methods in m2
             AmbiguityError e = (AmbiguityError)m2;
-            Symbol err1 = mostSpecific(argtypes, m1, e.sym, env, site, allowBoxing, useVarargs);
-            Symbol err2 = mostSpecific(argtypes, m1, e.sym2, env, site, allowBoxing, useVarargs);
-            if (err1 == err2) return err1;
-            if (err1 == e.sym && err2 == e.sym2) return m2;
-            if (err1 instanceof AmbiguityError &&
-                err2 instanceof AmbiguityError &&
-                ((AmbiguityError)err1).sym == ((AmbiguityError)err2).sym)
-                return ambiguityError(m1, m2);
-            else
-                return ambiguityError(err1, err2);
+            for (Symbol s : e.ambiguousSyms) {
+                if (mostSpecific(argtypes, m1, s, env, site, allowBoxing, useVarargs) != m1) {
+                    return e.addAmbiguousSymbol(m1);
+                }
+            }
+            return m1;
         default:
             throw new AssertionError();
         }
@@ -1274,12 +1213,19 @@
     }
     //where
     private boolean invocationMoreSpecific(Env<AttrContext> env, Type site, Symbol m2, List<Type> argtypes1, boolean allowBoxing, boolean useVarargs) {
-        noteWarner.clear();
-        Type mst = instantiate(env, site, m2, null,
-                types.lowerBounds(argtypes1), null,
-                allowBoxing, false, noteWarner);
-        return mst != null &&
-                !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
+        MethodResolutionContext prevContext = currentResolutionContext;
+        try {
+            currentResolutionContext = new MethodResolutionContext();
+            currentResolutionContext.step = allowBoxing ? BOX : BASIC;
+            noteWarner.clear();
+            Type mst = instantiate(env, site, m2, null,
+                    types.lowerBounds(argtypes1), null,
+                    allowBoxing, false, resolveMethodCheck, noteWarner);
+            return mst != null &&
+                    !noteWarner.hasLint(Lint.LintCategory.UNCHECKED);
+        } finally {
+            currentResolutionContext = prevContext;
+        }
     }
     //where
     private Symbol adjustVarargs(Symbol to, Symbol from, boolean useVarargs) {
@@ -1798,6 +1744,9 @@
 
         if ((kind & TYP) != 0) {
             sym = findType(env, name);
+            if (sym.kind==TYP) {
+                 reportDependence(env.enclClass.sym, sym);
+            }
             if (sym.exists()) return sym;
             else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
         }
@@ -1806,6 +1755,14 @@
         else return bestSoFar;
     }
 
+    /** Report dependencies.
+     * @param from The enclosing class sym
+     * @param to   The found identifier that the class depends on.
+     */
+    public void reportDependence(Symbol from, Symbol to) {
+        // Override if you want to collect the reported dependencies.
+    }
+
     /** Find an identifier in a package which matches a specified kind set.
      *  @param env       The current environment.
      *  @param name      The identifier's name.
@@ -2355,9 +2312,11 @@
         try {
             currentResolutionContext = new MethodResolutionContext();
             Name name = treeinfo.operatorName(optag);
+            env.info.pendingResolutionPhase = currentResolutionContext.step = BASIC;
             Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
                                     null, false, false, true);
             if (boxingEnabled && sym.kind >= WRONG_MTHS)
+                env.info.pendingResolutionPhase = currentResolutionContext.step = BOX;
                 sym = findMethod(env, syms.predefClass.type, name, argtypes,
                                  null, true, false, true);
             return accessMethod(sym, pos, env.enclClass.sym.type, name,
@@ -2513,6 +2472,10 @@
 
         @Override
         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
+            if (sym.kind == AMBIGUOUS) {
+                AmbiguityError a_err = (AmbiguityError)sym;
+                sym = a_err.mergeAbstracts(site);
+            }
             if (sym.kind >= AMBIGUOUS) {
                 //if nothing is found return the 'first' error
                 sym = accessMethod(sym, pos, location, site, name, true, argtypes, typeargtypes);
@@ -2568,6 +2531,10 @@
         abstract JCMemberReference.ReferenceKind referenceKind(Symbol sym);
 
         Symbol access(Env<AttrContext> env, DiagnosticPosition pos, Symbol location, Symbol sym) {
+            if (sym.kind == AMBIGUOUS) {
+                AmbiguityError a_err = (AmbiguityError)sym;
+                sym = a_err.mergeAbstracts(site);
+            }
             //skip error reporting
             return sym;
         }
@@ -3003,9 +2970,7 @@
 
         @Override
         public Symbol access(Name name, TypeSymbol location) {
-            if (sym.kind >= AMBIGUOUS)
-                return ((ResolveError)sym).access(name, location);
-            else if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
+            if ((sym.kind & ERRONEOUS) == 0 && (sym.kind & TYP) != 0)
                 return types.createErrorType(name, location, sym.type).tsym;
             else
                 return sym;
@@ -3064,16 +3029,20 @@
             if (hasLocation) {
                 return diags.create(dkind, log.currentSource(), pos,
                         errKey, kindname, idname, //symbol kindname, name
-                        typeargtypes, argtypes, //type parameters and arguments (if any)
+                        typeargtypes, args(argtypes), //type parameters and arguments (if any)
                         getLocationDiag(location, site)); //location kindname, type
             }
             else {
                 return diags.create(dkind, log.currentSource(), pos,
                         errKey, kindname, idname, //symbol kindname, name
-                        typeargtypes, argtypes); //type parameters and arguments (if any)
+                        typeargtypes, args(argtypes)); //type parameters and arguments (if any)
             }
         }
         //where
+        private Object args(List<Type> args) {
+            return args.isEmpty() ? args : methodArguments(args);
+        }
+
         private String getErrorKey(KindName kindname, boolean hasTypeArgs, boolean hasLocation) {
             String key = "cant.resolve";
             String suffix = hasLocation ? ".location" : "";
@@ -3323,14 +3292,32 @@
      * (either methods, constructors or operands) are ambiguous
      * given an actual arguments/type argument list.
      */
-    class AmbiguityError extends InvalidSymbolError {
+    class AmbiguityError extends ResolveError {
 
         /** The other maximally specific symbol */
-        Symbol sym2;
+        List<Symbol> ambiguousSyms = List.nil();
+
+        @Override
+        public boolean exists() {
+            return true;
+        }
 
         AmbiguityError(Symbol sym1, Symbol sym2) {
-            super(AMBIGUOUS, sym1, "ambiguity error");
-            this.sym2 = sym2;
+            super(AMBIGUOUS, "ambiguity error");
+            ambiguousSyms = flatten(sym2).appendList(flatten(sym1));
+        }
+
+        private List<Symbol> flatten(Symbol sym) {
+            if (sym.kind == AMBIGUOUS) {
+                return ((AmbiguityError)sym).ambiguousSyms;
+            } else {
+                return List.of(sym);
+            }
+        }
+
+        AmbiguityError addAmbiguousSymbol(Symbol s) {
+            ambiguousSyms = ambiguousSyms.prepend(s);
+            return this;
         }
 
         @Override
@@ -3341,24 +3328,60 @@
                 Name name,
                 List<Type> argtypes,
                 List<Type> typeargtypes) {
-            AmbiguityError pair = this;
-            while (true) {
-                if (pair.sym.kind == AMBIGUOUS)
-                    pair = (AmbiguityError)pair.sym;
-                else if (pair.sym2.kind == AMBIGUOUS)
-                    pair = (AmbiguityError)pair.sym2;
-                else break;
-            }
-            Name sname = pair.sym.name;
-            if (sname == names.init) sname = pair.sym.owner.name;
+            List<Symbol> diagSyms = ambiguousSyms.reverse();
+            Symbol s1 = diagSyms.head;
+            Symbol s2 = diagSyms.tail.head;
+            Name sname = s1.name;
+            if (sname == names.init) sname = s1.owner.name;
             return diags.create(dkind, log.currentSource(),
                       pos, "ref.ambiguous", sname,
-                      kindName(pair.sym),
-                      pair.sym,
-                      pair.sym.location(site, types),
-                      kindName(pair.sym2),
-                      pair.sym2,
-                      pair.sym2.location(site, types));
+                      kindName(s1),
+                      s1,
+                      s1.location(site, types),
+                      kindName(s2),
+                      s2,
+                      s2.location(site, types));
+        }
+
+        /**
+         * If multiple applicable methods are found during overload and none of them
+         * is more specific than the others, attempt to merge their signatures.
+         */
+        Symbol mergeAbstracts(Type site) {
+            Symbol fst = ambiguousSyms.last();
+            Symbol res = fst;
+            for (Symbol s : ambiguousSyms.reverse()) {
+                Type mt1 = types.memberType(site, res);
+                Type mt2 = types.memberType(site, s);
+                if ((s.flags() & ABSTRACT) == 0 ||
+                        !types.overrideEquivalent(mt1, mt2) ||
+                        !types.isSameTypes(fst.erasure(types).getParameterTypes(),
+                                       s.erasure(types).getParameterTypes())) {
+                    //ambiguity cannot be resolved
+                    return this;
+                } else {
+                    Type mst = mostSpecificReturnType(mt1, mt2);
+                    if (mst == null) {
+                        // Theoretically, this can't happen, but it is possible
+                        // due to error recovery or mixing incompatible class files
+                        return this;
+                    }
+                    Symbol mostSpecific = mst == mt1 ? res : s;
+                    List<Type> allThrown = chk.intersect(mt1.getThrownTypes(), mt2.getThrownTypes());
+                    Type newSig = types.createMethodTypeWithThrown(mostSpecific.type, allThrown);
+                    res = new MethodSymbol(
+                            mostSpecific.flags(),
+                            mostSpecific.name,
+                            newSig,
+                            mostSpecific.owner);
+                }
+            }
+            return res;
+        }
+
+        @Override
+        protected Symbol access(Name name, TypeSymbol location) {
+            return ambiguousSyms.last();
         }
     }
 
@@ -3435,6 +3458,10 @@
             candidates = candidates.append(c);
         }
 
+        DeferredAttrContext deferredAttrContext(Symbol sym, InferenceContext inferenceContext) {
+            return deferredAttr.new DeferredAttrContext(attrMode, sym, step, inferenceContext);
+        }
+
         /**
          * This class represents an overload resolution candidate. There are two
          * kinds of candidates: applicable methods and inapplicable methods;
--- a/langtools/src/share/classes/com/sun/tools/javac/file/ZipFileIndex.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/file/ZipFileIndex.java	Tue Jan 22 11:54:16 2013 -0800
@@ -548,17 +548,15 @@
                 }
 
                 if (i >= 0) {
-                    zipDir = new byte[get4ByteLittleEndian(endbuf, i + 12) + 2];
-                    zipDir[0] = endbuf[i + 10];
-                    zipDir[1] = endbuf[i + 11];
+                    zipDir = new byte[get4ByteLittleEndian(endbuf, i + 12)];
                     int sz = get4ByteLittleEndian(endbuf, i + 16);
                     // a negative offset or the entries field indicates a
                     // potential zip64 archive
-                    if (sz < 0 || get2ByteLittleEndian(zipDir, 0) == 0xffff) {
+                    if (sz < 0 || get2ByteLittleEndian(endbuf, i + 10) == 0xffff) {
                         throw new ZipFormatException("detected a zip64 archive");
                     }
                     zipRandomFile.seek(start + sz);
-                    zipRandomFile.readFully(zipDir, 2, zipDir.length - 2);
+                    zipRandomFile.readFully(zipDir, 0, zipDir.length);
                     return;
                 } else {
                     endbufend = endbufpos + 21;
@@ -568,14 +566,13 @@
         }
 
         private void buildIndex() throws IOException {
-            int entryCount = get2ByteLittleEndian(zipDir, 0);
+            int len = zipDir.length;
 
             // Add each of the files
-            if (entryCount > 0) {
+            if (len > 0) {
                 directories = new LinkedHashMap<RelativeDirectory, DirectoryEntry>();
                 ArrayList<Entry> entryList = new ArrayList<Entry>();
-                int pos = 2;
-                for (int i = 0; i < entryCount; i++) {
+                for (int pos = 0; pos < len; ) {
                     pos = readEntry(pos, entryList, directories);
                 }
 
--- a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassFile.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassFile.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,6 +26,8 @@
 package com.sun.tools.javac.jvm;
 
 import com.sun.tools.javac.code.Type;
+import com.sun.tools.javac.code.Types;
+import com.sun.tools.javac.code.Types.UniqueType;
 import com.sun.tools.javac.util.Name;
 
 
@@ -166,22 +168,29 @@
      */
     public static class NameAndType {
         Name name;
-        Type type;
+        UniqueType uniqueType;
+        Types types;
 
-        NameAndType(Name name, Type type) {
+        NameAndType(Name name, Type type, Types types) {
             this.name = name;
-            this.type = type;
+            this.uniqueType = new UniqueType(type, types);
+            this.types = types;
         }
 
-        public boolean equals(Object other) {
-            return
-                other instanceof NameAndType &&
-                name == ((NameAndType) other).name &&
-                type.equals(((NameAndType) other).type);
+        void setType(Type type) {
+            this.uniqueType = new UniqueType(type, types);
         }
 
+        @Override
+        public boolean equals(Object other) {
+            return (other instanceof NameAndType &&
+                    name == ((NameAndType) other).name &&
+                        uniqueType.equals(((NameAndType) other).uniqueType));
+        }
+
+        @Override
         public int hashCode() {
-            return name.hashCode() * type.hashCode();
+            return name.hashCode() * uniqueType.hashCode();
         }
     }
 }
--- a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java	Tue Jan 22 11:54:16 2013 -0800
@@ -217,6 +217,13 @@
      */
     boolean haveParameterNameIndices;
 
+    /** Set this to false every time we start reading a method
+     * and are saving parameter names.  Set it to true when we see
+     * MethodParameters, if it's set when we see a LocalVariableTable,
+     * then we ignore the parameter names from the LVT.
+     */
+    boolean sawMethodParameters;
+
     /**
      * The set of attribute names for which warnings have been generated for the current class
      */
@@ -488,20 +495,20 @@
         case CONSTANT_Fieldref: {
             ClassSymbol owner = readClassSymbol(getChar(index + 1));
             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
-            poolObj[i] = new VarSymbol(0, nt.name, nt.type, owner);
+            poolObj[i] = new VarSymbol(0, nt.name, nt.uniqueType.type, owner);
             break;
         }
         case CONSTANT_Methodref:
         case CONSTANT_InterfaceMethodref: {
             ClassSymbol owner = readClassSymbol(getChar(index + 1));
             NameAndType nt = (NameAndType)readPool(getChar(index + 3));
-            poolObj[i] = new MethodSymbol(0, nt.name, nt.type, owner);
+            poolObj[i] = new MethodSymbol(0, nt.name, nt.uniqueType.type, owner);
             break;
         }
         case CONSTANT_NameandType:
             poolObj[i] = new NameAndType(
                 readName(getChar(index + 1)),
-                readType(getChar(index + 3)));
+                readType(getChar(index + 3)), types);
             break;
         case CONSTANT_Integer:
             poolObj[i] = getInt(index + 1);
@@ -984,7 +991,7 @@
             new AttributeReader(names.LocalVariableTable, V45_3, CLASS_OR_MEMBER_ATTRIBUTE) {
                 protected void read(Symbol sym, int attrLen) {
                     int newbp = bp + attrLen;
-                    if (saveParameterNames) {
+                    if (saveParameterNames && !sawMethodParameters) {
                         // Pick up parameter names from the variable table.
                         // Parameter names are not explicitly identified as such,
                         // but all parameter name entries in the LocalVariableTable
@@ -1017,6 +1024,25 @@
                 }
             },
 
+            new AttributeReader(names.MethodParameters, V52, MEMBER_ATTRIBUTE) {
+                protected void read(Symbol sym, int attrlen) {
+                    int newbp = bp + attrlen;
+                    if (saveParameterNames) {
+                        sawMethodParameters = true;
+                        int numEntries = nextByte();
+                        parameterNameIndices = new int[numEntries];
+                        haveParameterNameIndices = true;
+                        for (int i = 0; i < numEntries; i++) {
+                            int nameIndex = nextChar();
+                            int flags = nextInt();
+                            parameterNameIndices[i] = nameIndex;
+                        }
+                    }
+                    bp = newbp;
+                }
+            },
+
+
             new AttributeReader(names.SourceFile, V45_3, CLASS_ATTRIBUTE) {
                 protected void read(Symbol sym, int attrLen) {
                     ClassSymbol c = (ClassSymbol) sym;
@@ -1224,7 +1250,7 @@
         if (nt == null)
             return null;
 
-        MethodType type = nt.type.asMethodType();
+        MethodType type = nt.uniqueType.type.asMethodType();
 
         for (Scope.Entry e = scope.lookup(nt.name); e.scope != null; e = e.next())
             if (e.sym.kind == MTH && isSameBinaryType(e.sym.type.asMethodType(), type))
@@ -1236,16 +1262,16 @@
         if ((flags & INTERFACE) != 0)
             // no enclosing instance
             return null;
-        if (nt.type.getParameterTypes().isEmpty())
+        if (nt.uniqueType.type.getParameterTypes().isEmpty())
             // no parameters
             return null;
 
         // A constructor of an inner class.
         // Remove the first argument (the enclosing instance)
-        nt.type = new MethodType(nt.type.getParameterTypes().tail,
-                                 nt.type.getReturnType(),
-                                 nt.type.getThrownTypes(),
-                                 syms.methodClass);
+        nt.setType(new MethodType(nt.uniqueType.type.getParameterTypes().tail,
+                                 nt.uniqueType.type.getReturnType(),
+                                 nt.uniqueType.type.getThrownTypes(),
+                                 syms.methodClass));
         // Try searching again
         return findMethod(nt, scope, flags);
     }
@@ -1826,6 +1852,7 @@
         } else
             Arrays.fill(parameterNameIndices, 0);
         haveParameterNameIndices = false;
+        sawMethodParameters = false;
     }
 
     /**
@@ -1845,12 +1872,16 @@
         // if no names were found in the class file, there's nothing more to do
         if (!haveParameterNameIndices)
             return;
-
-        int firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
-        // the code in readMethod may have skipped the first parameter when
-        // setting up the MethodType. If so, we make a corresponding allowance
-        // here for the position of the first parameter.  Note that this
-        // assumes the skipped parameter has a width of 1 -- i.e. it is not
+        // If we get parameter names from MethodParameters, then we
+        // don't need to skip.
+        int firstParam = 0;
+        if (!sawMethodParameters) {
+            firstParam = ((sym.flags() & STATIC) == 0) ? 1 : 0;
+            // the code in readMethod may have skipped the first
+            // parameter when setting up the MethodType. If so, we
+            // make a corresponding allowance here for the position of
+            // the first parameter.  Note that this assumes the
+            // skipped parameter has a width of 1 -- i.e. it is not
         // a double width type (long or double.)
         if (sym.name == names.init && currentOwner.hasOuterInstance()) {
             // Sometimes anonymous classes don't have an outer
@@ -1861,17 +1892,20 @@
         }
 
         if (sym.type != jvmType) {
-            // reading the method attributes has caused the symbol's type to
-            // be changed. (i.e. the Signature attribute.)  This may happen if
-            // there are hidden (synthetic) parameters in the descriptor, but
-            // not in the Signature.  The position of these hidden parameters
-            // is unspecified; for now, assume they are at the beginning, and
-            // so skip over them. The primary case for this is two hidden
-            // parameters passed into Enum constructors.
+                // reading the method attributes has caused the
+                // symbol's type to be changed. (i.e. the Signature
+                // attribute.)  This may happen if there are hidden
+                // (synthetic) parameters in the descriptor, but not
+                // in the Signature.  The position of these hidden
+                // parameters is unspecified; for now, assume they are
+                // at the beginning, and so skip over them. The
+                // primary case for this is two hidden parameters
+                // passed into Enum constructors.
             int skip = Code.width(jvmType.getParameterTypes())
                     - Code.width(sym.type.getParameterTypes());
             firstParam += skip;
         }
+        }
         List<Name> paramNames = List.nil();
         int index = firstParam;
         for (Type t: sym.type.getParameterTypes()) {
@@ -1959,7 +1993,7 @@
 
         if (readAllOfClassFile) {
             for (int i = 1; i < poolObj.length; i++) readPool(i);
-            c.pool = new Pool(poolObj.length, poolObj);
+            c.pool = new Pool(poolObj.length, poolObj, types);
         }
 
         // reset and read rest of classinfo
--- a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java	Tue Jan 22 11:54:16 2013 -0800
@@ -39,7 +39,12 @@
 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
 import com.sun.tools.javac.code.Symbol.*;
 import com.sun.tools.javac.code.Type.*;
+import com.sun.tools.javac.code.Types.UniqueType;
 import com.sun.tools.javac.file.BaseFileObject;
+import com.sun.tools.javac.jvm.Pool.DynamicMethod;
+import com.sun.tools.javac.jvm.Pool.Method;
+import com.sun.tools.javac.jvm.Pool.MethodHandle;
+import com.sun.tools.javac.jvm.Pool.Variable;
 import com.sun.tools.javac.util.*;
 
 import static com.sun.tools.javac.code.BoundKind.*;
@@ -142,7 +147,7 @@
     /** The bootstrap methods to be written in the corresponding class attribute
      *  (one for each invokedynamic)
      */
-    Map<MethodSymbol, Pool.MethodHandle> bootstrapMethods;
+    Map<DynamicMethod, MethodHandle> bootstrapMethods;
 
     /** The log to use for verbose output.
      */
@@ -477,10 +482,10 @@
         while (i < pool.pp) {
             Object value = pool.pool[i];
             Assert.checkNonNull(value);
-            if (value instanceof Pool.Method)
-                value = ((Pool.Method)value).m;
-            else if (value instanceof Pool.Variable)
-                value = ((Pool.Variable)value).v;
+            if (value instanceof Method)
+                value = ((Method)value).m;
+            else if (value instanceof Variable)
+                value = ((Variable)value).v;
 
             if (value instanceof MethodSymbol) {
                 MethodSymbol m = (MethodSymbol)value;
@@ -493,8 +498,9 @@
                 } else {
                     //invokedynamic
                     DynamicMethodSymbol dynSym = (DynamicMethodSymbol)m;
-                    Pool.MethodHandle handle = new Pool.MethodHandle(dynSym.bsmKind, dynSym.bsm);
-                    bootstrapMethods.put(dynSym, handle);
+                    MethodHandle handle = new MethodHandle(dynSym.bsmKind, dynSym.bsm, types);
+                    DynamicMethod dynMeth = new DynamicMethod(dynSym, types);
+                    bootstrapMethods.put(dynMeth, handle);
                     //init cp entries
                     pool.put(names.BootstrapMethods);
                     pool.put(handle);
@@ -531,7 +537,7 @@
                 NameAndType nt = (NameAndType)value;
                 poolbuf.appendByte(CONSTANT_NameandType);
                 poolbuf.appendChar(pool.put(nt.name));
-                poolbuf.appendChar(pool.put(typeSig(nt.type)));
+                poolbuf.appendChar(pool.put(typeSig(nt.uniqueType.type)));
             } else if (value instanceof Integer) {
                 poolbuf.appendByte(CONSTANT_Integer);
                 poolbuf.appendInt(((Integer)value).intValue());
@@ -549,17 +555,18 @@
             } else if (value instanceof String) {
                 poolbuf.appendByte(CONSTANT_String);
                 poolbuf.appendChar(pool.put(names.fromString((String)value)));
-            } else if (value instanceof MethodType) {
-                MethodType mtype = (MethodType)value;
-                poolbuf.appendByte(CONSTANT_MethodType);
-                poolbuf.appendChar(pool.put(typeSig(mtype)));
-            } else if (value instanceof Type) {
-                Type type = (Type)value;
-                if (type.hasTag(CLASS)) enterInner((ClassSymbol)type.tsym);
-                poolbuf.appendByte(CONSTANT_Class);
-                poolbuf.appendChar(pool.put(xClassName(type)));
-            } else if (value instanceof Pool.MethodHandle) {
-                Pool.MethodHandle ref = (Pool.MethodHandle)value;
+            } else if (value instanceof UniqueType) {
+                Type type = ((UniqueType)value).type;
+                if (type instanceof MethodType) {
+                    poolbuf.appendByte(CONSTANT_MethodType);
+                    poolbuf.appendChar(pool.put(typeSig((MethodType)type)));
+                } else {
+                    if (type.hasTag(CLASS)) enterInner((ClassSymbol)type.tsym);
+                    poolbuf.appendByte(CONSTANT_Class);
+                    poolbuf.appendChar(pool.put(xClassName(type)));
+                }
+            } else if (value instanceof MethodHandle) {
+                MethodHandle ref = (MethodHandle)value;
                 poolbuf.appendByte(CONSTANT_MethodHandle);
                 poolbuf.appendByte(ref.refKind);
                 poolbuf.appendChar(pool.put(ref.refSym));
@@ -589,7 +596,7 @@
         return new NameAndType(fieldName(sym),
                                retrofit
                                ? sym.erasure(types)
-                               : sym.externalType(types));
+                               : sym.externalType(types), types);
         // if we retrofit, then the NameAndType has been read in as is
         // and no change is necessary. If we compile normally, the
         // NameAndType is generated from a symbol reference, and the
@@ -714,10 +721,32 @@
             endAttr(alenIdx);
             acount++;
         }
-        acount += writeJavaAnnotations(sym.getAnnotationMirrors());
+        acount += writeJavaAnnotations(sym.getRawAttributes());
         return acount;
     }
 
+    /**
+     * Write method parameter names attribute.
+     */
+    int writeMethodParametersAttr(MethodSymbol m) {
+        if (m.params != null && 0 != m.params.length()) {
+            int attrIndex = writeAttr(names.MethodParameters);
+            databuf.appendByte(m.params.length());
+            for (VarSymbol s : m.params) {
+                // TODO: expand to cover synthesized, once we figure out
+                // how to represent that.
+                final int flags = (int) s.flags() & (FINAL | SYNTHETIC);
+                // output parameter info
+                databuf.appendChar(pool.put(s.name));
+                databuf.appendInt(flags);
+            }
+            endAttr(attrIndex);
+            return 1;
+        } else
+            return 0;
+    }
+
+
     /** Write method parameter annotations;
      *  return number of attributes written.
      */
@@ -725,7 +754,7 @@
         boolean hasVisible = false;
         boolean hasInvisible = false;
         if (m.params != null) for (VarSymbol s : m.params) {
-            for (Attribute.Compound a : s.getAnnotationMirrors()) {
+            for (Attribute.Compound a : s.getRawAttributes()) {
                 switch (types.getRetention(a)) {
                 case SOURCE: break;
                 case CLASS: hasInvisible = true; break;
@@ -741,7 +770,7 @@
             databuf.appendByte(m.params.length());
             for (VarSymbol s : m.params) {
                 ListBuffer<Attribute.Compound> buf = new ListBuffer<Attribute.Compound>();
-                for (Attribute.Compound a : s.getAnnotationMirrors())
+                for (Attribute.Compound a : s.getRawAttributes())
                     if (types.getRetention(a) == RetentionPolicy.RUNTIME)
                         buf.append(a);
                 databuf.appendChar(buf.length());
@@ -756,7 +785,7 @@
             databuf.appendByte(m.params.length());
             for (VarSymbol s : m.params) {
                 ListBuffer<Attribute.Compound> buf = new ListBuffer<Attribute.Compound>();
-                for (Attribute.Compound a : s.getAnnotationMirrors())
+                for (Attribute.Compound a : s.getRawAttributes())
                     if (types.getRetention(a) == RetentionPolicy.CLASS)
                         buf.append(a);
                 databuf.appendChar(buf.length());
@@ -951,14 +980,16 @@
     void writeBootstrapMethods() {
         int alenIdx = writeAttr(names.BootstrapMethods);
         databuf.appendChar(bootstrapMethods.size());
-        for (Map.Entry<MethodSymbol, Pool.MethodHandle> entry : bootstrapMethods.entrySet()) {
-            DynamicMethodSymbol dsym = (DynamicMethodSymbol)entry.getKey();
+        for (Map.Entry<DynamicMethod, MethodHandle> entry : bootstrapMethods.entrySet()) {
+            DynamicMethod dmeth = entry.getKey();
+            DynamicMethodSymbol dsym = (DynamicMethodSymbol)dmeth.baseSymbol();
             //write BSM handle
             databuf.appendChar(pool.get(entry.getValue()));
             //write static args length
             databuf.appendChar(dsym.staticArgs.length);
             //write static args array
-            for (Object o : dsym.staticArgs) {
+            Object[] uniqueArgs = dmeth.uniqueStaticArgs;
+            for (Object o : uniqueArgs) {
                 databuf.appendChar(pool.get(o));
             }
         }
@@ -1025,6 +1056,8 @@
             endAttr(alenIdx);
             acount++;
         }
+        if (options.isSet(PARAMETERS))
+            acount += writeMethodParametersAttr(m);
         acount += writeMemberAttrs(m);
         acount += writeParameterAttrs(m);
         endAttrs(acountIdx, acount);
@@ -1534,7 +1567,7 @@
         pool = c.pool;
         innerClasses = null;
         innerClassesQueue = null;
-        bootstrapMethods = new LinkedHashMap<MethodSymbol, Pool.MethodHandle>();
+        bootstrapMethods = new LinkedHashMap<DynamicMethod, MethodHandle>();
 
         Type supertype = types.supertype(c.type);
         List<Type> interfaces = types.interfaces(c.type);
@@ -1627,7 +1660,7 @@
         }
 
         acount += writeFlagAttrs(c.flags());
-        acount += writeJavaAnnotations(c.getAnnotationMirrors());
+        acount += writeJavaAnnotations(c.getRawAttributes());
         acount += writeEnclosingMethodAttribute(c);
         acount += writeExtraClassAttributes(c);
 
--- a/langtools/src/share/classes/com/sun/tools/javac/jvm/Code.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/Code.java	Tue Jan 22 11:54:16 2013 -0800
@@ -27,6 +27,7 @@
 
 import com.sun.tools.javac.code.*;
 import com.sun.tools.javac.code.Symbol.*;
+import com.sun.tools.javac.code.Types.UniqueType;
 import com.sun.tools.javac.util.*;
 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
 
@@ -901,6 +902,7 @@
         if (o instanceof ClassSymbol) return syms.classType;
         if (o instanceof Type.ArrayType) return syms.classType;
         if (o instanceof Type.MethodType) return syms.methodTypeType;
+        if (o instanceof UniqueType) return typeForPool(((UniqueType)o).type);
         if (o instanceof Pool.MethodHandle) return syms.methodHandleType;
         throw new AssertionError(o);
     }
@@ -1030,7 +1032,7 @@
             Object o = pool.pool[od];
             Type t = (o instanceof Symbol)
                 ? ((Symbol)o).erasure(types)
-                : types.erasure(((Type)o));
+                : types.erasure((((UniqueType)o).type));
             state.push(t);
             break; }
         case ldc2w:
--- a/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java	Tue Jan 22 11:54:16 2013 -0800
@@ -94,6 +94,10 @@
         return instance;
     }
 
+    /* Constant pool, reset by genClass.
+     */
+    private Pool pool;
+
     protected Gen(Context context) {
         context.put(genKey, this);
 
@@ -126,6 +130,7 @@
         genCrt = options.isSet(XJCOV);
         debugCode = options.isSet("debugcode");
         allowInvokedynamic = target.hasInvokedynamic() || options.isSet("invokedynamic");
+        pool = new Pool(types);
 
         generateIproxies =
             target.requiresIproxy() ||
@@ -174,10 +179,6 @@
      */
     private boolean useJsrLocally;
 
-    /* Constant pool, reset by genClass.
-     */
-    private Pool pool = new Pool();
-
     /** Code buffer, set by genMethod.
      */
     private Code code;
@@ -705,7 +706,7 @@
         }
         int startpc = code.curPc();
         genStat(tree, env);
-        if (tree.hasTag(BLOCK)) crtFlags |= CRT_BLOCK;
+        if (tree.hasTag(Tag.BLOCK)) crtFlags |= CRT_BLOCK;
         code.crt.put(tree, crtFlags, startpc, code.curPc());
     }
 
--- a/langtools/src/share/classes/com/sun/tools/javac/jvm/Pool.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/Pool.java	Tue Jan 22 11:54:16 2013 -0800
@@ -28,6 +28,9 @@
 import com.sun.tools.javac.code.Kinds;
 import com.sun.tools.javac.code.Symbol;
 import com.sun.tools.javac.code.Symbol.*;
+import com.sun.tools.javac.code.Type;
+import com.sun.tools.javac.code.Types;
+import com.sun.tools.javac.code.Types.UniqueType;
 
 import com.sun.tools.javac.util.ArrayUtils;
 import com.sun.tools.javac.util.Assert;
@@ -60,11 +63,14 @@
      */
     Map<Object,Integer> indices;
 
+    Types types;
+
     /** Construct a pool with given number of elements and element array.
      */
-    public Pool(int pp, Object[] pool) {
+    public Pool(int pp, Object[] pool, Types types) {
         this.pp = pp;
         this.pool = pool;
+        this.types = types;
         this.indices = new HashMap<Object,Integer>(pool.length);
         for (int i = 1; i < pp; i++) {
             if (pool[i] != null) indices.put(pool[i], i);
@@ -73,8 +79,8 @@
 
     /** Construct an empty pool.
      */
-    public Pool() {
-        this(1, new Object[64]);
+    public Pool(Types types) {
+        this(1, new Object[64], types);
     }
 
     /** Return the number of entries in the constant pool.
@@ -114,11 +120,13 @@
 
     Object makePoolValue(Object o) {
         if (o instanceof DynamicMethodSymbol) {
-            return new DynamicMethod((DynamicMethodSymbol)o);
+            return new DynamicMethod((DynamicMethodSymbol)o, types);
         } else if (o instanceof MethodSymbol) {
-            return new Method((MethodSymbol)o);
+            return new Method((MethodSymbol)o, types);
         } else if (o instanceof VarSymbol) {
-            return new Variable((VarSymbol)o);
+            return new Variable((VarSymbol)o, types);
+        } else if (o instanceof Type) {
+            return new UniqueType((Type)o, types);
         } else {
             return o;
         }
@@ -134,9 +142,11 @@
 
     static class Method extends DelegatedSymbol {
         MethodSymbol m;
-        Method(MethodSymbol m) {
+        UniqueType uniqueType;
+        Method(MethodSymbol m, Types types) {
             super(m);
             this.m = m;
+            this.uniqueType = new UniqueType(m.type, types);
         }
         public boolean equals(Object other) {
             if (!(other instanceof Method)) return false;
@@ -144,20 +154,22 @@
             return
                 o.name == m.name &&
                 o.owner == m.owner &&
-                o.type.equals(m.type);
+                ((Method)other).uniqueType.equals(uniqueType);
         }
         public int hashCode() {
             return
                 m.name.hashCode() * 33 +
                 m.owner.hashCode() * 9 +
-                m.type.hashCode();
+                uniqueType.hashCode();
         }
     }
 
     static class DynamicMethod extends Method {
+        public Object[] uniqueStaticArgs;
 
-        DynamicMethod(DynamicMethodSymbol m) {
-            super(m);
+        DynamicMethod(DynamicMethodSymbol m, Types types) {
+            super(m, types);
+            uniqueStaticArgs = getUniqueTypeArray(m.staticArgs, types);
         }
 
         @Override
@@ -168,7 +180,8 @@
             DynamicMethodSymbol dm2 = (DynamicMethodSymbol)((DynamicMethod)other).m;
             return dm1.bsm == dm2.bsm &&
                         dm1.bsmKind == dm2.bsmKind &&
-                        Arrays.equals(dm1.staticArgs, dm2.staticArgs);
+                        Arrays.equals(uniqueStaticArgs,
+                            ((DynamicMethod)other).uniqueStaticArgs);
         }
 
         @Override
@@ -178,17 +191,31 @@
             hash += dm.bsmKind * 7 +
                     dm.bsm.hashCode() * 11;
             for (int i = 0; i < dm.staticArgs.length; i++) {
-                hash += (dm.staticArgs[i].hashCode() * 23);
+                hash += (uniqueStaticArgs[i].hashCode() * 23);
             }
             return hash;
         }
+
+        private Object[] getUniqueTypeArray(Object[] objects, Types types) {
+            Object[] result = new Object[objects.length];
+            for (int i = 0; i < objects.length; i++) {
+                if (objects[i] instanceof Type) {
+                    result[i] = new UniqueType((Type)objects[i], types);
+                } else {
+                    result[i] = objects[i];
+                }
+            }
+            return result;
+        }
     }
 
     static class Variable extends DelegatedSymbol {
         VarSymbol v;
-        Variable(VarSymbol v) {
+        UniqueType uniqueType;
+        Variable(VarSymbol v, Types types) {
             super(v);
             this.v = v;
+            this.uniqueType = new UniqueType(v.type, types);
         }
         public boolean equals(Object other) {
             if (!(other instanceof Variable)) return false;
@@ -196,13 +223,13 @@
             return
                 o.name == v.name &&
                 o.owner == v.owner &&
-                o.type.equals(v.type);
+                ((Variable)other).uniqueType.equals(uniqueType);
         }
         public int hashCode() {
             return
                 v.name.hashCode() * 33 +
                 v.owner.hashCode() * 9 +
-                v.type.hashCode();
+                uniqueType.hashCode();
         }
     }
 
@@ -214,9 +241,12 @@
         /** Reference symbol */
         Symbol refSym;
 
-        public MethodHandle(int refKind, Symbol refSym) {
+        UniqueType uniqueType;
+
+        public MethodHandle(int refKind, Symbol refSym, Types types) {
             this.refKind = refKind;
             this.refSym = refSym;
+            this.uniqueType = new UniqueType(this.refSym.type, types);
             checkConsistent();
         }
         public boolean equals(Object other) {
@@ -227,14 +257,14 @@
             return
                 o.name == refSym.name &&
                 o.owner == refSym.owner &&
-                o.type.equals(refSym.type);
+                ((MethodHandle)other).uniqueType.equals(uniqueType);
         }
         public int hashCode() {
             return
                 refKind * 65 +
                 refSym.name.hashCode() * 33 +
                 refSym.owner.hashCode() * 9 +
-                refSym.type.hashCode();
+                uniqueType.hashCode();
         }
 
         /**
--- a/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java	Tue Jan 22 11:54:16 2013 -0800
@@ -928,6 +928,16 @@
         }
     }
 
+    /**
+     * Set needRootClasses to true, in JavaCompiler subclass constructor
+     * that want to collect public apis of classes supplied on the command line.
+     */
+    protected boolean needRootClasses = false;
+
+    /**
+     * The list of classes explicitly supplied on the command line for compilation.
+     * Not always populated.
+     */
     private List<JCClassDecl> rootClasses;
 
     /**
@@ -984,9 +994,10 @@
             }
         }
 
-        //If generating source, remember the classes declared in
-        //the original compilation units listed on the command line.
-        if (sourceOutput || stubOutput) {
+        // If generating source, or if tracking public apis,
+        // then remember the classes declared in
+        // the original compilation units listed on the command line.
+        if (needRootClasses || sourceOutput || stubOutput) {
             ListBuffer<JCClassDecl> cdefs = lb();
             for (JCCompilationUnit unit : roots) {
                 for (List<JCTree> defs = unit.defs;
@@ -1247,6 +1258,12 @@
                 attr.postAttr(env.tree);
             }
             compileStates.put(env, CompileState.ATTR);
+            if (rootClasses != null && rootClasses.contains(env.enclClass)) {
+                // This was a class that was explicitly supplied for compilation.
+                // If we want to capture the public api of this class,
+                // then now is a good time to do it.
+                reportPublicApi(env.enclClass.sym);
+            }
         }
         finally {
             log.useSource(prev);
@@ -1255,6 +1272,14 @@
         return env;
     }
 
+    /** Report the public api of a class that was supplied explicitly for compilation,
+     *  for example on the command line to javac.
+     * @param sym The symbol of the class.
+     */
+    public void reportPublicApi(ClassSymbol sym) {
+       // Override to collect the reported public api.
+    }
+
     /**
      * Perform dataflow checks on attributed parse trees.
      * These include checks for definite assignment and unreachable statements.
@@ -1675,7 +1700,7 @@
 
     /** Print numbers of errors and warnings.
      */
-    protected void printCount(String kind, int count) {
+    public void printCount(String kind, int count) {
         if (count != 0) {
             String key;
             if (count == 1)
--- a/langtools/src/share/classes/com/sun/tools/javac/main/Main.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/main/Main.java	Tue Jan 22 11:54:16 2013 -0800
@@ -44,6 +44,8 @@
 
 import com.sun.source.util.JavacTask;
 import com.sun.source.util.Plugin;
+import com.sun.tools.doclint.DocLint;
+import com.sun.tools.javac.api.BasicJavacTask;
 import com.sun.tools.javac.code.Source;
 import com.sun.tools.javac.file.CacheFSInfo;
 import com.sun.tools.javac.file.JavacFileManager;
@@ -428,6 +430,7 @@
             if (batchMode)
                 CacheFSInfo.preRegister(context);
 
+            // FIXME: this code will not be invoked if using JavacTask.parse/analyze/generate
             // invoke any available plugins
             String plugins = options.get(PLUGIN);
             if (plugins != null) {
@@ -448,7 +451,7 @@
                             try {
                                 if (task == null)
                                     task = JavacTask.instance(pEnv);
-                                plugin.call(task, p.tail.toArray(new String[p.tail.size()]));
+                                plugin.init(task, p.tail.toArray(new String[p.tail.size()]));
                             } catch (Throwable ex) {
                                 if (apiMode)
                                     throw new RuntimeException(ex);
@@ -464,10 +467,31 @@
                 }
             }
 
-            fileManager = context.get(JavaFileManager.class);
+            comp = JavaCompiler.instance(context);
 
-            comp = JavaCompiler.instance(context);
-            if (comp == null) return Result.SYSERR;
+            // FIXME: this code will not be invoked if using JavacTask.parse/analyze/generate
+            String xdoclint = options.get(XDOCLINT);
+            String xdoclintCustom = options.get(XDOCLINT_CUSTOM);
+            if (xdoclint != null || xdoclintCustom != null) {
+                Set<String> doclintOpts = new LinkedHashSet<String>();
+                if (xdoclint != null)
+                    doclintOpts.add(DocLint.XMSGS_OPTION);
+                if (xdoclintCustom != null) {
+                    for (String s: xdoclintCustom.split("\\s+")) {
+                        if (s.isEmpty())
+                            continue;
+                        doclintOpts.add(s.replace(XDOCLINT_CUSTOM.text, DocLint.XMSGS_CUSTOM_PREFIX));
+                    }
+                }
+                if (!(doclintOpts.size() == 1
+                        && doclintOpts.iterator().next().equals(DocLint.XMSGS_CUSTOM_PREFIX + "none"))) {
+                    JavacTask t = BasicJavacTask.instance(context);
+                    new DocLint().init(t, doclintOpts.toArray(new String[doclintOpts.size()]));
+                    comp.keepComments = true;
+                }
+            }
+
+            fileManager = context.get(JavaFileManager.class);
 
             if (!files.isEmpty()) {
                 // add filenames to fileObjects
--- a/langtools/src/share/classes/com/sun/tools/javac/main/Option.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/main/Option.java	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -25,28 +25,30 @@
 
 package com.sun.tools.javac.main;
 
+import java.io.File;
+import java.io.FileWriter;
+import java.io.PrintWriter;
 import java.util.Collections;
-import com.sun.tools.javac.util.Log.PrefixKind;
-import com.sun.tools.javac.util.Log.WriterKind;
-import com.sun.tools.javac.util.Log;
+import java.util.EnumSet;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.SourceVersion;
+
+import com.sun.tools.doclint.DocLint;
 import com.sun.tools.javac.code.Lint;
 import com.sun.tools.javac.code.Source;
 import com.sun.tools.javac.code.Type;
 import com.sun.tools.javac.jvm.Target;
+import com.sun.tools.javac.processing.JavacProcessingEnvironment;
+import com.sun.tools.javac.util.Log;
+import com.sun.tools.javac.util.Log.PrefixKind;
+import com.sun.tools.javac.util.Log.WriterKind;
 import com.sun.tools.javac.util.Options;
-import com.sun.tools.javac.processing.JavacProcessingEnvironment;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.PrintWriter;
-import java.util.EnumSet;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-import javax.lang.model.SourceVersion;
-
 import static com.sun.tools.javac.main.Option.ChoiceKind.*;
+import static com.sun.tools.javac.main.Option.OptionGroup.*;
 import static com.sun.tools.javac.main.Option.OptionKind.*;
-import static com.sun.tools.javac.main.Option.OptionGroup.*;
 
 /**
  * Options for javac. The specific Option to handle a command-line option
@@ -79,6 +81,24 @@
     XLINT_CUSTOM("-Xlint:", "opt.Xlint.suboptlist",
             EXTENDED,   BASIC, ANYOF, getXLintChoices()),
 
+    XDOCLINT("-Xdoclint", "opt.Xdoclint", EXTENDED, BASIC),
+
+    XDOCLINT_CUSTOM("-Xdoclint:", "opt.Xdoclint.subopts", "opt.Xdoclint.custom", EXTENDED, BASIC) {
+        @Override
+        public boolean matches(String option) {
+            return DocLint.isValidOption(
+                    option.replace(XDOCLINT_CUSTOM.text, DocLint.XMSGS_CUSTOM_PREFIX));
+        }
+
+        @Override
+        public boolean process(OptionHelper helper, String option) {
+            String prev = helper.get(XDOCLINT_CUSTOM);
+            String next = (prev == null) ? option : (prev + " " + option);
+            helper.put(XDOCLINT_CUSTOM.text, next);
+            return false;
+        }
+    },
+
     // -nowarn is retained for command-line backward compatibility
     NOWARN("-nowarn", "opt.nowarn", STANDARD, BASIC) {
         @Override
@@ -156,6 +176,8 @@
 
     PROCESSORPATH("-processorpath", "opt.arg.path", "opt.processorpath", STANDARD, FILEMANAGER),
 
+    PARAMETERS("-parameters","opt.parameters", STANDARD, BASIC),
+
     D("-d", "opt.arg.directory", "opt.d", STANDARD, FILEMANAGER),
 
     S("-s", "opt.arg.directory", "opt.sourceDest", STANDARD, FILEMANAGER),
@@ -289,7 +311,7 @@
 
     // This option exists only for the purpose of documenting itself.
     // It's actually implemented by the launcher.
-    J("-J", "opt.arg.flag", "opt.J", STANDARD, INFO) {
+    J("-J", "opt.arg.flag", "opt.J", STANDARD, INFO, true) {
         @Override
         public boolean process(OptionHelper helper, String option) {
             throw new AssertionError
@@ -394,7 +416,7 @@
 
     // This option exists only for the purpose of documenting itself.
     // It's actually implemented by the CommandLine class.
-    AT("@", "opt.arg.file", "opt.AT", STANDARD, INFO) {
+    AT("@", "opt.arg.file", "opt.AT", STANDARD, INFO, true) {
         @Override
         public boolean process(OptionHelper helper, String option) {
             throw new AssertionError("the @ flag should be caught by CommandLine.");
--- a/langtools/src/share/classes/com/sun/tools/javac/model/JavacTypes.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/model/JavacTypes.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,11 +25,16 @@
 
 package com.sun.tools.javac.model;
 
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Set;
-import java.util.EnumSet;
+
 import javax.lang.model.element.*;
 import javax.lang.model.type.*;
+
 import com.sun.tools.javac.code.*;
 import com.sun.tools.javac.code.Symbol.*;
 import com.sun.tools.javac.util.*;
@@ -301,4 +306,31 @@
             throw new IllegalArgumentException(o.toString());
         return clazz.cast(o);
     }
+
+    public Set<MethodSymbol> getOverriddenMethods(Element elem) {
+        if (elem.getKind() != ElementKind.METHOD
+                || elem.getModifiers().contains(Modifier.STATIC)
+                || elem.getModifiers().contains(Modifier.PRIVATE))
+            return Collections.emptySet();
+
+        if (!(elem instanceof MethodSymbol))
+            throw new IllegalArgumentException();
+
+        MethodSymbol m = (MethodSymbol) elem;
+        ClassSymbol origin = (ClassSymbol) m.owner;
+
+        Set<MethodSymbol> results = new LinkedHashSet<MethodSymbol>();
+        for (Type t : types.closure(origin.type)) {
+            if (t != origin.type) {
+                ClassSymbol c = (ClassSymbol) t.tsym;
+                for (Scope.Entry e = c.members().lookup(m.name); e.scope != null; e = e.next()) {
+                    if (e.sym.kind == Kinds.MTH && m.overrides(e.sym, origin, types, true)) {
+                        results.add((MethodSymbol) e.sym);
+                    }
+                }
+            }
+        }
+
+        return results;
+    }
 }
--- a/langtools/src/share/classes/com/sun/tools/javac/parser/DocCommentParser.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/parser/DocCommentParser.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,15 +25,12 @@
 
 package com.sun.tools.javac.parser;
 
-import com.sun.tools.javac.util.Filter;
 import java.text.BreakIterator;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.LinkedList;
 import java.util.Locale;
 import java.util.Map;
-import java.util.Queue;
 import java.util.Set;
 
 import com.sun.source.doctree.AttributeTree.ValueKind;
@@ -52,7 +49,6 @@
 import com.sun.tools.javac.tree.DocTreeMaker;
 import com.sun.tools.javac.tree.JCTree;
 import com.sun.tools.javac.util.DiagnosticSource;
-import com.sun.tools.javac.util.JCDiagnostic;
 import com.sun.tools.javac.util.List;
 import com.sun.tools.javac.util.ListBuffer;
 import com.sun.tools.javac.util.Log;
@@ -736,7 +732,9 @@
             nextChar();
             return m.at(p).Entity(names.fromChars(buf, namep, bp - namep - 1));
         } else {
-            String code = checkSemi ? "dc.missing.semicolon" : "dc.bad.entity";
+            String code = checkSemi
+                    ? "dc.missing.semicolon"
+                    : "dc.bad.entity";
             return erroneous(code, p);
         }
     }
@@ -888,8 +886,10 @@
     }
 
     protected void addPendingText(ListBuffer<DCTree> list, int textEnd) {
-        if (textStart != -1 && textStart <= textEnd) {
-            list.add(m.at(textStart).Text(newString(textStart, textEnd + 1)));
+        if (textStart != -1) {
+            if (textStart <= textEnd) {
+                list.add(m.at(textStart).Text(newString(textStart, textEnd + 1)));
+            }
             textStart = -1;
         }
     }
@@ -1196,6 +1196,16 @@
                                 return m.at(pos).See(html);
                             break;
 
+                        case '@':
+                            if (newline)
+                                throw new ParseException("dc.no.content");
+                            break;
+
+                        case EOI:
+                            if (bp == buf.length - 1)
+                                throw new ParseException("dc.no.content");
+                            break;
+
                         default:
                             if (isJavaIdentifierStart(ch) || ch == '#') {
                                 DCReference ref = reference(true);
--- a/langtools/src/share/classes/com/sun/tools/javac/resources/compiler.properties	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/resources/compiler.properties	Tue Jan 22 11:54:16 2013 -0800
@@ -2364,6 +2364,9 @@
 compiler.err.dc.missing.semicolon=\
     semicolon missing
 
+compiler.err.dc.no.content=\
+    no content
+
 compiler.err.dc.no.tag.name=\
     no tag name after '@'
 
--- a/langtools/src/share/classes/com/sun/tools/javac/resources/javac.properties	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/resources/javac.properties	Tue Jan 22 11:54:16 2013 -0800
@@ -55,6 +55,8 @@
     Specify where to find annotation processors
 javac.opt.processor=\
     Names of the annotation processors to run; bypasses default discovery process
+javac.opt.parameters=\
+    Generate metadata for reflection on method parameters
 javac.opt.proc.none.only=\
     Control whether annotation processing and/or compilation is done.
 javac.opt.d=\
@@ -138,6 +140,14 @@
     Enable recommended warnings
 javac.opt.Xlint.suboptlist=\
     Enable or disable specific warnings
+javac.opt.Xdoclint=\
+    Enable recommended checks for problems in javadoc comments
+javac.opt.Xdoclint.subopts = \
+    (all|[-]<group>)[/<access>]
+javac.opt.Xdoclint.custom=\n\
+\        Enable or disable specific checks for problems in javadoc comments,\n\
+\        where <group> is one of accessibility, html, reference, or syntax,\n\
+\        and <access> is one of public, protected, package, or private.
 javac.opt.Xstdout=\
     Redirect standard output
 javac.opt.X=\
--- a/langtools/src/share/classes/com/sun/tools/javac/sym/CreateSymbols.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/sym/CreateSymbols.java	Tue Jan 22 11:54:16 2013 -0800
@@ -33,6 +33,7 @@
 import com.sun.tools.javac.code.Attribute;
 import com.sun.tools.javac.code.Symtab;
 import com.sun.tools.javac.code.Type;
+import com.sun.tools.javac.code.Types;
 import com.sun.tools.javac.jvm.ClassReader;
 import com.sun.tools.javac.jvm.ClassWriter;
 import com.sun.tools.javac.jvm.Pool;
@@ -173,7 +174,8 @@
                                    List.<Pair<Symbol.MethodSymbol,Attribute>>nil());
 
         Type.moreInfo = true;
-        Pool pool = new Pool();
+        Types types = Types.instance(task.getContext());
+        Pool pool = new Pool(types);
         for (JavaFileObject file : fm.list(jarLocation, "", EnumSet.of(CLASS), true)) {
             String className = fm.inferBinaryName(jarLocation, file);
             int index = className.lastIndexOf('.');
--- a/langtools/src/share/classes/com/sun/tools/javac/tree/DCTree.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/tree/DCTree.java	Tue Jan 22 11:54:16 2013 -0800
@@ -36,6 +36,8 @@
 import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
 import com.sun.tools.javac.util.List;
 import com.sun.tools.javac.util.Name;
+import java.io.IOException;
+import java.io.StringWriter;
 import javax.tools.JavaFileObject;
 
 /**
@@ -65,6 +67,21 @@
         return new SimpleDiagnosticPosition(dc.comment.getSourcePos(pos));
     }
 
+    /** Convert a tree to a pretty-printed string. */
+    @Override
+    public String toString() {
+        StringWriter s = new StringWriter();
+        try {
+            new DocPretty(s).print(this);
+        }
+        catch (IOException e) {
+            // should never happen, because StringWriter is defined
+            // never to throw any IOExceptions
+            throw new AssertionError(e);
+        }
+        return s.toString();
+    }
+
     public static class DCDocComment extends DCTree implements DocCommentTree {
         final Comment comment; // required for the implicit source pos table
 
--- a/langtools/src/share/classes/com/sun/tools/javac/tree/DocPretty.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/tree/DocPretty.java	Tue Jan 22 11:54:16 2013 -0800
@@ -81,7 +81,7 @@
     /**
      * Print list.
      */
-    protected void print(List<? extends DocTree> list) throws IOException {
+    public void print(List<? extends DocTree> list) throws IOException {
         for (DocTree t: list) {
             print(t);
         }
--- a/langtools/src/share/classes/com/sun/tools/javac/tree/Pretty.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/tree/Pretty.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, 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
@@ -154,12 +154,13 @@
         }
         //we need to (i) replace all line terminators with a space and (ii) remove
         //occurrences of 'missing' in the Pretty output (generated when types are missing)
-        String res = s.toString().replaceAll("\\s+", " ").replaceAll("/\\*missing\\*/", "");
+        String res = s.toString().trim().replaceAll("\\s+", " ").replaceAll("/\\*missing\\*/", "");
         if (res.length() < maxLength) {
             return res;
         } else {
-            int split = (maxLength - trimSequence.length()) * 2 / 3;
-            return res.substring(0, split) + trimSequence + res.substring(split);
+            int head = (maxLength - trimSequence.length()) * 2 / 3;
+            int tail = maxLength - trimSequence.length() - head;
+            return res.substring(0, head) + trimSequence + res.substring(res.length() - tail);
         }
     }
 
--- a/langtools/src/share/classes/com/sun/tools/javac/tree/TreeInfo.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/tree/TreeInfo.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,6 +26,7 @@
 package com.sun.tools.javac.tree;
 
 
+
 import com.sun.source.tree.Tree;
 import com.sun.tools.javac.code.*;
 import com.sun.tools.javac.comp.AttrContext;
@@ -330,6 +331,13 @@
         return (docComments == null) ? null : docComments.getCommentText(tree);
     }
 
+    public static DCTree.DCDocComment getCommentTree(Env<?> env, JCTree tree) {
+        DocCommentTable docComments = (tree.hasTag(JCTree.Tag.TOPLEVEL))
+                ? ((JCCompilationUnit) tree).docComments
+                : env.toplevel.docComments;
+        return (docComments == null) ? null : docComments.getCommentTree(tree);
+    }
+
     /** The position of the first statement in a block, or the position of
      *  the block itself if it is empty.
      */
--- a/langtools/src/share/classes/com/sun/tools/javac/tree/TreeMaker.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/tree/TreeMaker.java	Tue Jan 22 11:54:16 2013 -0800
@@ -684,7 +684,7 @@
     public JCVariableDecl VarDef(VarSymbol v, JCExpression init) {
         return (JCVariableDecl)
             new JCVariableDecl(
-                Modifiers(v.flags(), Annotations(v.getAnnotationMirrors())),
+                Modifiers(v.flags(), Annotations(v.getRawAttributes())),
                 v.name,
                 Type(v.type),
                 init,
@@ -800,7 +800,7 @@
     public JCMethodDecl MethodDef(MethodSymbol m, Type mtype, JCBlock body) {
         return (JCMethodDecl)
             new JCMethodDecl(
-                Modifiers(m.flags(), Annotations(m.getAnnotationMirrors())),
+                Modifiers(m.flags(), Annotations(m.getRawAttributes())),
                 m.name,
                 Type(mtype.getReturnType()),
                 TypeParams(mtype.getTypeArguments()),
--- a/langtools/src/share/classes/com/sun/tools/javac/util/Names.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javac/util/Names.java	Tue Jan 22 11:54:16 2013 -0800
@@ -132,6 +132,7 @@
     public final Name LineNumberTable;
     public final Name LocalVariableTable;
     public final Name LocalVariableTypeTable;
+    public final Name MethodParameters;
     public final Name RuntimeInvisibleAnnotations;
     public final Name RuntimeInvisibleParameterAnnotations;
     public final Name RuntimeInvisibleTypeAnnotations;
@@ -265,6 +266,7 @@
         LineNumberTable = fromString("LineNumberTable");
         LocalVariableTable = fromString("LocalVariableTable");
         LocalVariableTypeTable = fromString("LocalVariableTypeTable");
+        MethodParameters = fromString("MethodParameters");
         RuntimeInvisibleAnnotations = fromString("RuntimeInvisibleAnnotations");
         RuntimeInvisibleParameterAnnotations = fromString("RuntimeInvisibleParameterAnnotations");
         RuntimeInvisibleTypeAnnotations = fromString("RuntimeInvisibleTypeAnnotations");
--- a/langtools/src/share/classes/com/sun/tools/javadoc/AnnotationDescImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/AnnotationDescImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -89,6 +89,15 @@
     }
 
     /**
+     * Check for the synthesized bit on the annotation.
+     *
+     * @return true if the annotation is synthesized.
+     */
+    public boolean isSynthesized() {
+        return annotation.isSynthesized();
+    }
+
+    /**
      * Returns a string representation of this annotation.
      * String is of one of the forms:
      *     @com.example.foo(name1=val1, name2=val2)
--- a/langtools/src/share/classes/com/sun/tools/javadoc/ClassDocImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/ClassDocImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -276,6 +276,10 @@
         return false;
     }
 
+    public boolean isFunctionalInterface() {
+        return env.types.isFunctionalInterface(tsym);
+    }
+
     /**
      * Return the package that this class is contained in.
      */
--- a/langtools/src/share/classes/com/sun/tools/javadoc/Messager.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/Messager.java	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -133,16 +133,6 @@
         this.programName = programName;
     }
 
-    @Override
-    protected int getDefaultMaxErrors() {
-        return Integer.MAX_VALUE;
-    }
-
-    @Override
-    protected int getDefaultMaxWarnings() {
-        return Integer.MAX_VALUE;
-    }
-
     public void setLocale(Locale locale) {
         this.locale = locale;
     }
--- a/langtools/src/share/classes/com/sun/tools/javadoc/MethodDocImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/MethodDocImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -76,19 +76,17 @@
     }
 
     /**
+     * Return true if this method is default
+     */
+    public boolean isDefault() {
+        return (sym.flags() & Flags.DEFAULT) != 0;
+    }
+
+    /**
      * Return true if this method is abstract
      */
     public boolean isAbstract() {
-        //### This is dubious, but old 'javadoc' apparently does it.
-        //### I regard this as a bug and an obstacle to treating the
-        //### doclet API as a proper compile-time reflection facility.
-        //### (maddox 09/26/2000)
-        if (containingClass().isInterface()) {
-            //### Don't force creation of ClassDocImpl for super here.
-            // Abstract modifier is implicit.  Strip/canonicalize it.
-            return false;
-        }
-        return Modifier.isAbstract(getModifiers());
+        return (Modifier.isAbstract(getModifiers()) && !isDefault());
     }
 
     /**
--- a/langtools/src/share/classes/com/sun/tools/javadoc/PackageDocImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/PackageDocImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -288,9 +288,9 @@
      * Return an empty array if there are none.
      */
     public AnnotationDesc[] annotations() {
-        AnnotationDesc res[] = new AnnotationDesc[sym.getAnnotationMirrors().length()];
+        AnnotationDesc res[] = new AnnotationDesc[sym.getRawAttributes().length()];
         int i = 0;
-        for (Attribute.Compound a : sym.getAnnotationMirrors()) {
+        for (Attribute.Compound a : sym.getRawAttributes()) {
             res[i++] = new AnnotationDescImpl(env, a);
         }
         return res;
--- a/langtools/src/share/classes/com/sun/tools/javadoc/ParameterImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/ParameterImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -99,9 +99,9 @@
      * Return an empty array if there are none.
      */
     public AnnotationDesc[] annotations() {
-        AnnotationDesc res[] = new AnnotationDesc[sym.getAnnotationMirrors().length()];
+        AnnotationDesc res[] = new AnnotationDesc[sym.getRawAttributes().length()];
         int i = 0;
-        for (Attribute.Compound a : sym.getAnnotationMirrors()) {
+        for (Attribute.Compound a : sym.getRawAttributes()) {
             res[i++] = new AnnotationDescImpl(env, a);
         }
         return res;
--- a/langtools/src/share/classes/com/sun/tools/javadoc/ProgramElementDocImpl.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javadoc/ProgramElementDocImpl.java	Tue Jan 22 11:54:16 2013 -0800
@@ -164,9 +164,9 @@
      * Return an empty array if there are none.
      */
     public AnnotationDesc[] annotations() {
-        AnnotationDesc res[] = new AnnotationDesc[sym.getAnnotationMirrors().length()];
+        AnnotationDesc res[] = new AnnotationDesc[sym.getRawAttributes().length()];
         int i = 0;
-        for (Attribute.Compound a : sym.getAnnotationMirrors()) {
+        for (Attribute.Compound a : sym.getRawAttributes()) {
             res[i++] = new AnnotationDescImpl(env, a);
         }
         return res;
--- a/langtools/src/share/classes/com/sun/tools/javap/AttributeWriter.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javap/AttributeWriter.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -46,6 +46,7 @@
 import com.sun.tools.classfile.LineNumberTable_attribute;
 import com.sun.tools.classfile.LocalVariableTable_attribute;
 import com.sun.tools.classfile.LocalVariableTypeTable_attribute;
+import com.sun.tools.classfile.MethodParameters_attribute;
 import com.sun.tools.classfile.RuntimeInvisibleAnnotations_attribute;
 import com.sun.tools.classfile.RuntimeInvisibleParameterAnnotations_attribute;
 import com.sun.tools.classfile.RuntimeVisibleAnnotations_attribute;
@@ -386,6 +387,28 @@
         return null;
     }
 
+    private static final String format = "%-31s%s";
+
+    public Void visitMethodParameters(MethodParameters_attribute attr,
+                                      Void ignore) {
+
+        final String header = String.format(format, "Name", "Flags");
+        println("MethodParameters:");
+        indent(+1);
+        println(header);
+        for (MethodParameters_attribute.Entry entry :
+                 attr.method_parameter_table) {
+            String flagstr =
+                (0 != (entry.flags & ACC_FINAL) ? " final" : "") +
+                (0 != (entry.flags & ACC_SYNTHETIC) ? " synthetic" : "");
+            println(String.format(format,
+                                  constantWriter.stringValue(entry.name_index),
+                                  flagstr));
+        }
+        indent(-1);
+        return null;
+    }
+
     public Void visitRuntimeVisibleAnnotations(RuntimeVisibleAnnotations_attribute attr, Void ignore) {
         println("RuntimeVisibleAnnotations:");
         indent(+1);
--- a/langtools/src/share/classes/com/sun/tools/javap/ClassWriter.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/com/sun/tools/javap/ClassWriter.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -206,7 +206,7 @@
             println("minor version: " + cf.minor_version);
             println("major version: " + cf.major_version);
             if (!options.compat)
-              writeList("flags: ", flags.getClassFlags(), NEWLINE);
+              writeList("flags: ", flags.getClassFlags(), "\n");
             indent(-1);
             constantWriter.writeConstantPool();
         } else {
@@ -383,7 +383,7 @@
             println("Signature: " + getValue(f.descriptor));
 
         if (options.verbose && !options.compat)
-            writeList("flags: ", flags.getFieldFlags(), NEWLINE);
+            writeList("flags: ", flags.getFieldFlags(), "\n");
 
         if (options.showAllAttrs) {
             for (Attribute attr: f.attributes)
@@ -480,7 +480,7 @@
         }
 
         if (options.verbose && !options.compat) {
-            writeList("flags: ", flags.getMethodFlags(), NEWLINE);
+            writeList("flags: ", flags.getMethodFlags(), "\n");
         }
 
         Code_attribute code = null;
@@ -749,5 +749,4 @@
     private int size;
     private ConstantPool constant_pool;
     private Method method;
-    private static final String NEWLINE = System.getProperty("line.separator", "\n");
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/jdeps/Archive.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.tools.jdeps;
+
+import com.sun.tools.classfile.Dependency;
+import com.sun.tools.classfile.Dependency.Location;
+import java.io.File;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+/**
+ * Represents the source of the class files.
+ */
+public class Archive {
+    private static Map<String,Archive> archiveForClass = new HashMap<String,Archive>();
+    public static Archive find(Location loc) {
+        return archiveForClass.get(loc.getName());
+    }
+
+    private final File file;
+    private final String filename;
+    private final DependencyRecorder recorder;
+    private final ClassFileReader reader;
+    public Archive(String name) {
+        this.file = null;
+        this.filename = name;
+        this.recorder = new DependencyRecorder();
+        this.reader = null;
+    }
+
+    public Archive(File f, ClassFileReader reader) {
+        this.file = f;
+        this.filename = f.getName();
+        this.recorder = new DependencyRecorder();
+        this.reader = reader;
+    }
+
+    public ClassFileReader reader() {
+        return reader;
+    }
+
+    public String getFileName() {
+        return filename;
+    }
+
+    public void addClass(String classFileName) {
+        Archive a = archiveForClass.get(classFileName);
+        assert(a == null || a == this); // ## issue warning?
+        if (!archiveForClass.containsKey(classFileName)) {
+            archiveForClass.put(classFileName, this);
+        }
+    }
+
+    public void addDependency(Dependency d) {
+        recorder.addDependency(d);
+    }
+
+    /**
+     * Returns a sorted map of a class to its dependencies.
+     */
+    public SortedMap<Location, SortedSet<Location>> getDependencies() {
+        DependencyRecorder.Filter filter = new DependencyRecorder.Filter() {
+            public boolean accept(Location origin, Location target) {
+                 return (archiveForClass.get(origin.getName()) !=
+                            archiveForClass.get(target.getName()));
+        }};
+
+        SortedMap<Location, SortedSet<Location>> result =
+            new TreeMap<Location, SortedSet<Location>>(locationComparator);
+        for (Map.Entry<Location, Set<Location>> e : recorder.dependencies().entrySet()) {
+            Location o = e.getKey();
+            for (Location t : e.getValue()) {
+                if (filter.accept(o, t)) {
+                    SortedSet<Location> odeps = result.get(o);
+                    if (odeps == null) {
+                        odeps = new TreeSet<Location>(locationComparator);
+                        result.put(o, odeps);
+                    }
+                    odeps.add(t);
+                }
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Returns the set of archives this archive requires.
+     */
+    public Set<Archive> getRequiredArchives() {
+        SortedSet<Archive> deps = new TreeSet<Archive>(new Comparator<Archive>() {
+            public int compare(Archive a1, Archive a2) {
+                return a1.toString().compareTo(a2.toString());
+            }
+        });
+
+        for (Map.Entry<Location, Set<Location>> e : recorder.dependencies().entrySet()) {
+            Location o = e.getKey();
+            Archive origin = Archive.find(o);
+            for (Location t : e.getValue()) {
+                Archive target = Archive.find(t);
+                assert(origin != null && target != null);
+                if (origin != target) {
+                    if (!deps.contains(target)) {
+                        deps.add(target);
+                    }
+                }
+            }
+        }
+        return deps;
+    }
+
+    public String toString() {
+        return file != null ? file.getPath() : filename;
+    }
+
+    private static class DependencyRecorder {
+        static interface Filter {
+            boolean accept(Location origin, Location target);
+        }
+
+        public void addDependency(Dependency d) {
+            Set<Location> odeps = map.get(d.getOrigin());
+            if (odeps == null) {
+                odeps = new HashSet<Location>();
+                map.put(d.getOrigin(), odeps);
+            }
+            odeps.add(d.getTarget());
+        }
+
+        public Map<Location, Set<Location>> dependencies() {
+            return map;
+        }
+
+        private final Map<Location, Set<Location>> map =
+            new HashMap<Location, Set<Location>>();
+    }
+
+    private static Comparator<Location> locationComparator =
+        new Comparator<Location>() {
+            public int compare(Location o1, Location o2) {
+                return o1.toString().compareTo(o2.toString());
+            }
+        };
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/jdeps/ClassFileReader.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,326 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.tools.jdeps;
+
+import com.sun.tools.classfile.ClassFile;
+import com.sun.tools.classfile.ConstantPoolException;
+import com.sun.tools.classfile.Dependencies.ClassFileError;
+import java.io.*;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.*;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+/**
+ * ClassFileReader reads ClassFile(s) of a given path that can be
+ * a .class file, a directory, or a JAR file.
+ */
+public class ClassFileReader {
+    /**
+     * Returns a ClassFileReader instance of a given path.
+     */
+    public static ClassFileReader newInstance(File path) throws IOException {
+        if (!path.exists()) {
+            throw new FileNotFoundException(path.getAbsolutePath());
+        }
+
+        if (path.isDirectory()) {
+            return new DirectoryReader(path.toPath());
+        } else if (path.getName().endsWith(".jar")) {
+            return new JarFileReader(path.toPath());
+        } else {
+            return new ClassFileReader(path.toPath());
+        }
+    }
+
+    protected final Path path;
+    protected final String baseFileName;
+    private ClassFileReader(Path path) {
+        this.path = path;
+        this.baseFileName = path.getFileName() != null
+                                ? path.getFileName().toString()
+                                : path.toString();
+    }
+
+    public String getFileName() {
+        return baseFileName;
+    }
+
+    /**
+     * Returns the ClassFile matching the given binary name
+     * or a fully-qualified class name.
+     */
+    public ClassFile getClassFile(String name) throws IOException {
+        if (name.indexOf('.') > 0) {
+            int i = name.lastIndexOf('.');
+            String pathname = name.replace('.', File.separatorChar) + ".class";
+            if (baseFileName.equals(pathname) ||
+                    baseFileName.equals(pathname.substring(0, i) + "$" +
+                                        pathname.substring(i+1, pathname.length()))) {
+                return readClassFile(path);
+            }
+        } else {
+            if (baseFileName.equals(name.replace('/', File.separatorChar) + ".class")) {
+                return readClassFile(path);
+            }
+        }
+        return null;
+    }
+
+    public Iterable<ClassFile> getClassFiles() throws IOException {
+        return new Iterable<ClassFile>() {
+            public Iterator<ClassFile> iterator() {
+                return new FileIterator();
+            }
+        };
+    }
+
+    protected ClassFile readClassFile(Path p) throws IOException {
+        InputStream is = null;
+        try {
+            is = Files.newInputStream(p);
+            return ClassFile.read(is);
+        } catch (ConstantPoolException e) {
+            throw new ClassFileError(e);
+        } finally {
+            if (is != null) {
+                is.close();
+            }
+        }
+    }
+
+    class FileIterator implements Iterator<ClassFile> {
+        int count;
+        FileIterator() {
+            this.count = 0;
+        }
+        public boolean hasNext() {
+            return count == 0 && baseFileName.endsWith(".class");
+        }
+
+        public ClassFile next() {
+            if (!hasNext()) {
+                throw new NoSuchElementException();
+            }
+            try {
+                ClassFile cf = readClassFile(path);
+                count++;
+                return cf;
+            } catch (IOException e) {
+                throw new ClassFileError(e);
+            }
+        }
+
+        public void remove() {
+            throw new UnsupportedOperationException("Not supported yet.");
+        }
+    }
+
+    public String toString() {
+        return path.toString();
+    }
+
+    private static class DirectoryReader extends ClassFileReader {
+        DirectoryReader(Path path) throws IOException {
+            super(path);
+        }
+
+        public ClassFile getClassFile(String name) throws IOException {
+            if (name.indexOf('.') > 0) {
+                int i = name.lastIndexOf('.');
+                String pathname = name.replace('.', File.separatorChar) + ".class";
+                Path p = path.resolve(pathname);
+                if (!p.toFile().exists()) {
+                    p = path.resolve(pathname.substring(0, i) + "$" +
+                                     pathname.substring(i+1, pathname.length()));
+                }
+                if (p.toFile().exists()) {
+                    return readClassFile(p);
+                }
+            } else {
+                Path p = path.resolve(name + ".class");
+                if (p.toFile().exists()) {
+                    return readClassFile(p);
+                }
+            }
+            return null;
+        }
+
+        public Iterable<ClassFile> getClassFiles() throws IOException {
+            final Iterator<ClassFile> iter = new DirectoryIterator();
+            return new Iterable<ClassFile>() {
+                public Iterator<ClassFile> iterator() {
+                    return iter;
+                }
+            };
+        }
+
+        private List<Path> walkTree(Path dir) throws IOException {
+            final List<Path> files = new ArrayList<Path>();
+            Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
+                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
+                        throws IOException {
+                    if (file.toFile().getName().endsWith(".class")) {
+                        files.add(file);
+                    }
+                    return FileVisitResult.CONTINUE;
+                }
+            });
+            return files;
+        }
+
+        class DirectoryIterator implements Iterator<ClassFile> {
+            private List<Path> entries;
+            private int index = 0;
+            DirectoryIterator() throws IOException {
+                entries = walkTree(path);
+                index = 0;
+            }
+
+            public boolean hasNext() {
+                return index != entries.size();
+            }
+
+            public ClassFile next() {
+                if (!hasNext()) {
+                    throw new NoSuchElementException();
+                }
+                Path path = entries.get(index++);
+                try {
+                    return readClassFile(path);
+                } catch (IOException e) {
+                    throw new ClassFileError(e);
+                }
+            }
+
+            public void remove() {
+                throw new UnsupportedOperationException("Not supported yet.");
+            }
+        }
+    }
+
+    private static class JarFileReader extends ClassFileReader {
+        final JarFile jarfile;
+        JarFileReader(Path path) throws IOException {
+            super(path);
+            this.jarfile = new JarFile(path.toFile());
+        }
+
+        public ClassFile getClassFile(String name) throws IOException {
+            if (name.indexOf('.') > 0) {
+                int i = name.lastIndexOf('.');
+                String entryName = name.replace('.', '/') + ".class";
+                JarEntry e = jarfile.getJarEntry(entryName);
+                if (e == null) {
+                    e = jarfile.getJarEntry(entryName.substring(0, i) + "$"
+                            + entryName.substring(i + 1, entryName.length()));
+                }
+                if (e != null) {
+                    return readClassFile(e);
+                }
+            } else {
+                JarEntry e = jarfile.getJarEntry(name + ".class");
+                if (e != null) {
+                    return readClassFile(e);
+                }
+            }
+            return null;
+        }
+
+        private ClassFile readClassFile(JarEntry e) throws IOException {
+            InputStream is = null;
+            try {
+                is = jarfile.getInputStream(e);
+                return ClassFile.read(is);
+            } catch (ConstantPoolException ex) {
+                throw new ClassFileError(ex);
+            } finally {
+                if (is != null)
+                    is.close();
+            }
+        }
+
+        public Iterable<ClassFile> getClassFiles() throws IOException {
+            final Iterator<ClassFile> iter = new JarFileIterator();
+            return new Iterable<ClassFile>() {
+                public Iterator<ClassFile> iterator() {
+                    return iter;
+                }
+            };
+        }
+
+        class JarFileIterator implements Iterator<ClassFile> {
+            private Enumeration<JarEntry> entries;
+            private JarEntry nextEntry;
+            JarFileIterator() {
+                this.entries = jarfile.entries();
+                while (entries.hasMoreElements()) {
+                    JarEntry e = entries.nextElement();
+                    String name = e.getName();
+                    if (name.endsWith(".class")) {
+                        this.nextEntry = e;
+                        break;
+                    }
+                }
+            }
+
+            public boolean hasNext() {
+                return nextEntry != null;
+            }
+
+            public ClassFile next() {
+                if (!hasNext()) {
+                    throw new NoSuchElementException();
+                }
+
+                ClassFile cf;
+                try {
+                    cf = readClassFile(nextEntry);
+                } catch (IOException ex) {
+                    throw new ClassFileError(ex);
+                }
+                JarEntry entry = nextEntry;
+                nextEntry = null;
+                while (entries.hasMoreElements()) {
+                    JarEntry e = entries.nextElement();
+                    String name = e.getName();
+                    if (name.endsWith(".class")) {
+                        nextEntry = e;
+                        break;
+                    }
+                }
+                return cf;
+            }
+
+            public void remove() {
+                throw new UnsupportedOperationException("Not supported yet.");
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/jdeps/JdepsTask.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,650 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.tools.jdeps;
+
+import com.sun.tools.classfile.ClassFile;
+import com.sun.tools.classfile.ConstantPoolException;
+import com.sun.tools.classfile.Dependencies;
+import com.sun.tools.classfile.Dependencies.ClassFileError;
+import com.sun.tools.classfile.Dependency;
+import com.sun.tools.classfile.Dependency.Location;
+import java.io.*;
+import java.text.MessageFormat;
+import java.util.*;
+import java.util.regex.Pattern;
+
+/**
+ * Implementation for the jdeps tool for static class dependency analysis.
+ */
+class JdepsTask {
+    class BadArgs extends Exception {
+        static final long serialVersionUID = 8765093759964640721L;
+        BadArgs(String key, Object... args) {
+            super(JdepsTask.this.getMessage(key, args));
+            this.key = key;
+            this.args = args;
+        }
+
+        BadArgs showUsage(boolean b) {
+            showUsage = b;
+            return this;
+        }
+        final String key;
+        final Object[] args;
+        boolean showUsage;
+    }
+
+    static abstract class Option {
+        Option(boolean hasArg, String... aliases) {
+            this.hasArg = hasArg;
+            this.aliases = aliases;
+        }
+
+        boolean isHidden() {
+            return false;
+        }
+
+        boolean matches(String opt) {
+            for (String a : aliases) {
+                if (a.equals(opt)) {
+                    return true;
+                } else if (opt.startsWith("--") && hasArg && opt.startsWith(a + "=")) {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        boolean ignoreRest() {
+            return false;
+        }
+
+        abstract void process(JdepsTask task, String opt, String arg) throws BadArgs;
+        final boolean hasArg;
+        final String[] aliases;
+    }
+
+    static abstract class HiddenOption extends Option {
+        HiddenOption(boolean hasArg, String... aliases) {
+            super(hasArg, aliases);
+        }
+
+        boolean isHidden() {
+            return true;
+        }
+    }
+
+    static Option[] recognizedOptions = {
+        new Option(false, "-h", "-?", "--help") {
+            void process(JdepsTask task, String opt, String arg) {
+                task.options.help = true;
+            }
+        },
+        new Option(false, "-s", "--summary") {
+            void process(JdepsTask task, String opt, String arg) {
+                task.options.showSummary = true;
+                task.options.verbose = Options.Verbose.SUMMARY;
+            }
+        },
+        new Option(false, "-v", "--verbose") {
+            void process(JdepsTask task, String opt, String arg) {
+                task.options.verbose = Options.Verbose.VERBOSE;
+            }
+        },
+        new Option(true, "-V", "--verbose-level") {
+            void process(JdepsTask task, String opt, String arg) throws BadArgs {
+                switch (arg) {
+                    case "package":
+                        task.options.verbose = Options.Verbose.PACKAGE;
+                        break;
+                    case "class":
+                        task.options.verbose = Options.Verbose.CLASS;
+                        break;
+                    default:
+                        throw task.new BadArgs("err.invalid.arg.for.option", opt);
+                }
+            }
+        },
+        new Option(true, "-c", "--classpath") {
+            void process(JdepsTask task, String opt, String arg) {
+                task.options.classpath = arg;
+            }
+        },
+        new Option(true, "-p", "--package") {
+            void process(JdepsTask task, String opt, String arg) {
+                task.options.packageNames.add(arg);
+            }
+        },
+        new Option(true, "-e", "--regex") {
+            void process(JdepsTask task, String opt, String arg) {
+                task.options.regex = arg;
+            }
+        },
+        new Option(false, "-P", "--profile") {
+            void process(JdepsTask task, String opt, String arg) {
+                task.options.showProfile = true;
+            }
+        },
+        new Option(false, "-R", "--recursive") {
+            void process(JdepsTask task, String opt, String arg) {
+                task.options.depth = 0;
+            }
+        },
+        new HiddenOption(true, "-d", "--depth") {
+            void process(JdepsTask task, String opt, String arg) throws BadArgs {
+                try {
+                    task.options.depth = Integer.parseInt(arg);
+                } catch (NumberFormatException e) {
+                    throw task.new BadArgs("err.invalid.arg.for.option", opt);
+                }
+            }
+        },
+        new Option(false, "--version") {
+            void process(JdepsTask task, String opt, String arg) {
+                task.options.version = true;
+            }
+        },
+        new HiddenOption(false, "--fullversion") {
+            void process(JdepsTask task, String opt, String arg) {
+                task.options.fullVersion = true;
+            }
+        },
+
+    };
+
+    private static final String PROGNAME = "jdeps";
+    private final Options options = new Options();
+    private final List<String> classes = new ArrayList<String>();
+
+    private PrintWriter log;
+    void setLog(PrintWriter out) {
+        log = out;
+    }
+
+    /**
+     * Result codes.
+     */
+    static final int EXIT_OK = 0, // Completed with no errors.
+                     EXIT_ERROR = 1, // Completed but reported errors.
+                     EXIT_CMDERR = 2, // Bad command-line arguments
+                     EXIT_SYSERR = 3, // System error or resource exhaustion.
+                     EXIT_ABNORMAL = 4;// terminated abnormally
+
+    int run(String[] args) {
+        if (log == null) {
+            log = new PrintWriter(System.out);
+        }
+        try {
+            handleOptions(args);
+            if (options.help) {
+                showHelp();
+            }
+            if (options.version || options.fullVersion) {
+                showVersion(options.fullVersion);
+            }
+            if (classes.isEmpty() && !options.wildcard) {
+                if (options.help || options.version || options.fullVersion) {
+                    return EXIT_OK;
+                } else {
+                    showHelp();
+                    return EXIT_CMDERR;
+                }
+            }
+            if (options.regex != null && options.packageNames.size() > 0) {
+                showHelp();
+                return EXIT_CMDERR;
+            }
+            if (options.showSummary && options.verbose != Options.Verbose.SUMMARY) {
+                showHelp();
+                return EXIT_CMDERR;
+            }
+            boolean ok = run();
+            return ok ? EXIT_OK : EXIT_ERROR;
+        } catch (BadArgs e) {
+            reportError(e.key, e.args);
+            if (e.showUsage) {
+                log.println(getMessage("main.usage.summary", PROGNAME));
+            }
+            return EXIT_CMDERR;
+        } catch (IOException e) {
+            return EXIT_ABNORMAL;
+        } finally {
+            log.flush();
+        }
+    }
+
+    private final List<Archive> sourceLocations = new ArrayList<Archive>();
+    private final Archive NOT_FOUND = new Archive(getMessage("artifact.not.found"));
+    private boolean run() throws IOException {
+        findDependencies();
+        switch (options.verbose) {
+            case VERBOSE:
+            case CLASS:
+                printClassDeps(log);
+                break;
+            case PACKAGE:
+                printPackageDeps(log);
+                break;
+            case SUMMARY:
+                for (Archive origin : sourceLocations) {
+                    for (Archive target : origin.getRequiredArchives()) {
+                        log.format("%-30s -> %s%n", origin, target);
+                    }
+                }
+                break;
+            default:
+                throw new InternalError("Should not reach here");
+        }
+        return true;
+    }
+
+    private boolean isValidClassName(String name) {
+        if (!Character.isJavaIdentifierStart(name.charAt(0))) {
+            return false;
+        }
+        for (int i=1; i < name.length(); i++) {
+            char c = name.charAt(i);
+            if (c != '.'  && !Character.isJavaIdentifierPart(c)) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    private void findDependencies() throws IOException {
+        Dependency.Finder finder = Dependencies.getClassDependencyFinder();
+        Dependency.Filter filter;
+        if (options.regex != null) {
+            filter = Dependencies.getRegexFilter(Pattern.compile(options.regex));
+        } else if (options.packageNames.size() > 0) {
+            filter = Dependencies.getPackageFilter(options.packageNames, false);
+        } else {
+            filter = new Dependency.Filter() {
+                public boolean accepts(Dependency dependency) {
+                    return !dependency.getOrigin().equals(dependency.getTarget());
+                }
+            };
+        }
+
+        List<Archive> archives = new ArrayList<Archive>();
+        Deque<String> roots = new LinkedList<String>();
+        for (String s : classes) {
+            File f = new File(s);
+            if (f.exists()) {
+                archives.add(new Archive(f, ClassFileReader.newInstance(f)));
+            } else {
+                if (isValidClassName(s)) {
+                    roots.add(s);
+                } else {
+                    warning("warn.invalid.arg", s);
+                }
+            }
+        }
+
+        List<Archive> classpaths = new ArrayList<Archive>(); // for class file lookup
+        if (options.wildcard) {
+            // include all archives from classpath to the initial list
+            archives.addAll(getClassPathArchives(options.classpath));
+        } else {
+            classpaths.addAll(getClassPathArchives(options.classpath));
+        }
+        classpaths.addAll(PlatformClassPath.getArchives());
+
+        // add all archives to the source locations for reporting
+        sourceLocations.addAll(archives);
+        sourceLocations.addAll(classpaths);
+
+        // Work queue of names of classfiles to be searched.
+        // Entries will be unique, and for classes that do not yet have
+        // dependencies in the results map.
+        Deque<String> deque = new LinkedList<String>();
+        Set<String> doneClasses = new HashSet<String>();
+
+        // get the immediate dependencies of the input files
+        for (Archive a : archives) {
+            for (ClassFile cf : a.reader().getClassFiles()) {
+                String classFileName;
+                try {
+                    classFileName = cf.getName();
+                } catch (ConstantPoolException e) {
+                    throw new ClassFileError(e);
+                }
+                a.addClass(classFileName);
+                if (!doneClasses.contains(classFileName)) {
+                    doneClasses.add(classFileName);
+                }
+                for (Dependency d : finder.findDependencies(cf)) {
+                    if (filter.accepts(d)) {
+                        String cn = d.getTarget().getName();
+                        if (!doneClasses.contains(cn) && !deque.contains(cn)) {
+                            deque.add(cn);
+                        }
+                        a.addDependency(d);
+                    }
+                }
+            }
+        }
+
+        // add Archive for looking up classes from the classpath
+        // for transitive dependency analysis
+        Deque<String> unresolved = roots;
+        int depth = options.depth > 0 ? options.depth : Integer.MAX_VALUE;
+        do {
+            String name;
+            while ((name = unresolved.poll()) != null) {
+                if (doneClasses.contains(name)) {
+                    continue;
+                }
+                ClassFile cf = null;
+                for (Archive a : classpaths) {
+                    cf = a.reader().getClassFile(name);
+                    if (cf != null) {
+                        String classFileName;
+                        try {
+                            classFileName = cf.getName();
+                        } catch (ConstantPoolException e) {
+                            throw new ClassFileError(e);
+                        }
+                        a.addClass(classFileName);
+                        if (!doneClasses.contains(classFileName)) {
+                            // if name is a fully-qualified class name specified
+                            // from command-line, this class might already be parsed
+                            doneClasses.add(classFileName);
+                            if (depth > 0) {
+                                for (Dependency d : finder.findDependencies(cf)) {
+                                    if (filter.accepts(d)) {
+                                        String cn = d.getTarget().getName();
+                                        if (!doneClasses.contains(cn) && !deque.contains(cn)) {
+                                            deque.add(cn);
+                                        }
+                                        a.addDependency(d);
+                                    }
+                                }
+                            }
+                        }
+                        break;
+                    }
+                }
+                if (cf == null) {
+                    NOT_FOUND.addClass(name);
+                }
+            }
+            unresolved = deque;
+            deque = new LinkedList<String>();
+        } while (!unresolved.isEmpty() && depth-- > 0);
+    }
+
+    private void printPackageDeps(PrintWriter out) {
+        for (Archive source : sourceLocations) {
+            SortedMap<Location, SortedSet<Location>> deps = source.getDependencies();
+            if (deps.isEmpty())
+                continue;
+
+            for (Archive target : source.getRequiredArchives()) {
+                out.format("%s -> %s%n", source, target);
+            }
+
+            Map<String, Archive> pkgs = new TreeMap<String, Archive>();
+            SortedMap<String, Archive> targets = new TreeMap<String, Archive>();
+            String pkg = "";
+            for (Map.Entry<Location, SortedSet<Location>> e : deps.entrySet()) {
+                String cn = e.getKey().getClassName();
+                String p = packageOf(e.getKey());
+                Archive origin = Archive.find(e.getKey());
+                assert origin != null;
+                if (!pkgs.containsKey(p)) {
+                    pkgs.put(p, origin);
+                } else if (pkgs.get(p) != origin) {
+                    warning("warn.split.package", p, origin, pkgs.get(p));
+                }
+
+                if (!p.equals(pkg)) {
+                    printTargets(out, targets);
+                    pkg = p;
+                    targets.clear();
+                    out.format("   %s (%s)%n", p, origin.getFileName());
+                }
+
+                for (Location t : e.getValue()) {
+                    p = packageOf(t);
+                    Archive target = Archive.find(t);
+                    if (!targets.containsKey(p)) {
+                        targets.put(p, target);
+                    }
+                }
+            }
+            printTargets(out, targets);
+            out.println();
+        }
+    }
+
+    private void printTargets(PrintWriter out, Map<String, Archive> targets) {
+        for (Map.Entry<String, Archive> t : targets.entrySet()) {
+            String pn = t.getKey();
+            out.format("      -> %-40s %s%n", pn, getPackageInfo(pn, t.getValue()));
+        }
+    }
+
+    private String getPackageInfo(String pn, Archive source) {
+        if (PlatformClassPath.contains(source)) {
+            String name = PlatformClassPath.getProfileName(pn);
+            if (name.isEmpty()) {
+                return "JDK internal API (" + source.getFileName() + ")";
+            }
+            return options.showProfile ? name : "";
+        }
+        return source.getFileName();
+    }
+
+    private static String packageOf(Location loc) {
+        String pkg = loc.getPackageName();
+        return pkg.isEmpty() ? "<unnamed>" : pkg;
+    }
+
+    private void printClassDeps(PrintWriter out) {
+        for (Archive source : sourceLocations) {
+            SortedMap<Location, SortedSet<Location>> deps = source.getDependencies();
+            if (deps.isEmpty())
+                continue;
+
+            for (Archive target : source.getRequiredArchives()) {
+                out.format("%s -> %s%n", source, target);
+            }
+            out.format("%s%n", source);
+            for (Map.Entry<Location, SortedSet<Location>> e : deps.entrySet()) {
+                String cn = e.getKey().getClassName();
+                Archive origin = Archive.find(e.getKey());
+                out.format("   %s (%s)%n", cn, origin.getFileName());
+                for (Location t : e.getValue()) {
+                    cn = t.getClassName();
+                    Archive target = Archive.find(t);
+                    out.format("      -> %-60s %s%n", cn, getPackageInfo(t.getPackageName(), target));
+                }
+            }
+            out.println();
+        }
+    }
+    public void handleOptions(String[] args) throws BadArgs {
+        // process options
+        for (int i=0; i < args.length; i++) {
+            if (args[i].charAt(0) == '-') {
+                String name = args[i];
+                Option option = getOption(name);
+                String param = null;
+                if (option.hasArg) {
+                    if (name.startsWith("--") && name.indexOf('=') > 0) {
+                        param = name.substring(name.indexOf('=') + 1, name.length());
+                    } else if (i + 1 < args.length) {
+                        param = args[++i];
+                    }
+                    if (param == null || param.isEmpty() || param.charAt(0) == '-') {
+                        throw new BadArgs("err.missing.arg", name).showUsage(true);
+                    }
+                }
+                option.process(this, name, param);
+                if (option.ignoreRest()) {
+                    i = args.length;
+                }
+            } else {
+                // process rest of the input arguments
+                for (; i < args.length; i++) {
+                    String name = args[i];
+                    if (name.charAt(0) == '-') {
+                        throw new BadArgs("err.option.after.class", name).showUsage(true);
+                    }
+                    if (name.equals("*") || name.equals("\"*\"")) {
+                        options.wildcard = true;
+                    } else {
+                        classes.add(name);
+                    }
+                }
+            }
+        }
+    }
+
+    private Option getOption(String name) throws BadArgs {
+        for (Option o : recognizedOptions) {
+            if (o.matches(name)) {
+                return o;
+            }
+        }
+        throw new BadArgs("err.unknown.option", name).showUsage(true);
+    }
+
+    private void reportError(String key, Object... args) {
+        log.println(getMessage("error.prefix") + " " + getMessage(key, args));
+    }
+
+    private void warning(String key, Object... args) {
+        log.println(getMessage("warn.prefix") + " " + getMessage(key, args));
+    }
+
+    private void showHelp() {
+        log.println(getMessage("main.usage", PROGNAME));
+        for (Option o : recognizedOptions) {
+            String name = o.aliases[0].substring(1); // there must always be at least one name
+            name = name.charAt(0) == '-' ? name.substring(1) : name;
+            if (o.isHidden() || name.equals("h")) {
+                continue;
+            }
+            log.println(getMessage("main.opt." + name));
+        }
+    }
+
+    private void showVersion(boolean full) {
+        log.println(version(full ? "full" : "release"));
+    }
+
+    private String version(String key) {
+        // key=version:  mm.nn.oo[-milestone]
+        // key=full:     mm.mm.oo[-milestone]-build
+        if (ResourceBundleHelper.versionRB == null) {
+            return System.getProperty("java.version");
+        }
+        try {
+            return ResourceBundleHelper.versionRB.getString(key);
+        } catch (MissingResourceException e) {
+            return getMessage("version.unknown", System.getProperty("java.version"));
+        }
+    }
+
+    public String getMessage(String key, Object... args) {
+        try {
+            return MessageFormat.format(ResourceBundleHelper.bundle.getString(key), args);
+        } catch (MissingResourceException e) {
+            throw new InternalError("Missing message: " + key);
+        }
+    }
+
+    private static class Options {
+        enum Verbose {
+            CLASS,
+            PACKAGE,
+            SUMMARY,
+            VERBOSE
+        };
+
+        boolean help;
+        boolean version;
+        boolean fullVersion;
+        boolean showFlags;
+        boolean showProfile;
+        boolean showSummary;
+        boolean wildcard;
+        String regex;
+        String classpath = "";
+        int depth = 1;
+        Verbose verbose = Verbose.PACKAGE;
+        Set<String> packageNames = new HashSet<String>();
+    }
+
+    private static class ResourceBundleHelper {
+        static final ResourceBundle versionRB;
+        static final ResourceBundle bundle;
+
+        static {
+            Locale locale = Locale.getDefault();
+            try {
+                bundle = ResourceBundle.getBundle("com.sun.tools.jdeps.resources.jdeps", locale);
+            } catch (MissingResourceException e) {
+                throw new InternalError("Cannot find jdeps resource bundle for locale " + locale);
+            }
+            try {
+                versionRB = ResourceBundle.getBundle("com.sun.tools.jdeps.resources.version");
+            } catch (MissingResourceException e) {
+                throw new InternalError("version.resource.missing");
+            }
+        }
+    }
+
+    private List<Archive> getArchives(List<String> filenames) throws IOException {
+        List<Archive> result = new ArrayList<Archive>();
+        for (String s : filenames) {
+            File f = new File(s);
+            if (f.exists()) {
+                result.add(new Archive(f, ClassFileReader.newInstance(f)));
+            } else {
+                warning("warn.file.not.exist", s);
+            }
+        }
+        return result;
+    }
+
+    private List<Archive> getClassPathArchives(String paths) throws IOException {
+        List<Archive> result = new ArrayList<Archive>();
+        if (paths.isEmpty()) {
+            return result;
+        }
+        for (String p : paths.split(File.pathSeparator)) {
+            if (p.length() > 0) {
+                File f = new File(p);
+                if (f.exists()) {
+                    result.add(new Archive(f, ClassFileReader.newInstance(f)));
+                }
+            }
+        }
+        return result;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/jdeps/Main.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.tools.jdeps;
+
+import java.io.*;
+
+/**
+ *
+ * Usage:
+ *    jdeps [options] files ...
+ * where options include:
+ *    -p package-name   restrict analysis to classes in this package
+ *                      (may be given multiple times)
+ *    -e regex          restrict analysis to packages matching pattern
+ *                      (-p and -e are exclusive)
+ *    -v                show class-level dependencies
+ *                      default: package-level dependencies
+ *    -r --recursive    transitive dependencies analysis
+ *    -classpath paths  Classpath to locate class files
+ *    -all              process all class files in the given classpath
+ */
+public class Main {
+    public static void main(String... args) throws Exception {
+        JdepsTask t = new JdepsTask();
+        int rc = t.run(args);
+        System.exit(rc);
+    }
+
+
+    /**
+     * Entry point that does <i>not</i> call System.exit.
+     *
+     * @param args command line arguments
+     * @param out output stream
+     * @return an exit code. 0 means success, non-zero means an error occurred.
+     */
+    public static int run(String[] args, PrintWriter out) {
+        JdepsTask t = new JdepsTask();
+        t.setLog(out);
+        return t.run(args);
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/jdeps/PlatformClassPath.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.tools.jdeps;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.*;
+
+/**
+ * ClassPath for Java SE and JDK
+ */
+class PlatformClassPath {
+    /*
+     * Profiles for Java SE
+     *
+     * This is a temporary workaround until a common API is defined for langtools
+     * to determine which profile a given classname belongs to.  The list of
+     * packages and profile names are hardcoded in jdk.properties and
+     * split packages are not supported.
+     */
+    static class Profile {
+        final String name;
+        final Set<String> packages;
+
+        Profile(String name) {
+            this.name = name;
+            this.packages = new HashSet<String>();
+        }
+    }
+
+    private final static String JAVAFX = "javafx";
+    private final static Map<String,Profile> map = getProfilePackages();
+    static String getProfileName(String packageName) {
+        Profile profile = map.get(packageName);
+        if (packageName.startsWith(JAVAFX + ".")) {
+            profile = map.get(JAVAFX);
+        }
+        return profile != null ? profile.name : "";
+    }
+
+    private final static List<Archive> javaHomeArchives = init();
+    static List<Archive> getArchives() {
+        return javaHomeArchives;
+    }
+
+    static boolean contains(Archive archive) {
+        return javaHomeArchives.contains(archive);
+    }
+
+    private static List<Archive> init() {
+        List<Archive> result = new ArrayList<Archive>();
+        String javaHome = System.getProperty("java.home");
+        List<File> files = new ArrayList<File>();
+        File jre = new File(javaHome, "jre");
+        File lib = new File(javaHome, "lib");
+
+        try {
+            if (jre.exists() && jre.isDirectory()) {
+                result.addAll(addJarFiles(new File(jre, "lib")));
+                result.addAll(addJarFiles(lib));
+            } else if (lib.exists() && lib.isDirectory()) {
+                // either a JRE or a jdk build image
+                File classes = new File(javaHome, "classes");
+                if (classes.exists() && classes.isDirectory()) {
+                    // jdk build outputdir
+                    result.add(new Archive(classes, ClassFileReader.newInstance(classes)));
+                }
+                // add other JAR files
+                result.addAll(addJarFiles(lib));
+            } else {
+                throw new RuntimeException("\"" + javaHome + "\" not a JDK home");
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+
+        // add a JavaFX profile if there is jfxrt.jar
+        for (Archive archive : result) {
+            if (archive.getFileName().equals("jfxrt.jar")) {
+                map.put(JAVAFX, new Profile("jfxrt.jar"));
+            }
+        }
+        return result;
+    }
+
+    private static List<Archive> addJarFiles(File f) throws IOException {
+        final List<Archive> result = new ArrayList<Archive>();
+        final Path root = f.toPath();
+        final Path ext = root.resolve("ext");
+        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
+            @Override
+            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
+                throws IOException
+            {
+                if (dir.equals(root) || dir.equals(ext)) {
+                    return FileVisitResult.CONTINUE;
+                } else {
+                    // skip other cobundled JAR files
+                    return FileVisitResult.SKIP_SUBTREE;
+                }
+            }
+            @Override
+            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
+                throws IOException
+            {
+                File f = file.toFile();
+                String fn = f.getName();
+                if (fn.endsWith(".jar") && !fn.equals("alt-rt.jar")) {
+                    result.add(new Archive(f, ClassFileReader.newInstance(f)));
+                }
+                return FileVisitResult.CONTINUE;
+            }
+        });
+        return result;
+    }
+
+    private static Map<String,Profile> getProfilePackages() {
+        Map<String,Profile> map = new HashMap<String,Profile>();
+
+        // read the properties as a ResourceBundle as the build compiles
+        // the properties file into Java class.  Another alternative is
+        // to load it as Properties and fix the build to exclude this file.
+        ResourceBundle profileBundle =
+            ResourceBundle.getBundle("com.sun.tools.jdeps.resources.jdk");
+
+        int i=1;
+        String key;
+        while (profileBundle.containsKey((key = "profile." + i + ".name"))) {
+            Profile profile = new Profile(profileBundle.getString(key));
+            String n = profileBundle.getString("profile." + i + ".packages");
+            String[] pkgs = n.split("\\s+");
+            for (String p : pkgs) {
+                if (p.isEmpty()) continue;
+                assert(map.containsKey(p) == false);
+                profile.packages.add(p);
+                map.put(p, profile);
+            }
+            i++;
+        }
+        return map;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/jdeps/resources/jdeps.properties	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,57 @@
+main.usage.summary=\
+Usage: {0} <options> <classes...>\n\
+use -h, -? or --help for a list of possible options
+
+main.usage=\
+Usage: {0} <options> <classes...>\n\
+where <classes> can be a pathname to a .class file, a directory, a JAR file,\n\
+or a fully-qualified classname or wildcard "*".  Possible options include:
+
+error.prefix=Error:
+warn.prefix=Warning:
+
+main.opt.h=\
+\  -h -?      --help                    Print this usage message
+
+main.opt.version=\
+\             --version                 Version information
+
+main.opt.V=\
+\  -V <level> --verbose-level=<level>   Print package-level or class-level dependencies\n\
+\                                       Valid levels are: "package" and "class"
+
+main.opt.v=\
+\  -v         --verbose                 Print additional information
+
+main.opt.s=\
+\  -s         --summary                 Print dependency summary only
+
+main.opt.p=\
+\  -p <pkg name> --package=<pkg name>   Restrict analysis to classes in this package\n\
+\                                       (may be given multiple times)
+
+main.opt.e=\
+\  -e <regex> --regex=<regex>           Restrict analysis to packages matching pattern\n\
+\                                       (-p and -e are exclusive)
+
+main.opt.P=\
+\  -P         --profile                 Show profile or the file containing a package
+
+main.opt.c=\
+\  -c <path>  --classpath=<path>        Specify where to find class files
+
+main.opt.R=\
+\  -R         --recursive               Recursively traverse all dependencies
+
+main.opt.d=\
+\  -d <depth> --depth=<depth>           Specify the depth of the transitive dependency analysis
+
+err.unknown.option=unknown option: {0}
+err.missing.arg=no value given for {0}
+err.internal.error=internal error: {0} {1} {2}
+err.invalid.arg.for.option=invalid argument for option: {0}
+err.option.after.class=option must be specified before classes: {0}
+warn.invalid.arg=Invalid classname or pathname not exist: {0}
+warn.split.package=package {0} defined in {1} {2}
+
+artifact.not.found=not found
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/jdeps/resources/jdk.properties	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,262 @@
+# This properties file does not need localization.
+
+profile.1.name = compact1
+profile.1.packages = \
+    java.io \
+    java.lang \
+    java.lang.annotation \
+    java.lang.invoke \
+    java.lang.ref \
+    java.lang.reflect \
+    java.math \
+    java.net \
+    java.nio \
+    java.nio.channels \
+    java.nio.channels.spi \
+    java.nio.charset \
+    java.nio.charset.spi \
+    java.nio.file \
+    java.nio.file.attribute \
+    java.nio.file.spi \
+    java.security \
+    java.security.cert \
+    java.security.interfaces \
+    java.security.spec \
+    java.text \
+    java.text.spi \
+    java.util \
+    java.util.concurrent \
+    java.util.concurrent.atomic \
+    java.util.concurrent.locks \
+    java.util.jar \
+    java.util.logging \
+    java.util.regex \
+    java.util.spi \
+    java.util.zip \
+    javax.crypto \
+    javax.crypto.interfaces \
+    javax.crypto.spec \
+    javax.security.auth \
+    javax.security.auth.callback \
+    javax.security.auth.login \
+    javax.security.auth.spi \
+    javax.security.auth.x500 \
+    javax.net \
+    javax.net.ssl \
+    javax.security.cert \
+    \
+    com.sun.net.ssl \
+    com.sun.nio.file \
+    com.sun.nio.sctp \
+    com.sun.security.auth \
+    com.sun.security.auth.login
+
+profile.2.name = compact2
+profile.2.packages = \
+    java.sql \
+    javax.sql \
+    javax.xml \
+    javax.xml.datatype \
+    javax.xml.namespace \
+    javax.xml.parsers \
+    javax.xml.stream \
+    javax.xml.stream.events \
+    javax.xml.stream.util \
+    javax.xml.transform \
+    javax.xml.transform.dom \
+    javax.xml.transform.sax \
+    javax.xml.transform.stax \
+    javax.xml.transform.stream \
+    javax.xml.validation \
+    javax.xml.xpath \
+    org.w3c.dom \
+    org.w3c.dom.bootstrap \
+    org.w3c.dom.events \
+    org.w3c.dom.ls \
+    org.xml.sax \
+    org.xml.sax.ext \
+    org.xml.sax.helpers \
+    java.rmi \
+    java.rmi.activation \
+    java.rmi.dgc \
+    java.rmi.registry \
+    java.rmi.server \
+    javax.rmi.ssl \
+    javax.transaction \
+    javax.transaction.xa \
+    \
+    com.sun.net.httpserver \
+    com.sun.net.httpserver.spi
+
+profile.3.name = compact3
+profile.3.packages = \
+    java.lang.instrument \
+    java.lang.management \
+    java.security.acl \
+    java.util.prefs \
+    javax.management \
+    javax.management.loading \
+    javax.management.modelmbean \
+    javax.management.monitor \
+    javax.management.openmbean \
+    javax.management.relation \
+    javax.management.remote \
+    javax.management.remote.rmi \
+    javax.management.timer \
+    javax.naming \
+    javax.naming.directory \
+    javax.naming.event \
+    javax.naming.ldap \
+    javax.naming.spi \
+    javax.sql.rowset \
+    javax.sql.rowset.serial \
+    javax.sql.rowset.spi \
+    javax.security.auth.kerberos \
+    javax.security.sasl \
+    javax.script \
+    javax.smartcardio \
+    javax.xml.crypto \
+    javax.xml.crypto.dom \
+    javax.xml.crypto.dsig \
+    javax.xml.crypto.dsig.dom \
+    javax.xml.crypto.dsig.keyinfo \
+    javax.xml.crypto.dsig.spec \
+    javax.annotation.processing \
+    javax.lang.model \
+    javax.lang.model.element \
+    javax.lang.model.type \
+    javax.lang.model.util \
+    javax.tools \
+    javax.tools.annotation \
+    org.ietf.jgss \
+    \
+    com.sun.management \
+    com.sun.security.auth.callback \
+    com.sun.security.auth.module \
+    com.sun.security.jgss
+
+profile.4.name = Full JRE
+profile.4.packages = \
+    java.applet \
+    java.awt \
+    java.awt.color \
+    java.awt.datatransfer \
+    java.awt.dnd \
+    java.awt.dnd.peer \
+    java.awt.event \
+    java.awt.font \
+    java.awt.geom \
+    java.awt.im \
+    java.awt.im.spi \
+    java.awt.image \
+    java.awt.image.renderable \
+    java.awt.peer \
+    java.awt.print \
+    java.beans \
+    java.beans.beancontext \
+    javax.accessibility \
+    javax.imageio \
+    javax.imageio.event \
+    javax.imageio.metadata \
+    javax.imageio.plugins.bmp \
+    javax.imageio.plugins.jpeg \
+    javax.imageio.spi \
+    javax.imageio.stream \
+    javax.print \
+    javax.print.attribute \
+    javax.print.attribute.standard \
+    javax.print.event \
+    javax.sound.midi \
+    javax.sound.midi.spi \
+    javax.sound.sampled \
+    javax.sound.sampled.spi \
+    javax.swing \
+    javax.swing.border \
+    javax.swing.colorchooser \
+    javax.swing.event \
+    javax.swing.filechooser \
+    javax.swing.plaf \
+    javax.swing.plaf.basic \
+    javax.swing.plaf.metal \
+    javax.swing.plaf.multi \
+    javax.swing.plaf.nimbus \
+    javax.swing.plaf.synth \
+    javax.swing.table \
+    javax.swing.text \
+    javax.swing.text.html \
+    javax.swing.text.html.parser \
+    javax.swing.text.rtf \
+    javax.swing.tree \
+    javax.swing.undo \
+    javax.activation \
+    javax.jws \
+    javax.jws.soap \
+    javax.rmi \
+    javax.rmi.CORBA \
+    javax.xml.bind \
+    javax.xml.bind.annotation \
+    javax.xml.bind.annotation.adapters \
+    javax.xml.bind.attachment \
+    javax.xml.bind.helpers \
+    javax.xml.bind.util \
+    javax.xml.soap \
+    javax.xml.ws \
+    javax.xml.ws.handler \
+    javax.xml.ws.handler.soap \
+    javax.xml.ws.http \
+    javax.xml.ws.soap \
+    javax.xml.ws.spi \
+    javax.xml.ws.spi.http \
+    javax.xml.ws.wsaddressing \
+    javax.annotation \
+    org.omg.CORBA \
+    org.omg.CORBA.DynAnyPackage \
+    org.omg.CORBA.ORBPackage \
+    org.omg.CORBA.TypeCodePackage \
+    org.omg.CORBA.portable \
+    org.omg.CORBA_2_3 \
+    org.omg.CORBA_2_3.portable \
+    org.omg.CosNaming \
+    org.omg.CosNaming.NamingContextExtPackage \
+    org.omg.CosNaming.NamingContextPackage \
+    org.omg.Dynamic \
+    org.omg.DynamicAny \
+    org.omg.DynamicAny.DynAnyFactoryPackage \
+    org.omg.DynamicAny.DynAnyPackage \
+    org.omg.IOP \
+    org.omg.IOP.CodecFactoryPackage \
+    org.omg.IOP.CodecPackage \
+    org.omg.Messaging \
+    org.omg.PortableInterceptor \
+    org.omg.PortableInterceptor.ORBInitInfoPackage \
+    org.omg.PortableServer \
+    org.omg.PortableServer.CurrentPackage \
+    org.omg.PortableServer.POAManagerPackage \
+    org.omg.PortableServer.POAPackage \
+    org.omg.PortableServer.ServantLocatorPackage \
+    org.omg.PortableServer.portable \
+    org.omg.SendingContext \
+    org.omg.stub.java.rmi \
+    org.omg.stub.javax.management.remote.rmi
+
+# Remaining JDK supported API
+profile.5.name = JDK tools
+profile.5.packages = \
+    com.sun.jdi \
+    com.sun.jdi.connect \
+    com.sun.jdi.connect.spi \
+    com.sun.jdi.event \
+    com.sun.jdi.request \
+    com.sun.javadoc \
+    com.sun.tools.doclets \
+    com.sun.tools.doctree \
+    com.sun.source.tree \
+    com.sun.source.util \
+    com.sun.tools.attach \
+    com.sun.tools.attach.spi \
+    com.sun.tools.jconsole \
+    com.sun.tools.javac \
+    com.sun.tools.javah \
+    com.sun.tools.javap \
+    com.sun.tools.javadoc \
+    com.sun.servicetag
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/share/classes/com/sun/tools/jdeps/resources/version.properties-template	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,28 @@
+#
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.  Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+jdk=$(JDK_VERSION)
+full=$(FULL_VERSION)
+release=$(RELEASE)
--- a/langtools/src/share/classes/javax/lang/model/element/Element.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/javax/lang/model/element/Element.java	Tue Jan 22 11:54:16 2013 -0800
@@ -179,6 +179,10 @@
      * instance initializer}, an empty name is returned.
      *
      * @return the simple name of this element
+     * @see PackageElement#getSimpleName
+     * @see ExecutableElement#getSimpleName
+     * @see TypeElement#getSimpleName
+     * @see VariableElement#getSimpleName
      */
     Name getSimpleName();
 
@@ -202,6 +206,11 @@
      * {@linkplain TypeParameterElement#getGenericElement the
      * generic element} of the type parameter is returned.
      *
+     * <li> If this is a {@linkplain
+     * VariableElement#getEnclosingElement method or constructor
+     * parameter}, {@linkplain ExecutableElement the executable
+     * element} which declares the parameter is returned.
+     *
      * </ul>
      *
      * @return the enclosing element, or {@code null} if there is none
--- a/langtools/src/share/classes/javax/lang/model/element/ExecutableElement.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/javax/lang/model/element/ExecutableElement.java	Tue Jan 22 11:54:16 2013 -0800
@@ -78,6 +78,16 @@
     boolean isVarArgs();
 
     /**
+     * Returns {@code true} if this method is a default method and
+     * returns {@code false} otherwise.
+     *
+     * @return {@code true} if this method is a default method and
+     * {@code false} otherwise
+     * @since 1.8
+     */
+    boolean isDefault();
+
+    /**
      * Returns the exceptions and other throwables listed in this
      * method or constructor's {@code throws} clause in declaration
      * order.
--- a/langtools/src/share/classes/javax/lang/model/element/VariableElement.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/javax/lang/model/element/VariableElement.java	Tue Jan 22 11:54:16 2013 -0800
@@ -62,4 +62,29 @@
      * @jls 4.12.4 final Variables
      */
     Object getConstantValue();
+
+    /**
+     * Returns the simple name of this variable element.
+     *
+     * <p>For method and constructor parameters, the name of each
+     * parameter must be distinct from the names of all other
+     * parameters of the same executable.  If the original source
+     * names are not available, an implementation may synthesize names
+     * subject to the distinctness requirement above.
+     *
+     * @return the simple name of this variable element
+     */
+    @Override
+    Name getSimpleName();
+
+    /**
+     * Returns the enclosing element of this variable.
+     *
+     * The enclosing element of a method or constructor parameter is
+     * the executable declaring the parameter.
+     *
+     * @return the enclosing element of this variable
+     */
+    @Override
+    Element getEnclosingElement();
 }
--- a/langtools/src/share/classes/javax/lang/model/element/package-info.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/javax/lang/model/element/package-info.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -48,9 +48,12 @@
  * {@linkplain java.lang.annotation.RetentionPolicy#SOURCE source}
  * {@linkplain java.lang.annotation.Retention retention} cannot be
  * recovered from class files and class files might not be able to
- * provide source position information.  The {@linkplain
- * javax.lang.model.element.Modifier modifiers} on an element may
- * differ in some cases including
+ * provide source position information.
+ *
+ * Names of parameters may not be recoverable from class files.
+ *
+ * The {@linkplain javax.lang.model.element.Modifier modifiers} on an
+ * element may differ in some cases including:
  *
  * <ul>
  * <li> {@code strictfp} on a class or interface
--- a/langtools/src/share/classes/javax/lang/model/util/AbstractAnnotationValueVisitor7.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/javax/lang/model/util/AbstractAnnotationValueVisitor7.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/javax/lang/model/util/AbstractTypeVisitor8.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/javax/lang/model/util/AbstractTypeVisitor8.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/src/share/classes/javax/lang/model/util/ElementKindVisitor8.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/src/share/classes/javax/lang/model/util/ElementKindVisitor8.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/Makefile	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/Makefile	Tue Jan 22 11:54:16 2013 -0800
@@ -229,7 +229,7 @@
 all: $(JPRT_CLEAN) jtreg-tests jck-compiler-tests jck-runtime-tests $(JPRT_ARCHIVE_BUNDLE) all-summary
 	@echo "Testing completed successfully"
 
-jtreg apt javac javadoc javah javap: $(JPRT_CLEAN) jtreg-tests $(JPRT_ARCHIVE_BUNDLE) jtreg-summary
+jtreg apt javac javadoc javah javap jdeps: $(JPRT_CLEAN) jtreg-tests $(JPRT_ARCHIVE_BUNDLE) jtreg-summary
 	@echo "Testing completed successfully"
 
 jck-compiler: $(JPRT_CLEAN) jck-compiler-tests $(JPRT_ARCHIVE_BUNDLE) jck-compiler-summary
@@ -246,6 +246,7 @@
 javadoc:	JTREG_TESTDIRS = tools/javadoc com/sun/javadoc
 javah:		JTREG_TESTDIRS = tools/javah
 javap:		JTREG_TESTDIRS = tools/javap
+jdeps:		JTREG_TESTDIRS = tools/jdeps
 
 # Run jtreg tests
 #
@@ -426,7 +427,7 @@
 
 # Phony targets (e.g. these are not filenames)
 .PHONY: all clean \
-	jtreg javac javadoc javah javap jtreg-tests jtreg-summary check-jtreg \
+	jtreg javac javadoc javah javap jdeps jtreg-tests jtreg-summary check-jtreg \
 	jck-compiler jck-compiler-tests jck-compiler-summary \
 	jck-runtime jck-runtime-tests jck-runtime-summary check-jck
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testAbstractMethod/TestAbstractMethod.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug      8004891
+ * @summary  Make sure that the abstract method is identified correctly
+ *           if the abstract modifier is present explicitly or implicitly.
+ * @author   bpatel
+ * @library  ../lib/
+ * @build    JavadocTester TestAbstractMethod
+ * @run main TestAbstractMethod
+ */
+
+public class TestAbstractMethod extends JavadocTester {
+
+    //Test information.
+    private static final String BUG_ID = "8004891";
+
+    //Javadoc arguments.
+    private static final String[] ARGS = new String[] {
+        "-d", BUG_ID, "-sourcepath", SRC_DIR, "pkg"
+    };
+
+    //Input for string search tests.
+    private static final String[][] TEST = {
+        {BUG_ID + FS + "pkg" + FS + "A.html",
+            "<td class=\"colFirst\"><code>default void</code></td>"},
+        {BUG_ID + FS + "pkg" + FS + "A.html",
+            "<caption><span id=\"t0\" class=\"activeTableTab\"><span>" +
+            "All Methods</span><span class=\"tabEnd\">&nbsp;</span></span>" +
+            "<span id=\"t2\" class=\"tableTab\"><span>" +
+            "<a href=\"javascript:show(2);\">Instance Methods</a></span>" +
+            "<span class=\"tabEnd\">&nbsp;</span></span><span id=\"t3\" " +
+            "class=\"tableTab\"><span><a href=\"javascript:show(4);\">" +
+            "Abstract Methods</a></span><span class=\"tabEnd\">&nbsp;</span>" +
+            "</span><span id=\"t5\" class=\"tableTab\"><span>" +
+            "<a href=\"javascript:show(16);\">Default Methods</a></span>" +
+            "<span class=\"tabEnd\">&nbsp;</span></span></caption>"},
+        {BUG_ID + FS + "pkg" + FS + "B.html",
+            "<caption><span id=\"t0\" class=\"activeTableTab\"><span>" +
+            "All Methods</span><span class=\"tabEnd\">&nbsp;</span></span>" +
+            "<span id=\"t2\" class=\"tableTab\"><span>" +
+            "<a href=\"javascript:show(2);\">Instance Methods</a></span>" +
+            "<span class=\"tabEnd\">&nbsp;</span></span><span id=\"t3\" " +
+            "class=\"tableTab\"><span><a href=\"javascript:show(4);\">Abstract " +
+            "Methods</a></span><span class=\"tabEnd\">&nbsp;</span></span>" +
+            "<span id=\"t4\" class=\"tableTab\"><span>" +
+            "<a href=\"javascript:show(8);\">Concrete Methods</a></span>" +
+            "<span class=\"tabEnd\">&nbsp;</span></span></caption>"},
+        {BUG_ID + FS + "pkg" + FS + "B.html",
+            "<td class=\"colFirst\"><code>abstract void</code></td>"},
+        {BUG_ID + FS + "pkg" + FS + "C.html",
+            "<caption><span id=\"t0\" class=\"activeTableTab\"><span>" +
+            "All Methods</span><span class=\"tabEnd\">&nbsp;</span></span>" +
+            "<span id=\"t2\" class=\"tableTab\"><span>" +
+            "<a href=\"javascript:show(2);\">Instance Methods</a></span>" +
+            "<span class=\"tabEnd\">&nbsp;</span></span>" +
+            "<span id=\"t5\" class=\"tableTab\"><span>" +
+            "<a href=\"javascript:show(16);\">Default Methods</a></span>" +
+            "<span class=\"tabEnd\">&nbsp;</span></span></caption>"},
+        {BUG_ID + FS + "pkg" + FS + "C.html",
+            "<td class=\"colFirst\"><code>default void</code></td>"}
+    };
+    private static final String[][] NEGATED_TEST = {
+        {BUG_ID + FS + "pkg" + FS + "A.html",
+            "<td class=\"colFirst\"><code>abstract void</code></td>"},
+        {BUG_ID + FS + "pkg" + FS + "B.html",
+            "<span><a href=\"javascript:show(16);\">Default Methods</a></span>" +
+            "<span class=\"tabEnd\">&nbsp;</span>"},
+        {BUG_ID + FS + "pkg" + FS + "B.html",
+            "<td class=\"colFirst\"><code>default void</code></td>"},
+        {BUG_ID + FS + "pkg" + FS + "C.html",
+            "<span><a href=\"javascript:show(4);\">Abstract Methods</a></span>" +
+            "<span class=\"tabEnd\">&nbsp;</span>"}
+    };
+
+    /**
+     * The entry point of the test.
+     * @param args the array of command line arguments.
+     */
+    public static void main(String[] args) {
+        TestAbstractMethod tester = new TestAbstractMethod();
+        run(tester, ARGS, TEST, NEGATED_TEST);
+        tester.printSummary();
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getBugId() {
+        return BUG_ID;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getBugName() {
+        return getClass().getName();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testAbstractMethod/pkg/A.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+public interface A {
+
+    public void method1();
+
+    public default void defaultMethod() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testAbstractMethod/pkg/B.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+public abstract class B {
+
+    public abstract void method1();
+
+    public void method2() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testAbstractMethod/pkg/C.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+public interface C {
+
+    public default void onlyMethod() { }
+}
--- a/langtools/test/com/sun/javadoc/testHtmlTableTags/TestHtmlTableTags.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/com/sun/javadoc/testHtmlTableTags/TestHtmlTableTags.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -207,7 +207,7 @@
             "Instance Methods</a></span><span class=\"tabEnd\">&nbsp;</span></span>" +
             "<span id=\"t4\" class=\"tableTab\"><span><a href=\"javascript:show(8);\">" +
             "Concrete Methods</a></span><span class=\"tabEnd\">&nbsp;</span></span>" +
-            "<span id=\"t5\" class=\"tableTab\"><span><a href=\"javascript:show(16);\">" +
+            "<span id=\"t6\" class=\"tableTab\"><span><a href=\"javascript:show(32);\">" +
             "Deprecated Methods</a></span><span class=\"tabEnd\">&nbsp;</span></span>" +
             "</caption>"
         },
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testLambdaFeature/TestLambdaFeature.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug      8004893
+ * @summary  Make sure that the lambda feature changes work fine in
+ *           javadoc.
+ * @author   bpatel
+ * @library  ../lib/
+ * @build    JavadocTester TestLambdaFeature
+ * @run main TestLambdaFeature
+ */
+
+public class TestLambdaFeature extends JavadocTester {
+
+    //Test information.
+    private static final String BUG_ID = "8004893";
+
+    //Javadoc arguments.
+    private static final String[] ARGS = new String[] {
+        "-d", BUG_ID, "-sourcepath", SRC_DIR, "pkg"
+    };
+
+    //Input for string search tests.
+    private static final String[][] TEST = {
+        {BUG_ID + FS + "pkg" + FS + "A.html",
+            "<td class=\"colFirst\"><code>default void</code></td>"},
+        {BUG_ID + FS + "pkg" + FS + "A.html",
+            "<pre>default&nbsp;void&nbsp;defaultMethod()</pre>"},
+        {BUG_ID + FS + "pkg" + FS + "A.html",
+            "<caption><span id=\"t0\" class=\"activeTableTab\"><span>" +
+            "All Methods</span><span class=\"tabEnd\">&nbsp;</span></span>" +
+            "<span id=\"t2\" class=\"tableTab\"><span>" +
+            "<a href=\"javascript:show(2);\">Instance Methods</a></span>" +
+            "<span class=\"tabEnd\">&nbsp;</span></span><span id=\"t3\" " +
+            "class=\"tableTab\"><span><a href=\"javascript:show(4);\">" +
+            "Abstract Methods</a></span><span class=\"tabEnd\">&nbsp;</span>" +
+            "</span><span id=\"t5\" class=\"tableTab\"><span>" +
+            "<a href=\"javascript:show(16);\">Default Methods</a></span>" +
+            "<span class=\"tabEnd\">&nbsp;</span></span></caption>"},
+        {BUG_ID + FS + "pkg" + FS + "A.html",
+            "<dl>" + NL + "<dt>Functional Interface:</dt>" + NL +
+            "<dd>This is a functional interface and can therefore be used as " +
+            "the assignment target for a lambda expression or method " +
+            "reference. </dd>" + NL + "</dl>"}
+    };
+    private static final String[][] NEGATED_TEST = {
+        {BUG_ID + FS + "pkg" + FS + "A.html",
+            "<td class=\"colFirst\"><code>default default void</code></td>"},
+        {BUG_ID + FS + "pkg" + FS + "A.html",
+            "<pre>default&nbsp;default&nbsp;void&nbsp;defaultMethod()</pre>"},
+        {BUG_ID + FS + "pkg" + FS + "B.html",
+            "<td class=\"colFirst\"><code>default void</code></td>"},
+        {BUG_ID + FS + "pkg" + FS + "B.html",
+            "<dl>" + NL + "<dt>Functional Interface:</dt>"}
+    };
+
+    /**
+     * The entry point of the test.
+     * @param args the array of command line arguments.
+     */
+    public static void main(String[] args) {
+        TestLambdaFeature tester = new TestLambdaFeature();
+        run(tester, ARGS, TEST, NEGATED_TEST);
+        tester.printSummary();
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getBugId() {
+        return BUG_ID;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getBugName() {
+        return getClass().getName();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testLambdaFeature/pkg/A.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+public interface A {
+
+    public void method1();
+
+    public default void defaultMethod() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testLambdaFeature/pkg/B.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+public abstract class B {
+
+    public abstract void method1();
+
+    public void method2() { }
+}
--- a/langtools/test/com/sun/javadoc/testMethodTypes/TestMethodTypes.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/com/sun/javadoc/testMethodTypes/TestMethodTypes.java	Tue Jan 22 11:54:16 2013 -0800
@@ -55,7 +55,7 @@
             "Instance Methods</a></span><span class=\"tabEnd\">&nbsp;</span></span>" +
             "<span id=\"t4\" class=\"tableTab\"><span><a href=\"javascript:show(8);\">" +
             "Concrete Methods</a></span><span class=\"tabEnd\">&nbsp;</span></span>" +
-            "<span id=\"t5\" class=\"tableTab\"><span><a href=\"javascript:show(16);\">" +
+            "<span id=\"t6\" class=\"tableTab\"><span><a href=\"javascript:show(32);\">" +
             "Deprecated Methods</a></span><span class=\"tabEnd\">&nbsp;</span></span>" +
             "</caption>"
         },
@@ -87,7 +87,7 @@
             "Abstract Methods</a></span><span class=\"tabEnd\">&nbsp;</span></span>" +
             "<span id=\"t4\" class=\"tableTab\"><span><a href=\"javascript:show(8);\">" +
             "Concrete Methods</a></span><span class=\"tabEnd\">&nbsp;</span></span>" +
-            "<span id=\"t5\" class=\"tableTab\"><span><a href=\"javascript:show(16);\">" +
+            "<span id=\"t6\" class=\"tableTab\"><span><a href=\"javascript:show(32);\">" +
             "Deprecated Methods</a></span><span class=\"tabEnd\">&nbsp;</span></span>" +
             "</caption>"
         },
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/TestRepeatedAnnotations.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug      8005092
+ * @summary  Test repeated annotations output.
+ * @author   bpatel
+ * @library  ../lib/
+ * @build    JavadocTester TestRepeatedAnnotations
+ * @run main TestRepeatedAnnotations
+ */
+
+public class TestRepeatedAnnotations extends JavadocTester {
+
+    //Test information.
+    private static final String BUG_ID = "8005092";
+
+    //Javadoc arguments.
+    private static final String[] ARGS = new String[] {
+        "-d", BUG_ID, "-sourcepath", SRC_DIR, "pkg", "pkg1"
+    };
+
+    //Input for string search tests.
+    private static final String[][] TEST = {
+        {BUG_ID + FS + "pkg" + FS + "C.html",
+            "<a href=\"../pkg/ContaineeSynthDoc.html\" " +
+            "title=\"annotation in pkg\">@ContaineeSynthDoc</a> " +
+            "<a href=\"../pkg/ContaineeSynthDoc.html\" " +
+            "title=\"annotation in pkg\">@ContaineeSynthDoc</a>"},
+        {BUG_ID + FS + "pkg" + FS + "C.html",
+            "<a href=\"../pkg/ContaineeRegDoc.html\" " +
+            "title=\"annotation in pkg\">@ContaineeRegDoc</a> " +
+            "<a href=\"../pkg/ContaineeRegDoc.html\" " +
+            "title=\"annotation in pkg\">@ContaineeRegDoc</a>"},
+        {BUG_ID + FS + "pkg" + FS + "C.html",
+            "<a href=\"../pkg/RegContainerDoc.html\" " +
+            "title=\"annotation in pkg\">@RegContainerDoc</a>" +
+            "(<a href=\"../pkg/RegContainerDoc.html#value()\">value</a>={" +
+            "<a href=\"../pkg/RegContaineeNotDoc.html\" " +
+            "title=\"annotation in pkg\">@RegContaineeNotDoc</a>," +
+            "<a href=\"../pkg/RegContaineeNotDoc.html\" " +
+            "title=\"annotation in pkg\">@RegContaineeNotDoc</a>})"},
+        {BUG_ID + FS + "pkg" + FS + "C.html",
+            "<a href=\"../pkg/ContaineeSynthDoc.html\" " +
+            "title=\"annotation in pkg\">@ContaineeSynthDoc</a> " +
+            "<a href=\"../pkg/ContaineeSynthDoc.html\" " +
+            "title=\"annotation in pkg\">@ContaineeSynthDoc</a> " +
+            "<a href=\"../pkg/ContaineeSynthDoc.html\" " +
+            "title=\"annotation in pkg\">@ContaineeSynthDoc</a>"},
+        {BUG_ID + FS + "pkg" + FS + "C.html",
+            "<a href=\"../pkg/ContainerSynthDoc.html\" " +
+            "title=\"annotation in pkg\">@ContainerSynthDoc</a>(" +
+            "<a href=\"../pkg/ContainerSynthDoc.html#value()\">value</a>=" +
+            "<a href=\"../pkg/ContaineeSynthDoc.html\" " +
+            "title=\"annotation in pkg\">@ContaineeSynthDoc</a>)"},
+        {BUG_ID + FS + "pkg" + FS + "C.html",
+            "<a href=\"../pkg/ContaineeSynthDoc.html\" " +
+            "title=\"annotation in pkg\">@ContaineeSynthDoc</a> " +
+            "<a href=\"../pkg/ContaineeSynthDoc.html\" " +
+            "title=\"annotation in pkg\">@ContaineeSynthDoc</a>"},
+
+        {BUG_ID + FS + "pkg" + FS + "D.html",
+            "<a href=\"../pkg/RegDoc.html\" title=\"annotation in pkg\">@RegDoc</a>" +
+            "(<a href=\"../pkg/RegDoc.html#x()\">x</a>=1)"},
+        {BUG_ID + FS + "pkg" + FS + "D.html",
+            "<a href=\"../pkg/RegArryDoc.html\" title=\"annotation in pkg\">@RegArryDoc</a>" +
+            "(<a href=\"../pkg/RegArryDoc.html#y()\">y</a>=1)"},
+        {BUG_ID + FS + "pkg" + FS + "D.html",
+            "<a href=\"../pkg/RegArryDoc.html\" title=\"annotation in pkg\">@RegArryDoc</a>" +
+            "(<a href=\"../pkg/RegArryDoc.html#y()\">y</a>={1,2})"},
+        {BUG_ID + FS + "pkg" + FS + "D.html",
+            "<a href=\"../pkg/NonSynthDocContainer.html\" " +
+            "title=\"annotation in pkg\">@NonSynthDocContainer</a>" +
+            "(<a href=\"../pkg/NonSynthDocContainer.html#value()\">value</a>=" +
+            "<a href=\"../pkg/RegArryDoc.html\" title=\"annotation in pkg\">@RegArryDoc</a>)"},
+
+        {BUG_ID + FS + "pkg1" + FS + "C.html",
+            "<a href=\"../pkg1/RegContainerValDoc.html\" " +
+            "title=\"annotation in pkg1\">@RegContainerValDoc</a>" +
+            "(<a href=\"../pkg1/RegContainerValDoc.html#value()\">value</a>={" +
+            "<a href=\"../pkg1/RegContaineeNotDoc.html\" " +
+            "title=\"annotation in pkg1\">@RegContaineeNotDoc</a>," +
+            "<a href=\"../pkg1/RegContaineeNotDoc.html\" " +
+            "title=\"annotation in pkg1\">@RegContaineeNotDoc</a>}," +
+            "<a href=\"../pkg1/RegContainerValDoc.html#y()\">y</a>=3)"},
+        {BUG_ID + FS + "pkg1" + FS + "C.html",
+            "<a href=\"../pkg1/ContainerValDoc.html\" " +
+            "title=\"annotation in pkg1\">@ContainerValDoc</a>" +
+            "(<a href=\"../pkg1/ContainerValDoc.html#value()\">value</a>={" +
+            "<a href=\"../pkg1/ContaineeNotDoc.html\" " +
+            "title=\"annotation in pkg1\">@ContaineeNotDoc</a>," +
+            "<a href=\"../pkg1/ContaineeNotDoc.html\" " +
+            "title=\"annotation in pkg1\">@ContaineeNotDoc</a>}," +
+            "<a href=\"../pkg1/ContainerValDoc.html#x()\">x</a>=1)"}
+    };
+
+    private static final String[][] NEGATED_TEST = {
+        {BUG_ID + FS + "pkg" + FS + "C.html",
+            "<a href=\"../pkg/RegContaineeDoc.html\" " +
+            "title=\"annotation in pkg\">@RegContaineeDoc</a> " +
+            "<a href=\"../pkg/RegContaineeDoc.html\" " +
+            "title=\"annotation in pkg\">@RegContaineeDoc</a>"},
+        {BUG_ID + FS + "pkg" + FS + "C.html",
+            "<a href=\"../pkg/RegContainerNotDoc.html\" " +
+            "title=\"annotation in pkg\">@RegContainerNotDoc</a>" +
+            "(<a href=\"../pkg/RegContainerNotDoc.html#value()\">value</a>={" +
+            "<a href=\"../pkg/RegContaineeNotDoc.html\" " +
+            "title=\"annotation in pkg\">@RegContaineeNotDoc</a>," +
+            "<a href=\"../pkg/RegContaineeNotDoc.html\" " +
+            "title=\"annotation in pkg\">@RegContaineeNotDoc</a>})"},
+
+        {BUG_ID + FS + "pkg1" + FS + "C.html",
+            "<a href=\"../pkg1/ContaineeSynthDoc.html\" " +
+            "title=\"annotation in pkg1\">@ContaineeSynthDoc</a> " +
+            "<a href=\"../pkg1/ContaineeSynthDoc.html\" " +
+            "title=\"annotation in pkg1\">@ContaineeSynthDoc</a>"},
+        {BUG_ID + FS + "pkg1" + FS + "C.html",
+            "<a href=\"../pkg1/RegContainerValNotDoc.html\" " +
+            "title=\"annotation in pkg1\">@RegContainerValNotDoc</a>" +
+            "(<a href=\"../pkg1/RegContainerValNotDoc.html#value()\">value</a>={" +
+            "<a href=\"../pkg1/RegContaineeDoc.html\" " +
+            "title=\"annotation in pkg1\">@RegContaineeDoc</a>," +
+            "<a href=\"../pkg1/RegContaineeDoc.html\" " +
+            "title=\"annotation in pkg1\">@RegContaineeDoc</a>}," +
+            "<a href=\"../pkg1/RegContainerValNotDoc.html#y()\">y</a>=4)"},
+        {BUG_ID + FS + "pkg1" + FS + "C.html",
+            "<a href=\"../pkg1/ContainerValNotDoc.html\" " +
+            "title=\"annotation in pkg1\">@ContainerValNotDoc</a>" +
+            "(<a href=\"../pkg1/ContainerValNotDoc.html#value()\">value</a>={" +
+            "<a href=\"../pkg1/ContaineeNotDoc.html\" " +
+            "title=\"annotation in pkg1\">@ContaineeNotDoc</a>," +
+            "<a href=\"../pkg1/ContaineeNotDoc.html\" " +
+            "title=\"annotation in pkg1\">@ContaineeNotDoc</a>}," +
+            "<a href=\"../pkg1/ContainerValNotDoc.html#x()\">x</a>=2)"},
+        {BUG_ID + FS + "pkg1" + FS + "C.html",
+            "<a href=\"../pkg1/ContainerSynthNotDoc.html\" " +
+            "title=\"annotation in pkg1\">@ContainerSynthNotDoc</a>(" +
+            "<a href=\"../pkg1/ContainerSynthNotDoc.html#value()\">value</a>=" +
+            "<a href=\"../pkg1/ContaineeSynthDoc.html\" " +
+            "title=\"annotation in pkg1\">@ContaineeSynthDoc</a>)"}
+    };
+
+    /**
+     * The entry point of the test.
+     * @param args the array of command line arguments.
+     */
+    public static void main(String[] args) {
+        TestRepeatedAnnotations tester = new TestRepeatedAnnotations();
+        run(tester, ARGS, TEST, NEGATED_TEST);
+        tester.printSummary();
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getBugId() {
+        return BUG_ID;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    public String getBugName() {
+        return getClass().getName();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/C.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+@ContainerSynthDoc(value={@ContaineeSynthDoc,@ContaineeSynthDoc})
+@ContainerRegDoc(value={@ContaineeRegDoc,@ContaineeRegDoc})
+@RegContainerDoc(value={@RegContaineeNotDoc,@RegContaineeNotDoc})
+@ContainerRegNotDoc(value={@RegContaineeDoc,@RegContaineeDoc})
+@RegContainerNotDoc(value={@RegContaineeNotDoc,@RegContaineeNotDoc})
+@ContaineeSynthDoc @ContaineeSynthDoc @ContaineeSynthDoc
+public class C {
+
+    @ContainerSynthDoc(value={@ContaineeSynthDoc})
+    public void test1() {}
+
+    @ContaineeSynthDoc @ContaineeSynthDoc
+    public void test2() {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/ContaineeRegDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a documented annotation contained by ContainerRegDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+@Documented
+public @interface ContaineeRegDoc {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/ContaineeSynthDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a documented synthesized annotation contained by ContainerSynthDoc.
+ * It will be used to annotate Class C and a method in the class using a synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+@Documented
+@ContainedBy(ContainerSynthDoc.class)
+public @interface ContaineeSynthDoc {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/ContainerRegDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a documented annotation container for ContaineeRegDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+@Documented
+public @interface ContainerRegDoc {
+
+    ContaineeRegDoc[] value();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/ContainerRegNotDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a non-documented annotation container for RegContaineeDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+public @interface ContainerRegNotDoc {
+
+    RegContaineeDoc[] value();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/ContainerSynthDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a documented synthesized annotation container for ContaineeSynthDoc.
+ * It will be used to annotate Class C and a method in the class using a synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+@Documented
+@ContainerFor(ContaineeSynthDoc.class)
+public @interface ContainerSynthDoc {
+
+    ContaineeSynthDoc[] value();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/D.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+@RegDoc(x=1)
+public class D {
+
+    @RegArryDoc(y={1})
+    public void test1() {}
+
+    @RegArryDoc(y={1,2})
+    public void test2() {}
+
+    @NonSynthDocContainer(value={@RegArryDoc})
+    public void test3() {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/NonSynthDocContainer.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a documented annotation.
+ * It will be used to annotate methods in class D.
+ *
+ * @author Bhavesh Patel
+ */
+@Documented
+public @interface NonSynthDocContainer {
+
+    RegArryDoc[] value();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/RegArryDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a documented annotation.
+ * It will be used to annotate methods in Class D.
+ *
+ * @author Bhavesh Patel
+ */
+@Documented
+public @interface RegArryDoc {
+
+    int[] y();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/RegContaineeDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a documented annotation contained by ContainerRegNotDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+@Documented
+public @interface RegContaineeDoc {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/RegContaineeNotDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a non-documented annotation contained by RegContainerNotDoc
+ * and RegContainerDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+public @interface RegContaineeNotDoc {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/RegContainerDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a documented annotation container for RegContainerDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+@Documented
+public @interface RegContainerDoc {
+
+    RegContaineeNotDoc[] value();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/RegContainerNotDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a non-documented annotation container for RegContaineeNotDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+public @interface RegContainerNotDoc {
+
+    RegContaineeNotDoc[] value();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg/RegDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a documented annotation.
+ * It will be used to annotate Class D.
+ *
+ * @author Bhavesh Patel
+ */
+@Documented
+public @interface RegDoc {
+
+    int x();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg1/C.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg1;
+
+@ContainerSynthNotDoc(value={@ContaineeSynthDoc,@ContaineeSynthDoc})
+@RegContainerValDoc(value={@RegContaineeNotDoc,@RegContaineeNotDoc},y=3)
+@ContainerValDoc(value={@ContaineeNotDoc,@ContaineeNotDoc},x=1)
+@RegContainerValNotDoc(value={@RegContaineeDoc,@RegContaineeDoc},y=4)
+@ContainerValNotDoc(value={@ContaineeNotDoc,@ContaineeNotDoc},x=2)
+public class C {
+
+    @ContainerSynthNotDoc(value={@ContaineeSynthDoc})
+    public void test1() {}
+
+    @ContaineeSynthDoc @ContaineeSynthDoc
+    public void test2() {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg1/ContaineeNotDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg1;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a non-documented annotation contained by ContainerValNotDoc
+ * and ContainerValDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+public @interface ContaineeNotDoc {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg1/ContaineeSynthDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg1;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a documented synthesized annotation contained by ContainerSynthNotDoc.
+ * It will be used to annotate Class C and methods in the class using a synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+@Documented
+@ContainedBy(ContainerSynthNotDoc.class)
+public @interface ContaineeSynthDoc {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg1/ContainerSynthNotDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg1;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a non-documented synthesized annotation container for ContaineeSynthDoc.
+ * It will be used to annotate Class C and methods in the class using a synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+@ContainerFor(ContaineeSynthDoc.class)
+public @interface ContainerSynthNotDoc {
+
+    ContaineeSynthDoc[] value();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg1/ContainerValDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg1;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a documented annotation container for ContaineeNotDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+@Documented
+public @interface ContainerValDoc {
+
+    ContaineeNotDoc[] value();
+
+    int x();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg1/ContainerValNotDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg1;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a non-documented annotation container for ContaineeNotDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+public @interface ContainerValNotDoc {
+
+    ContaineeNotDoc[] value();
+
+    int x();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg1/RegContaineeDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg1;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a documented annotation contained by RegContainerValNotDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+@Documented
+public @interface RegContaineeDoc {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg1/RegContaineeNotDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg1;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a non-documented annotation contained by RegContainerValDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+public @interface RegContaineeNotDoc {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg1/RegContainerValDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg1;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a documented annotation container for RegContaineeNotDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+@Documented
+public @interface RegContainerValDoc {
+
+    RegContaineeNotDoc[] value();
+
+    int y();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testRepeatedAnnotations/pkg1/RegContainerValNotDoc.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package pkg1;
+
+import java.lang.annotation.*;
+
+/**
+ * This annotation is a non-documented annotation container for RegContaineeDoc.
+ * It will be used to annotate Class C using a non-synthesized form.
+ *
+ * @author Bhavesh Patel
+ */
+public @interface RegContainerValNotDoc {
+
+    RegContaineeDoc[] value();
+
+    int y();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/AccessTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,65 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -ref AccessTest.protected.out AccessTest.java
+ * @run main DocLintTester -Xmsgs -ref AccessTest.private.out AccessTest.java
+ * @run main DocLintTester -Xmsgs:syntax -ref AccessTest.private.out AccessTest.java
+ * @run main DocLintTester -Xmsgs:syntax/public -ref AccessTest.public.out AccessTest.java
+ * @run main DocLintTester -Xmsgs:syntax/protected -ref AccessTest.protected.out AccessTest.java
+ * @run main DocLintTester -Xmsgs:syntax/package -ref AccessTest.package.out AccessTest.java
+ * @run main DocLintTester -Xmsgs:syntax/private -ref AccessTest.private.out AccessTest.java
+ * @run main DocLintTester -Xmsgs:all,-syntax AccessTest.java
+ * @run main DocLintTester -Xmsgs:all,-syntax/public AccessTest.java
+ * @run main DocLintTester -Xmsgs:all,-syntax/protected -ref AccessTest.public.out AccessTest.java
+ * @run main DocLintTester -Xmsgs:all,-syntax/package -ref AccessTest.protected.out AccessTest.java
+ * @run main DocLintTester -Xmsgs:all,-syntax/private -ref AccessTest.package.out AccessTest.java
+ */
+
+/** */
+public class AccessTest {
+    /**
+     * public a < b
+     */
+    public void public_syntax_error() { }
+
+    /**
+     * protected a < b
+     */
+    protected void protected_syntax_error() { }
+
+    /**
+     * package-private a < b
+     */
+    void syntax_error() { }
+
+    /**
+     * private a < b
+     */
+    private void private_syntax_error() { }
+}
+
+/** */
+class AccessTest2 {
+    /**
+     * public a < b
+     */
+    public void public_syntax_error() { }
+
+    /**
+     * protected a < b
+     */
+    protected void protected_syntax_error() { }
+
+    /**
+     * package-private a < b
+     */
+    void syntax_error() { }
+
+    /**
+     * private a < b
+     */
+    private void private_syntax_error() { }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/AccessTest.package.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,20 @@
+AccessTest.java:23: error: malformed HTML
+     * public a < b
+                ^
+AccessTest.java:28: error: malformed HTML
+     * protected a < b
+                   ^
+AccessTest.java:33: error: malformed HTML
+     * package-private a < b
+                         ^
+AccessTest.java:46: error: malformed HTML
+     * public a < b
+                ^
+AccessTest.java:51: error: malformed HTML
+     * protected a < b
+                   ^
+AccessTest.java:56: error: malformed HTML
+     * package-private a < b
+                         ^
+6 errors
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/AccessTest.private.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,27 @@
+AccessTest.java:23: error: malformed HTML
+     * public a < b
+                ^
+AccessTest.java:28: error: malformed HTML
+     * protected a < b
+                   ^
+AccessTest.java:33: error: malformed HTML
+     * package-private a < b
+                         ^
+AccessTest.java:38: error: malformed HTML
+     * private a < b
+                 ^
+AccessTest.java:46: error: malformed HTML
+     * public a < b
+                ^
+AccessTest.java:51: error: malformed HTML
+     * protected a < b
+                   ^
+AccessTest.java:56: error: malformed HTML
+     * package-private a < b
+                         ^
+AccessTest.java:61: error: malformed HTML
+     * private a < b
+                 ^
+8 errors
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/AccessTest.protected.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,8 @@
+AccessTest.java:23: error: malformed HTML
+     * public a < b
+                ^
+AccessTest.java:28: error: malformed HTML
+     * protected a < b
+                   ^
+2 errors
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/AccessTest.public.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,5 @@
+AccessTest.java:23: error: malformed HTML
+     * public a < b
+                ^
+1 error
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/AccessibilityTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,44 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-accessibility AccessibilityTest.java
+ * @run main DocLintTester -ref AccessibilityTest.out AccessibilityTest.java
+ */
+
+/** */
+public class AccessibilityTest {
+
+    /**
+     * <h2> ... </h2>
+     */
+    public void missing_h1() { }
+
+    /**
+     * <h1> ... </h1>
+     * <h3> ... </h3>
+     */
+    public void missing_h2() { }
+
+    /**
+     * <img src="x.jpg">
+     */
+    public void missing_alt() { }
+
+    /**
+     * <table summary="ok"><tr><th>head<tr><td>data</table>
+     */
+    public void table_with_summary() { }
+
+    /**
+     * <table><caption>ok</caption><tr><th>head<tr><td>data</table>
+     */
+    public void table_with_caption() { }
+
+    /**
+     * <table><tr><th>head<tr><td>data</table>
+     */
+    public void table_without_summary_and_caption() { }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/AccessibilityTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,13 @@
+AccessibilityTest.java:14: error: header used out of sequence: <H2>
+     * <h2> ... </h2>
+       ^
+AccessibilityTest.java:20: error: header used out of sequence: <H3>
+     * <h3> ... </h3>
+       ^
+AccessibilityTest.java:25: error: no "alt" attribute for image
+     * <img src="x.jpg">
+       ^
+AccessibilityTest.java:40: error: no summary or caption for table
+     * <table><tr><th>head<tr><td>data</table>
+                                      ^
+4 errors
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/DocLintTester.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.sun.tools.doclint.DocLint;
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+
+public class DocLintTester {
+
+    public static void main(String... args) throws Exception {
+        new DocLintTester().run(args);
+    }
+
+    public void run(String... args) throws Exception {
+        String testSrc = System.getProperty("test.src");
+
+        File refFile = null;
+        List<String> opts = new ArrayList<String>();
+        List<File> files = new ArrayList<File>();
+        for (int i = 0; i < args.length; i++) {
+            String arg = args[i];
+            if (arg.equals("-ref")) {
+                refFile = new File(testSrc, args[++i]);
+            } else if (arg.startsWith("-Xmsgs")) {
+                opts.add(arg);
+            } else
+                files.add(new File(testSrc, arg));
+        }
+
+        check(opts, files, refFile);
+
+        if (errors > 0)
+            throw new Exception(errors + " errors occurred");
+    }
+
+    void check(List<String> opts, List<File> files, File refFile) throws Exception {
+        List<String> args = new ArrayList<String>();
+        args.addAll(opts);
+        for (File file: files)
+            args.add(file.getPath());
+
+        StringWriter sw = new StringWriter();
+        PrintWriter pw = new PrintWriter(sw);
+        new DocLint().run(pw, args.toArray(new String[args.size()]));
+        pw.flush();
+        String out = normalizeNewlines(removeFileNames(sw.toString())).trim();
+        if (out != null)
+            System.err.println("Output:\n" + out);
+
+        if (refFile == null) {
+            if (!out.isEmpty())
+                error("unexpected output");
+        } else {
+            String expect = readFile(refFile);
+            if (!expect.equals(out)) {
+                error("expected output not found");
+                System.err.println("EXPECT>>" + expect + "<<");
+                System.err.println(" FOUND>>" + out    + "<<");
+            }
+        }
+    }
+
+    String readFile(File file) throws IOException {
+        StringBuilder sb = new StringBuilder();
+        Reader in = new BufferedReader(new FileReader(file));
+        try {
+            char[] buf = new char[1024];
+            int n;
+            while ((n = in.read(buf)) != -1)
+                sb.append(buf, 0, n);
+        } finally {
+            in.close();
+        }
+        return sb.toString().trim();
+    }
+
+    private static final Pattern dirFileLine = Pattern.compile(
+            "(?m)"                          // multi-line mode
+            + "^(.*?)"                      // directory part of file name
+            + "([A-Za-z0-9.]+:[0-9]+:)");   // file name and line number
+
+    String removeFileNames(String s) {
+        Matcher m = dirFileLine.matcher(s);
+        StringBuffer sb = new StringBuffer();
+        while (m.find()) {
+            m.appendReplacement(sb, "$2");
+        }
+        m.appendTail(sb);
+        return sb.toString();
+    }
+
+    private static final String nl = System.getProperty("line.separator");
+    String normalizeNewlines(String s) {
+        return (nl.equals("\n") ? s : s.replace(nl, "\n"));
+    }
+
+
+    void error(String msg) {
+        System.err.println("Error: " + msg);
+        errors++;
+    }
+
+    int errors;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptyAuthorTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,12 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-syntax EmptyAuthorTest.java
+ * @run main DocLintTester -Xmsgs:syntax -ref EmptyAuthorTest.out EmptyAuthorTest.java
+ */
+
+/** @author */
+public class EmptyAuthorTest {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptyAuthorTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,5 @@
+EmptyAuthorTest.java:10: warning: no description for @author
+/** @author */
+    ^
+1 warning
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptyExceptionTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,14 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-syntax EmptyExceptionTest.java
+ * @run main DocLintTester -Xmsgs:syntax -ref EmptyExceptionTest.out EmptyExceptionTest.java
+ */
+
+/** . */
+public class EmptyExceptionTest {
+    /** @exception NullPointerException */
+    int emptyException() throws NullPointerException { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptyExceptionTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,4 @@
+EmptyExceptionTest.java:12: warning: no description for @exception
+    /** @exception NullPointerException */
+        ^
+1 warning
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptyParamTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,14 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-syntax EmptyParamTest.java
+ * @run main DocLintTester -Xmsgs:syntax -ref EmptyParamTest.out EmptyParamTest.java
+ */
+
+/** . */
+public class EmptyParamTest {
+    /** @param i */
+    int emptyParam(int i) { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptyParamTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,5 @@
+EmptyParamTest.java:12: warning: no description for @param
+    /** @param i */
+        ^
+1 warning
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptyReturnTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,14 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-syntax EmptyReturnTest.java
+ * @run main DocLintTester -Xmsgs:syntax -ref EmptyReturnTest.out EmptyReturnTest.java
+ */
+
+/** . */
+public class EmptyReturnTest {
+    /** @return */
+    int emptyReturn() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptyReturnTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,5 @@
+EmptyReturnTest.java:12: warning: no description for @return
+    /** @return */
+        ^
+1 warning
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptySerialDataTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,17 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-syntax EmptySerialDataTest.java
+ * @run main DocLintTester -Xmsgs:syntax -ref EmptySerialDataTest.out EmptySerialDataTest.java
+ */
+
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+
+/** . */
+public class EmptySerialDataTest implements Serializable {
+    /** @serialData */
+    private void writeObject(ObjectOutputStream s) { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptySerialDataTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,5 @@
+EmptySerialDataTest.java:15: warning: no description for @serialData
+    /** @serialData */
+        ^
+1 warning
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptySerialFieldTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,22 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-syntax EmptySerialFieldTest.java
+ * @run main DocLintTester -Xmsgs:syntax -ref EmptySerialFieldTest.out EmptySerialFieldTest.java
+ */
+
+import java.io.ObjectStreamField;
+import java.io.Serializable;
+
+/** . */
+public class EmptySerialFieldTest implements Serializable {
+
+    /**
+     * @serialField empty    String
+     */
+    private static final ObjectStreamField[] serialPersistentFields = {
+        new ObjectStreamField("empty", String.class),
+    };
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptySerialFieldTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,5 @@
+EmptySerialFieldTest.java:17: warning: no description for @serialField
+     * @serialField empty    String
+       ^
+1 warning
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptySinceTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,14 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-syntax EmptySinceTest.java
+ * @run main DocLintTester -Xmsgs:syntax -ref EmptySinceTest.out EmptySinceTest.java
+ */
+
+/** . */
+public class EmptySinceTest {
+    /** @since */
+    int emptySince() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptySinceTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,5 @@
+EmptySinceTest.java:12: warning: no description for @since
+    /** @since */
+        ^
+1 warning
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptyVersionTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,14 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-syntax EmptyVersionTest.java
+ * @run main DocLintTester -Xmsgs:syntax -ref EmptyVersionTest.out EmptyVersionTest.java
+ */
+
+/** . */
+public class EmptyVersionTest {
+    /** @version */
+    int missingVersion() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/EmptyVersionTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,4 @@
+EmptyVersionTest.java:12: warning: no description for @version
+    /** @version */
+        ^
+1 warning
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/HtmlAttrsTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,27 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-html HtmlAttrsTest.java
+ * @run main DocLintTester -ref HtmlAttrsTest.out HtmlAttrsTest.java
+ */
+
+/** */
+public class HtmlAttrsTest {
+    /**
+     * <p xyz>
+     */
+    public void unknown() { }
+
+    /**
+     * <img name="x" alt="alt">
+     */
+    public void obsolete() { }
+
+    /**
+     * <font size="3"> text </font>
+     */
+    public void obsolete_use_css() { }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/HtmlAttrsTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,12 @@
+HtmlAttrsTest.java:13: error: unknown attribute: xyz
+     * <p xyz>
+          ^
+HtmlAttrsTest.java:18: warning: attribute obsolete: name
+     * <img name="x" alt="alt">
+            ^
+HtmlAttrsTest.java:23: warning: attribute obsolete, use CSS instead: size
+     * <font size="3"> text </font>
+             ^
+1 error
+2 warnings
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/HtmlTagsTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,58 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-html HtmlTagsTest.java
+ * @run main DocLintTester -ref HtmlTagsTest.out HtmlTagsTest.java
+ */
+
+/** */
+public class HtmlTagsTest {
+    /**
+     * <xyz> ... </xyz>
+     */
+    public void unknownTag1() { }
+
+    /**
+     * <div> <xyz> </div>
+     */
+    public void unknownTag2() { }
+
+    /**
+     * <br/>
+     */
+    public void selfClosingTag() { }
+
+    /**
+     * <html>
+     */
+    public void not_allowed() { }
+
+    /**
+     * <span> <p> </span>
+     */
+    public void not_allowed_inline() { }
+
+    /**
+     * {@link java.lang.String <p> }
+     * {@link java.lang.String <p> }
+     */
+    public void not_allowed_inline_2() { }
+
+    /**
+     * <img src="any.jpg" alt="alt"> </img>
+     */
+    public void end_not_allowed() { }
+
+    /**
+     * <i> <b> </i>
+     */
+    public void start_not_matched() { }
+
+    /**
+     * <i> </b> </i>
+     */
+    public void end_unexpected() { }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/HtmlTagsTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,38 @@
+HtmlTagsTest.java:13: error: unknown tag: xyz
+     * <xyz> ... </xyz>
+       ^
+HtmlTagsTest.java:13: error: unknown tag: xyz
+     * <xyz> ... </xyz>
+                 ^
+HtmlTagsTest.java:18: error: unknown tag: xyz
+     * <div> <xyz> </div>
+             ^
+HtmlTagsTest.java:23: error: self-closing element not allowed
+     * <br/>
+       ^
+HtmlTagsTest.java:28: error: element not allowed in documentation comments: <html>
+     * <html>
+       ^
+HtmlTagsTest.java:33: error: block element not allowed within inline element <span>: p
+     * <span> <p> </span>
+              ^
+HtmlTagsTest.java:38: error: block element not allowed within @link: p
+     * {@link java.lang.String <p> }
+                               ^
+HtmlTagsTest.java:39: error: block element not allowed within @link: p
+     * {@link java.lang.String <p> }
+                               ^
+HtmlTagsTest.java:44: error: invalid end tag: </img>
+     * <img src="any.jpg" alt="alt"> </img>
+                                     ^
+HtmlTagsTest.java:49: error: end tag missing: </b>
+     * <i> <b> </i>
+           ^
+HtmlTagsTest.java:54: error: unexpected end tag: </b>
+     * <i> </b> </i>
+           ^
+HtmlTagsTest.java:54: warning: empty <i> tag
+     * <i> </b> </i>
+                ^
+11 errors
+1 warning
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/MissingCommentTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,14 @@
+/*
+ * @test /nodynamiccopyright/
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-missing MissingCommentTest.java
+ * @run main DocLintTester -Xmsgs:missing -ref MissingCommentTest.out MissingCommentTest.java
+ */
+
+public class MissingCommentTest {
+    MissingCommentTest() { }
+
+    int missingComment;
+
+    void missingComment() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/MissingCommentTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,14 @@
+MissingCommentTest.java:8: warning: no comment
+public class MissingCommentTest {
+       ^
+MissingCommentTest.java:9: warning: no comment
+    MissingCommentTest() { }
+    ^
+MissingCommentTest.java:11: warning: no comment
+    int missingComment;
+        ^
+MissingCommentTest.java:13: warning: no comment
+    void missingComment() { }
+         ^
+4 warnings
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/MissingParamsTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,23 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-missing MissingParamsTest.java
+ * @run main DocLintTester -Xmsgs:missing -ref MissingParamsTest.out MissingParamsTest.java
+ */
+
+/** . */
+public class MissingParamsTest {
+    /** */
+    MissingParamsTest(int param) { }
+
+    /** */
+    <T> MissingParamsTest() { }
+
+    /** */
+    void missingParam(int param) { }
+
+    /** */
+    <T> void missingTyparam() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/MissingParamsTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,14 @@
+MissingParamsTest.java:13: warning: no @param for param
+    MissingParamsTest(int param) { }
+    ^
+MissingParamsTest.java:16: warning: no @param for <T>
+    <T> MissingParamsTest() { }
+        ^
+MissingParamsTest.java:19: warning: no @param for param
+    void missingParam(int param) { }
+         ^
+MissingParamsTest.java:22: warning: no @param for <T>
+    <T> void missingTyparam() { }
+             ^
+4 warnings
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/MissingReturnTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,23 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-missing MissingReturnTest.java
+ * @run main DocLintTester -Xmsgs:missing -ref MissingReturnTest.out MissingReturnTest.java
+ */
+
+/** . */
+public class MissingReturnTest {
+    /** no return allowed */
+    MissingReturnTest() { }
+
+    /** no return allowed */
+    void return_void() { }
+
+    /** no return required */
+    Void return_Void() { }
+
+    /** */
+    int missingReturn() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/MissingReturnTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,5 @@
+MissingReturnTest.java:22: warning: no @return
+    int missingReturn() { }
+        ^
+1 warning
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/MissingThrowsTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,14 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-missing MissingThrowsTest.java
+ * @run main DocLintTester -Xmsgs:missing -ref MissingThrowsTest.out MissingThrowsTest.java
+ */
+
+/** */
+public class MissingThrowsTest {
+    /** */
+    void missingThrows() throws Exception { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/MissingThrowsTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,4 @@
+MissingThrowsTest.java:13: warning: no @throws for java.lang.Exception
+    void missingThrows() throws Exception { }
+         ^
+1 warning
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/OptionTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8004832
+ * @summary Add new doclint package
+ */
+
+import com.sun.tools.doclint.DocLint;
+
+public class OptionTest {
+    public static void main(String... args) throws Exception {
+        new OptionTest().run();
+    }
+
+    String[] positiveTests = {
+        "-Xmsgs",
+        "-Xmsgs:all",
+        "-Xmsgs:none",
+        "-Xmsgs:accessibility",
+        "-Xmsgs:html",
+        "-Xmsgs:missing",
+        "-Xmsgs:reference",
+        "-Xmsgs:syntax",
+        "-Xmsgs:html/public",
+        "-Xmsgs:html/protected",
+        "-Xmsgs:html/package",
+        "-Xmsgs:html/private",
+        "-Xmsgs:-html/public",
+        "-Xmsgs:-html/protected",
+        "-Xmsgs:-html/package",
+        "-Xmsgs:-html/private",
+        "-Xmsgs:html,syntax",
+        "-Xmsgs:html,-syntax",
+        "-Xmsgs:-html,syntax",
+        "-Xmsgs:-html,-syntax",
+        "-Xmsgs:html/public,syntax",
+        "-Xmsgs:html,syntax/public",
+        "-Xmsgs:-html/public,syntax/public"
+    };
+
+    String[] negativeTests = {
+        "-typo",
+        "-Xmsgs:-all",
+        "-Xmsgs:-none",
+        "-Xmsgs:typo",
+        "-Xmsgs:html/typo",
+        "-Xmsgs:html/public,typo",
+        "-Xmsgs:html/public,syntax/typo",
+    };
+
+    void run() throws Exception {
+        test(positiveTests, true);
+        test(negativeTests, false);
+
+        if (errors > 0)
+            throw new Exception(errors + " errors occurred");
+    }
+
+    void test(String[] tests, boolean expect) {
+        for (String test: tests) {
+            System.err.println("test: " + test);
+            boolean found = DocLint.isValidOption(test);
+            if (found != expect)
+                error("Unexpected result: " + found + ",expected: " + expect);
+        }
+    }
+
+    void error(String msg) {
+        System.err.println("Error: " + msg);
+        errors++;
+    }
+
+    int errors;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/OverridesTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:all OverridesTest.java
+ */
+
+/*
+ * This is a test that missing comments on methods may be inherited
+ * from overridden methods. As such, there should be no errors due
+ * to missing comments (or any other types of error) in this test.
+ */
+
+/** An interface. */
+interface I1 {
+    /**
+     * A method
+     * @param p a param
+     * @throws Exception an exception
+     * @return an int
+     */
+    int m(int p) throws Exception;
+}
+
+/** An extending interface. */
+interface I2 extends I1 { }
+
+/** An abstract class. */
+abstract class C1 {
+    /**
+     * A method
+     * @param p a param
+     * @throws Exception an exception
+     * @return an int
+     */
+    int m(int p) throws Exception;
+}
+
+/** An implementing class. */
+class C2 implements I1 {
+    int m(int  p) throws Exception { return p; }
+}
+
+/** An extending class. */
+class C3 extends C1 {
+    int m(int  p) throws Exception { return p; }
+}
+
+/** An extending and implementing class. */
+class C4 extends C1 implements I1 {
+    int m(int  p) throws Exception { return p; }
+}
+
+/** An implementing class using inheritdoc. */
+class C5 implements I1 {
+    /** {@inheritDoc} */
+    int m(int  p) throws Exception { return p; }
+}
+
+/** An implementing class with incomplete documentation. */
+class C6 implements I1 {
+    /** Overriding method */
+    int m(int  p) throws Exception { return p; }
+}
+
+/** A class implementing an inherited interface. */
+class C7 implements I2 {
+    int m(int  p) throws Exception { return p; }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/ReferenceTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,52 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-reference ReferenceTest.java
+ * @run main DocLintTester -ref ReferenceTest.out ReferenceTest.java
+ */
+
+/** */
+public class ReferenceTest {
+    /**
+     * @param x description
+     */
+    public int invalid_param;
+
+    /**
+     * @param x description
+     */
+    public class InvalidParam { }
+
+    /**
+     * @param x description
+     */
+    public void param_name_not_found(int a) { }
+
+    /**
+     * @param <X> description
+     */
+    public class typaram_name_not_found { }
+
+    /**
+     * @see Object#tooStrong()
+     */
+    public void ref_not_found() { }
+
+    /**
+     * @return x description
+     */
+    public int invalid_return;
+
+    /**
+     * @return x description
+     */
+    public void invalid_return();
+
+    /**
+     * @throws Exception description
+     */
+    public void exception_not_thrown() { }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/ReferenceTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,30 @@
+ReferenceTest.java:13: error: invalid use of @param
+     * @param x description
+       ^
+ReferenceTest.java:18: error: invalid use of @param
+     * @param x description
+       ^
+ReferenceTest.java:23: error: @param name not found
+     * @param x description
+              ^
+ReferenceTest.java:25: warning: no @param for a
+    public void param_name_not_found(int a) { }
+                ^
+ReferenceTest.java:28: error: @param name not found
+     * @param <X> description
+               ^
+ReferenceTest.java:33: error: reference not found
+     * @see Object#tooStrong()
+            ^
+ReferenceTest.java:38: error: invalid use of @return
+     * @return x description
+       ^
+ReferenceTest.java:43: error: invalid use of @return
+     * @return x description
+       ^
+ReferenceTest.java:48: error: exception not thrown: java.lang.Exception
+     * @throws Exception description
+               ^
+8 errors
+1 warning
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/RunTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @bug 8000103
+ * @summary Create doclint utility
+ */
+
+import com.sun.tools.doclint.DocLint;
+import com.sun.tools.doclint.DocLint.BadArgs;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.lang.annotation.Annotation;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+/** javadoc error on toplevel:  a & b. */
+public class RunTest {
+    /** javadoc error on member: a < b */
+    public static void main(String... args) throws Exception {
+        new RunTest().run();
+    }
+
+
+    File testSrc = new File(System.getProperty("test.src"));
+    File thisFile = new File(testSrc, RunTest.class.getSimpleName() + ".java");
+
+    void run() throws Exception {
+        for (Method m: getClass().getDeclaredMethods()) {
+            Annotation a = m.getAnnotation(Test.class);
+            if (a != null) {
+                System.err.println("test: " + m.getName());
+                try {
+                    StringWriter sw = new StringWriter();
+                    PrintWriter pw = new PrintWriter(sw);;
+                    m.invoke(this, new Object[] { pw });
+                    String out = sw.toString();
+                    System.err.println(">>> " + out.replace("\n", "\n>>> "));
+                    if (!out.contains("a < b"))
+                        error("\"a < b\" not found");
+                    if (!out.contains("a & b"))
+                        error("\"a & b\" not found");
+                } catch (InvocationTargetException e) {
+                    Throwable cause = e.getCause();
+                    throw (cause instanceof Exception) ? ((Exception) cause) : e;
+                }
+                System.err.println();
+            }
+        }
+
+        if (errors > 0)
+            throw new Exception(errors + " errors occurred");
+    }
+
+
+    void error(String msg) {
+        System.err.println("Error: " + msg);
+        errors++;
+    }
+
+    int errors;
+
+    /** Marker annotation for test cases. */
+    @Retention(RetentionPolicy.RUNTIME)
+    @interface Test { }
+
+    @Test
+    void testMain(PrintWriter pw) throws BadArgs, IOException {
+        String[] args = { "-Xmsgs", thisFile.getPath() };
+        DocLint d = new DocLint();
+        d.run(pw, args);
+    }
+}
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/SyntaxTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,17 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:-syntax SyntaxTest.java
+ * @run main DocLintTester -ref SyntaxTest.out SyntaxTest.java
+ */
+
+/** */
+public class SyntaxTest {
+    /**
+     * a < b
+     */
+    public void syntax_error() { }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/SyntaxTest.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,5 @@
+SyntaxTest.java:13: error: malformed HTML
+     * a < b
+         ^
+1 error
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/SyntheticTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester -Xmsgs:all SyntheticTest.java
+ */
+
+/**
+ * This is a test that messages are not generated for synthesized elements
+ * such as default constructors and enum methods.
+ */
+public class SyntheticTest {
+    // No explicit constructor implies a default constructor
+
+    /** enum E */
+    enum E {
+        /** enum member E1 */
+        E1,
+        /** enum member E2 */
+        E2,
+        /** enum member E3 */
+        E3
+    }
+}
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/ValidTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @build DocLintTester
+ * @run main DocLintTester ValidTest.java
+ */
+
+class ValidTest {
+    /**
+     * &lt; &gt; &amp; &#40;
+     */
+    void entities() { }
+
+    /**
+     * <h1> ... </h1>
+     * <h2> ... </h2>
+     * <h3> ... </h3>
+     * <h4> ... </h4>
+     * <h5> ... </h5>
+     * <h6> ... </h6>
+     */
+    void all_headers() { }
+
+    /**
+     * <h1> ... </h1>
+     * <h2> ... </h2>
+     * <h3> ... </h3>
+     * <h1> ... </h1>
+     * <h2> ... </h2>
+     * <h3> ... </h3>
+     * <h2> ... </h2>
+     */
+    void header_series() { }
+
+    /**
+     * <div> <p>   </div>
+     */
+    void autoclose_tags() { }
+
+    /**
+     * @param x
+     */
+    void method_param(int x) { }
+
+    /**
+     * @param <T>
+     */
+    <T> T method_typaram(T t) { return t; }
+
+    /**
+     * @param <T>
+     */
+    class ClassTyparam<T> { }
+
+    /**
+     * @param <T>
+     */
+    interface InterfaceTyparam<T> { }
+
+    /**
+     * @return x
+     */
+    int return_int() { return 0; }
+
+    /**
+     * @exception Exception
+     */
+    void throws_Exception1() throws Exception { }
+
+    /**
+     * @throws Exception
+     */
+    void throws_Exception2() throws Exception { }
+
+    class X {
+        /**
+         * @param x
+         */
+        X(int x) { } // constructor parameter
+
+        /**
+         * @param <T>
+         */
+        <T> X(T t) { } // constructor type parameter
+    }
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/AnchorAlreadyDefined.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,17 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref AnchorAlreadyDefined.out AnchorAlreadyDefined.java
+ */
+
+// tidy: Warning: <.*> anchor ".*" already defined
+
+/**
+ * <a name="here">valid</a>
+ * <a name="here">duplicate</a>
+ * <h1 id="here">duplicate</h1>
+ */
+public class AnchorAlreadyDefined { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/AnchorAlreadyDefined.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,7 @@
+AnchorAlreadyDefined.java:14: error: anchor already defined: here
+ * <a name="here">duplicate</a>
+      ^
+AnchorAlreadyDefined.java:15: error: anchor already defined: here
+ * <h1 id="here">duplicate</h1>
+       ^
+2 errors
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/BadEnd.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,16 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref BadEnd.out BadEnd.java
+ */
+
+// tidy: Warning: <.*> is probably intended as </.*>
+
+/**
+ * <a name="here"> text <a>
+ * <code> text <code>
+ */
+public class BadEnd { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/BadEnd.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,17 @@
+BadEnd.java:14: warning: nested tag not allowed: <code>
+ * <code> text <code>
+               ^
+BadEnd.java:14: error: element not closed: code
+ * <code> text <code>
+               ^
+BadEnd.java:14: error: element not closed: code
+ * <code> text <code>
+   ^
+BadEnd.java:13: error: element not closed: a
+ * <a name="here"> text <a>
+                        ^
+BadEnd.java:13: error: element not closed: a
+ * <a name="here"> text <a>
+   ^
+4 errors
+1 warning
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/InsertImplicit.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,16 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref InsertImplicit.out InsertImplicit.java
+ */
+
+// tidy: Warning: inserting implicit <.*>
+
+/**
+ * </p>
+ * <i> <blockquote> abc </blockquote> </i>
+ */
+public class InsertImplicit { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/InsertImplicit.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,7 @@
+InsertImplicit.java:13: error: unexpected end tag: </p>
+ * </p>
+   ^
+InsertImplicit.java:14: error: block element not allowed within inline element <i>: blockquote
+ * <i> <blockquote> abc </blockquote> </i>
+       ^
+2 errors
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/InvalidEntity.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,22 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref InvalidEntity.out InvalidEntity.java
+ */
+
+// tidy: Warning: replacing invalid numeric character reference .*
+
+// See
+// http://www.w3.org/TR/html4/sgml/entities.html
+// http://stackoverflow.com/questions/631406/what-is-the-difference-between-em-dash-151-and-8212
+
+/**
+ * &#01;
+ * &#x01;
+ * &splodge;
+ *
+ */
+public class InvalidEntity { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/InvalidEntity.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,10 @@
+InvalidEntity.java:17: error: invalid entity &#01;
+ * &#01;
+   ^
+InvalidEntity.java:18: error: invalid entity &#x01;
+ * &#x01;
+   ^
+InvalidEntity.java:19: error: invalid entity &splodge;
+ * &splodge;
+   ^
+3 errors
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/InvalidName.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,18 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref InvalidName.out InvalidName.java
+ */
+
+// tidy: Warning: <a> cannot copy name attribute to id
+
+/**
+ * <a name="abc">valid</a>
+ * <a name="abc123">valid</a>
+ * <a name="a.1:2-3_4">valid</a>
+ * <a name="foo()">invalid</a>
+ */
+public class InvalidName { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/InvalidName.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,4 @@
+InvalidName.java:16: error: invalid name for anchor: "foo()"
+ * <a name="foo()">invalid</a>
+      ^
+1 error
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/InvalidTag.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,15 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref InvalidTag.out InvalidTag.java
+ */
+
+// tidy: Error: <.*> is not recognized!
+
+/**
+ * List<String> list = new ArrayList<>();
+ */
+public class InvalidTag { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/InvalidTag.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,10 @@
+InvalidTag.java:13: error: unknown tag: String
+ * List<String> list = new ArrayList<>();
+       ^
+InvalidTag.java:13: error: malformed HTML
+ * List<String> list = new ArrayList<>();
+                                    ^
+InvalidTag.java:13: error: bad use of '>'
+ * List<String> list = new ArrayList<>();
+                                     ^
+3 errors
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/InvalidURI.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,21 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref InvalidURI.out InvalidURI.java
+ */
+
+// tidy: Warning: <a> escaping malformed URI reference
+// tidy: Warning: <.*> attribute ".*" lacks value
+
+/**
+ * <a href="abc">valid</a>
+ * <a href="abc%20def">valid</a>
+ * <a href="abc def">invalid</a>
+ * <a href>no value</a>
+ * <a href= >no value</a>
+ * <a href="" >no value</a>
+ */
+public class InvalidURI { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/InvalidURI.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,13 @@
+InvalidURI.java:16: error: invalid uri: "abc def"
+ * <a href="abc def">invalid</a>
+      ^
+InvalidURI.java:17: error: attribute lacks value
+ * <a href>no value</a>
+      ^
+InvalidURI.java:18: error: attribute lacks value
+ * <a href= >no value</a>
+      ^
+InvalidURI.java:19: error: attribute lacks value
+ * <a href="" >no value</a>
+      ^
+4 errors
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/MissingGT.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,16 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref MissingGT.out MissingGT.java
+ */
+
+// tidy: Warning: <.*> missing '>' for end of tag
+
+/**
+ * <img src="image.gif"
+ * <i>  text </i>
+ */
+public class MissingGT { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/MissingGT.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,4 @@
+MissingGT.java:13: error: malformed HTML
+ * <img src="image.gif"
+   ^
+1 error
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/MissingTag.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,17 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref MissingTag.out MissingTag.java
+ */
+
+// tidy: Warning: missing <.*>
+// tidy: Warning: missing </.*> before </.*>
+
+/**
+ * </p>
+ * <h1> <b> text </h1>
+ */
+public class MissingTag { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/MissingTag.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,7 @@
+MissingTag.java:14: error: unexpected end tag: </p>
+ * </p>
+   ^
+MissingTag.java:15: error: end tag missing: </b>
+ * <h1> <b> text </h1>
+        ^
+2 errors
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/NestedTag.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,16 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref NestedTag.out NestedTag.java
+ */
+
+// tidy: Warning: nested emphasis <.*>
+
+/**
+ * <b><b> text </b></b>
+ * {@link java.lang.String <code>String</code>}
+ */
+public class NestedTag { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/NestedTag.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,7 @@
+NestedTag.java:13: warning: nested tag not allowed: <b>
+ * <b><b> text </b></b>
+      ^
+NestedTag.java:14: warning: nested tag not allowed: <code>
+ * {@link java.lang.String <code>String</code>}
+                           ^
+2 warnings
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/ParaInPre.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,20 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref ParaInPre.out ParaInPre.java
+ */
+
+// tidy: Warning: replacing <p> by <br>
+// tidy: Warning: using <br> in place of <p>
+
+/**
+ * <pre>
+ *     text
+ *     <p>
+ *     more text
+ * </pre>
+ */
+public class ParaInPre { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/ParaInPre.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,4 @@
+ParaInPre.java:16: warning: unexpected use of <p> inside <pre> element
+ *     <p>
+       ^
+1 warning
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/README.txt	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,21 @@
+The utilities in this directory can be used to determine
+common issues in javadoc comments by running the standard
+"tidy" program on the output of javadoc, and analysing
+the messages that are reported.
+
+tidy.sh is a script that will run the "tidy" program on
+the files in a directory, writing the results to a new
+directroy.
+
+tidystats.Main is a Java program that can analyze the 
+files produced by the tidy.sh script to generate a 
+summary report about the warnings that were found.
+
+
+The tests is this directory are focussed on verifying
+that doclint detects issues in javadoc comments that will
+give rise to issues detected by "tidy" in the output
+generated by javadoc. 
+
+For more information on the "tidy" program, see the HTML Tidy
+Library Project page at http://tidy.sourceforge.net/.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/RepeatedAttr.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,15 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref RepeatedAttr.out RepeatedAttr.java
+ */
+
+// tidy: Warning: <.*> dropping value ".*" for repeated attribute ".*"
+
+/**
+ * <img src="image.gif" alt alt="summary">
+ */
+public class RepeatedAttr { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/RepeatedAttr.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,4 @@
+RepeatedAttr.java:13: error: repeated attribute: alt
+ * <img src="image.gif" alt alt="summary">
+                            ^
+1 error
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/TextNotAllowed.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,26 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref TextNotAllowed.out TextNotAllowed.java
+ */
+
+// tidy: Warning: plain text isn't allowed in <.*> elements
+
+/**
+ * <table summary=description> abc </table>
+ * <table summary=description> <tbody> abc </tbody> </table>
+ * <table summary=description> <tr> abc </tr> </table>
+ *
+ * <dl> abc </dl>
+ * <ol> abc </ol>
+ * <ul> abc </ul>
+ *
+ * <ul>
+ *     <li> item
+ *     <li> item
+ * </ul>
+ */
+public class TextNotAllowed { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/TextNotAllowed.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,19 @@
+TextNotAllowed.java:13: error: text not allowed in <table> element
+ * <table summary=description> abc </table>
+                                   ^
+TextNotAllowed.java:14: error: text not allowed in <tbody> element
+ * <table summary=description> <tbody> abc </tbody> </table>
+                                           ^
+TextNotAllowed.java:15: error: text not allowed in <tr> element
+ * <table summary=description> <tr> abc </tr> </table>
+                                        ^
+TextNotAllowed.java:17: error: text not allowed in <dl> element
+ * <dl> abc </dl>
+            ^
+TextNotAllowed.java:18: error: text not allowed in <ol> element
+ * <ol> abc </ol>
+            ^
+TextNotAllowed.java:19: error: text not allowed in <ul> element
+ * <ul> abc </ul>
+            ^
+6 errors
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/TrimmingEmptyTag.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,29 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref TrimmingEmptyTag.out TrimmingEmptyTag.java
+ */
+
+// tidy: Warning: trimming empty <.*>
+
+/**
+ * <b></b>
+ * <table summary=description></table>
+ * <table><caption></caption></table>
+ * <code></code>
+ * <dl></dl>
+ * <dl><dt></dt><dd></dd></dl>
+ * <font></font>
+ * <i></i>
+ * <ol></ol>
+ * <p></p>
+ * <pre></pre>
+ * <span></span>
+ * <tt></tt>
+ * <ul></ul>
+ * <ul><li></li></ul>
+ */
+public class TrimmingEmptyTag { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/TrimmingEmptyTag.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,46 @@
+TrimmingEmptyTag.java:13: warning: empty <b> tag
+ * <b></b>
+      ^
+TrimmingEmptyTag.java:14: warning: empty <table> tag
+ * <table summary=description></table>
+                              ^
+TrimmingEmptyTag.java:15: warning: empty <caption> tag
+ * <table><caption></caption></table>
+                   ^
+TrimmingEmptyTag.java:16: warning: empty <code> tag
+ * <code></code>
+         ^
+TrimmingEmptyTag.java:17: warning: empty <dl> tag
+ * <dl></dl>
+       ^
+TrimmingEmptyTag.java:18: warning: empty <dt> tag
+ * <dl><dt></dt><dd></dd></dl>
+           ^
+TrimmingEmptyTag.java:18: warning: empty <dd> tag
+ * <dl><dt></dt><dd></dd></dl>
+                    ^
+TrimmingEmptyTag.java:19: warning: empty <font> tag
+ * <font></font>
+         ^
+TrimmingEmptyTag.java:20: warning: empty <i> tag
+ * <i></i>
+      ^
+TrimmingEmptyTag.java:21: warning: empty <ol> tag
+ * <ol></ol>
+       ^
+TrimmingEmptyTag.java:22: warning: empty <p> tag
+ * <p></p>
+      ^
+TrimmingEmptyTag.java:23: warning: empty <pre> tag
+ * <pre></pre>
+        ^
+TrimmingEmptyTag.java:24: warning: empty <span> tag
+ * <span></span>
+         ^
+TrimmingEmptyTag.java:25: warning: empty <tt> tag
+ * <tt></tt>
+       ^
+TrimmingEmptyTag.java:26: warning: empty <ul> tag
+ * <ul></ul>
+       ^
+15 warnings
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/UnescapedOrUnknownEntity.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,19 @@
+/*
+ * @test /nodynamiccopyright/
+ * @bug 8004832
+ * @summary Add new doclint package
+ * @library ..
+ * @build DocLintTester
+ * @run main DocLintTester -ref UnescapedOrUnknownEntity.out UnescapedOrUnknownEntity.java
+ */
+
+// tidy: Warning: unescaped & or unknown entity ".*"
+// tidy: Warning: unescaped & which should be written as &amp;
+// tidy: Warning: entity ".*" doesn't end in ';'
+
+/**
+ * L&F
+ * Drag&Drop
+ * if (a & b);
+ */
+public class UnescapedOrUnknownEntity { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/UnescapedOrUnknownEntity.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,11 @@
+UnescapedOrUnknownEntity.java:15: error: semicolon missing
+ * L&F
+    ^
+UnescapedOrUnknownEntity.java:16: error: semicolon missing
+ * Drag&Drop
+       ^
+UnescapedOrUnknownEntity.java:17: error: bad HTML entity
+ * if (a & b);
+         ^
+3 errors
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/util/Main.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,182 @@
+package tidystats;
+
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class Main {
+    public static void main(String... args) throws IOException {
+        new Main().run(args);
+    }
+
+    void run(String... args) throws IOException {
+        FileSystem fs = FileSystems.getDefault();
+        List<Path> paths = new ArrayList<>();
+
+        int i;
+        for (i = 0; i < args.length; i++) {
+            String arg = args[i];
+            if (arg.startsWith("-"))
+                throw new IllegalArgumentException(arg);
+            else
+                break;
+        }
+
+        for ( ; i < args.length; i++) {
+            Path p = fs.getPath(args[i]);
+            paths.add(p);
+        }
+
+        for (Path p: paths) {
+            scan(p);
+        }
+
+        print("%6d files read", files);
+        print("%6d files had no errors or warnings", ok);
+        print("%6d files reported \"Not all warnings/errors were shown.\"", overflow);
+        print("%6d errors found", errs);
+        print("%6d warnings found", warns);
+        print("%6d recommendations to use CSS", css);
+        print("");
+
+        Map<Integer, Set<String>> sortedCounts = new TreeMap<>(
+                new Comparator<Integer>() {
+                    @Override
+                    public int compare(Integer o1, Integer o2) {
+                        return o2.compareTo(o1);
+                    }
+                });
+
+        for (Map.Entry<Pattern, Integer> e: counts.entrySet()) {
+            Pattern p = e.getKey();
+            Integer n = e.getValue();
+            Set<String> set = sortedCounts.get(n);
+            if (set == null)
+                sortedCounts.put(n, (set = new TreeSet<>()));
+            set.add(p.toString());
+        }
+
+        for (Map.Entry<Integer, Set<String>> e: sortedCounts.entrySet()) {
+            for (String p: e.getValue()) {
+                if (p.startsWith(".*")) p = p.substring(2);
+                print("%6d: %s", e.getKey(), p);
+            }
+        }
+    }
+
+    void scan(Path p) throws IOException {
+        if (Files.isDirectory(p)) {
+            for (Path c: Files.newDirectoryStream(p)) {
+                scan(c);
+            }
+        } else if (isTidyFile(p)) {
+            scan(Files.readAllLines(p, Charset.defaultCharset()));
+        }
+    }
+
+    boolean isTidyFile(Path p) {
+        return Files.isRegularFile(p) && p.getFileName().toString().endsWith(".tidy");
+    }
+
+    void scan(List<String> lines) {
+        Matcher m;
+        files++;
+        for (String line: lines) {
+            if (okPattern.matcher(line).matches()) {
+                ok++;
+            } else if ((m = countPattern.matcher(line)).matches()) {
+                warns += Integer.valueOf(m.group(1));
+                errs += Integer.valueOf(m.group(2));
+                if (m.group(3) != null)
+                    overflow++;
+            } else if ((m = guardPattern.matcher(line)).matches()) {
+                boolean found = false;
+                for (Pattern p: patterns) {
+                    if ((m = p.matcher(line)).matches()) {
+                        found = true;
+                        count(p);
+                        break;
+                    }
+                }
+                if (!found)
+                    System.err.println("Unrecognized line: " + line);
+            } else if (cssPattern.matcher(line).matches()) {
+                css++;
+            }
+        }
+    }
+
+    Map<Pattern, Integer> counts = new HashMap<>();
+    void count(Pattern p) {
+        Integer i = counts.get(p);
+        counts.put(p, (i == null) ? 1 : i + 1);
+    }
+
+    void print(String format, Object... args) {
+        System.out.println(String.format(format, args));
+    }
+
+    Pattern okPattern = Pattern.compile("No warnings or errors were found.");
+    Pattern countPattern = Pattern.compile("([0-9]+) warnings, ([0-9]+) errors were found!.*?(Not all warnings/errors were shown.)?");
+    Pattern cssPattern = Pattern.compile("You are recommended to use CSS.*");
+    Pattern guardPattern = Pattern.compile("line [0-9]+ column [0-9]+ - (Error|Warning):.*");
+
+    Pattern[] patterns = {
+        Pattern.compile(".*Error: <.*> is not recognized!"),
+        Pattern.compile(".*Error: missing quote mark for attribute value"),
+        Pattern.compile(".*Warning: <.*> anchor \".*\" already defined"),
+        Pattern.compile(".*Warning: <.*> attribute \".*\" has invalid value \".*\""),
+        Pattern.compile(".*Warning: <.*> attribute \".*\" lacks value"),
+        Pattern.compile(".*Warning: <.*> attribute \".*\" lacks value"),
+        Pattern.compile(".*Warning: <.*> attribute with missing trailing quote mark"),
+        Pattern.compile(".*Warning: <.*> dropping value \".*\" for repeated attribute \".*\""),
+        Pattern.compile(".*Warning: <.*> inserting \".*\" attribute"),
+        Pattern.compile(".*Warning: <.*> is probably intended as </.*>"),
+        Pattern.compile(".*Warning: <.*> isn't allowed in <.*> elements"),
+        Pattern.compile(".*Warning: <.*> lacks \".*\" attribute"),
+        Pattern.compile(".*Warning: <.*> missing '>' for end of tag"),
+        Pattern.compile(".*Warning: <.*> proprietary attribute \".*\""),
+        Pattern.compile(".*Warning: <.*> unexpected or duplicate quote mark"),
+        Pattern.compile(".*Warning: <a> cannot copy name attribute to id"),
+        Pattern.compile(".*Warning: <a> escaping malformed URI reference"),
+        Pattern.compile(".*Warning: <blockquote> proprietary attribute \"pre\""),
+        Pattern.compile(".*Warning: discarding unexpected <.*>"),
+        Pattern.compile(".*Warning: discarding unexpected </.*>"),
+        Pattern.compile(".*Warning: entity \".*\" doesn't end in ';'"),
+        Pattern.compile(".*Warning: inserting implicit <.*>"),
+        Pattern.compile(".*Warning: inserting missing 'title' element"),
+        Pattern.compile(".*Warning: missing <!DOCTYPE> declaration"),
+        Pattern.compile(".*Warning: missing <.*>"),
+        Pattern.compile(".*Warning: missing </.*> before <.*>"),
+        Pattern.compile(".*Warning: nested emphasis <.*>"),
+        Pattern.compile(".*Warning: plain text isn't allowed in <.*> elements"),
+        Pattern.compile(".*Warning: replacing <p> by <br>"),
+        Pattern.compile(".*Warning: replacing invalid numeric character reference .*"),
+        Pattern.compile(".*Warning: replacing unexpected .* by </.*>"),
+        Pattern.compile(".*Warning: trimming empty <.*>"),
+        Pattern.compile(".*Warning: unescaped & or unknown entity \".*\""),
+        Pattern.compile(".*Warning: unescaped & which should be written as &amp;"),
+        Pattern.compile(".*Warning: using <br> in place of <p>")
+    };
+
+    int files;
+    int ok;
+    int warns;
+    int errs;
+    int css;
+    int overflow;
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/doclint/tidy/util/tidy.sh	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,52 @@
+#!/bin/sh
+#
+# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+# Run the "tidy" program over the files in a directory.
+#
+# Usage:
+#   sh tidy.sh <dir>
+#
+# The "tidy" program will be run on each HTML file in <dir>,
+# and the output placed in the corresponding location in a new
+# directory <dir>.tidy.  The console output from running "tidy" will
+# be saved in a corresponding file with an additional .tidy extension.
+#
+# Non-HTML files will be copied without modification from <dir> to
+# <dir>.tidy, so that relative links within the directory tree are
+# unaffected.
+
+dir=$1
+odir=$dir.tidy
+
+( cd $dir ; find . -type f ) | \
+    while read file ; do
+        mkdir -p $odir/$(dirname $file)
+        case $file in
+            *.html )
+                cat $dir/$file | tidy 1>$odir/$file 2>$odir/$file.tidy
+                ;;
+            * ) cp $dir/$file $odir/$file
+                ;;
+        esac
+    done
--- a/langtools/test/tools/javac/7129225/TestImportStar.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/7129225/TestImportStar.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
 /* @test
  * @bug 7129225
  * @summary import xxx.* isn't handled correctly by annotation processing
- * @library ../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor
  * @compile/fail/ref=NegTest.ref -XDrawDiagnostics TestImportStar.java
  * @compile Anno.java AnnoProcessor.java
--- a/langtools/test/tools/javac/7153958/CPoolRefClassContainingInlinedCts.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/7153958/CPoolRefClassContainingInlinedCts.java	Tue Jan 22 11:54:16 2013 -0800
@@ -27,7 +27,7 @@
  * @test
  * @bug 7153958
  * @summary add constant pool reference to class containing inlined constants
- * @compile pkg/ClassToBeStaticallyImported.java
+ * @compile pkg/ClassToBeStaticallyImported.java CPoolRefClassContainingInlinedCts.java
  * @run main CPoolRefClassContainingInlinedCts
  */
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/8000518/DuplicateConstantPoolEntry.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8000518
+ * @summary Javac generates duplicate name_and_type constant pool entry for
+ * class BinaryOpValueExp.java
+ * @run main DuplicateConstantPoolEntry
+ */
+
+import com.sun.source.util.JavacTask;
+import com.sun.tools.classfile.ClassFile;
+import com.sun.tools.classfile.ConstantPoolException;
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.util.Arrays;
+import java.util.List;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileObject;
+import javax.tools.SimpleJavaFileObject;
+import javax.tools.ToolProvider;
+
+/*
+ * This bug was reproduced having two classes B and C referenced from a class A
+ * class C should be compiled and generated in advance. Later class A and B should
+ * be compiled like this: javac A.java B.java
+ */
+
+public class DuplicateConstantPoolEntry {
+
+    public static void main(String args[]) throws Exception {
+        new DuplicateConstantPoolEntry().run();
+    }
+
+    void run() throws Exception {
+        generateFilesNeeded();
+        checkReference();
+    }
+
+    void generateFilesNeeded() throws Exception {
+
+        StringJavaFileObject[] CSource = new StringJavaFileObject[] {
+            new StringJavaFileObject("C.java",
+                "class C {C(String s) {}}"),
+        };
+
+        List<StringJavaFileObject> AandBSource = Arrays.asList(
+                new StringJavaFileObject("A.java",
+                    "class A {void test() {new B(null);new C(null);}}"),
+                new StringJavaFileObject("B.java",
+                    "class B {B(String s) {}}")
+        );
+
+        final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
+        JavacTask compileC = (JavacTask)tool.getTask(null, null, null, null, null,
+                Arrays.asList(CSource));
+        if (!compileC.call()) {
+            throw new AssertionError("Compilation error while compiling C.java sources");
+        }
+        JavacTask compileAB = (JavacTask)tool.getTask(null, null, null,
+                Arrays.asList("-cp", "."), null, AandBSource);
+        if (!compileAB.call()) {
+            throw new AssertionError("Compilation error while compiling A and B sources");
+        }
+    }
+
+    void checkReference() throws IOException, ConstantPoolException {
+        File file = new File("A.class");
+        ClassFile classFile = ClassFile.read(file);
+        for (int i = 1;
+                i < classFile.constant_pool.size() - 1;
+                i += classFile.constant_pool.get(i).size()) {
+            for (int j = i + classFile.constant_pool.get(i).size();
+                    j < classFile.constant_pool.size();
+                    j += classFile.constant_pool.get(j).size()) {
+                if (classFile.constant_pool.get(i).toString().
+                        equals(classFile.constant_pool.get(j).toString())) {
+                    throw new AssertionError(
+                            "Duplicate entries in the constant pool at positions " +
+                            i + " and " + j);
+                }
+            }
+        }
+    }
+
+    private static class StringJavaFileObject extends SimpleJavaFileObject {
+        StringJavaFileObject(String name, String text) {
+            super(URI.create(name), JavaFileObject.Kind.SOURCE);
+            this.text = text;
+        }
+        @Override
+        public CharSequence getCharContent(boolean b) {
+            return text;
+        }
+        private String text;
+    }
+}
--- a/langtools/test/tools/javac/Diagnostics/6769027/T6769027.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/Diagnostics/6769027/T6769027.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,14 +26,19 @@
  * @bug     6769027
  * @summary Source line should be displayed immediately after the first diagnostic line
  * @author  Maurizio Cimadamore
+ * @library ../../lib
+ * @build JavacTestingAbstractThreadedTest
  * @run main/othervm T6769027
  */
+
 import java.net.URI;
 import java.util.regex.Matcher;
 import javax.tools.*;
 import com.sun.tools.javac.util.*;
 
-public class T6769027 {
+public class T6769027
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     enum OutputKind {
         RAW("rawDiagnostics","rawDiagnostics"),
@@ -314,7 +319,7 @@
 
         @Override
         protected java.io.PrintWriter getWriterForDiagnosticType(JCDiagnostic.DiagnosticType dt) {
-            return new java.io.PrintWriter(System.out);
+            return outWriter;
         }
 
         @Override
@@ -323,13 +328,42 @@
         }
     }
 
-    int nerrors = 0;
+    OutputKind outputKind;
+    ErrorKind errorKind;
+    MultilineKind multiKind;
+    MultilinePolicy multiPolicy;
+    PositionKind posKind;
+    XDiagsSource xdiagsSource;
+    XDiagsCompact xdiagsCompact;
+    CaretKind caretKind;
+    SourceLineKind sourceLineKind;
+    IndentKind summaryIndent;
+    IndentKind detailsIndent;
+    IndentKind sourceIndent;
+    IndentKind subdiagsIndent;
 
-    void exec(OutputKind outputKind, ErrorKind errorKind, MultilineKind multiKind,
+    T6769027(OutputKind outputKind, ErrorKind errorKind, MultilineKind multiKind,
             MultilinePolicy multiPolicy, PositionKind posKind, XDiagsSource xdiagsSource,
             XDiagsCompact xdiagsCompact, CaretKind caretKind, SourceLineKind sourceLineKind,
             IndentKind summaryIndent, IndentKind detailsIndent, IndentKind sourceIndent,
             IndentKind subdiagsIndent) {
+        this.outputKind = outputKind;
+        this.errorKind = errorKind;
+        this.multiKind = multiKind;
+        this.multiPolicy = multiPolicy;
+        this.posKind = posKind;
+        this.xdiagsSource = xdiagsSource;
+        this.xdiagsCompact = xdiagsCompact;
+        this.caretKind = caretKind;
+        this.sourceLineKind = sourceLineKind;
+        this.summaryIndent = summaryIndent;
+        this.detailsIndent = detailsIndent;
+        this.sourceIndent = sourceIndent;
+        this.subdiagsIndent = subdiagsIndent;
+    }
+
+    @Override
+    public void run() {
         Context ctx = new Context();
         Options options = Options.instance(ctx);
         outputKind.init(options);
@@ -362,23 +396,10 @@
             d = new JCDiagnostic.MultilineDiagnostic(d, subdiags);
         }
         String diag = log.getDiagnosticFormatter().format(d, messages.getCurrentLocale());
-        checkOutput(diag,
-                outputKind,
-                errorKind,
-                multiKind,
-                multiPolicy,
-                posKind,
-                xdiagsSource,
-                xdiagsCompact,
-                caretKind,
-                sourceLineKind,
-                summaryIndent,
-                detailsIndent,
-                sourceIndent,
-                subdiagsIndent);
+        checkOutput(diag);
     }
 
-    void test() {
+    public static void main(String[] args) throws Exception {
         for (OutputKind outputKind : OutputKind.values()) {
             for (ErrorKind errKind : ErrorKind.values()) {
                 for (MultilineKind multiKind : MultilineKind.values()) {
@@ -392,7 +413,7 @@
                                                 for (IndentKind detailsIndent : IndentKind.values()) {
                                                     for (IndentKind sourceIndent : IndentKind.values()) {
                                                         for (IndentKind subdiagsIndent : IndentKind.values()) {
-                                                            exec(outputKind,
+                                                            pool.execute(new T6769027(outputKind,
                                                                 errKind,
                                                                 multiKind,
                                                                 multiPolicy,
@@ -404,7 +425,7 @@
                                                                 summaryIndent,
                                                                 detailsIndent,
                                                                 sourceIndent,
-                                                                subdiagsIndent);
+                                                                subdiagsIndent));
                                                         }
                                                     }
                                                 }
@@ -418,15 +439,11 @@
                 }
             }
         }
-        if (nerrors != 0)
-            throw new AssertionError(nerrors + " errors found");
+
+        checkAfterExec(false);
     }
 
-    void printInfo(String msg, OutputKind outputKind, ErrorKind errorKind, MultilineKind multiKind,
-            MultilinePolicy multiPolicy, PositionKind posKind, XDiagsSource xdiagsSource,
-            XDiagsCompact xdiagsCompact, CaretKind caretKind, SourceLineKind sourceLineKind,
-            IndentKind summaryIndent, IndentKind detailsIndent, IndentKind sourceIndent,
-            IndentKind subdiagsIndent, String errorLine) {
+    void printInfo(String msg, String errorLine) {
         String sep = "*********************************************************";
         String desc = "raw=" + outputKind + " pos=" + posKind + " key=" + errorKind.key() +
                 " multiline=" + multiKind +" multiPolicy=" + multiPolicy.value +
@@ -434,18 +451,14 @@
                 " caret=" + caretKind + " sourcePosition=" + sourceLineKind +
                 " summaryIndent=" + summaryIndent + " detailsIndent=" + detailsIndent +
                 " sourceIndent=" + sourceIndent + " subdiagsIndent=" + subdiagsIndent;
-        System.out.println(sep);
-        System.out.println(desc);
-        System.out.println(sep);
-        System.out.println(msg);
-        System.out.println("Diagnostic formatting problem - expected diagnostic...\n" + errorLine);
+        errWriter.println(sep);
+        errWriter.println(desc);
+        errWriter.println(sep);
+        errWriter.println(msg);
+        errWriter.println("Diagnostic formatting problem - expected diagnostic...\n" + errorLine);
     }
 
-    void checkOutput(String msg, OutputKind outputKind, ErrorKind errorKind, MultilineKind multiKind,
-            MultilinePolicy multiPolicy, PositionKind posKind, XDiagsSource xdiagsSource,
-            XDiagsCompact xdiagsCompact, CaretKind caretKind, SourceLineKind sourceLineKind,
-            IndentKind summaryIndent, IndentKind detailsIndent, IndentKind sourceIndent,
-            IndentKind subdiagsIndent) {
+    void checkOutput(String msg) {
         boolean shouldPrintSource = posKind == PositionKind.POS &&
                 xdiagsSource != XDiagsSource.NO_SOURCE &&
                 (xdiagsSource == XDiagsSource.SOURCE ||
@@ -453,7 +466,8 @@
         String errorLine = posKind.getOutput(outputKind) +
                 errorKind.getOutput(outputKind, summaryIndent, detailsIndent);
         if (xdiagsCompact != XDiagsCompact.COMPACT)
-            errorLine += multiKind.getOutput(outputKind, errorKind, multiPolicy, summaryIndent, detailsIndent, subdiagsIndent);
+            errorLine += multiKind.getOutput(outputKind, errorKind, multiPolicy,
+                    summaryIndent, detailsIndent, subdiagsIndent);
         String[] lines = errorLine.split("\n");
         if (xdiagsCompact == XDiagsCompact.COMPACT) {
             errorLine = lines[0];
@@ -474,26 +488,9 @@
         }
 
         if (!msg.equals(errorLine)) {
-            printInfo(msg,
-                    outputKind,
-                    errorKind,
-                    multiKind,
-                    multiPolicy,
-                    posKind,
-                    xdiagsSource,
-                    xdiagsCompact,
-                    caretKind,
-                    sourceLineKind,
-                    summaryIndent,
-                    detailsIndent,
-                    sourceIndent,
-                    subdiagsIndent,
-                    errorLine);
-            nerrors++;
+            printInfo(msg, errorLine);
+            errCount.incrementAndGet();
         }
     }
 
-    public static void main(String... args) throws Exception {
-        new T6769027().test();
-    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/MethodParameters.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,344 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8004727
+ * @summary javac should generate method parameters correctly.
+ */
+// key: opt.arg.parameters
+import com.sun.tools.classfile.*;
+import com.sun.tools.javac.file.JavacFileManager;
+import com.sun.tools.javac.main.Main;
+import com.sun.tools.javac.util.Context;
+import com.sun.tools.javac.util.Name;
+import com.sun.tools.javac.util.Names;
+import java.io.*;
+import javax.lang.model.element.*;
+import java.util.*;
+
+public class MethodParameters {
+
+    static final String Foo_name = "Foo";
+    static final String Foo_contents =
+        "public class Foo {\n" +
+        "  Foo() {}\n" +
+        "  void foo0() {}\n" +
+        "  void foo2(int j, int k) {}\n" +
+        "}";
+    static final String Bar_name = "Bar";
+    static final String Bar_contents =
+        "public class Bar {\n" +
+        "  Bar(int i) {}" +
+        "  Foo foo() { return new Foo(); }\n" +
+        "}";
+    static final String Baz_name = "Baz";
+    static final String Baz_contents =
+        "public class Baz {\n" +
+        "  int baz;" +
+        "  Baz(int i) {}" +
+        "}";
+    static final String Qux_name = "Qux";
+    static final String Qux_contents =
+        "public class Qux extends Baz {\n" +
+        "  Qux(int i) { super(i); }" +
+        "}";
+    static final File classesdir = new File("methodparameters");
+
+    public static void main(String... args) throws Exception {
+        new MethodParameters().run();
+    }
+
+    void run() throws Exception {
+        classesdir.mkdir();
+        final File Foo_java =
+            writeFile(classesdir, Foo_name + ".java", Foo_contents);
+        final File Bar_java =
+            writeFile(classesdir, Bar_name + ".java", Bar_contents);
+        final File Baz_java =
+            writeFile(classesdir, Baz_name + ".java", Baz_contents);
+        System.err.println("Test compile with -parameter");
+        compile("-parameters", "-d", classesdir.getPath(), Foo_java.getPath());
+        // First test: make sure javac doesn't choke to death on
+        // MethodParameter attributes
+        System.err.println("Test compile with classfile containing MethodParameter attributes");
+        compile("-parameters", "-d", classesdir.getPath(),
+                "-cp", classesdir.getPath(), Bar_java.getPath());
+        System.err.println("Examine class foo");
+        checkFoo();
+        checkBar();
+        System.err.println("Test debug information conflict");
+        compile("-g", "-parameters", "-d", classesdir.getPath(),
+                "-cp", classesdir.getPath(), Baz_java.getPath());
+        System.err.println("Introducing debug information conflict");
+        Baz_java.delete();
+        modifyBaz(false);
+        System.err.println("Checking language model");
+        inspectBaz();
+        System.err.println("Permuting attributes");
+        modifyBaz(true);
+        System.err.println("Checking language model");
+        inspectBaz();
+
+        if(0 != errors)
+            throw new Exception("MethodParameters test failed with " +
+                                errors + " errors");
+    }
+
+    void inspectBaz() throws Exception {
+        final File Qux_java =
+            writeFile(classesdir, Qux_name + ".java", Qux_contents);
+        final String[] args = { "-XDsave-parameter-names", "-d",
+                                classesdir.getPath(),
+                                "-cp", classesdir.getPath(),
+                                Qux_java.getPath() };
+        final StringWriter sw = new StringWriter();
+        final PrintWriter pw = new PrintWriter(sw);
+
+        // We need to be able to crack open javac and look at its data
+        // structures.  We'll rig up a compiler instance, but keep its
+        // Context, thus allowing us to get at the ClassReader.
+        Context context = new Context();
+        Main comp =  new Main("javac", pw);
+        JavacFileManager.preRegister(context);
+
+        // Compile Qux, which uses Baz.
+        comp.compile(args, context);
+        pw.close();
+        final String out = sw.toString();
+        if (out.length() > 0)
+            System.err.println(out);
+
+        // Now get the class reader, construct a name for Baz, and load it.
+        com.sun.tools.javac.jvm.ClassReader cr =
+            com.sun.tools.javac.jvm.ClassReader.instance(context);
+        Name name = Names.instance(context).fromString(Baz_name);
+
+        // Now walk down the language model and check the name of the
+        // parameter.
+        final Element baz = cr.loadClass(name);
+        for (Element e : baz.getEnclosedElements()) {
+            if (e instanceof ExecutableElement) {
+                final ExecutableElement ee = (ExecutableElement) e;
+                final List<? extends VariableElement> params =
+                    ee.getParameters();
+                if (1 != params.size())
+                    throw new Exception("Classfile Baz badly formed: wrong number of methods");
+                final VariableElement param = params.get(0);
+                if (!param.getSimpleName().contentEquals("baz")) {
+                    errors++;
+                    System.err.println("javac did not correctly resolve the metadata conflict, parameter's name reads as " + param.getSimpleName());
+                } else
+                    System.err.println("javac did correctly resolve the metadata conflict");
+            }
+        }
+    }
+
+    void modifyBaz(boolean flip) throws Exception {
+        final File Baz_class = new File(classesdir, Baz_name + ".class");
+        final ClassFile baz = ClassFile.read(Baz_class);
+        final int ind = baz.constant_pool.getUTF8Index("baz");
+        MethodParameters_attribute mpattr = null;
+        int mpind = 0;
+        Code_attribute cattr = null;
+        int cind = 0;
+
+        // Find the indexes of the MethodParameters and the Code attributes
+        if (baz.methods.length != 1)
+            throw new Exception("Classfile Baz badly formed: wrong number of methods");
+        if (!baz.methods[0].getName(baz.constant_pool).equals("<init>"))
+            throw new Exception("Classfile Baz badly formed: method has name " +
+                                baz.methods[0].getName(baz.constant_pool));
+        for (int i = 0; i < baz.methods[0].attributes.attrs.length; i++) {
+            if (baz.methods[0].attributes.attrs[i] instanceof
+                MethodParameters_attribute) {
+                mpattr = (MethodParameters_attribute)
+                    baz.methods[0].attributes.attrs[i];
+                mpind = i;
+            } else if (baz.methods[0].attributes.attrs[i] instanceof
+                       Code_attribute) {
+                cattr = (Code_attribute) baz.methods[0].attributes.attrs[i];
+                cind = i;
+            }
+        }
+        if (null == mpattr)
+            throw new Exception("Classfile Baz badly formed: no method parameters info");
+        if (null == cattr)
+            throw new Exception("Classfile Baz badly formed: no local variable table");
+
+        int flags = mpattr.method_parameter_table[0].flags;
+
+        // Alter the MethodParameters attribute, changing the name of
+        // the parameter from i to baz.  This requires Black Magic...
+        //
+        // The (well-designed) classfile library (correctly) does not
+        // allow us to mess around with the attribute data structures,
+        // or arbitrarily generate new ones.
+        //
+        // Instead, we install a new subclass of Attribute that
+        // hijacks the Visitor pattern and outputs the sequence of
+        // bytes that we want.  This only works in this particular
+        // instance, because we know we'll only every see one kind of
+        // visitor.
+        //
+        // If anyone ever changes the makeup of the Baz class, or
+        // tries to install some kind of visitor that gets run prior
+        // to serialization, this will break.
+        baz.methods[0].attributes.attrs[mpind] =
+            new Attribute(mpattr.attribute_name_index,
+                          mpattr.attribute_length) {
+                public <R, D> R accept(Visitor<R, D> visitor, D data) {
+                    if (data instanceof ByteArrayOutputStream) {
+                        ByteArrayOutputStream out =
+                            (ByteArrayOutputStream) data;
+                        out.write(1);
+                        out.write((ind >> 8) & 0xff);
+                        out.write(ind & 0xff);
+                        out.write((flags >> 24) & 0xff);
+                        out.write((flags >> 16) & 0xff);
+                        out.write((flags >> 8) & 0xff);
+                        out.write(flags & 0xff);
+                    } else
+                        throw new RuntimeException("Output stream is of type " + data.getClass() + ", which is not handled by this test.  Update the test and it should work.");
+                    return null;
+                }
+            };
+
+        // Flip the code and method attributes.  This is for checking
+        // that order doesn't matter.
+        if (flip) {
+            baz.methods[0].attributes.attrs[mpind] = cattr;
+            baz.methods[0].attributes.attrs[cind] = mpattr;
+        }
+
+        new ClassWriter().write(baz, Baz_class);
+    }
+
+    // Run a bunch of structural tests on foo to make sure it looks right.
+    void checkFoo() throws Exception {
+        final File Foo_class = new File(classesdir, Foo_name + ".class");
+        final ClassFile foo = ClassFile.read(Foo_class);
+        for (int i = 0; i < foo.methods.length; i++) {
+            System.err.println("Examine method Foo." + foo.methods[i].getName(foo.constant_pool));
+            if (foo.methods[i].getName(foo.constant_pool).equals("foo2")) {
+                for (int j = 0; j < foo.methods[i].attributes.attrs.length; j++)
+                    if (foo.methods[i].attributes.attrs[j] instanceof
+                        MethodParameters_attribute) {
+                        MethodParameters_attribute mp =
+                            (MethodParameters_attribute)
+                            foo.methods[i].attributes.attrs[j];
+                        System.err.println("Foo.foo2 should have 2 parameters: j and k");
+                        if (2 != mp.method_parameter_table_length)
+                            error("expected 2 method parameter entries in foo2, got " +
+                                  mp.method_parameter_table_length);
+                        else if (!foo.constant_pool.getUTF8Value(mp.method_parameter_table[0].name_index).equals("j"))
+                            error("expected first parameter to foo2 to be \"j\", got \"" +
+                                  foo.constant_pool.getUTF8Value(mp.method_parameter_table[0].name_index) +
+                                  "\" instead");
+                        else if  (!foo.constant_pool.getUTF8Value(mp.method_parameter_table[1].name_index).equals("k"))
+                            error("expected first parameter to foo2 to be \"k\", got \"" +
+                                  foo.constant_pool.getUTF8Value(mp.method_parameter_table[1].name_index) +
+                                  "\" instead");
+                    }
+            }
+            else if (foo.methods[i].getName(foo.constant_pool).equals("<init>")) {
+                for (int j = 0; j < foo.methods[i].attributes.attrs.length; j++) {
+                    if (foo.methods[i].attributes.attrs[j] instanceof
+                        MethodParameters_attribute)
+                        error("Zero-argument constructor shouldn't have MethodParameters");
+                }
+            }
+            else if (foo.methods[i].getName(foo.constant_pool).equals("foo0")) {
+                for (int j = 0; j < foo.methods[i].attributes.attrs.length; j++)
+                    if (foo.methods[i].attributes.attrs[j] instanceof
+                        MethodParameters_attribute)
+                        error("Zero-argument method shouldn't have MethodParameters");
+            }
+            else
+                error("Unknown method " + foo.methods[i].getName(foo.constant_pool) + " showed up in class Foo");
+        }
+    }
+
+    // Run a bunch of structural tests on Bar to make sure it looks right.
+    void checkBar() throws Exception {
+        final File Bar_class = new File(classesdir, Bar_name + ".class");
+        final ClassFile bar = ClassFile.read(Bar_class);
+        for (int i = 0; i < bar.methods.length; i++) {
+            System.err.println("Examine method Bar." + bar.methods[i].getName(bar.constant_pool));
+            if (bar.methods[i].getName(bar.constant_pool).equals("<init>")) {
+                for (int j = 0; j < bar.methods[i].attributes.attrs.length; j++)
+                    if (bar.methods[i].attributes.attrs[j] instanceof
+                        MethodParameters_attribute) {
+                        MethodParameters_attribute mp =
+                            (MethodParameters_attribute)
+                            bar.methods[i].attributes.attrs[j];
+                        System.err.println("Bar constructor should have 1 parameter: i");
+                        if (1 != mp.method_parameter_table_length)
+                            error("expected 1 method parameter entries in constructor, got " +
+                                  mp.method_parameter_table_length);
+                        else if (!bar.constant_pool.getUTF8Value(mp.method_parameter_table[0].name_index).equals("i"))
+                            error("expected first parameter to foo2 to be \"i\", got \"" +
+                                  bar.constant_pool.getUTF8Value(mp.method_parameter_table[0].name_index) +
+                                  "\" instead");
+                    }
+            }
+            else if (bar.methods[i].getName(bar.constant_pool).equals("foo")) {
+                for (int j = 0; j < bar.methods[i].attributes.attrs.length; j++) {
+                    if (bar.methods[i].attributes.attrs[j] instanceof
+                        MethodParameters_attribute)
+                        error("Zero-argument constructor shouldn't have MethodParameters");
+                }
+            }
+        }
+    }
+
+    String compile(String... args) throws Exception {
+        System.err.println("compile: " + Arrays.asList(args));
+        StringWriter sw = new StringWriter();
+        PrintWriter pw = new PrintWriter(sw);
+        int rc = com.sun.tools.javac.Main.compile(args, pw);
+        pw.close();
+        String out = sw.toString();
+        if (out.length() > 0)
+            System.err.println(out);
+        if (rc != 0)
+            error("compilation failed, rc=" + rc);
+        return out;
+    }
+
+    File writeFile(File dir, String path, String body) throws IOException {
+        File f = new File(dir, path);
+        f.getParentFile().mkdirs();
+        FileWriter out = new FileWriter(f);
+        out.write(body);
+        out.close();
+        return f;
+    }
+
+    void error(String msg) {
+        System.err.println("Error: " + msg);
+        errors++;
+    }
+
+    int errors;
+}
--- a/langtools/test/tools/javac/StringsInSwitch/StringSwitches.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/StringsInSwitch/StringSwitches.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/T7093325.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/T7093325.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,35 +25,29 @@
  * @test
  * @bug 7093325
  * @summary Redundant entry in bytecode exception table
+ * @library lib
+ * @build JavacTestingAbstractThreadedTest
+ * @run main T7093325
  */
 
+import java.io.File;
+import java.net.URI;
+import java.util.Arrays;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileObject;
+import javax.tools.SimpleJavaFileObject;
+import javax.tools.ToolProvider;
+
 import com.sun.source.util.JavacTask;
 import com.sun.tools.classfile.Attribute;
 import com.sun.tools.classfile.ClassFile;
 import com.sun.tools.classfile.Code_attribute;
 import com.sun.tools.classfile.ConstantPool.*;
 import com.sun.tools.classfile.Method;
-import com.sun.tools.javac.api.JavacTool;
 
-import java.io.File;
-import java.net.URI;
-import java.util.Arrays;
-import javax.tools.JavaCompiler;
-import javax.tools.JavaFileObject;
-import javax.tools.SimpleJavaFileObject;
-import javax.tools.StandardJavaFileManager;
-import javax.tools.ToolProvider;
-
-
-public class T7093325 {
-
-    /** global decls ***/
-
-    // Create a single file manager and reuse it for each compile to save time.
-    static StandardJavaFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);
-
-    //statistics
-    static int checkCount = 0;
+public class T7093325
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     enum StatementKind {
         THROW("throw new RuntimeException();", false, false),
@@ -89,7 +83,8 @@
             if (this.ordinal() == 0) {
                 return catchStr;
             } else {
-                return CatchArity.values()[this.ordinal() - 1].catchers() + catchStr;
+                return CatchArity.values()[this.ordinal() - 1].catchers() +
+                        catchStr;
             }
         }
     }
@@ -98,31 +93,36 @@
         for (CatchArity ca : CatchArity.values()) {
             for (StatementKind stmt0 : StatementKind.values()) {
                 if (ca.ordinal() == 0) {
-                    new T7093325(ca, stmt0).compileAndCheck();
+                    pool.execute(new T7093325(ca, stmt0));
                     continue;
                 }
                 for (StatementKind stmt1 : StatementKind.values()) {
                     if (ca.ordinal() == 1) {
-                        new T7093325(ca, stmt0, stmt1).compileAndCheck();
+                        pool.execute(new T7093325(ca, stmt0, stmt1));
                         continue;
                     }
                     for (StatementKind stmt2 : StatementKind.values()) {
                         if (ca.ordinal() == 2) {
-                            new T7093325(ca, stmt0, stmt1, stmt2).compileAndCheck();
+                            pool.execute(new T7093325(ca, stmt0, stmt1, stmt2));
                             continue;
                         }
                         for (StatementKind stmt3 : StatementKind.values()) {
                             if (ca.ordinal() == 3) {
-                                new T7093325(ca, stmt0, stmt1, stmt2, stmt3).compileAndCheck();
+                                pool.execute(
+                                    new T7093325(ca, stmt0, stmt1, stmt2, stmt3));
                                 continue;
                             }
                             for (StatementKind stmt4 : StatementKind.values()) {
                                 if (ca.ordinal() == 4) {
-                                    new T7093325(ca, stmt0, stmt1, stmt2, stmt3, stmt4).compileAndCheck();
+                                    pool.execute(
+                                        new T7093325(ca, stmt0, stmt1,
+                                                     stmt2, stmt3, stmt4));
                                     continue;
                                 }
                                 for (StatementKind stmt5 : StatementKind.values()) {
-                                    new T7093325(ca, stmt0, stmt1, stmt2, stmt3, stmt4, stmt5).compileAndCheck();
+                                    pool.execute(
+                                        new T7093325(ca, stmt0, stmt1, stmt2,
+                                                     stmt3, stmt4, stmt5));
                                 }
                             }
                         }
@@ -131,7 +131,7 @@
             }
         }
 
-        System.out.println("Total checks made: " + checkCount);
+        checkAfterExec();
     }
 
     /** instance decls **/
@@ -144,17 +144,18 @@
         this.stmts = stmts;
     }
 
-    void compileAndCheck() throws Exception {
+    @Override
+    public void run() {
+        int id = checkCount.incrementAndGet();
         final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
-        JavaSource source = new JavaSource();
-        JavacTask ct = (JavacTask)tool.getTask(null, fm, null,
+        JavaSource source = new JavaSource(id);
+        JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), null,
                 null, null, Arrays.asList(source));
         ct.call();
-        verifyBytecode(source);
+        verifyBytecode(source, id);
     }
 
-    void verifyBytecode(JavaSource source) {
-        checkCount++;
+    void verifyBytecode(JavaSource source, int id) {
         boolean lastInlined = false;
         boolean hasCode = false;
         int gapsCount = 0;
@@ -172,11 +173,12 @@
 
         //System.out.printf("gaps %d \n %s \n", gapsCount, source.toString());
 
-        File compiledTest = new File("Test.class");
+        File compiledTest = new File(String.format("Test%s.class", id));
         try {
             ClassFile cf = ClassFile.read(compiledTest);
             if (cf == null) {
-                throw new Error("Classfile not found: " + compiledTest.getName());
+                throw new Error("Classfile not found: " +
+                                compiledTest.getName());
             }
 
             Method test_method = null;
@@ -232,7 +234,7 @@
                 "class C extends RuntimeException {} \n" +
                 "class D extends RuntimeException {} \n" +
                 "class E extends RuntimeException {} \n" +
-                "class Test {\n" +
+                "class Test#ID {\n" +
                 "   void test() {\n" +
                 "   try { #S0 } #C finally { System.out.println(); }\n" +
                 "   }\n" +
@@ -240,10 +242,12 @@
 
         String source;
 
-        public JavaSource() {
-            super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
+        public JavaSource(int id) {
+            super(URI.create(String.format("myfo:/Test%s.java", id)),
+                  JavaFileObject.Kind.SOURCE);
             source = source_template.replace("#C", ca.catchers());
             source = source.replace("#S0", stmts[0].stmt);
+            source = source.replace("#ID", String.valueOf(id));
             for (int i = 1; i < ca.ordinal() + 1; i++) {
                 source = source.replace("#S" + i, stmts[i].stmt);
             }
@@ -259,4 +263,5 @@
             return source;
         }
     }
+
 }
--- a/langtools/test/tools/javac/api/T6395981.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/api/T6395981.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/cast/intersection/IntersectionTypeCastTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/cast/intersection/IntersectionTypeCastTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,23 +25,26 @@
  * @test
  * @bug 8002099
  * @summary Add support for intersection types in cast expression
+ * @library ../../lib
+ * @build JavacTestingAbstractThreadedTest
+ * @run main/timeout=360 IntersectionTypeCastTest
  */
 
-import com.sun.source.util.JavacTask;
-import com.sun.tools.javac.util.List;
-import com.sun.tools.javac.util.ListBuffer;
 import java.net.URI;
 import java.util.Arrays;
 import javax.tools.Diagnostic;
 import javax.tools.JavaCompiler;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
-import javax.tools.StandardJavaFileManager;
 import javax.tools.ToolProvider;
 
-public class IntersectionTypeCastTest {
+import com.sun.source.util.JavacTask;
+import com.sun.tools.javac.util.List;
+import com.sun.tools.javac.util.ListBuffer;
 
-    static int checkCount = 0;
+public class IntersectionTypeCastTest
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     interface Type {
         boolean subtypeOf(Type that);
@@ -59,7 +62,8 @@
         String typeStr;
         InterfaceKind superInterface;
 
-        InterfaceKind(String declStr, String typeStr, InterfaceKind superInterface) {
+        InterfaceKind(String declStr, String typeStr,
+                InterfaceKind superInterface) {
             this.declStr = declStr;
             this.typeStr = typeStr;
             this.superInterface = superInterface;
@@ -67,7 +71,8 @@
 
         @Override
         public boolean subtypeOf(Type that) {
-            return this == that || superInterface == that || that == ClassKind.OBJECT;
+            return this == that || superInterface == that ||
+                   that == ClassKind.OBJECT;
         }
 
         @Override
@@ -88,19 +93,27 @@
 
     enum ClassKind implements Type {
         OBJECT(null, "Object"),
-        CA("#M class CA implements A { }\n", "CA", InterfaceKind.A),
-        CB("#M class CB implements B { }\n", "CB", InterfaceKind.B),
-        CAB("#M class CAB implements A, B { }\n", "CAB", InterfaceKind.A, InterfaceKind.B),
-        CC("#M class CC implements C { }\n", "CC", InterfaceKind.C, InterfaceKind.A),
-        CCA("#M class CCA implements C, A { }\n", "CCA", InterfaceKind.C, InterfaceKind.A),
-        CCB("#M class CCB implements C, B { }\n", "CCB", InterfaceKind.C, InterfaceKind.A, InterfaceKind.B),
-        CCAB("#M class CCAB implements C, A, B { }\n", "CCAB", InterfaceKind.C, InterfaceKind.A, InterfaceKind.B);
+        CA("#M class CA implements A { }\n", "CA",
+           InterfaceKind.A),
+        CB("#M class CB implements B { }\n", "CB",
+           InterfaceKind.B),
+        CAB("#M class CAB implements A, B { }\n", "CAB",
+            InterfaceKind.A, InterfaceKind.B),
+        CC("#M class CC implements C { }\n", "CC",
+           InterfaceKind.C, InterfaceKind.A),
+        CCA("#M class CCA implements C, A { }\n", "CCA",
+            InterfaceKind.C, InterfaceKind.A),
+        CCB("#M class CCB implements C, B { }\n", "CCB",
+            InterfaceKind.C, InterfaceKind.A, InterfaceKind.B),
+        CCAB("#M class CCAB implements C, A, B { }\n", "CCAB",
+             InterfaceKind.C, InterfaceKind.A, InterfaceKind.B);
 
         String declTemplate;
         String typeStr;
         List<InterfaceKind> superInterfaces;
 
-        ClassKind(String declTemplate, String typeStr, InterfaceKind... superInterfaces) {
+        ClassKind(String declTemplate, String typeStr,
+                InterfaceKind... superInterfaces) {
             this.declTemplate = declTemplate;
             this.typeStr = typeStr;
             this.superInterfaces = List.from(superInterfaces);
@@ -114,7 +127,8 @@
 
         @Override
         public boolean subtypeOf(Type that) {
-            return this == that || superInterfaces.contains(that) || that == OBJECT;
+            return this == that || superInterfaces.contains(that) ||
+                    that == OBJECT;
         }
 
         @Override
@@ -170,9 +184,11 @@
         }
 
         String getCast() {
-            String temp = kind.castTemplate.replaceAll("#C", types[0].asString());
+            String temp = kind.castTemplate.replaceAll("#C",
+                    types[0].asString());
             for (int i = 0; i < kind.interfaceBounds ; i++) {
-                temp = temp.replace(String.format("#I%d", i), types[i + 1].asString());
+                temp = temp.replace(String.format("#I%d", i),
+                                    types[i + 1].asString());
             }
             return temp;
         }
@@ -195,7 +211,8 @@
                             t1.subtypeOf(t2) ||
                             t2.subtypeOf(t1) ||
                             (t1.isInterface() && t2.isInterface()) || //side-cast (1)
-                            (mod == ModifierKind.NONE && (t1.isInterface() != t2.isInterface())); //side-cast (2)
+                            (mod == ModifierKind.NONE &&
+                            (t1.isInterface() != t2.isInterface())); //side-cast (2)
                     if (!compat) return false;
                 }
             }
@@ -204,18 +221,15 @@
     }
 
     public static void main(String... args) throws Exception {
-        //create default shared JavaCompiler - reused across multiple compilations
-        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
-        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
-
         for (ModifierKind mod : ModifierKind.values()) {
             for (CastInfo cast1 : allCastInfo()) {
                 for (CastInfo cast2 : allCastInfo()) {
-                    new IntersectionTypeCastTest(mod, cast1, cast2).run(comp, fm);
+                    pool.execute(
+                        new IntersectionTypeCastTest(mod, cast1, cast2));
                 }
             }
         }
-        System.out.println("Total check executed: " + checkCount);
+        checkAfterExec();
     }
 
     static List<CastInfo> allCastInfo() {
@@ -235,11 +249,14 @@
                         } else {
                             for (InterfaceKind intf2 : InterfaceKind.values()) {
                                 if (kind.interfaceBounds == 2) {
-                                    buf.append(new CastInfo(kind, clazz, intf1, intf2));
+                                    buf.append(
+                                            new CastInfo(kind, clazz, intf1, intf2));
                                     continue;
                                 } else {
                                     for (InterfaceKind intf3 : InterfaceKind.values()) {
-                                        buf.append(new CastInfo(kind, clazz, intf1, intf2, intf3));
+                                        buf.append(
+                                                new CastInfo(kind, clazz, intf1,
+                                                             intf2, intf3));
                                         continue;
                                     }
                                 }
@@ -265,6 +282,22 @@
         this.diagChecker = new DiagnosticChecker();
     }
 
+    @Override
+    public void run() {
+        final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
+
+        JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), diagChecker,
+                Arrays.asList("-XDallowIntersectionTypes"),
+                null, Arrays.asList(source));
+        try {
+            ct.analyze();
+        } catch (Throwable ex) {
+            throw new AssertionError("Error thrown when compiling the following code:\n" +
+                    source.getCharContent(true));
+        }
+        check();
+    }
+
     class JavaSource extends SimpleJavaFileObject {
 
         String bodyTemplate = "class Test {\n" +
@@ -282,7 +315,8 @@
             for (InterfaceKind ik : InterfaceKind.values()) {
                 source += ik.declStr;
             }
-            source += bodyTemplate.replaceAll("#C1", cast1.getCast()).replaceAll("#C2", cast2.getCast());
+            source += bodyTemplate.replaceAll("#C1", cast1.getCast()).
+                    replaceAll("#C2", cast2.getCast());
         }
 
         @Override
@@ -291,21 +325,11 @@
         }
     }
 
-    void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
-        JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
-                Arrays.asList("-XDallowIntersectionTypes"), null, Arrays.asList(source));
-        try {
-            ct.analyze();
-        } catch (Throwable ex) {
-            throw new AssertionError("Error thrown when compiling the following code:\n" + source.getCharContent(true));
-        }
-        check();
-    }
+    void check() {
+        checkCount.incrementAndGet();
 
-    void check() {
-        checkCount++;
-
-        boolean errorExpected = cast1.hasDuplicateTypes() || cast2.hasDuplicateTypes();
+        boolean errorExpected = cast1.hasDuplicateTypes() ||
+                cast2.hasDuplicateTypes();
 
         errorExpected |= !cast2.compatibleWith(mod, cast1);
 
@@ -317,7 +341,8 @@
         }
     }
 
-    static class DiagnosticChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
+    static class DiagnosticChecker
+        implements javax.tools.DiagnosticListener<JavaFileObject> {
 
         boolean errorFound;
 
@@ -327,4 +352,5 @@
             }
         }
     }
+
 }
--- a/langtools/test/tools/javac/cast/intersection/model/Model01.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/cast/intersection/model/Model01.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 8002099
  * @summary Add support for intersection types in cast expression
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor ModelChecker
  * @compile -XDallowIntersectionTypes -processor ModelChecker Model01.java
  */
--- a/langtools/test/tools/javac/classreader/T7031108.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/classreader/T7031108.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 7031108
  * @summary NPE in javac.jvm.ClassReader.findMethod in PackageElement.enclosedElements from AP in incr build
- * @library ../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor T7031108
  * @run main T7031108
  */
--- a/langtools/test/tools/javac/defaultMethods/defaultMethodExecution/DefaultMethodRegressionTests.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/defaultMethods/defaultMethodExecution/DefaultMethodRegressionTests.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/defaultMethods/super/TestDefaultSuperCall.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/defaultMethods/super/TestDefaultSuperCall.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,25 +24,25 @@
 /*
  * @test
  * @summary Automatic test for checking correctness of default super/this resolution
+ * @library ../../lib
+ * @build JavacTestingAbstractThreadedTest
+ * @run main TestDefaultSuperCall
  */
 
-import com.sun.source.util.JavacTask;
 import java.net.URI;
 import java.util.Arrays;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Locale;
-import java.util.Map;
 import javax.tools.Diagnostic;
-import javax.tools.JavaCompiler;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
-import javax.tools.StandardJavaFileManager;
-import javax.tools.ToolProvider;
+
+import com.sun.source.util.JavacTask;
 
-public class TestDefaultSuperCall {
-
-    static int checkCount = 0;
+public class TestDefaultSuperCall
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     enum InterfaceKind {
         DEFAULT("interface A extends B { default void m() { } }"),
@@ -212,7 +212,7 @@
         List<String> elementsWithMethod;
 
         Shape(ElementKind... elements) {
-            System.err.println("elements = " + Arrays.toString(elements));
+            errWriter.println("elements = " + Arrays.toString(elements));
             enclosingElements = new ArrayList<>();
             enclosingNames = new ArrayList<>();
             elementsWithMethod = new ArrayList<>();
@@ -231,28 +231,26 @@
                     elementsWithMethod.add(prevName);
                 }
                 String element = ek.templateDecl.replaceAll("#N", name);
-                shapeStr = shapeStr == null ? element : shapeStr.replaceAll("#B", element);
+                shapeStr = shapeStr ==
+                        null ? element : shapeStr.replaceAll("#B", element);
                 prevName = name;
             }
         }
 
         String getShape(QualifierKind qk, ExprKind ek) {
             String methName = ek == ExprKind.THIS ? "test" : "m";
-            String call = qk.getQualifier(this) + "." + ek.exprStr + "." + methName + "();";
+            String call = qk.getQualifier(this) + "." +
+                    ek.exprStr + "." + methName + "();";
             return shapeStr.replaceAll("#B", call);
         }
 
         String enclosingAt(int index) {
-            return index < enclosingNames.size() ? enclosingNames.get(index) : "BAD";
+            return index < enclosingNames.size() ?
+                    enclosingNames.get(index) : "BAD";
         }
     }
 
     public static void main(String... args) throws Exception {
-
-        //create default shared JavaCompiler - reused across multiple compilations
-        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
-        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
-
         for (InterfaceKind ik : InterfaceKind.values()) {
             for (PruneKind pk : PruneKind.values()) {
                 for (ElementKind ek1 : ElementKind.values()) {
@@ -264,10 +262,14 @@
                             for (ElementKind ek4 : ElementKind.values()) {
                                 if (!ek4.isAllowedEnclosing(ek3, false)) continue;
                                 for (ElementKind ek5 : ElementKind.values()) {
-                                    if (!ek5.isAllowedEnclosing(ek4, false) || ek5.isClassDecl()) continue;
+                                    if (!ek5.isAllowedEnclosing(ek4, false) ||
+                                            ek5.isClassDecl()) continue;
                                     for (QualifierKind qk : QualifierKind.values()) {
                                         for (ExprKind ek : ExprKind.values()) {
-                                            new TestDefaultSuperCall(ik, pk, new Shape(ek1, ek2, ek3, ek4, ek5), qk, ek).run(comp, fm);
+                                            pool.execute(
+                                                    new TestDefaultSuperCall(ik, pk,
+                                                    new Shape(ek1, ek2, ek3,
+                                                    ek4, ek5), qk, ek));
                                         }
                                     }
                                 }
@@ -277,7 +279,8 @@
                 }
             }
         }
-        System.out.println("Total check executed: " + checkCount);
+
+        checkAfterExec();
     }
 
     InterfaceKind ik;
@@ -288,7 +291,8 @@
     JavaSource source;
     DiagnosticChecker diagChecker;
 
-    TestDefaultSuperCall(InterfaceKind ik, PruneKind pk, Shape sh, QualifierKind qk, ExprKind ek) {
+    TestDefaultSuperCall(InterfaceKind ik, PruneKind pk, Shape sh,
+            QualifierKind qk, ExprKind ek) {
         this.ik = ik;
         this.pk = pk;
         this.sh = sh;
@@ -321,13 +325,14 @@
         }
     }
 
-    void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
-        JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
+    public void run() {
+        JavacTask ct = (JavacTask)comp.getTask(null, fm.get(), diagChecker,
                 null, null, Arrays.asList(source));
         try {
             ct.analyze();
         } catch (Throwable ex) {
-            throw new AssertionError("Error thrown when analyzing the following source:\n" + source.getCharContent(true));
+            processException(ex);
+            return;
         }
         check();
     }
@@ -370,7 +375,8 @@
 
             int lastIdx = sh.enclosingElements.size() - 1;
             boolean found = lastIdx == -1 ? false :
-                    sh.enclosingElements.get(lastIdx).hasSuper() && qk.allowSuperCall(ik, pk);
+                    sh.enclosingElements.get(lastIdx).hasSuper() &&
+                    qk.allowSuperCall(ik, pk);
 
             errorExpected |= !found;
             if (!found) {
@@ -378,9 +384,10 @@
             }
         }
 
-        checkCount++;
+        checkCount.incrementAndGet();
         if (diagChecker.errorFound != errorExpected) {
-            throw new AssertionError("Problem when compiling source:\n" + source.getCharContent(true) +
+            throw new AssertionError("Problem when compiling source:\n" +
+                    source.getCharContent(true) +
                     "\nenclosingElems: " + sh.enclosingElements +
                     "\nenclosingNames: " + sh.enclosingNames +
                     "\nelementsWithMethod: " + sh.elementsWithMethod +
@@ -392,15 +399,17 @@
         }
     }
 
-    static class DiagnosticChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
+    static class DiagnosticChecker
+        implements javax.tools.DiagnosticListener<JavaFileObject> {
 
         boolean errorFound;
 
         public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
             if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
-                System.err.println(diagnostic.getMessage(Locale.getDefault()));
+                errWriter.println(diagnostic.getMessage(Locale.getDefault()));
                 errorFound = true;
             }
         }
     }
+
 }
--- a/langtools/test/tools/javac/diags/examples/DuplicateAnnotation.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/diags/examples/DuplicateAnnotation.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/NoContent.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// key: compiler.err.dc.no.content
+// key: compiler.note.note
+// key: compiler.note.proc.messager
+// run: backdoor
+// options: -processor DocCommentProcessor -proc:only
+
+/** @see */
+class NoContent {
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/doclint/DocLintTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,225 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8004833
+ * @summary Integrate doclint support into javac
+ */
+
+import java.io.File;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.net.URI;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import javax.tools.Diagnostic;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileObject;
+import javax.tools.SimpleJavaFileObject;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.StandardLocation;
+import javax.tools.ToolProvider;
+import static javax.tools.Diagnostic.Kind.*;
+
+import com.sun.source.util.JavacTask;
+import com.sun.tools.javac.main.Main;
+import java.util.EnumSet;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class DocLintTest {
+    public static void main(String... args) throws Exception {
+        new DocLintTest().run();
+    }
+
+    JavaCompiler javac;
+    StandardJavaFileManager fm;
+    JavaFileObject file;
+
+    final String code =
+        /* 01 */    "/** Class comment. */\n" +
+        /* 02 */    "public class Test {\n" +
+        /* 03 */    "    /** Method comment. */\n" +
+        /* 04 */    "    public void method() { }\n" +
+        /* 05 */    "\n" +
+        /* 06 */    "    /** Syntax < error. */\n" +
+        /* 07 */    "    private void syntaxError() { }\n" +
+        /* 08 */    "\n" +
+        /* 09 */    "    /** @see DoesNotExist */\n" +
+        /* 10 */    "    protected void referenceError() { }\n" +
+        /* 08 */    "\n" +
+        /* 09 */    "    /** @return */\n" +
+        /* 10 */    "    public int emptyReturn() { return 0; }\n" +
+        /* 11 */    "}\n";
+
+    final String rawDiags = "-XDrawDiagnostics";
+    private enum Message {
+        // doclint messages
+        DL_ERR6(ERROR, "Test.java:6:16: compiler.err.proc.messager: malformed HTML"),
+        DL_ERR9(ERROR, "Test.java:9:14: compiler.err.proc.messager: reference not found"),
+        DL_WRN12(WARNING, "Test.java:12:9: compiler.warn.proc.messager: no description for @return"),
+
+        OPT_BADARG(ERROR, "invalid flag: -Xdoclint:badarg");
+
+        final Diagnostic.Kind kind;
+        final String text;
+
+        static Message get(String text) {
+            for (Message m: values()) {
+                if (m.text.equals(text))
+                    return m;
+            }
+            return null;
+        }
+
+        Message(Diagnostic.Kind kind, String text) {
+            this.kind = kind;
+            this.text = text;
+        }
+
+        @Override
+        public String toString() {
+            return "[" + kind + ",\"" + text + "\"]";
+        }
+    }
+    void run() throws Exception {
+        javac = ToolProvider.getSystemJavaCompiler();
+        fm = javac.getStandardFileManager(null, null, null);
+        fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(".")));
+        file = new SimpleJavaFileObject(URI.create("Test.java"), JavaFileObject.Kind.SOURCE) {
+            @Override
+            public CharSequence getCharContent(boolean ignoreEncoding) {
+                return code;
+            }
+        };
+
+        test(Collections.<String>emptyList(),
+                Main.Result.OK,
+                EnumSet.noneOf(Message.class));
+
+        test(Arrays.asList("-Xdoclint:none"),
+                Main.Result.OK,
+                EnumSet.noneOf(Message.class));
+
+        test(Arrays.asList(rawDiags, "-Xdoclint"),
+                Main.Result.ERROR,
+                EnumSet.of(Message.DL_ERR6, Message.DL_ERR9, Message.DL_WRN12));
+
+        test(Arrays.asList(rawDiags, "-Xdoclint:all/public"),
+                Main.Result.OK,
+                EnumSet.of(Message.DL_WRN12));
+
+        test(Arrays.asList(rawDiags, "-Xdoclint:syntax"),
+                Main.Result.ERROR,
+                EnumSet.of(Message.DL_ERR6, Message.DL_WRN12));
+
+        test(Arrays.asList(rawDiags, "-Xdoclint:reference"),
+                Main.Result.ERROR,
+                EnumSet.of(Message.DL_ERR9));
+
+        test(Arrays.asList(rawDiags, "-Xdoclint:badarg"),
+                Main.Result.CMDERR,
+                EnumSet.of(Message.OPT_BADARG));
+
+        if (errors > 0)
+            throw new Exception(errors + " errors occurred");
+    }
+
+    void test(List<String> opts, Main.Result expectResult, Set<Message> expectMessages) {
+        System.err.println("test: " + opts);
+        StringWriter sw = new StringWriter();
+        PrintWriter pw = new PrintWriter(sw);
+        List<JavaFileObject> files = Arrays.asList(file);
+        try {
+            JavacTask t = (JavacTask) javac.getTask(pw, fm, null, opts, null, files);
+            boolean ok = t.call();
+            pw.close();
+            String out = sw.toString().replaceAll("[\r\n]+", "\n");
+            if (!out.isEmpty())
+                System.err.println(out);
+            if (ok && expectResult != Main.Result.OK) {
+                error("Compilation succeeded unexpectedly");
+            } else if (!ok && expectResult != Main.Result.ERROR) {
+                error("Compilation failed unexpectedly");
+            } else
+                check(out, expectMessages);
+        } catch (IllegalArgumentException e) {
+            System.err.println(e);
+            String expectOut = expectMessages.iterator().next().text;
+            if (expectResult != Main.Result.CMDERR)
+                error("unexpected exception caught");
+            else if (!e.getMessage().equals(expectOut)) {
+                error("unexpected exception message: "
+                        + e.getMessage()
+                        + " expected: " + expectOut);
+            }
+        }
+
+//        if (errors > 0)
+//            throw new Error("stop");
+    }
+
+    private void check(String out, Set<Message> expect) {
+        Pattern stats = Pattern.compile("^([1-9]+) (error|warning)(s?)");
+        Set<Message> found = EnumSet.noneOf(Message.class);
+        int e = 0, w = 0;
+        if (!out.isEmpty()) {
+            for (String line: out.split("[\r\n]+")) {
+                Matcher s = stats.matcher(line);
+                if (s.matches()) {
+                    int i = Integer.valueOf(s.group(1));
+                    if (s.group(2).equals("error"))
+                        e++;
+                    else
+                        w++;
+                    continue;
+                }
+
+                Message m = Message.get(line);
+                if (m == null)
+                    error("Unexpected line: " + line);
+                else
+                    found.add(m);
+            }
+        }
+        for (Message m: expect) {
+            if (!found.contains(m))
+                error("expected message not found: " + m.text);
+        }
+        for (Message m: found) {
+            if (!expect.contains(m))
+                error("unexpected message found: " + m.text);
+        }
+    }
+
+    void error(String msg) {
+        System.err.println("Error: " + msg);
+        errors++;
+    }
+
+    int errors;
+}
--- a/langtools/test/tools/javac/enum/6350057/T6350057.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/enum/6350057/T6350057.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6350057 7025809
  * @summary Test that parameters on implicit enum methods have the right kind
  * @author  Joseph D. Darcy
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor T6350057
  * @compile -processor T6350057 -proc:only TestEnum.java
  */
--- a/langtools/test/tools/javac/enum/6424358/T6424358.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/enum/6424358/T6424358.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6424358 7025809
  * @summary Synthesized static enum method values() is final
  * @author  Peter von der Ah\u00e9
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor T6424358
  * @compile -processor T6424358 -proc:only T6424358.java
  */
--- a/langtools/test/tools/javac/failover/CheckAttributedTree.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/failover/CheckAttributedTree.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -21,7 +21,15 @@
  * questions.
  */
 
-import com.sun.source.util.TaskEvent;
+/*
+ * @test
+ * @bug 6970584
+ * @summary assorted position errors in compiler syntax trees
+ * @library ../lib
+ * @build JavacTestingAbstractThreadedTest
+ * @run main CheckAttributedTree -q -r -et ERRONEOUS .
+ */
+
 import java.awt.BorderLayout;
 import java.awt.Color;
 import java.awt.Dimension;
@@ -34,6 +42,20 @@
 import java.awt.event.ActionListener;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.lang.model.element.Element;
 import javax.swing.DefaultComboBoxModel;
 import javax.swing.JComboBox;
 import javax.swing.JComponent;
@@ -49,23 +71,14 @@
 import javax.swing.text.BadLocationException;
 import javax.swing.text.DefaultHighlighter;
 import javax.swing.text.Highlighter;
-import java.io.File;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.List;
 import javax.tools.Diagnostic;
 import javax.tools.DiagnosticListener;
 import javax.tools.JavaFileObject;
-import javax.tools.StandardJavaFileManager;
 
 import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.util.TaskEvent;
 import com.sun.source.util.JavacTask;
 import com.sun.source.util.TaskListener;
-import com.sun.tools.javac.api.JavacTool;
 import com.sun.tools.javac.code.Symbol;
 import com.sun.tools.javac.code.Type;
 import com.sun.tools.javac.tree.EndPosTable;
@@ -76,11 +89,6 @@
 import com.sun.tools.javac.tree.TreeScanner;
 import com.sun.tools.javac.util.Pair;
 
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-import javax.lang.model.element.Element;
-
 import static com.sun.tools.javac.tree.JCTree.Tag.*;
 
 /**
@@ -95,13 +103,7 @@
  * covering any new language features that may be tested in this test suite.
  */
 
-/*
- * @test
- * @bug 6970584
- * @summary assorted position errors in compiler syntax trees
- * @run main CheckAttributedTree -q -r -et ERRONEOUS .
- */
-public class CheckAttributedTree {
+public class CheckAttributedTree extends JavacTestingAbstractThreadedTest {
     /**
      * Main entry point.
      * If test.src is set, program runs in jtreg mode, and will throw an Error
@@ -110,9 +112,10 @@
      * args is the value of ${test.src}. In jtreg mode, the -r option can be
      * given to change the default base directory to the root test directory.
      */
-    public static void main(String... args) {
+    public static void main(String... args) throws Exception {
         String testSrc = System.getProperty("test.src");
         File baseDir = (testSrc == null) ? null : new File(testSrc);
+        throwAssertionOnError = false;
         boolean ok = new CheckAttributedTree().run(baseDir, args);
         if (!ok) {
             if (testSrc != null)  // jtreg mode
@@ -130,7 +133,7 @@
      * @param args command line args
      * @return true if successful or in gui mode
      */
-    boolean run(File baseDir, String... args) {
+    boolean run(File baseDir, String... args) throws Exception {
         if (args.length == 0) {
             usage(System.out);
             return true;
@@ -145,8 +148,10 @@
                 gui = true;
             else if (arg.equals("-q"))
                 quiet = true;
-            else if (arg.equals("-v"))
+            else if (arg.equals("-v")) {
                 verbose = true;
+                printAll = true;
+            }
             else if (arg.equals("-t") && i + 1 < args.length)
                 tags.add(args[++i]);
             else if (arg.equals("-ef") && i + 1 < args.length)
@@ -179,12 +184,11 @@
                 error("File not found: " + file);
         }
 
-        if (fileCount != 1)
-            System.err.println(fileCount + " files read");
-        if (errors > 0)
-            System.err.println(errors + " errors");
+        if (fileCount.get() != 1)
+            errWriter.println(fileCount + " files read");
+        checkAfterExec(false);
 
-        return (gui || errors == 0);
+        return (gui || errCount.get() == 0);
     }
 
     /**
@@ -215,7 +219,7 @@
      * for java files.
      * @param file the file or directory to test
      */
-    void test(File file) {
+    void test(final File file) {
         if (excludeFiles.contains(file)) {
             if (!quiet)
                 error("File " + file + " excluded");
@@ -230,20 +234,24 @@
         }
 
         if (file.isFile() && file.getName().endsWith(".java")) {
-            try {
-                if (verbose)
-                    System.err.println(file);
-                fileCount++;
-                NPETester p = new NPETester();
-                p.test(read(file));
-            } catch (AttributionException e) {
-                if (!quiet) {
-                    error("Error attributing " + file + "\n" + e.getMessage());
+            pool.execute(new Runnable() {
+                @Override
+                public void run() {
+                    try {
+                        if (verbose)
+                            errWriter.println(file);
+                        fileCount.incrementAndGet();
+                        NPETester p = new NPETester();
+                        p.test(read(file));
+                    } catch (AttributionException e) {
+                        if (!quiet) {
+                            error("Error attributing " + file + "\n" + e.getMessage());
+                        }
+                    } catch (IOException e) {
+                        error("Error reading " + file + ": " + e);
+                    }
                 }
-            } catch (IOException e) {
-                error("Error reading " + file + ": " + e);
-            }
-            return;
+            });
         }
 
         if (!quiet)
@@ -254,8 +262,6 @@
     StringWriter sw = new StringWriter();
     PrintWriter pw = new PrintWriter(sw);
     Reporter r = new Reporter(pw);
-    JavacTool tool = JavacTool.create();
-    StandardJavaFileManager fm = tool.getStandardFileManager(r, null, null);
 
     /**
      * Read a file.
@@ -265,11 +271,10 @@
      * @throws TreePosTest.ParseException if any errors occur while parsing the file
      */
     List<Pair<JCCompilationUnit, JCTree>> read(File file) throws IOException, AttributionException {
-        JavacTool tool = JavacTool.create();
         r.errors = 0;
-        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file);
+        Iterable<? extends JavaFileObject> files = fm.get().getJavaFileObjects(file);
         String[] opts = { "-XDshouldStopPolicy=ATTR", "-XDverboseCompilePolicy" };
-        JavacTask task = tool.getTask(pw, fm, r, Arrays.asList(opts), null, files);
+        JavacTask task = (JavacTask)comp.getTask(pw, fm.get(), r, Arrays.asList(opts), null, files);
         final List<Element> analyzedElems = new ArrayList<>();
         task.setTaskListener(new TaskListener() {
             public void started(TaskEvent e) {
@@ -308,13 +313,9 @@
      */
     void error(String msg) {
         System.err.println(msg);
-        errors++;
+        errCount.incrementAndGet();
     }
 
-    /** Number of files that have been analyzed. */
-    int fileCount;
-    /** Number of errors reported. */
-    int errors;
     /** Flag: don't report irrelevant files. */
     boolean quiet;
     /** Flag: show errors in GUI viewer. */
@@ -385,7 +386,8 @@
                         viewer = new Viewer();
                     viewer.addEntry(sourcefile, label, encl, self);
                 }
-                error(label + self.toString() + " encl: " + encl.toString() + " in file: " + sourcefile + "  " + self.tree);
+                error(label + self.toString() + " encl: " + encl.toString() +
+                        " in file: " + sourcefile + "  " + self.tree);
             }
         }
 
@@ -754,4 +756,8 @@
             final Info self;
         }
     }
+
+    /** Number of files that have been analyzed. */
+    static AtomicInteger fileCount = new AtomicInteger();
+
 }
--- a/langtools/test/tools/javac/file/T7018098.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/file/T7018098.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 7018098
  * @summary CacheFSInfo persists too long
- * @library ../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor T7018098
  * @run main T7018098
  */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/file/zip/8003512/LoadClassFromJava6CreatedJarTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,183 @@
+
+/*
+ * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8003512
+ * @summary javac doesn't work with jar files with >64k entries
+ * @compile -target 6 -source 6 -XDignore.symbol.file LoadClassFromJava6CreatedJarTest.java ../Utils.java
+ * @run main/timeout=360 LoadClassFromJava6CreatedJarTest
+ */
+
+/*
+ * The test creates a jar file with more than 64K entries. The jar file is
+ * created executing the LoadClassFromJava6CreatedJarTest$MakeJar
+ * class with a JVM version 6. The test must include Java 6 features only.
+ *
+ * The aim is to verify classes included in jar files with more than 64K entries
+ * created with Java 6 can be loaded by more recent versions of Java.
+ *
+ * A path to JDK or JRE version 6 is needed. This can be provided
+ * by passing this option to jtreg:
+ * -javaoption:-Djava6.home="/path/to/jdk_or_jre6"
+ */
+
+import java.io.BufferedInputStream;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.Arrays;
+import java.util.List;
+import java.util.zip.CRC32;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+public class LoadClassFromJava6CreatedJarTest {
+
+    static final String javaHome6 = System.getProperty("java6.home");
+    static final String testClasses = System.getProperty("test.classes");
+
+    public static void main(String... args)
+            throws IOException, InterruptedException {
+        if (javaHome6 != null) {
+            new LoadClassFromJava6CreatedJarTest().run();
+        } else {
+            System.out.println(
+                "The test LoadClassFromJava6CreatedJarTest cannot be executed. " +
+                "In order to run it you should pass an option with " +
+                "this form -javaoption:-Djava6.home=\"/path/to/jdk_or_jre6\" " +
+                "to jtreg.");
+        }
+    }
+
+    void run() throws IOException, InterruptedException {
+        File classA = new File("A.java");
+        Utils.createJavaFile(classA, null);
+        if (!Utils.compile("-target", "6", "-source", "6",
+            classA.getAbsolutePath())) {
+            throw new AssertionError("Test failed while compiling class A");
+        }
+
+        executeCommand(Arrays.asList(javaHome6 + "/bin/java", "-classpath",
+            testClasses, "LoadClassFromJava6CreatedJarTest$MakeJar"));
+
+        File classB = new File("B.java");
+        Utils.createJavaFile(classB, classA);
+        if (!Utils.compile("-cp", "a.jar", classB.getAbsolutePath())) {
+            throw new AssertionError("Test failed while compiling class Main");
+        }
+    }
+
+    void executeCommand(List<String> command)
+            throws IOException, InterruptedException {
+        ProcessBuilder pb = new ProcessBuilder(command).
+            redirectErrorStream(true);
+        Process p = pb.start();
+        BufferedReader r =
+            new BufferedReader(new InputStreamReader(p.getInputStream()));
+        String line;
+        while ((line = r.readLine()) != null) {
+            System.err.println(line);
+        }
+        int rc = p.waitFor();
+        if (rc != 0) {
+            throw new AssertionError("Unexpected exit code: " + rc);
+        }
+    }
+
+    static class MakeJar {
+        public static void main(String[] args) throws Throwable {
+            File classFile = new File("A.class");
+            ZipOutputStream zos = null;
+            FileInputStream fis = null;
+            final int MAX = Short.MAX_VALUE * 2 + 10;
+            ZipEntry ze = null;
+            try {
+                zos = new ZipOutputStream(new FileOutputStream("a.jar"));
+                zos.setLevel(ZipOutputStream.STORED);
+                zos.setMethod(ZipOutputStream.STORED);
+                for (int i = 0; i < MAX ; i++) {
+                    ze = new ZipEntry("X" + i + ".txt");
+                    ze.setSize(0);
+                    ze.setCompressedSize(0);
+                    ze.setCrc(0);
+                    zos.putNextEntry(ze);
+                }
+
+                // add a class file
+                ze = new ZipEntry("A.class");
+                ze.setCompressedSize(classFile.length());
+                ze.setSize(classFile.length());
+                ze.setCrc(computeCRC(classFile));
+                zos.putNextEntry(ze);
+                fis = new FileInputStream(classFile);
+                for (int c; (c = fis.read()) >= 0;) {
+                    zos.write(c);
+                }
+            } finally {
+                zos.close();
+                fis.close();
+            }
+        }
+
+        private static final int BUFFER_LEN = Short.MAX_VALUE * 2;
+
+        static long getCount(long minlength) {
+            return (minlength / BUFFER_LEN) + 1;
+        }
+
+        static long computeCRC(long minlength) {
+            CRC32 crc = new CRC32();
+            byte[] buffer = new byte[BUFFER_LEN];
+            long count = getCount(minlength);
+            for (long i = 0; i < count; i++) {
+                crc.update(buffer);
+            }
+            return crc.getValue();
+        }
+
+        static long computeCRC(File inFile) throws IOException {
+            byte[] buffer = new byte[8192];
+            CRC32 crc = new CRC32();
+            FileInputStream fis = null;
+            BufferedInputStream bis = null;
+            try {
+                fis = new FileInputStream(inFile);
+                bis = new BufferedInputStream(fis);
+                int n = bis.read(buffer);
+                while (n > 0) {
+                    crc.update(buffer, 0, n);
+                    n = bis.read(buffer);
+                }
+            } finally {
+                bis.close();
+                fis.close();
+            }
+            return crc.getValue();
+        }
+    }
+}
--- a/langtools/test/tools/javac/file/zip/Utils.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/file/zip/Utils.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -21,6 +21,12 @@
  * questions.
  */
 
+/*
+ * This utils class is been used by test T8003512 which is compiled with Java 6
+ * only features. So if this class is modified, it should be so using Java 6
+ * features only.
+ */
+
 import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.Closeable;
--- a/langtools/test/tools/javac/generics/diamond/7046778/DiamondAndInnerClassTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/generics/diamond/7046778/DiamondAndInnerClassTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,21 +25,21 @@
  * @test
  * @bug 7046778
  * @summary Project Coin: problem with diamond and member inner classes
+ * @library ../../../lib
+ * @build JavacTestingAbstractThreadedTest
+ * @run main DiamondAndInnerClassTest
  */
 
 import com.sun.source.util.JavacTask;
 import java.net.URI;
 import java.util.Arrays;
 import javax.tools.Diagnostic;
-import javax.tools.JavaCompiler;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
-import javax.tools.StandardJavaFileManager;
-import javax.tools.ToolProvider;
 
-public class DiamondAndInnerClassTest {
-
-    static int checkCount = 0;
+public class DiamondAndInnerClassTest
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     enum TypeArgumentKind {
         NONE(""),
@@ -151,11 +151,6 @@
     }
 
     public static void main(String... args) throws Exception {
-
-        //create default shared JavaCompiler - reused across multiple compilations
-        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
-        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
-
         for (InnerClassDeclArity innerClassDeclArity : InnerClassDeclArity.values()) {
             for (TypeQualifierArity declType : TypeQualifierArity.values()) {
                 if (!declType.matches(innerClassDeclArity)) continue;
@@ -168,53 +163,79 @@
                             //no diamond on decl site
                             if (taDecl1 == TypeArgumentKind.DIAMOND) continue;
                             for (TypeArgumentKind taSite1 : TypeArgumentKind.values()) {
-                                boolean isSiteRaw = taSite1 == TypeArgumentKind.NONE;
+                                boolean isSiteRaw =
+                                        taSite1 == TypeArgumentKind.NONE;
                                 //diamond only allowed on the last type qualifier
                                 if (taSite1 == TypeArgumentKind.DIAMOND &&
-                                        innerClassDeclArity != InnerClassDeclArity.ONE) continue;
+                                        innerClassDeclArity !=
+                                        InnerClassDeclArity.ONE)
+                                    continue;
                                 for (ArgumentKind arg1 : ArgumentKind.values()) {
                                     if (innerClassDeclArity == innerClassDeclArity.ONE) {
-                                        new DiamondAndInnerClassTest(innerClassDeclArity, declType, newClassType,
-                                                argList, new TypeArgumentKind[] {taDecl1},
-                                                new TypeArgumentKind[] {taSite1}, new ArgumentKind[] {arg1}).run(comp, fm);
+                                        pool.execute(
+                                                new DiamondAndInnerClassTest(
+                                                innerClassDeclArity, declType,
+                                                newClassType, argList,
+                                                new TypeArgumentKind[] {taDecl1},
+                                                new TypeArgumentKind[] {taSite1},
+                                                new ArgumentKind[] {arg1}));
                                         continue;
                                     }
                                     for (TypeArgumentKind taDecl2 : TypeArgumentKind.values()) {
                                         //no rare types
-                                        if (isDeclRaw != (taDecl2 == TypeArgumentKind.NONE)) continue;
+                                        if (isDeclRaw != (taDecl2 == TypeArgumentKind.NONE))
+                                            continue;
                                         //no diamond on decl site
-                                        if (taDecl2 == TypeArgumentKind.DIAMOND) continue;
+                                        if (taDecl2 == TypeArgumentKind.DIAMOND)
+                                            continue;
                                         for (TypeArgumentKind taSite2 : TypeArgumentKind.values()) {
                                             //no rare types
-                                            if (isSiteRaw != (taSite2 == TypeArgumentKind.NONE)) continue;
+                                            if (isSiteRaw != (taSite2 == TypeArgumentKind.NONE))
+                                                continue;
                                             //diamond only allowed on the last type qualifier
                                             if (taSite2 == TypeArgumentKind.DIAMOND &&
-                                                    innerClassDeclArity != InnerClassDeclArity.TWO) continue;
+                                                    innerClassDeclArity != InnerClassDeclArity.TWO)
+                                                continue;
                                             for (ArgumentKind arg2 : ArgumentKind.values()) {
                                                 if (innerClassDeclArity == innerClassDeclArity.TWO) {
-                                                    new DiamondAndInnerClassTest(innerClassDeclArity, declType, newClassType,
-                                                            argList, new TypeArgumentKind[] {taDecl1, taDecl2},
+                                                    pool.execute(
+                                                            new DiamondAndInnerClassTest(
+                                                            innerClassDeclArity,
+                                                            declType,
+                                                            newClassType,
+                                                            argList,
+                                                            new TypeArgumentKind[] {taDecl1, taDecl2},
                                                             new TypeArgumentKind[] {taSite1, taSite2},
-                                                            new ArgumentKind[] {arg1, arg2}).run(comp, fm);
+                                                            new ArgumentKind[] {arg1, arg2}));
                                                     continue;
                                                 }
                                                 for (TypeArgumentKind taDecl3 : TypeArgumentKind.values()) {
                                                     //no rare types
-                                                    if (isDeclRaw != (taDecl3 == TypeArgumentKind.NONE)) continue;
+                                                    if (isDeclRaw != (taDecl3 == TypeArgumentKind.NONE))
+                                                        continue;
                                                     //no diamond on decl site
-                                                    if (taDecl3 == TypeArgumentKind.DIAMOND) continue;
+                                                    if (taDecl3 == TypeArgumentKind.DIAMOND)
+                                                        continue;
                                                     for (TypeArgumentKind taSite3 : TypeArgumentKind.values()) {
                                                         //no rare types
-                                                        if (isSiteRaw != (taSite3 == TypeArgumentKind.NONE)) continue;
+                                                        if (isSiteRaw != (taSite3 == TypeArgumentKind.NONE))
+                                                            continue;
                                                         //diamond only allowed on the last type qualifier
                                                         if (taSite3 == TypeArgumentKind.DIAMOND &&
-                                                                innerClassDeclArity != InnerClassDeclArity.THREE) continue;
+                                                            innerClassDeclArity != InnerClassDeclArity.THREE)
+                                                            continue;
                                                         for (ArgumentKind arg3 : ArgumentKind.values()) {
-                                                            if (innerClassDeclArity == innerClassDeclArity.THREE) {
-                                                                new DiamondAndInnerClassTest(innerClassDeclArity, declType, newClassType,
-                                                                        argList, new TypeArgumentKind[] {taDecl1, taDecl2, taDecl3},
+                                                            if (innerClassDeclArity ==
+                                                                    innerClassDeclArity.THREE) {
+                                                                pool.execute(
+                                                                        new DiamondAndInnerClassTest(
+                                                                        innerClassDeclArity,
+                                                                        declType,
+                                                                        newClassType,
+                                                                        argList,
+                                                                        new TypeArgumentKind[] {taDecl1, taDecl2, taDecl3},
                                                                         new TypeArgumentKind[] {taSite1, taSite2, taSite3},
-                                                                        new ArgumentKind[] {arg1, arg2, arg3}).run(comp, fm);
+                                                                        new ArgumentKind[] {arg1, arg2, arg3}));
                                                                 continue;
                                                             }
                                                         }
@@ -230,7 +251,8 @@
                 }
             }
         }
-        System.out.println("Total check executed: " + checkCount);
+
+        checkAfterExec();
     }
 
     InnerClassDeclArity innerClassDeclArity;
@@ -244,9 +266,9 @@
     DiagnosticChecker diagChecker;
 
     DiamondAndInnerClassTest(InnerClassDeclArity innerClassDeclArity,
-            TypeQualifierArity declType, TypeQualifierArity siteType, ArgumentListArity argList,
-            TypeArgumentKind[] declTypeArgumentKinds, TypeArgumentKind[] siteTypeArgumentKinds,
-            ArgumentKind[] argumentKinds) {
+            TypeQualifierArity declType, TypeQualifierArity siteType,
+            ArgumentListArity argList, TypeArgumentKind[] declTypeArgumentKinds,
+            TypeArgumentKind[] siteTypeArgumentKinds, ArgumentKind[] argumentKinds) {
         this.innerClassDeclArity = innerClassDeclArity;
         this.declType = declType;
         this.siteType = siteType;
@@ -267,9 +289,9 @@
         public JavaSource() {
             super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
             source = innerClassDeclArity.classDeclStr.replace("#B", bodyTemplate)
-                             .replace("#D", declType.getType(declTypeArgumentKinds))
-                             .replace("#S", siteType.getType(siteTypeArgumentKinds))
-                             .replace("#AL", argList.getArgs(argumentKinds));
+                    .replace("#D", declType.getType(declTypeArgumentKinds))
+                    .replace("#S", siteType.getType(siteTypeArgumentKinds))
+                    .replace("#AL", argList.getArgs(argumentKinds));
         }
 
         @Override
@@ -278,36 +300,39 @@
         }
     }
 
-    void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
-        JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
+    @Override
+    public void run() {
+        JavacTask ct = (JavacTask)comp.getTask(null, fm.get(), diagChecker,
                 null, null, Arrays.asList(source));
         try {
             ct.analyze();
         } catch (Throwable ex) {
-            throw new AssertionError("Error thrown when compiling the following code:\n" + source.getCharContent(true));
+            throw new AssertionError("Error thrown when compiling the following code:\n" +
+                    source.getCharContent(true));
         }
         check();
     }
 
     void check() {
-        checkCount++;
+        checkCount.incrementAndGet();
 
         boolean errorExpected = false;
 
-        TypeArgumentKind[] expectedArgKinds = new TypeArgumentKind[innerClassDeclArity.n];
+        TypeArgumentKind[] expectedArgKinds =
+                new TypeArgumentKind[innerClassDeclArity.n];
 
         for (int i = 0 ; i < innerClassDeclArity.n ; i++) {
             if (!declTypeArgumentKinds[i].compatible(siteTypeArgumentKinds[i])) {
                 errorExpected = true;
                 break;
             }
-            expectedArgKinds[i] = siteTypeArgumentKinds[i] == TypeArgumentKind.DIAMOND ?
+            expectedArgKinds[i] = siteTypeArgumentKinds[i] ==
+                    TypeArgumentKind.DIAMOND ?
                 declTypeArgumentKinds[i] : siteTypeArgumentKinds[i];
         }
 
         if (!errorExpected) {
             for (int i = 0 ; i < innerClassDeclArity.n ; i++) {
-                //System.out.println("check " + expectedArgKinds[i] + " against " + argumentKinds[i]);
                 if (!expectedArgKinds[i].compatible(argumentKinds[i])) {
                     errorExpected = true;
                     break;
@@ -323,7 +348,8 @@
         }
     }
 
-    static class DiagnosticChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
+    static class DiagnosticChecker
+        implements javax.tools.DiagnosticListener<JavaFileObject> {
 
         boolean errorFound;
 
@@ -333,4 +359,5 @@
             }
         }
     }
+
 }
--- a/langtools/test/tools/javac/generics/rawOverride/7062745/GenericOverrideTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/generics/rawOverride/7062745/GenericOverrideTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -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
@@ -24,22 +24,23 @@
 /*
  * @test
  * @bug 7062745
- * @summary  Regression: difference in overload resolution when two methods are maximally specific
+ * @summary  Regression: difference in overload resolution when two methods
+ * are maximally specific
+ * @library ../../../lib
+ * @build JavacTestingAbstractThreadedTest
+ * @run main GenericOverrideTest
  */
 
-import com.sun.source.util.JavacTask;
 import java.net.URI;
 import java.util.Arrays;
 import javax.tools.Diagnostic;
-import javax.tools.JavaCompiler;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
-import javax.tools.StandardJavaFileManager;
-import javax.tools.ToolProvider;
+import com.sun.source.util.JavacTask;
 
-public class GenericOverrideTest {
-
-    static int checkCount = 0;
+public class GenericOverrideTest
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     enum SignatureKind {
         NON_GENERIC(""),
@@ -126,11 +127,6 @@
     }
 
     public static void main(String... args) throws Exception {
-
-        //create default shared JavaCompiler - reused across multiple compilations
-        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
-        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
-
         for (SignatureKind sig1 : SignatureKind.values()) {
             for (ReturnTypeKind rt1 : ReturnTypeKind.values()) {
                 for (TypeArgumentKind ta1 : TypeArgumentKind.values()) {
@@ -141,8 +137,12 @@
                                 if (!ta2.compatibleWith(sig2)) continue;
                                 for (ReturnTypeKind rt3 : ReturnTypeKind.values()) {
                                     for (TypeArgumentKind ta3 : TypeArgumentKind.values()) {
-                                        if (!ta3.compatibleWith(SignatureKind.NON_GENERIC)) continue;
-                                        new GenericOverrideTest(sig1, rt1, ta1, sig2, rt2, ta2, rt3, ta3).run(comp, fm);
+                                        if (!ta3.compatibleWith(SignatureKind.NON_GENERIC))
+                                            continue;
+                                        pool.execute(
+                                                new GenericOverrideTest(sig1,
+                                                rt1, ta1, sig2, rt2,
+                                                ta2, rt3, ta3));
                                     }
                                 }
                             }
@@ -151,7 +151,8 @@
                 }
             }
         }
-        System.out.println("Total check executed: " + checkCount);
+
+        checkAfterExec();
     }
 
     SignatureKind sig1, sig2;
@@ -161,7 +162,8 @@
     DiagnosticChecker diagChecker;
 
     GenericOverrideTest(SignatureKind sig1, ReturnTypeKind rt1, TypeArgumentKind ta1,
-            SignatureKind sig2, ReturnTypeKind rt2, TypeArgumentKind ta2, ReturnTypeKind rt3, TypeArgumentKind ta3) {
+            SignatureKind sig2, ReturnTypeKind rt2, TypeArgumentKind ta2,
+            ReturnTypeKind rt3, TypeArgumentKind ta3) {
         this.sig1 = sig1;
         this.sig2 = sig2;
         this.rt1 = rt1;
@@ -204,19 +206,21 @@
         }
     }
 
-    void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
-        JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
+    @Override
+    public void run() {
+        JavacTask ct = (JavacTask)comp.getTask(null, fm.get(), diagChecker,
                 null, null, Arrays.asList(source));
         try {
             ct.analyze();
         } catch (Throwable ex) {
-            throw new AssertionError("Error thrown when compiling the following code:\n" + source.getCharContent(true));
+            throw new AssertionError("Error thrown when compiling the following code:\n" +
+                    source.getCharContent(true));
         }
         check();
     }
 
     void check() {
-        checkCount++;
+        checkCount.incrementAndGet();
 
         boolean errorExpected = false;
         int mostSpecific = 0;
@@ -234,14 +238,17 @@
         //check that either TA1 <= TA2 or TA2 <= TA1 (unless most specific return found above is raw)
         if (!errorExpected) {
             if (ta1 != ta2) {
-                boolean useStrictCheck = ta1.moreSpecificThan(ta2, true) || ta2.moreSpecificThan(ta1, true);
+                boolean useStrictCheck = ta1.moreSpecificThan(ta2, true) ||
+                        ta2.moreSpecificThan(ta1, true);
                 if (!ta1.moreSpecificThan(ta2, useStrictCheck) &&
                         !ta2.moreSpecificThan(ta1, useStrictCheck)) {
                     errorExpected = true;
                 } else {
                     int mostSpecific2 = ta1.moreSpecificThan(ta2, useStrictCheck) ? 1 : 2;
                     if (mostSpecific != 0 && mostSpecific2 != mostSpecific) {
-                        errorExpected = mostSpecific == 1 ? ta1 != TypeArgumentKind.NONE : ta2 != TypeArgumentKind.NONE;
+                        errorExpected = mostSpecific == 1 ?
+                                ta1 != TypeArgumentKind.NONE :
+                                ta2 != TypeArgumentKind.NONE;
                     } else {
                         mostSpecific = mostSpecific2;
                     }
@@ -273,7 +280,8 @@
         }
     }
 
-    static class DiagnosticChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
+    static class DiagnosticChecker
+        implements javax.tools.DiagnosticListener<JavaFileObject> {
 
         boolean errorFound;
 
@@ -283,4 +291,5 @@
             }
         }
     }
+
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/lambda/BadMethodCall2.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,13 @@
+/**
+ * @test /nodynamiccopyright/
+ * @bug 8004099
+ * @summary Bad compiler diagnostic generated when poly expression is passed to non-existent method
+ * @compile/fail/ref=BadMethodCall2.out -XDrawDiagnostics BadMethodCall2.java
+ */
+class BadMethodCall2 {
+     void test(Object rec) {
+         rec.nonExistent(System.out::println);
+         rec.nonExistent(()->{});
+         rec.nonExistent(true ? "1" : "2");
+     }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/lambda/BadMethodCall2.out	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,4 @@
+BadMethodCall2.java:9:13: compiler.err.cant.resolve.location.args: kindname.method, nonExistent, , @309, (compiler.misc.location.1: kindname.variable, rec, java.lang.Object)
+BadMethodCall2.java:10:13: compiler.err.cant.resolve.location.args: kindname.method, nonExistent, , @356, (compiler.misc.location.1: kindname.variable, rec, java.lang.Object)
+BadMethodCall2.java:11:13: compiler.err.cant.resolve.location.args: kindname.method, nonExistent, , @390, (compiler.misc.location.1: kindname.variable, rec, java.lang.Object)
+3 errors
--- a/langtools/test/tools/javac/lambda/FunctionalInterfaceConversionTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambda/FunctionalInterfaceConversionTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,20 +27,24 @@
  * @summary Add lambda tests
  *  perform several automated checks in lambda conversion, esp. around accessibility
  * @author  Maurizio Cimadamore
+ * @library ../lib
+ * @build JavacTestingAbstractThreadedTest
  * @run main FunctionalInterfaceConversionTest
  */
 
-import com.sun.source.util.JavacTask;
+import java.io.IOException;
 import java.net.URI;
 import java.util.Arrays;
 import javax.tools.Diagnostic;
 import javax.tools.JavaCompiler;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
-import javax.tools.StandardJavaFileManager;
 import javax.tools.ToolProvider;
+import com.sun.source.util.JavacTask;
 
-public class FunctionalInterfaceConversionTest {
+public class FunctionalInterfaceConversionTest
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     enum PackageKind {
         NO_PKG(""),
@@ -139,8 +143,6 @@
     }
 
     public static void main(String[] args) throws Exception {
-        final JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
-        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
         for (PackageKind samPkg : PackageKind.values()) {
             for (ModifierKind modKind : ModifierKind.values()) {
                 for (SamKind samKind : SamKind.values()) {
@@ -150,8 +152,11 @@
                                 for (TypeKind argType : TypeKind.values()) {
                                     for (TypeKind thrownType : TypeKind.values()) {
                                         for (ExprKind exprKind : ExprKind.values()) {
-                                            new FunctionalInterfaceConversionTest(samPkg, modKind, samKind,
-                                                    samMeth, clientMeth, retType, argType, thrownType, exprKind).test(comp, fm);
+                                            pool.execute(
+                                                new FunctionalInterfaceConversionTest(
+                                                    samPkg, modKind, samKind,
+                                                    samMeth, clientMeth, retType,
+                                                    argType, thrownType, exprKind));
                                         }
                                     }
                                 }
@@ -161,6 +166,8 @@
                 }
             }
         }
+
+        checkAfterExec(false);
     }
 
     PackageKind samPkg;
@@ -175,24 +182,30 @@
     DiagnosticChecker dc;
 
     SourceFile samSourceFile = new SourceFile("Sam.java", "#P \n #C") {
+        @Override
         public String toString() {
             return template.replaceAll("#P", samPkg.getPkgDecl()).
-                    replaceAll("#C", samKind.getSam(samMeth.getMethod(retType, argType, thrownType)));
+                    replaceAll("#C", samKind.getSam(
+                    samMeth.getMethod(retType, argType, thrownType)));
         }
     };
 
-    SourceFile pkgClassSourceFile = new SourceFile("PackageClass.java",
-                                                   "#P\n #M class PackageClass extends Exception { }") {
+    SourceFile pkgClassSourceFile =
+            new SourceFile("PackageClass.java",
+                           "#P\n #M class PackageClass extends Exception { }") {
+        @Override
         public String toString() {
             return template.replaceAll("#P", samPkg.getPkgDecl()).
                     replaceAll("#M", modKind.modifier_str);
         }
     };
 
-    SourceFile clientSourceFile = new SourceFile("Client.java",
-                                                 "#I\n abstract class Client { \n" +
-                                                 "  Sam s = #E;\n" +
-                                                 "  #M \n }") {
+    SourceFile clientSourceFile =
+            new SourceFile("Client.java",
+                           "#I\n abstract class Client { \n" +
+                           "  Sam s = #E;\n" +
+                           "  #M \n }") {
+        @Override
         public String toString() {
             return template.replaceAll("#I", samPkg.getImportStat())
                     .replaceAll("#E", exprKind.exprStr)
@@ -200,9 +213,10 @@
         }
     };
 
-    FunctionalInterfaceConversionTest(PackageKind samPkg, ModifierKind modKind, SamKind samKind,
-            MethodKind samMeth, MethodKind clientMeth, TypeKind retType, TypeKind argType,
-            TypeKind thrownType, ExprKind exprKind) {
+    FunctionalInterfaceConversionTest(PackageKind samPkg, ModifierKind modKind,
+            SamKind samKind, MethodKind samMeth, MethodKind clientMeth,
+            TypeKind retType, TypeKind argType, TypeKind thrownType,
+            ExprKind exprKind) {
         this.samPkg = samPkg;
         this.modKind = modKind;
         this.samKind = samKind;
@@ -215,12 +229,20 @@
         this.dc = new DiagnosticChecker();
     }
 
-    void test(JavaCompiler comp, StandardJavaFileManager fm) throws Exception {
-        JavacTask ct = (JavacTask)comp.getTask(null, fm, dc,
-                null, null, Arrays.asList(samSourceFile, pkgClassSourceFile, clientSourceFile));
-        ct.analyze();
+    @Override
+    public void run() {
+        final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
+
+        JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), dc, null, null,
+                Arrays.asList(samSourceFile, pkgClassSourceFile, clientSourceFile));
+        try {
+            ct.analyze();
+        } catch (IOException ex) {
+            throw new AssertionError("Test failing with cause", ex.getCause());
+        }
         if (dc.errorFound == checkSamConversion()) {
-            throw new AssertionError(samSourceFile + "\n\n" + pkgClassSourceFile + "\n\n" + clientSourceFile);
+            throw new AssertionError(samSourceFile + "\n\n" +
+                pkgClassSourceFile + "\n\n" + clientSourceFile);
         }
     }
 
@@ -264,13 +286,16 @@
             return toString();
         }
 
+        @Override
         public abstract String toString();
     }
 
-    static class DiagnosticChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
+    static class DiagnosticChecker
+        implements javax.tools.DiagnosticListener<JavaFileObject> {
 
         boolean errorFound = false;
 
+        @Override
         public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
             if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
                 errorFound = true;
--- a/langtools/test/tools/javac/lambda/LambdaParserTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambda/LambdaParserTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,21 +27,21 @@
  * @bug 8003280
  * @summary Add lambda tests
  *  Add parser support for lambda expressions
+ * @library ../lib
+ * @build JavacTestingAbstractThreadedTest
+ * @run main LambdaParserTest
  */
 
-import com.sun.source.util.JavacTask;
 import java.net.URI;
 import java.util.Arrays;
 import javax.tools.Diagnostic;
-import javax.tools.JavaCompiler;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
-import javax.tools.StandardJavaFileManager;
-import javax.tools.ToolProvider;
+import com.sun.source.util.JavacTask;
 
-public class LambdaParserTest {
-
-    static int checkCount = 0;
+public class LambdaParserTest
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     enum LambdaKind {
         NILARY_EXPR("()->x"),
@@ -173,25 +173,26 @@
     }
 
     public static void main(String... args) throws Exception {
-
-        //create default shared JavaCompiler - reused across multiple compilations
-        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
-        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
-
         for (LambdaKind lk : LambdaKind.values()) {
             for (LambdaParameterKind pk1 : LambdaParameterKind.values()) {
-                if (lk.arity() < 1 && pk1 != LambdaParameterKind.IMPLICIT) continue;
+                if (lk.arity() < 1 && pk1 != LambdaParameterKind.IMPLICIT)
+                    continue;
                 for (LambdaParameterKind pk2 : LambdaParameterKind.values()) {
-                    if (lk.arity() < 2 && pk2 != LambdaParameterKind.IMPLICIT) continue;
+                    if (lk.arity() < 2 && pk2 != LambdaParameterKind.IMPLICIT)
+                        continue;
                     for (ModifierKind mk1 : ModifierKind.values()) {
-                        if (mk1 != ModifierKind.NONE && lk.isShort()) continue;
-                        if (lk.arity() < 1 && mk1 != ModifierKind.NONE) continue;
+                        if (mk1 != ModifierKind.NONE && lk.isShort())
+                            continue;
+                        if (lk.arity() < 1 && mk1 != ModifierKind.NONE)
+                            continue;
                         for (ModifierKind mk2 : ModifierKind.values()) {
-                            if (lk.arity() < 2 && mk2 != ModifierKind.NONE) continue;
+                            if (lk.arity() < 2 && mk2 != ModifierKind.NONE)
+                                continue;
                             for (SubExprKind sk : SubExprKind.values()) {
                                 for (ExprKind ek : ExprKind.values()) {
-                                    new LambdaParserTest(pk1, pk2, mk1, mk2, lk, sk, ek)
-                                            .run(comp, fm);
+                                    pool.execute(
+                                        new LambdaParserTest(pk1, pk2, mk1,
+                                                             mk2, lk, sk, ek));
                                 }
                             }
                         }
@@ -199,7 +200,8 @@
                 }
             }
         }
-        System.out.println("Total check executed: " + checkCount);
+
+        checkAfterExec();
     }
 
     LambdaParameterKind pk1;
@@ -212,8 +214,9 @@
     JavaSource source;
     DiagnosticChecker diagChecker;
 
-    LambdaParserTest(LambdaParameterKind pk1, LambdaParameterKind pk2, ModifierKind mk1,
-            ModifierKind mk2, LambdaKind lk, SubExprKind sk, ExprKind ek) {
+    LambdaParserTest(LambdaParameterKind pk1, LambdaParameterKind pk2,
+            ModifierKind mk1, ModifierKind mk2, LambdaKind lk,
+            SubExprKind sk, ExprKind ek) {
         this.pk1 = pk1;
         this.pk2 = pk2;
         this.mk1 = mk1;
@@ -235,7 +238,8 @@
 
         public JavaSource() {
             super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
-            source = template.replaceAll("#E", ek.expressionString(pk1, pk2, mk1, mk2, lk, sk));
+            source = template.replaceAll("#E",
+                    ek.expressionString(pk1, pk2, mk1, mk2, lk, sk));
         }
 
         @Override
@@ -244,19 +248,20 @@
         }
     }
 
-    void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
-        JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
+    public void run() {
+        JavacTask ct = (JavacTask)comp.getTask(null, fm.get(), diagChecker,
                 null, null, Arrays.asList(source));
         try {
             ct.parse();
         } catch (Throwable ex) {
-            throw new AssertionError("Error thrown when parsing the following source:\n" + source.getCharContent(true));
+            processException(ex);
+            return;
         }
         check();
     }
 
     void check() {
-        checkCount++;
+        checkCount.incrementAndGet();
 
         boolean errorExpected = (lk.arity() > 0 && !mk1.compatibleWith(pk1)) ||
                 (lk.arity() > 1 && !mk2.compatibleWith(pk2));
@@ -275,7 +280,8 @@
         }
     }
 
-    static class DiagnosticChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
+    static class DiagnosticChecker
+        implements javax.tools.DiagnosticListener<JavaFileObject> {
 
         boolean errorFound;
 
@@ -285,4 +291,5 @@
             }
         }
     }
+
 }
--- a/langtools/test/tools/javac/lambda/MethodReferenceParserTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambda/MethodReferenceParserTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,21 +27,21 @@
  * @bug 8003280
  * @summary Add lambda tests
  *  Add parser support for method references
+ * @library ../lib
+ * @build JavacTestingAbstractThreadedTest
+ * @run main MethodReferenceParserTest
  */
 
-import com.sun.source.util.JavacTask;
 import java.net.URI;
 import java.util.Arrays;
 import javax.tools.Diagnostic;
-import javax.tools.JavaCompiler;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
-import javax.tools.StandardJavaFileManager;
-import javax.tools.ToolProvider;
+import com.sun.source.util.JavacTask;
 
-public class MethodReferenceParserTest {
-
-    static int checkCount = 0;
+public class MethodReferenceParserTest
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     enum ReferenceKind {
         METHOD_REF("#Q::#Gm"),
@@ -88,7 +88,8 @@
             this.contextTemplate = contextTemplate;
         }
 
-        String contextString(ExprKind ek, ReferenceKind rk, QualifierKind qk, GenericKind gk, SubExprKind sk) {
+        String contextString(ExprKind ek, ReferenceKind rk, QualifierKind qk,
+                GenericKind gk, SubExprKind sk) {
             return contextTemplate.replaceAll("#E", ek.expressionString(rk, qk, gk, sk));
         }
     }
@@ -165,25 +166,21 @@
     }
 
     public static void main(String... args) throws Exception {
-
-        //create default shared JavaCompiler - reused across multiple compilations
-        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
-        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
-
         for (ReferenceKind rk : ReferenceKind.values()) {
             for (QualifierKind qk : QualifierKind.values()) {
                 for (GenericKind gk : GenericKind.values()) {
                     for (SubExprKind sk : SubExprKind.values()) {
                         for (ExprKind ek : ExprKind.values()) {
                             for (ContextKind ck : ContextKind.values()) {
-                                new MethodReferenceParserTest(rk, qk, gk, sk, ek, ck).run(comp, fm);
+                                pool.execute(new MethodReferenceParserTest(rk, qk, gk, sk, ek, ck));
                             }
                         }
                     }
                 }
             }
         }
-        System.out.println("Total check executed: " + checkCount);
+
+        checkAfterExec();
     }
 
     ReferenceKind rk;
@@ -227,19 +224,21 @@
         }
     }
 
-    void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
-        JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
+    @Override
+    public void run() {
+        JavacTask ct = (JavacTask)comp.getTask(null, fm.get(), diagChecker,
                 null, null, Arrays.asList(source));
         try {
             ct.parse();
         } catch (Throwable ex) {
-            throw new AssertionError("Error thrown when parsing the following source:\n" + source.getCharContent(true));
+            processException(ex);
+            return;
         }
         check();
     }
 
     void check() {
-        checkCount++;
+        checkCount.incrementAndGet();
 
         if (diagChecker.errorFound != rk.erroneous()) {
             throw new Error("invalid diagnostics for source:\n" +
@@ -259,4 +258,5 @@
             }
         }
     }
+
 }
--- a/langtools/test/tools/javac/lambda/TargetType21.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambda/TargetType21.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
     <R,A> void call(SAM3<R,A> sam) { }
 
     void test() {
-        call(x -> { throw new Exception(); }); //ok - resolves to call(SAM1)
+        call(x -> { throw new Exception(); }); //ambiguous
         call(x -> { System.out.println(""); }); //ok - resolves to call(SAM2)
         call(x -> { return (Object) null; }); //error - call(SAM3) is not applicable because of cyclic inference
         call(x -> { return null; }); ////ok - resolves to call(SAM1)
--- a/langtools/test/tools/javac/lambda/TargetType21.out	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambda/TargetType21.out	Tue Jan 22 11:54:16 2013 -0800
@@ -1,3 +1,3 @@
 TargetType21.java:28:9: compiler.err.ref.ambiguous: call, kindname.method, call(TargetType21.SAM1), TargetType21, kindname.method, call(TargetType21.SAM2), TargetType21
-TargetType21.java:30:9: compiler.err.cant.apply.symbols: kindname.method, call, @755,{(compiler.misc.inapplicable.method: kindname.method, TargetType21, call(TargetType21.SAM1), (compiler.misc.no.conforming.assignment.exists: (compiler.misc.incompatible.ret.type.in.lambda: (compiler.misc.inconvertible.types: java.lang.Object, java.lang.String)))),(compiler.misc.inapplicable.method: kindname.method, TargetType21, call(TargetType21.SAM2), (compiler.misc.no.conforming.assignment.exists: (compiler.misc.incompatible.ret.type.in.lambda: (compiler.misc.unexpected.ret.val)))),(compiler.misc.inapplicable.method: kindname.method, TargetType21, <R,A>call(TargetType21.SAM3<R,A>), (compiler.misc.cyclic.inference: A))}
+TargetType21.java:30:9: compiler.err.cant.apply.symbols: kindname.method, call, @737,{(compiler.misc.inapplicable.method: kindname.method, TargetType21, call(TargetType21.SAM1), (compiler.misc.no.conforming.assignment.exists: (compiler.misc.incompatible.ret.type.in.lambda: (compiler.misc.inconvertible.types: java.lang.Object, java.lang.String)))),(compiler.misc.inapplicable.method: kindname.method, TargetType21, call(TargetType21.SAM2), (compiler.misc.no.conforming.assignment.exists: (compiler.misc.incompatible.ret.type.in.lambda: (compiler.misc.unexpected.ret.val)))),(compiler.misc.inapplicable.method: kindname.method, TargetType21, <R,A>call(TargetType21.SAM3<R,A>), (compiler.misc.cyclic.inference: A))}
 2 errors
--- a/langtools/test/tools/javac/lambda/TestInvokeDynamic.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambda/TestInvokeDynamic.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,7 +28,9 @@
  * @bug 8003280
  * @summary Add lambda tests
  *  Add back-end support for invokedynamic
- *
+ * @library ../lib
+ * @build JavacTestingAbstractThreadedTest
+ * @run main TestInvokeDynamic
  */
 
 import com.sun.source.tree.MethodInvocationTree;
@@ -50,6 +52,7 @@
 import com.sun.tools.javac.code.Symbol;
 import com.sun.tools.javac.code.Symbol.MethodSymbol;
 import com.sun.tools.javac.code.Symtab;
+import com.sun.tools.javac.code.Types;
 import com.sun.tools.javac.jvm.Pool;
 import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
 import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
@@ -65,7 +68,6 @@
 
 import javax.tools.Diagnostic;
 import javax.tools.JavaCompiler;
-import javax.tools.JavaFileManager;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
 import javax.tools.StandardJavaFileManager;
@@ -73,69 +75,80 @@
 
 import static com.sun.tools.javac.jvm.ClassFile.*;
 
-public class TestInvokeDynamic {
-
-    static int checkCount = 0;
+public class TestInvokeDynamic
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     enum StaticArgumentKind {
         STRING("Hello!", "String", "Ljava/lang/String;") {
             @Override
             boolean check(CPInfo cpInfo) throws Exception {
                 return (cpInfo instanceof CONSTANT_String_info) &&
-                        ((CONSTANT_String_info)cpInfo).getString().equals(value);
+                        ((CONSTANT_String_info)cpInfo).getString()
+                        .equals(value);
             }
         },
         CLASS(null, "Class<?>", "Ljava/lang/Class;") {
             @Override
             boolean check(CPInfo cpInfo) throws Exception {
                 return (cpInfo instanceof CONSTANT_Class_info) &&
-                        ((CONSTANT_Class_info)cpInfo).getName().equals("java/lang/String");
+                        ((CONSTANT_Class_info)cpInfo).getName()
+                        .equals("java/lang/String");
             }
         },
         INTEGER(1, "int", "I") {
             @Override
             boolean check(CPInfo cpInfo) throws Exception {
                 return (cpInfo instanceof CONSTANT_Integer_info) &&
-                        ((CONSTANT_Integer_info)cpInfo).value == ((Integer)value).intValue();
+                        ((CONSTANT_Integer_info)cpInfo).value ==
+                        ((Integer)value).intValue();
             }
         },
         LONG(1L, "long", "J") {
             @Override
             boolean check(CPInfo cpInfo) throws Exception {
                 return (cpInfo instanceof CONSTANT_Long_info) &&
-                        ((CONSTANT_Long_info)cpInfo).value == ((Long)value).longValue();
+                        ((CONSTANT_Long_info)cpInfo).value ==
+                        ((Long)value).longValue();
             }
         },
         FLOAT(1.0f, "float", "F") {
             @Override
             boolean check(CPInfo cpInfo) throws Exception {
                 return (cpInfo instanceof CONSTANT_Float_info) &&
-                        ((CONSTANT_Float_info)cpInfo).value == ((Float)value).floatValue();
+                        ((CONSTANT_Float_info)cpInfo).value ==
+                        ((Float)value).floatValue();
             }
         },
         DOUBLE(1.0, "double","D") {
             @Override
             boolean check(CPInfo cpInfo) throws Exception {
                 return (cpInfo instanceof CONSTANT_Double_info) &&
-                        ((CONSTANT_Double_info)cpInfo).value == ((Double)value).doubleValue();
+                        ((CONSTANT_Double_info)cpInfo).value ==
+                        ((Double)value).doubleValue();
             }
         },
         METHOD_HANDLE(null, "MethodHandle", "Ljava/lang/invoke/MethodHandle;") {
             @Override
             boolean check(CPInfo cpInfo) throws Exception {
-                if (!(cpInfo instanceof CONSTANT_MethodHandle_info)) return false;
-                CONSTANT_MethodHandle_info handleInfo = (CONSTANT_MethodHandle_info)cpInfo;
+                if (!(cpInfo instanceof CONSTANT_MethodHandle_info))
+                    return false;
+                CONSTANT_MethodHandle_info handleInfo =
+                        (CONSTANT_MethodHandle_info)cpInfo;
                 return handleInfo.getCPRefInfo().getClassName().equals("Array") &&
                         handleInfo.reference_kind == RefKind.REF_invokeVirtual &&
-                        handleInfo.getCPRefInfo().getNameAndTypeInfo().getName().equals("clone") &&
-                        handleInfo.getCPRefInfo().getNameAndTypeInfo().getType().equals("()Ljava/lang/Object;");
+                        handleInfo.getCPRefInfo()
+                        .getNameAndTypeInfo().getName().equals("clone") &&
+                        handleInfo.getCPRefInfo()
+                        .getNameAndTypeInfo().getType().equals("()Ljava/lang/Object;");
             }
         },
         METHOD_TYPE(null, "MethodType", "Ljava/lang/invoke/MethodType;") {
             @Override
             boolean check(CPInfo cpInfo) throws Exception {
                 return (cpInfo instanceof CONSTANT_MethodType_info) &&
-                        ((CONSTANT_MethodType_info)cpInfo).getType().equals("()Ljava/lang/Object;");
+                        ((CONSTANT_MethodType_info)cpInfo).getType()
+                        .equals("()Ljava/lang/Object;");
             }
         };
 
@@ -143,7 +156,8 @@
         String sourceTypeStr;
         String bytecodeTypeStr;
 
-        StaticArgumentKind(Object value, String sourceTypeStr, String bytecodeTypeStr) {
+        StaticArgumentKind(Object value, String sourceTypeStr,
+                String bytecodeTypeStr) {
             this.value = value;
             this.sourceTypeStr = sourceTypeStr;
             this.bytecodeTypeStr = bytecodeTypeStr;
@@ -151,7 +165,7 @@
 
         abstract boolean check(CPInfo cpInfo) throws Exception;
 
-        Object getValue(Symtab syms, Names names) {
+        Object getValue(Symtab syms, Names names, Types types) {
             switch (this) {
                 case STRING:
                 case INTEGER:
@@ -162,7 +176,8 @@
                 case CLASS:
                     return syms.stringType.tsym;
                 case METHOD_HANDLE:
-                    return new Pool.MethodHandle(REF_invokeVirtual, syms.arrayCloneMethod);
+                    return new Pool.MethodHandle(REF_invokeVirtual,
+                            syms.arrayCloneMethod, types);
                 case METHOD_TYPE:
                     return syms.arrayCloneMethod.type;
                 default:
@@ -185,23 +200,21 @@
     }
 
     public static void main(String... args) throws Exception {
-        // Create a single file manager and compiler and reuse it for each compile to save time.
-        StandardJavaFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);
-        final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
         for (StaticArgumentsArity arity : StaticArgumentsArity.values()) {
             if (arity.arity == 0) {
-                new TestInvokeDynamic(arity).compileAndCheck(fm, tool);
+                pool.execute(new TestInvokeDynamic(arity));
             } else {
                 for (StaticArgumentKind sak1 : StaticArgumentKind.values()) {
                     if (arity.arity == 1) {
-                        new TestInvokeDynamic(arity, sak1).compileAndCheck(fm, tool);
+                        pool.execute(new TestInvokeDynamic(arity, sak1));
                     } else {
                         for (StaticArgumentKind sak2 : StaticArgumentKind.values()) {
                             if (arity.arity == 2) {
-                                new TestInvokeDynamic(arity, sak1, sak2).compileAndCheck(fm, tool);
+                                pool.execute(new TestInvokeDynamic(arity, sak1, sak2));
                             } else {
                                 for (StaticArgumentKind sak3 : StaticArgumentKind.values()) {
-                                    new TestInvokeDynamic(arity, sak1, sak2, sak3).compileAndCheck(fm, tool);
+                                    pool.execute(
+                                        new TestInvokeDynamic(arity, sak1, sak2, sak3));
                                 }
                             }
                         }
@@ -210,42 +223,47 @@
             }
         }
 
-        System.out.println("Total checks made: " + checkCount);
+        checkAfterExec();
     }
 
     StaticArgumentsArity arity;
     StaticArgumentKind[] saks;
-    JavaSource source;
     DiagChecker dc;
 
     TestInvokeDynamic(StaticArgumentsArity arity, StaticArgumentKind... saks) {
         this.arity = arity;
         this.saks = saks;
-        source = new JavaSource();
         dc = new DiagChecker();
     }
 
-    void compileAndCheck(JavaFileManager fm, JavaCompiler tool) throws Exception {
-        JavacTaskImpl ct = (JavacTaskImpl)tool.getTask(null, fm, dc,
+    public void run() {
+        int id = checkCount.incrementAndGet();
+        JavaSource source = new JavaSource(id);
+        JavacTaskImpl ct = (JavacTaskImpl)comp.getTask(null, fm.get(), dc,
                 null, null, Arrays.asList(source));
         Context context = ct.getContext();
         Symtab syms = Symtab.instance(context);
         Names names = Names.instance(context);
-        ct.addTaskListener(new Indifier(syms, names));
+        Types types = Types.instance(context);
+        ct.addTaskListener(new Indifier(syms, names, types));
         try {
             ct.generate();
         } catch (Throwable t) {
             t.printStackTrace();
-            throw new AssertionError(String.format("Error thrown when compiling following code\n%s", source.source));
+            throw new AssertionError(
+                    String.format("Error thrown when compiling following code\n%s",
+                    source.source));
         }
         if (dc.diagFound) {
-            throw new AssertionError(String.format("Diags found when compiling following code\n%s\n\n%s", source.source, dc.printDiags()));
+            throw new AssertionError(
+                    String.format("Diags found when compiling following code\n%s\n\n%s",
+                    source.source, dc.printDiags()));
         }
-        verifyBytecode();
+        verifyBytecode(id);
     }
 
-    void verifyBytecode() {
-        File compiledTest = new File("Test.class");
+    void verifyBytecode(int id) {
+        File compiledTest = new File(String.format("Test%d.class", id));
         try {
             ClassFile cf = ClassFile.read(compiledTest);
             Method testMethod = null;
@@ -258,7 +276,8 @@
             if (testMethod == null) {
                 throw new Error("Test method not found");
             }
-            Code_attribute ea = (Code_attribute)testMethod.attributes.get(Attribute.Code);
+            Code_attribute ea =
+                    (Code_attribute)testMethod.attributes.get(Attribute.Code);
             if (testMethod == null) {
                 throw new Error("Code attribute for test() method not found");
             }
@@ -268,10 +287,12 @@
             for (Instruction i : ea.getInstructions()) {
                 if (i.getMnemonic().equals("invokedynamic")) {
                     CONSTANT_InvokeDynamic_info indyInfo =
-                            (CONSTANT_InvokeDynamic_info)cf.constant_pool.get(i.getShort(1));
+                         (CONSTANT_InvokeDynamic_info)cf
+                            .constant_pool.get(i.getShort(1));
                     bsmIdx = indyInfo.bootstrap_method_attr_index;
                     if (!indyInfo.getNameAndTypeInfo().getType().equals("()V")) {
-                        throw new AssertionError("type mismatch for CONSTANT_InvokeDynamic_info");
+                        throw new
+                            AssertionError("type mismatch for CONSTANT_InvokeDynamic_info");
                     }
                 }
             }
@@ -279,34 +300,41 @@
                 throw new Error("Missing invokedynamic in generated code");
             }
 
-            BootstrapMethods_attribute bsm_attr = (BootstrapMethods_attribute)cf.getAttribute(Attribute.BootstrapMethods);
+            BootstrapMethods_attribute bsm_attr =
+                    (BootstrapMethods_attribute)cf
+                    .getAttribute(Attribute.BootstrapMethods);
             if (bsm_attr.bootstrap_method_specifiers.length != 1) {
-                throw new Error("Bad number of method specifiers in BootstrapMethods attribute");
+                throw new Error("Bad number of method specifiers " +
+                        "in BootstrapMethods attribute");
             }
             BootstrapMethods_attribute.BootstrapMethodSpecifier bsm_spec =
                     bsm_attr.bootstrap_method_specifiers[0];
 
             if (bsm_spec.bootstrap_arguments.length != arity.arity) {
-                throw new Error("Bad number of static invokedynamic args in BootstrapMethod attribute");
+                throw new Error("Bad number of static invokedynamic args " +
+                        "in BootstrapMethod attribute");
             }
 
             int count = 0;
             for (StaticArgumentKind sak : saks) {
-                if (!sak.check(cf.constant_pool.get(bsm_spec.bootstrap_arguments[count]))) {
+                if (!sak.check(cf.constant_pool
+                        .get(bsm_spec.bootstrap_arguments[count]))) {
                     throw new Error("Bad static argument value " + sak);
                 }
                 count++;
             }
 
             CONSTANT_MethodHandle_info bsm_handle =
-                    (CONSTANT_MethodHandle_info)cf.constant_pool.get(bsm_spec.bootstrap_method_ref);
+                    (CONSTANT_MethodHandle_info)cf.constant_pool
+                    .get(bsm_spec.bootstrap_method_ref);
 
             if (bsm_handle.reference_kind != RefKind.REF_invokeStatic) {
                 throw new Error("Bad kind on boostrap method handle");
             }
 
             CONSTANT_Methodref_info bsm_ref =
-                    (CONSTANT_Methodref_info)cf.constant_pool.get(bsm_handle.reference_index);
+                    (CONSTANT_Methodref_info)cf.constant_pool
+                    .get(bsm_handle.reference_index);
 
             if (!bsm_ref.getClassInfo().getName().equals("Bootstrap")) {
                 throw new Error("Bad owner of boostrap method");
@@ -316,8 +344,11 @@
                 throw new Error("Bad boostrap method name");
             }
 
-            if (!bsm_ref.getNameAndTypeInfo().getType().equals(asBSMSignatureString())) {
-                throw new Error("Bad boostrap method type" + bsm_ref.getNameAndTypeInfo().getType() + " " + asBSMSignatureString());
+            if (!bsm_ref.getNameAndTypeInfo()
+                    .getType().equals(asBSMSignatureString())) {
+                throw new Error("Bad boostrap method type" +
+                        bsm_ref.getNameAndTypeInfo().getType() + " " +
+                        asBSMSignatureString());
             }
         } catch (Exception e) {
             e.printStackTrace();
@@ -339,20 +370,22 @@
 
         static final String source_template = "import java.lang.invoke.*;\n" +
                 "class Bootstrap {\n" +
-                "   public static CallSite bsm(MethodHandles.Lookup lookup, String name, MethodType methodType #SARGS) {\n" +
+                "   public static CallSite bsm(MethodHandles.Lookup lookup, " +
+                "String name, MethodType methodType #SARGS) {\n" +
                 "       return null;\n" +
                 "   }\n" +
                 "}\n" +
-                "class Test {\n" +
+                "class Test#ID {\n" +
                 "   void m() { }\n" +
                 "   void test() { m(); }\n" +
                 "}";
 
         String source;
 
-        JavaSource() {
+        JavaSource(int id) {
             super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
-            source = source_template.replace("#SARGS", asSignatureString());
+            source = source_template.replace("#SARGS", asSignatureString())
+                    .replace("#ID", String.valueOf(id));
         }
 
         @Override
@@ -378,10 +411,12 @@
         MethodSymbol bsm;
         Symtab syms;
         Names names;
+        Types types;
 
-        Indifier(Symtab syms, Names names) {
+        Indifier(Symtab syms, Names names, Types types) {
             this.syms = syms;
             this.names = names;
+            this.types = types;
         }
 
         @Override
@@ -405,9 +440,10 @@
             if (!oldSym.isConstructor()) {
                 Object[] staticArgs = new Object[arity.arity];
                 for (int i = 0; i < arity.arity ; i++) {
-                    staticArgs[i] = saks[i].getValue(syms, names);
+                    staticArgs[i] = saks[i].getValue(syms, names, types);
                 }
-                ident.sym = new Symbol.DynamicMethodSymbol(oldSym.name, oldSym.owner, REF_invokeStatic, bsm, oldSym.type, staticArgs);
+                ident.sym = new Symbol.DynamicMethodSymbol(oldSym.name,
+                        oldSym.owner, REF_invokeStatic, bsm, oldSym.type, staticArgs);
             }
             return null;
         }
@@ -422,7 +458,8 @@
         }
     }
 
-    static class DiagChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
+    static class DiagChecker
+        implements javax.tools.DiagnosticListener<JavaFileObject> {
 
         boolean diagFound;
         ArrayList<String> diags = new ArrayList<>();
@@ -441,4 +478,5 @@
             return buf.toString();
         }
     }
+
 }
--- a/langtools/test/tools/javac/lambda/methodReferenceExecution/MethodReferenceTestKinds.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambda/methodReferenceExecution/MethodReferenceTestKinds.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/lambda/methodReferenceExecution/MethodReferenceTestSueCase1.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambda/methodReferenceExecution/MethodReferenceTestSueCase1.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/lambda/methodReferenceExecution/MethodReferenceTestSueCase2.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambda/methodReferenceExecution/MethodReferenceTestSueCase2.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/lambda/methodReferenceExecution/MethodReferenceTestSueCase4.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambda/methodReferenceExecution/MethodReferenceTestSueCase4.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/lambda/mostSpecific/StructuralMostSpecificTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambda/mostSpecific/StructuralMostSpecificTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,24 +26,23 @@
  * @bug 8003280
  * @summary Add lambda tests
  *  Automatic test for checking correctness of structural most specific test routine
- * @run main/timeout=360 StructuralMostSpecificTest
+ * @library ../../lib
+ * @build JavacTestingAbstractThreadedTest
+ * @run main/timeout=600 StructuralMostSpecificTest
  */
 
-import com.sun.source.util.JavacTask;
-import com.sun.tools.javac.api.ClientCodeWrapper;
-import com.sun.tools.javac.util.JCDiagnostic;
 import java.net.URI;
 import java.util.Arrays;
 import javax.tools.Diagnostic;
-import javax.tools.JavaCompiler;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
-import javax.tools.StandardJavaFileManager;
-import javax.tools.ToolProvider;
+import com.sun.source.util.JavacTask;
+import com.sun.tools.javac.api.ClientCodeWrapper;
+import com.sun.tools.javac.util.JCDiagnostic;
 
-public class StructuralMostSpecificTest {
-
-    static int checkCount = 0;
+public class StructuralMostSpecificTest
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     enum RetTypeKind {
         SHORT("short"),
@@ -105,7 +104,7 @@
         VOID("return;"),
         SHORT("return (short)0;"),
         INT("return 0;"),
-        INTEGER("return (Integer)null"),
+        INTEGER("return (Integer)null;"),
         NULL("return null;");
 
         String retStr;
@@ -142,11 +141,6 @@
     }
 
     public static void main(String... args) throws Exception {
-
-        //create default shared JavaCompiler - reused across multiple compilations
-        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
-        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
-
         for (LambdaReturnKind lrk : LambdaReturnKind.values()) {
             for (RetTypeKind rk1 : RetTypeKind.values()) {
                 for (RetTypeKind rk2 : RetTypeKind.values()) {
@@ -154,7 +148,9 @@
                         for (ExceptionKind ek2 : ExceptionKind.values()) {
                             for (ArgTypeKind ak11 : ArgTypeKind.values()) {
                                 for (ArgTypeKind ak12 : ArgTypeKind.values()) {
-                                    new StructuralMostSpecificTest(lrk, rk1, rk2, ek1, ek2, ak11, ak12).run(comp, fm);
+                                    pool.execute(
+                                        new StructuralMostSpecificTest(lrk, rk1,
+                                            rk2, ek1, ek2, ak11, ak12));
                                 }
                             }
                         }
@@ -162,7 +158,8 @@
                 }
             }
         }
-        System.out.println("Total check executed: " + checkCount);
+
+        checkAfterExec();
     }
 
     LambdaReturnKind lrk;
@@ -218,20 +215,22 @@
         }
     }
 
-    void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
-        JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
+    public void run() {
+        JavacTask ct = (JavacTask)comp.getTask(null, fm.get(), diagChecker,
                 Arrays.asList("-XDverboseResolution=all,-predef,-internal,-object-init"),
                 null, Arrays.asList(source));
         try {
             ct.analyze();
         } catch (Throwable ex) {
-            throw new AssertionError("Error thron when analyzing the following source:\n" + source.getCharContent(true));
+            throw new
+                AssertionError("Error thron when analyzing the following source:\n" +
+                    source.getCharContent(true));
         }
         check();
     }
 
     void check() {
-        checkCount++;
+        checkCount.incrementAndGet();
 
         if (!lrk.compatibleWith(rt1) || !lrk.compatibleWith(rt2))
             return;
@@ -265,8 +264,8 @@
         }
     }
 
-    boolean moreSpecific(RetTypeKind rk1, RetTypeKind rk2, ExceptionKind ek1, ExceptionKind ek2,
-            ArgTypeKind ak1, ArgTypeKind ak2) {
+    boolean moreSpecific(RetTypeKind rk1, RetTypeKind rk2, ExceptionKind ek1,
+            ExceptionKind ek2, ArgTypeKind ak1, ArgTypeKind ak2) {
         if (!rk1.moreSpecificThan(rk2))
             return false;
 
@@ -276,7 +275,8 @@
         return true;
     }
 
-    static class DiagnosticChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
+    static class DiagnosticChecker
+        implements javax.tools.DiagnosticListener<JavaFileObject> {
 
         boolean ambiguityFound;
         String mostSpecificSig;
@@ -287,12 +287,16 @@
                         diagnostic.getCode().equals("compiler.err.ref.ambiguous")) {
                     ambiguityFound = true;
                 } else if (diagnostic.getKind() == Diagnostic.Kind.NOTE &&
-                        diagnostic.getCode().equals("compiler.note.verbose.resolve.multi")) {
+                        diagnostic.getCode()
+                        .equals("compiler.note.verbose.resolve.multi")) {
                     ClientCodeWrapper.DiagnosticSourceUnwrapper dsu =
-                            (ClientCodeWrapper.DiagnosticSourceUnwrapper)diagnostic;
-                    JCDiagnostic.MultilineDiagnostic mdiag = (JCDiagnostic.MultilineDiagnostic)dsu.d;
+                        (ClientCodeWrapper.DiagnosticSourceUnwrapper)diagnostic;
+                    JCDiagnostic.MultilineDiagnostic mdiag =
+                        (JCDiagnostic.MultilineDiagnostic)dsu.d;
                     int mostSpecificIndex = (Integer)mdiag.getArgs()[2];
-                    mostSpecificSig = ((JCDiagnostic)mdiag.getSubdiagnostics().get(mostSpecificIndex)).getArgs()[1].toString();
+                    mostSpecificSig =
+                        ((JCDiagnostic)mdiag.getSubdiagnostics()
+                            .get(mostSpecificIndex)).getArgs()[1].toString();
                 }
             } catch (RuntimeException t) {
                 t.printStackTrace();
@@ -300,4 +304,5 @@
             }
         }
     }
+
 }
--- a/langtools/test/tools/javac/lambda/typeInference/combo/TypeInferenceComboTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambda/typeInference/combo/TypeInferenceComboTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,22 +25,24 @@
  * @test
  * @bug 8003280
  * @summary Add lambda tests
- *  perform automated checks in type inference in lambda expressions in different contexts
+ *  perform automated checks in type inference in lambda expressions
+ *  in different contexts
+ * @library ../../../lib
+ * @build JavacTestingAbstractThreadedTest
  * @compile  TypeInferenceComboTest.java
  * @run main/timeout=360 TypeInferenceComboTest
  */
 
-import com.sun.source.util.JavacTask;
 import java.net.URI;
 import java.util.Arrays;
 import javax.tools.Diagnostic;
-import javax.tools.JavaCompiler;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
-import javax.tools.ToolProvider;
-import javax.tools.StandardJavaFileManager;
+import com.sun.source.util.JavacTask;
 
-public class TypeInferenceComboTest {
+public class TypeInferenceComboTest
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
     enum Context {
         ASSIGNMENT("SAM#Type s = #LBody;"),
         METHOD_CALL("#GenericDeclKind void method1(SAM#Type s) { }\n" +
@@ -59,27 +61,35 @@
             this.context = context;
         }
 
-        String getContext(SamKind sk, TypeKind samTargetT, Keyword kw, TypeKind parameterT, TypeKind returnT, LambdaKind lk, ParameterKind pk, GenericDeclKind gdk, LambdaBody lb) {
+        String getContext(SamKind sk, TypeKind samTargetT, Keyword kw,
+                TypeKind parameterT, TypeKind returnT, LambdaKind lk,
+                ParameterKind pk, GenericDeclKind gdk, LambdaBody lb) {
             String result = context;
             if (sk == SamKind.GENERIC) {
                 if(this == Context.METHOD_CALL) {
-                    result = result.replaceAll("#GenericDeclKind", gdk.getGenericDeclKind(samTargetT));
+                    result = result.replaceAll("#GenericDeclKind",
+                            gdk.getGenericDeclKind(samTargetT));
                     if(gdk == GenericDeclKind.NON_GENERIC)
-                        result = result.replaceAll("#Type", "<" + samTargetT.typeStr + ">");
+                        result = result.replaceAll("#Type", "<" +
+                                samTargetT.typeStr + ">");
                     else //#GenericDeclKind is <T> or <T extends xxx>
                         result = result.replaceAll("#Type", "<T>");
                 }
                 else {
                     if(kw == Keyword.VOID)
-                        result = result.replaceAll("#Type", "<" + samTargetT.typeStr + ">");
+                        result = result.replaceAll("#Type", "<" +
+                                samTargetT.typeStr + ">");
                     else
-                        result = result.replaceAll("#Type", "<? " + kw.keyStr + " " + samTargetT.typeStr + ">");
+                        result = result.replaceAll("#Type", "<? " + kw.keyStr +
+                                " " + samTargetT.typeStr + ">");
                 }
             }
             else
-                result = result.replaceAll("#Type", "").replaceAll("#GenericDeclKind", "");
+                result = result.replaceAll("#Type", "").
+                        replaceAll("#GenericDeclKind", "");
 
-            return result.replaceAll("#LBody", lb.getLambdaBody(samTargetT, parameterT, returnT, lk, pk));
+            return result.replaceAll("#LBody",
+                    lb.getLambdaBody(samTargetT, parameterT, returnT, lk, pk));
         }
     }
 
@@ -94,8 +104,10 @@
         }
 
         String getSam(TypeKind parameterT, TypeKind returnT) {
-            return sam_str.replaceAll("#ARG", parameterT == TypeKind.VOID ? "" : parameterT.typeStr + " arg")
-                          .replaceAll("#R", returnT.typeStr);
+            return sam_str.replaceAll("#ARG",
+                    parameterT == TypeKind.VOID ?
+                        "" : parameterT.typeStr + " arg")
+                    .replaceAll("#R", returnT.typeStr);
         }
     }
 
@@ -104,7 +116,8 @@
         STRING("String", "\"hello\""),
         INTEGER("Integer", "1"),
         INT("int", "0"),
-        COMPARATOR("java.util.Comparator<String>", "(java.util.Comparator<String>)(a, b) -> a.length()-b.length()"),
+        COMPARATOR("java.util.Comparator<String>",
+                "(java.util.Comparator<String>)(a, b) -> a.length()-b.length()"),
         SAM("SAM2", "null"),
         GENERIC("T", null);
 
@@ -152,8 +165,10 @@
     }
 
     enum LambdaBody {
-        RETURN_VOID("() -> #RET"),//no parameters, return type is one of the TypeKind
-        RETURN_ARG("(#PK arg) -> #RET");//has parameters, return type is one of the TypeKind
+        //no parameters, return type is one of the TypeKind
+        RETURN_VOID("() -> #RET"),
+        //has parameters, return type is one of the TypeKind
+        RETURN_ARG("(#PK arg) -> #RET");
 
         String bodyStr;
 
@@ -161,12 +176,14 @@
             this.bodyStr = bodyStr;
         }
 
-        String getLambdaBody(TypeKind samTargetT, TypeKind parameterT, TypeKind returnT, LambdaKind lk, ParameterKind pk) {
+        String getLambdaBody(TypeKind samTargetT, TypeKind parameterT,
+                TypeKind returnT, LambdaKind lk, ParameterKind pk) {
             String result = bodyStr.replaceAll("#PK", pk.paramTemplate);
 
             if(result.contains("#TYPE")) {
                 if (parameterT == TypeKind.GENERIC && this != RETURN_VOID)
-                    result = result.replaceAll("#TYPE", samTargetT == null? "": samTargetT.typeStr);
+                    result = result.replaceAll("#TYPE",
+                            samTargetT == null? "": samTargetT.typeStr);
                 else
                     result = result.replaceAll("#TYPE", parameterT.typeStr);
             }
@@ -174,9 +191,12 @@
                 return result.replaceAll("#RET", lk.stmt.replaceAll("#VAL", "arg"));
             else {
                 if(returnT != TypeKind.GENERIC)
-                    return result.replaceAll("#RET", lk.stmt.replaceAll("#VAL", (returnT==TypeKind.VOID && lk==LambdaKind.EXPRESSION)? "{}" : returnT.valStr));
+                    return result.replaceAll("#RET", lk.stmt.replaceAll("#VAL",
+                            (returnT==TypeKind.VOID &&
+                            lk==LambdaKind.EXPRESSION) ? "{}" : returnT.valStr));
                 else
-                    return result.replaceAll("#RET", lk.stmt.replaceAll("#VAL", samTargetT.valStr));
+                    return result.replaceAll("#RET",
+                            lk.stmt.replaceAll("#VAL", samTargetT.valStr));
             }
         }
     }
@@ -203,8 +223,10 @@
         }
         else if (lambdaBodyType != LambdaBody.RETURN_ARG)
             return false;
-        if (  genericDeclKind == GenericDeclKind.GENERIC_NOBOUND || genericDeclKind == GenericDeclKind.GENERIC_BOUND ) {
-            if ( parameterType == TypeKind.GENERIC && parameterKind == ParameterKind.IMPLICIT) //cyclic inference
+        if (  genericDeclKind == GenericDeclKind.GENERIC_NOBOUND ||
+                genericDeclKind == GenericDeclKind.GENERIC_BOUND ) {
+            if ( parameterType == TypeKind.GENERIC &&
+                    parameterKind == ParameterKind.IMPLICIT) //cyclic inference
                 return false;
         }
         return true;
@@ -216,7 +238,8 @@
                          "}\n";
     SourceFile samSourceFile = new SourceFile("Sam.java", templateStr) {
         public String toString() {
-            return template.replaceAll("#C", samKind.getSam(parameterType, returnType));
+            return template.replaceAll("#C",
+                    samKind.getSam(parameterType, returnType));
         }
     };
 
@@ -225,22 +248,35 @@
                                                  "    #Context\n" +
                                                  "}") {
         public String toString() {
-            return template.replaceAll("#Context", context.getContext(samKind, samTargetType, keyword, parameterType, returnType, lambdaKind, parameterKind, genericDeclKind, lambdaBodyType));
+            return template.replaceAll("#Context",
+                    context.getContext(samKind, samTargetType, keyword,
+                    parameterType, returnType, lambdaKind, parameterKind,
+                    genericDeclKind, lambdaBodyType));
         }
     };
 
-    void test() throws Exception {
-        System.out.println("kk:");
+    public void run() {
+        outWriter.println("kk:");
         StringBuilder sb = new StringBuilder("SamKind:");
-        sb.append(samKind).append(" SamTargetType:").append(samTargetType).append(" ParameterType:").append(parameterType)
-            .append(" ReturnType:").append(returnType).append(" Context:").append(context).append(" LambdaKind:").append(lambdaKind)
-            .append(" LambdaBodyType:").append(lambdaBodyType).append(" ParameterKind:").append(parameterKind).append(" Keyword:").append(keyword);
-        System.out.println(sb);
+        sb.append(samKind).append(" SamTargetType:")
+            .append(samTargetType).append(" ParameterType:").append(parameterType)
+            .append(" ReturnType:").append(returnType).append(" Context:")
+            .append(context).append(" LambdaKind:").append(lambdaKind)
+            .append(" LambdaBodyType:").append(lambdaBodyType)
+            .append(" ParameterKind:").append(parameterKind).append(" Keyword:")
+            .append(keyword);
+        outWriter.println(sb);
         DiagnosticChecker dc = new DiagnosticChecker();
-        JavacTask ct = (JavacTask)comp.getTask(null, fm, dc, null, null, Arrays.asList(samSourceFile, clientSourceFile));
-        ct.analyze();
+        JavacTask ct = (JavacTask)comp.getTask(null, fm.get(), dc,
+                null, null, Arrays.asList(samSourceFile, clientSourceFile));
+        try {
+            ct.analyze();
+        } catch (Throwable t) {
+            processException(t);
+        }
         if (dc.errorFound == checkTypeInference()) {
-            throw new AssertionError(samSourceFile + "\n\n" + clientSourceFile + "\n" + parameterType + " " + returnType);
+            throw new AssertionError(samSourceFile + "\n\n" +
+                    clientSourceFile + "\n" + parameterType + " " + returnType);
         }
     }
 
@@ -261,7 +297,8 @@
         public abstract String toString();
     }
 
-    static class DiagnosticChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
+    static class DiagnosticChecker
+        implements javax.tools.DiagnosticListener<JavaFileObject> {
 
         boolean errorFound = false;
 
@@ -283,10 +320,9 @@
     Keyword keyword;
     GenericDeclKind genericDeclKind;
 
-    static JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
-    static StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
-
-    TypeInferenceComboTest(SamKind sk, TypeKind samTargetT, TypeKind parameterT, TypeKind returnT, LambdaBody lb, Context c, LambdaKind lk, ParameterKind pk, Keyword kw, GenericDeclKind gdk) {
+    TypeInferenceComboTest(SamKind sk, TypeKind samTargetT, TypeKind parameterT,
+            TypeKind returnT, LambdaBody lb, Context c, LambdaKind lk,
+            ParameterKind pk, Keyword kw, GenericDeclKind gdk) {
         samKind = sk;
         samTargetType = samTargetT;
         parameterType = parameterT;
@@ -308,24 +344,14 @@
                             for(LambdaKind lambdaK : LambdaKind.values()) {
                                 for (SamKind sk : SamKind.values()) {
                                     if (sk == SamKind.NON_GENERIC) {
-                                        if(parameterT != TypeKind.GENERIC && returnT != TypeKind.GENERIC )
-                                            new TypeInferenceComboTest(sk, null, parameterT, returnT, lb, ct, lambdaK, parameterK, null, null).test();
+                                        generateNonGenericSAM(ct, returnT,
+                                                parameterT, lb, parameterK,
+                                                lambdaK, sk);
                                     }
                                     else if (sk == SamKind.GENERIC) {
-                                        for (Keyword kw : Keyword.values()) {
-                                            for (TypeKind samTargetT : TypeKind.values()) {
-                                                if(samTargetT != TypeKind.VOID && samTargetT != TypeKind.INT && samTargetT != TypeKind.GENERIC
-                                                   && (parameterT == TypeKind.GENERIC || returnT == TypeKind.GENERIC)) {
-                                                    if(ct != Context.METHOD_CALL) {
-                                                        new TypeInferenceComboTest(sk, samTargetT, parameterT, returnT, lb, ct, lambdaK, parameterK, kw, null).test();
-                                                    }
-                                                    else {//Context.METHOD_CALL
-                                                        for (GenericDeclKind gdk : GenericDeclKind.values())
-                                                            new TypeInferenceComboTest(sk, samTargetT, parameterT, returnT, lb, ct, lambdaK, parameterK, kw, gdk).test();
-                                                    }
-                                                }
-                                            }
-                                        }
+                                        generateGenericSAM(ct, returnT,
+                                                parameterT, lb, parameterK,
+                                                lambdaK, sk);
                                     }
                                 }
                             }
@@ -334,5 +360,44 @@
                 }
             }
         }
+
+        checkAfterExec(false);
     }
+
+    static void generateNonGenericSAM(Context ct, TypeKind returnT,
+            TypeKind parameterT, LambdaBody lb, ParameterKind parameterK,
+            LambdaKind lambdaK, SamKind sk) {
+        if(parameterT != TypeKind.GENERIC && returnT != TypeKind.GENERIC ) {
+            pool.execute(new TypeInferenceComboTest(sk, null, parameterT,
+                    returnT, lb, ct, lambdaK, parameterK, null, null));
+        }
+    }
+
+    static void generateGenericSAM(Context ct, TypeKind returnT,
+            TypeKind parameterT, LambdaBody lb, ParameterKind parameterK,
+            LambdaKind lambdaK, SamKind sk) {
+        for (Keyword kw : Keyword.values()) {
+            for (TypeKind samTargetT : TypeKind.values()) {
+                if(samTargetT != TypeKind.VOID &&
+                   samTargetT != TypeKind.INT &&
+                   samTargetT != TypeKind.GENERIC &&
+                   (parameterT == TypeKind.GENERIC ||
+                   returnT == TypeKind.GENERIC)) {
+                    if(ct != Context.METHOD_CALL) {
+                        pool.execute(
+                            new TypeInferenceComboTest(sk, samTargetT, parameterT,
+                                returnT, lb, ct, lambdaK, parameterK, kw, null));
+                    } else {//Context.METHOD_CALL
+                        for (GenericDeclKind gdk :
+                                GenericDeclKind.values())
+                            pool.execute(
+                                    new TypeInferenceComboTest(sk, samTargetT,
+                                    parameterT, returnT, lb, ct, lambdaK,
+                                    parameterK, kw, gdk));
+                    }
+                }
+            }
+         }
+    }
+
 }
--- a/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/AttributeInjector.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/AttributeInjector.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/ClassFile.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/ClassFile.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/ClassFilePreprocessor.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/ClassFilePreprocessor.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/ClassToInterfaceConverter.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/ClassToInterfaceConverter.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/Compiler.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/Compiler.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/DirectedClassLoader.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/DirectedClassLoader.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/SourceModel.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/SourceModel.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/TestHarness.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/separate/TestHarness.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/vm/DefaultMethodsTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/vm/DefaultMethodsTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/vm/FDSeparateCompilationTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/lambdaShapes/org/openjdk/tests/vm/FDSeparateCompilationTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/lib/JavacTestingAbstractThreadedTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.atomic.AtomicInteger;
+import javax.tools.JavaCompiler;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.ToolProvider;
+
+/**
+ * An abstract superclass for threaded tests.
+ *
+ * This class will try to read a property named test.concurrency.
+ * The property can be provided by passing this option to jtreg:
+ * -javaoption:-Dtest.concurrency=#
+ *
+ * If the property is not set the class will use a heuristic to determine the
+ * maximum number of threads that can be fired to execute a given test.
+ */
+public abstract class JavacTestingAbstractThreadedTest {
+
+    protected static int getThreadPoolSize() {
+        Integer testConc = Integer.getInteger("test.concurrency");
+        if (testConc != null) return testConc;
+        int cores = Runtime.getRuntime().availableProcessors();
+        return Math.max(2, Math.min(8, cores / 2));
+    }
+
+    protected static void checkAfterExec() throws InterruptedException {
+        checkAfterExec(true);
+    };
+
+    protected static boolean throwAssertionOnError = true;
+
+    protected static boolean printAll = false;
+
+    protected static StringWriter errSWriter = new StringWriter();
+    protected static PrintWriter errWriter = new PrintWriter(errSWriter);
+
+    protected static StringWriter outSWriter = new StringWriter();
+    protected static PrintWriter outWriter = new PrintWriter(outSWriter);
+
+    protected static void checkAfterExec(boolean printCheckCount)
+            throws InterruptedException {
+        pool.shutdown();
+        while (!pool.isTerminated()) {
+            Thread.sleep(10);
+        }
+        if (errCount.get() > 0) {
+            if (throwAssertionOnError) {
+                closePrinters();
+                System.err.println(errSWriter.toString());
+                throw new AssertionError(
+                    String.format("%d errors found", errCount.get()));
+            } else {
+                System.err.println(
+                        String.format("%d errors found", errCount.get()));
+            }
+        } else if (printCheckCount) {
+            outWriter.println("Total check executed: " + checkCount.get());
+        }
+        closePrinters();
+        if (printAll) {
+            System.out.println(errSWriter.toString());
+            System.out.println(outSWriter.toString());
+        }
+    }
+
+    protected static void closePrinters() {
+        errWriter.close();
+        outWriter.close();
+    }
+
+    protected static void processException(Throwable t) {
+        errCount.incrementAndGet();
+        t.printStackTrace(errWriter);
+        pool.shutdown();
+    }
+
+    //number of checks executed
+    protected static AtomicInteger checkCount = new AtomicInteger();
+
+    //number of errors found while running combo tests
+    protected static AtomicInteger errCount = new AtomicInteger();
+
+    //create default shared JavaCompiler - reused across multiple compilations
+    protected static JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
+
+    protected static ExecutorService pool = Executors.newFixedThreadPool(
+            getThreadPoolSize(), new ThreadFactory() {
+        @Override
+        public Thread newThread(Runnable r) {
+            Thread t = new Thread(r);
+            t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
+                @Override
+                public void uncaughtException(Thread t, Throwable e) {
+                    pool.shutdown();
+                    errCount.incrementAndGet();
+                    e.printStackTrace(System.err);
+                }
+            });
+            return t;
+        }
+    });
+
+    /*
+     * File manager is not thread-safe so it cannot be re-used across multiple
+     * threads. However we cache per-thread FileManager to avoid excessive
+     * object creation
+     */
+    protected static final ThreadLocal<StandardJavaFileManager> fm =
+        new ThreadLocal<StandardJavaFileManager>() {
+            @Override protected StandardJavaFileManager initialValue() {
+                return comp.getStandardFileManager(null, null, null);
+            }
+        };
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/main/Option_J_At_Test.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,70 @@
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+/*
+ * 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 8006037
+ * @summary extra space in javac -help for -J and @ options
+ */
+
+public class Option_J_At_Test {
+    public static void main(String... args) throws Exception {
+        new Option_J_At_Test().run();
+    }
+
+    void run() throws Exception {
+        StringWriter sw = new StringWriter();
+        PrintWriter pw = new PrintWriter(sw);
+        String[] help = { "-help" };
+        int rc = com.sun.tools.javac.Main.compile(help, pw);
+        pw.flush();
+        String out = sw.toString();
+        System.out.println(out);
+        check(out, "-J<flag>",     true);
+        check(out, "-J <flag>",    false);
+        check(out, "@<filename>",  true);
+        check(out, "@ <filename>", false);
+        if (errors > 0)
+            throw new Exception(errors + " errors found");
+    }
+
+    void check(String out, String text, boolean expect) {
+        if (out.contains(text) != expect) {
+            if (expect)
+                error("expected string not found: " + text);
+            else
+                error("unexpected string found: " + text);
+        }
+    }
+
+    void error(String msg) {
+        System.err.println("Error: " + msg);
+        errors++;
+    }
+
+    int errors;
+}
--- a/langtools/test/tools/javac/multicatch/7030606/DisjunctiveTypeWellFormednessTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/multicatch/7030606/DisjunctiveTypeWellFormednessTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,19 +25,21 @@
  * @test
  * @bug 7030606
  * @summary Project-coin: multi-catch types should be pairwise disjoint
+ * @library ../../lib
+ * @build JavacTestingAbstractThreadedTest
+ * @run main DisjunctiveTypeWellFormednessTest
  */
 
-import com.sun.source.util.JavacTask;
 import java.net.URI;
 import java.util.Arrays;
 import javax.tools.Diagnostic;
-import javax.tools.JavaCompiler;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
-import javax.tools.StandardJavaFileManager;
-import javax.tools.ToolProvider;
+import com.sun.source.util.JavacTask;
 
-public class DisjunctiveTypeWellFormednessTest {
+public class DisjunctiveTypeWellFormednessTest
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     enum Alternative {
         EXCEPTION("Exception"),
@@ -92,40 +94,37 @@
     }
 
     public static void main(String... args) throws Exception {
-
-        //create default shared JavaCompiler - reused across multiple compilations
-        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
-        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
-
         for (Arity arity : Arity.values()) {
             for (Alternative a1 : Alternative.values()) {
                 if (arity == Arity.ONE) {
-                    new DisjunctiveTypeWellFormednessTest(a1).run(comp, fm);
+                    pool.execute(new DisjunctiveTypeWellFormednessTest(a1));
                     continue;
                 }
                 for (Alternative a2 : Alternative.values()) {
                     if (arity == Arity.TWO) {
-                        new DisjunctiveTypeWellFormednessTest(a1, a2).run(comp, fm);
+                        pool.execute(new DisjunctiveTypeWellFormednessTest(a1, a2));
                         continue;
                     }
                     for (Alternative a3 : Alternative.values()) {
                         if (arity == Arity.THREE) {
-                            new DisjunctiveTypeWellFormednessTest(a1, a2, a3).run(comp, fm);
+                            pool.execute(new DisjunctiveTypeWellFormednessTest(a1, a2, a3));
                             continue;
                         }
                         for (Alternative a4 : Alternative.values()) {
                             if (arity == Arity.FOUR) {
-                                new DisjunctiveTypeWellFormednessTest(a1, a2, a3, a4).run(comp, fm);
+                                pool.execute(new DisjunctiveTypeWellFormednessTest(a1, a2, a3, a4));
                                 continue;
                             }
                             for (Alternative a5 : Alternative.values()) {
-                                new DisjunctiveTypeWellFormednessTest(a1, a2, a3, a4, a5).run(comp, fm);
+                                pool.execute(new DisjunctiveTypeWellFormednessTest(a1, a2, a3, a4, a5));
                             }
                         }
                     }
                 }
             }
         }
+
+        checkAfterExec(false);
     }
 
     Alternative[] alternatives;
@@ -159,10 +158,16 @@
         }
     }
 
-    void run(JavaCompiler tool, StandardJavaFileManager fm) throws Exception {
-        JavacTask ct = (JavacTask)tool.getTask(null, fm, diagChecker,
+    @Override
+    public void run() {
+        JavacTask ct = (JavacTask)comp.getTask(null, fm.get(), diagChecker,
                 null, null, Arrays.asList(source));
-        ct.analyze();
+        try {
+            ct.analyze();
+        } catch (Throwable t) {
+            processException(t);
+            return;
+        }
         check();
     }
 
@@ -202,4 +207,5 @@
             }
         }
     }
+
 }
--- a/langtools/test/tools/javac/multicatch/model/ModelChecker.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/multicatch/model/ModelChecker.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6993963 7025809
  * @summary Project Coin: Use precise exception analysis for effectively final catch parameters
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor ModelChecker
  * @compile -processor ModelChecker Model01.java
  */
--- a/langtools/test/tools/javac/nativeHeaders/javahComparison/CompareTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/nativeHeaders/javahComparison/CompareTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007,2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/langtools/test/tools/javac/options/T7022337.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/options/T7022337.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @test
  * @bug 7022337
  * @summary repeated warnings about bootclasspath not set
- * @library ../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor T7022337
  * @run main T7022337
  */
--- a/langtools/test/tools/javac/plugin/showtype/ShowTypePlugin.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/plugin/showtype/ShowTypePlugin.java	Tue Jan 22 11:54:16 2013 -0800
@@ -41,7 +41,7 @@
         return "showtype";
     }
 
-    public void call(JavacTask task, String... args) {
+    public void init(JavacTask task, String... args) {
         Pattern pattern = null;
         if (args.length == 1)
             pattern = Pattern.compile(args[0]);
--- a/langtools/test/tools/javac/plugin/showtype/Test.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/plugin/showtype/Test.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,22 +1,3 @@
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.nio.charset.Charset;
-import java.nio.file.Files;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Locale;
-import java.util.Objects;
-import javax.tools.JavaCompiler;
-import javax.tools.JavaFileManager;
-import javax.tools.JavaFileObject;
-import javax.tools.StandardJavaFileManager;
-import javax.tools.StandardLocation;
-import javax.tools.ToolProvider;
-
 /*
  * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@@ -42,10 +23,28 @@
 
 /**
  *  @test
- *  @bug 8001098
+ *  @bug 8001098 8004961
  *  @summary Provide a simple light-weight "plug-in" mechanism for javac
  */
 
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Objects;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileManager;
+import javax.tools.JavaFileObject;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.StandardLocation;
+import javax.tools.ToolProvider;
+
 public class Test {
     public static void main(String... args) throws Exception {
         new Test().run();
--- a/langtools/test/tools/javac/processing/6348499/T6348499.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/6348499/T6348499.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6441871
  * @summary javac crashes at com.sun.tools.javac.jvm.ClassReader$BadClassFile
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor A
  * @run main T6348499
  */
--- a/langtools/test/tools/javac/processing/6359313/T6359313.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/6359313/T6359313.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6359313
  * @summary error compiling annotated package
  * @author  Peter von der Ah\u00e9
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile T6359313.java
  * @compile -processor T6359313 package-info.java Foo.java
--- a/langtools/test/tools/javac/processing/6365040/T6365040.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/6365040/T6365040.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6365040 6358129
  * @summary Test -processor foo,bar,baz
  * @author  Joseph D. Darcy
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile ProcFoo.java
  * @compile ProcBar.java
--- a/langtools/test/tools/javac/processing/6413690/T6413690.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/6413690/T6413690.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6413690 6380018
  * @summary JavacProcessingEnvironment does not enter trees from preceding rounds
  * @author  Peter von der Ah\u00e9
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile T6413690.java
  * @compile -XDfatalEnterError -verbose -processor T6413690 src/Super.java TestMe.java
--- a/langtools/test/tools/javac/processing/6414633/T6414633.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/6414633/T6414633.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6414633 6440109
  * @summary Only the first processor message at a source location is reported
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build    JavacTestingAbstractProcessor A T6414633
  * @run main T6414633
  */
--- a/langtools/test/tools/javac/processing/6430209/T6430209.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/6430209/T6430209.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6441871
  * @summary spurious compiler error elicited by packageElement.getEnclosedElements()
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor b6341534
  * @run main T6430209
  */
--- a/langtools/test/tools/javac/processing/6499119/ClassProcessor.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/6499119/ClassProcessor.java	Tue Jan 22 11:54:16 2013 -0800
@@ -32,7 +32,7 @@
  * @test
  * @bug 6499119
  * @summary Created package-info class file modeled improperly
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile ClassProcessor.java package-info.java
  * @compile/process -cp . -processor ClassProcessor -Akind=java  java.lang.Object
--- a/langtools/test/tools/javac/processing/6511613/clss41701.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/6511613/clss41701.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6511613
  * @summary javac unexpectedly doesn't fail in some cases if an annotation processor specified
  *
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor DummyProcessor
  * @compile/fail clss41701.java
  * @compile/fail -processor DummyProcessor clss41701.java
--- a/langtools/test/tools/javac/processing/6512707/T6512707.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/6512707/T6512707.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6512707
  * @summary "incompatible types" after (unrelated) annotation processing
  * @author  Peter Runge
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile T6512707.java
  * @compile -processor T6512707 TestAnnotation.java
--- a/langtools/test/tools/javac/processing/6634138/T6634138.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/6634138/T6634138.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6634138
  * @author  Joseph D. Darcy
  * @summary Verify source files output after processing is over are compiled
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile T6634138.java
  * @compile -processor T6634138 Dummy.java
--- a/langtools/test/tools/javac/processing/6994946/SemanticErrorTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/6994946/SemanticErrorTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -2,7 +2,7 @@
  * @test /nodynamiccopyright/
  * @bug 6994946
  * @summary option to specify only syntax errors as unrecoverable
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor TestProcessor
  * @compile/fail/ref=SemanticErrorTest.1.out -XDrawDiagnostics                                  -processor TestProcessor SemanticErrorTest.java
  * @compile/fail/ref=SemanticErrorTest.2.out -XDrawDiagnostics -XDonlySyntaxErrorsUnrecoverable -processor TestProcessor SemanticErrorTest.java
--- a/langtools/test/tools/javac/processing/6994946/SyntaxErrorTest.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/6994946/SyntaxErrorTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -2,7 +2,7 @@
  * @test /nodynamiccopyright/
  * @bug 6994946
  * @summary option to specify only syntax errors as unrecoverable
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor TestProcessor
  * @compile/fail/ref=SyntaxErrorTest.out -XDrawDiagnostics                                  -processor TestProcessor SyntaxErrorTest.java
  * @compile/fail/ref=SyntaxErrorTest.out -XDrawDiagnostics -XDonlySyntaxErrorsUnrecoverable -processor TestProcessor SyntaxErrorTest.java
--- a/langtools/test/tools/javac/processing/T6920317.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/T6920317.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6920317
  * @summary package-info.java file has to be specified on the javac cmdline, else it will not be avail
- * @library ../lib
+ * @library /tools/javac/lib
  */
 
 import java.io.*;
--- a/langtools/test/tools/javac/processing/T7196462.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/T7196462.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 7196462
  * @summary JavacProcessingEnvironment should tolerate BasicJavacTask
- * @library ../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor T7196462
  * @compile/process -processor T7196462 T7196462.java
  */
--- a/langtools/test/tools/javac/processing/TestWarnErrorCount.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/TestWarnErrorCount.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @test
  * @bug 7022337
  * @summary repeated warnings about bootclasspath not set
- * @library ../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor TestWarnErrorCount
  * @run main TestWarnErrorCount
  */
--- a/langtools/test/tools/javac/processing/environment/TestSourceVersion.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/environment/TestSourceVersion.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6402506
  * @summary Test that getSourceVersion works properly
  * @author  Joseph D. Darcy
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile TestSourceVersion.java
  * @compile -processor TestSourceVersion -proc:only -source 1.2 -AExpectedVersion=RELEASE_2 HelloWorld.java
--- a/langtools/test/tools/javac/processing/environment/round/TestContext.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/environment/round/TestContext.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6988836
  * @summary A new JavacElements is created for each round of annotation processing
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor TestContext
  * @compile/process -processor TestContext -XprintRounds TestContext
  */
--- a/langtools/test/tools/javac/processing/environment/round/TestElementsAnnotatedWith.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/environment/round/TestElementsAnnotatedWith.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6397298 6400986 6425592 6449798 6453386 6508401 6498938 6911854
  * @summary Tests that getElementsAnnotatedWith works properly.
  * @author  Joseph D. Darcy
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile TestElementsAnnotatedWith.java
  * @compile InheritedAnnotation.java
--- a/langtools/test/tools/javac/processing/errors/TestErrorCount.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/errors/TestErrorCount.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6988079
  * @summary Errors reported via Messager.printMessage(ERROR,"error message") are not tallied correctly
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor TestErrorCount
  * @compile/fail/ref=TestErrorCount.out -XDrawDiagnostics -processor TestErrorCount TestErrorCount.java
  */
--- a/langtools/test/tools/javac/processing/errors/TestFatalityOfParseErrors.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/errors/TestFatalityOfParseErrors.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6403459
  * @summary Test that generating programs with syntax errors is a fatal condition
  * @author  Joseph D. Darcy
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor
  * @compile TestReturnCode.java
  * @compile TestFatalityOfParseErrors.java
--- a/langtools/test/tools/javac/processing/errors/TestOptionSyntaxErrors.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/errors/TestOptionSyntaxErrors.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6406212
  * @summary Test that annotation processor options with illegal syntax are rejected
  * @author  Joseph D. Darcy
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor CompileFail
  * @compile TestOptionSyntaxErrors.java
  * @run main CompileFail CMDERR -A TestOptionSyntaxErrors.java
--- a/langtools/test/tools/javac/processing/errors/TestParseErrors/TestParseErrors.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/errors/TestParseErrors/TestParseErrors.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6988407
  * @summary javac crashes running processor on errant code; it used to print error message
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor TestParseErrors
  * @compile/fail/ref=TestParseErrors.out -XDrawDiagnostics -proc:only -processor TestParseErrors ParseErrors.java
  */
--- a/langtools/test/tools/javac/processing/errors/TestReturnCode.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/errors/TestReturnCode.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6403468
  * @summary Test that an erroneous return code results from raising an error.
  * @author  Joseph D. Darcy
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor CompileFail
  * @compile TestReturnCode.java
  *
--- a/langtools/test/tools/javac/processing/filer/TestFilerConstraints.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/filer/TestFilerConstraints.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6380018 6453386 6457283
  * @summary Test that the constraints guaranteed by the Filer and maintained
  * @author  Joseph D. Darcy
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build TestFilerConstraints
  * @compile -encoding iso-8859-1 -processor TestFilerConstraints -proc:only TestFilerConstraints.java
  */
--- a/langtools/test/tools/javac/processing/filer/TestGetResource.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/filer/TestGetResource.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6380018 6449798
  * @summary Test Filer.getResource
  * @author  Joseph D. Darcy
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build  JavacTestingAbstractProcessor TestGetResource
  * @compile -processor TestGetResource -proc:only -Aphase=write TestGetResource.java
  * @compile -processor TestGetResource -proc:only -Aphase=read  TestGetResource.java
--- a/langtools/test/tools/javac/processing/filer/TestGetResource2.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/filer/TestGetResource2.java	Tue Jan 22 11:54:16 2013 -0800
@@ -24,7 +24,7 @@
 /* @test
  * @bug 6929404
  * @summary Filer.getResource(SOURCE_PATH, ...) does not work when -sourcepath contains >1 entry
- * @library ../../lib
+ * @library /tools/javac/lib
  */
 
 import java.io.*;
--- a/langtools/test/tools/javac/processing/filer/TestInvalidRelativeNames.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/filer/TestInvalidRelativeNames.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6502392
  * @summary Invalid relative names for Filer.createResource and Filer.getResource
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile TestInvalidRelativeNames.java
  * @compile/process -processor TestInvalidRelativeNames java.lang.Object
--- a/langtools/test/tools/javac/processing/filer/TestLastRound.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/filer/TestLastRound.java	Tue Jan 22 11:54:16 2013 -0800
@@ -24,7 +24,7 @@
 /*
  * @test 6966604
  * @summary JavacFiler not correctly notified of lastRound
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile TestLastRound.java
  * @compile/fail/ref=TestLastRound.out -XDrawDiagnostics -Werror -proc:only -processor TestLastRound TestLastRound.java
--- a/langtools/test/tools/javac/processing/filer/TestPackageInfo.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/filer/TestPackageInfo.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6380018 6392177 6993311
  * @summary Test the ability to create and process package-info.java files
  * @author  Joseph D. Darcy
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile TestPackageInfo.java
  * @compile -processor TestPackageInfo -proc:only foo/bar/package-info.java TestPackageInfo.java
--- a/langtools/test/tools/javac/processing/filer/TestValidRelativeNames.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/filer/TestValidRelativeNames.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6999891
  * @summary Test valid relative names for Filer.createResource and Filer.getResource
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile TestValidRelativeNames.java
  * @compile/process -processor TestValidRelativeNames -Amode=create java.lang.Object
--- a/langtools/test/tools/javac/processing/messager/6362067/T6362067.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/messager/6362067/T6362067.java	Tue Jan 22 11:54:16 2013 -0800
@@ -2,7 +2,7 @@
  * @test  /nodynamiccopyright/
  * @bug     6362067
  * @summary Messager methods do not print out source position information
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor T6362067
  * @compile -processor T6362067 -proc:only T6362067.java
  * @compile/ref=T6362067.out -XDrawDiagnostics -processor T6362067 -proc:only T6362067.java
--- a/langtools/test/tools/javac/processing/messager/MessagerBasics.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/messager/MessagerBasics.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6341173 6341072
  * @summary Test presence of Messager methods
  * @author  Joseph D. Darcy
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile MessagerBasics.java
  * @compile -processor MessagerBasics -proc:only MessagerBasics.java
--- a/langtools/test/tools/javac/processing/model/6194785/T6194785.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/6194785/T6194785.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6194785
  * @summary ParameterDeclaration.getSimpleName does not return actual name from class files
  * @author  Peter von der Ah\u00e9
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile -g T6194785.java T6194785a.java
  * @compile -processor T6194785 foo.T6194785a T6194785.java
--- a/langtools/test/tools/javac/processing/model/6341534/T6341534.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/6341534/T6341534.java	Tue Jan 22 11:54:16 2013 -0800
@@ -27,7 +27,7 @@
  * @summary PackageElement.getEnclosedElements results in NullPointerException from parse(JavaCompiler.java:429)
  * @author  Steve Sides
  * @author  Peter von der Ahe
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile T6341534.java
  * @compile -proc:only -processor T6341534 dir/package-info.java
--- a/langtools/test/tools/javac/processing/model/element/TestAnonClassNames.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestAnonClassNames.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6449781 6930508
  * @summary Test that reported names of anonymous classes are non-null.
  * @author  Joseph D. Darcy
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor TestAnonSourceNames
  * @compile -processor TestAnonSourceNames TestAnonClassNames.java
  * @run main TestAnonClassNames
--- a/langtools/test/tools/javac/processing/model/element/TestElement.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestElement.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6453386
  * @summary Test basic properties of javax.lang.element.Element
  * @author  Joseph D. Darcy
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor TestElement
  * @compile -processor TestElement -proc:only TestElement.java
  */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/processing/model/element/TestExecutableElement.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8005046
+ * @summary Test basic properties of javax.lang.element.Element
+ * @author  Joseph D. Darcy
+ * @library /tools/javac/lib
+ * @build   JavacTestingAbstractProcessor TestExecutableElement
+ * @compile -processor TestExecutableElement -proc:only TestExecutableElement.java
+ */
+
+import java.lang.annotation.*;
+import java.util.Formatter;
+import java.util.Set;
+import java.util.Objects;
+import javax.annotation.processing.*;
+import javax.lang.model.SourceVersion;
+import static javax.lang.model.SourceVersion.*;
+import javax.lang.model.element.*;
+import javax.lang.model.util.*;
+import static javax.lang.model.util.ElementFilter.*;
+import static javax.tools.Diagnostic.Kind.*;
+import static javax.tools.StandardLocation.*;
+
+/**
+ * Test some basic workings of javax.lang.element.ExecutableElement
+ */
+public class TestExecutableElement extends JavacTestingAbstractProcessor implements ProviderOfDefault {
+    @IsDefault(false)
+    public boolean process(Set<? extends TypeElement> annotations,
+                           RoundEnvironment roundEnv) {
+        int errors = 0;
+        if (!roundEnv.processingOver()) {
+            boolean hasRun = false;
+            for (Element element : roundEnv.getRootElements()) {
+                for (ExecutableElement method : methodsIn(element.getEnclosedElements())) {
+                    hasRun = true;
+                    errors += checkIsDefault(method);
+                }
+            }
+
+            if (!hasRun) {
+                messager.printMessage(ERROR, "No test cases run; test fails.");
+            }
+        }
+        return true;
+    }
+
+    @IsDefault(false)
+    int checkIsDefault(ExecutableElement method) {
+        System.out.println("Testing " + method);
+        IsDefault expectedIsDefault = method.getAnnotation(IsDefault.class);
+
+        boolean expectedDefault = (expectedIsDefault != null) ?
+            expectedIsDefault.value() :
+            false;
+
+        boolean methodIsDefault = method.isDefault();
+
+        if (methodIsDefault != expectedDefault) {
+            messager.printMessage(ERROR,
+                                  new Formatter().format("Unexpected Executable.isDefault result: got %s, expected %s",
+                                                         expectedDefault,
+                                                         methodIsDefault).toString(),
+                                  method);
+            return 1;
+        }
+        return 0;
+    }
+}
+
+/**
+ * Expected value of the ExecutableElement.isDefault method.
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.METHOD)
+@interface IsDefault {
+    boolean value();
+}
+
+/**
+ * Test interface to provide a default method.
+ */
+interface ProviderOfDefault {
+    @IsDefault(false)
+    boolean process(Set<? extends TypeElement> annotations,
+                    RoundEnvironment roundEnv);
+
+    @IsDefault(true)
+    default void quux() {};
+}
--- a/langtools/test/tools/javac/processing/model/element/TestMissingElement/TestMissingElement.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestMissingElement/TestMissingElement.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @test
  * @bug 6639645 7026414 7025809
  * @summary Modeling type implementing missing interfaces
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor TestMissingElement
  * @compile -proc:only -XprintRounds -processor TestMissingElement InvalidSource.java
  */
--- a/langtools/test/tools/javac/processing/model/element/TestMissingElement2/TestMissingClass.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestMissingElement2/TestMissingClass.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6639645
  * @summary Modeling type implementing missing interfaces
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor Generator
  * @compile -XprintRounds -processor Generator TestMissingClass.java
  * @run main TestMissingClass
--- a/langtools/test/tools/javac/processing/model/element/TestMissingElement2/TestMissingGenericClass1.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestMissingElement2/TestMissingGenericClass1.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6639645
  * @summary Modeling type implementing missing interfaces
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @clean MissingGenericClass1
  * @build JavacTestingAbstractProcessor Generator
  * @compile -XprintRounds -processor Generator TestMissingGenericClass1.java
--- a/langtools/test/tools/javac/processing/model/element/TestMissingElement2/TestMissingGenericClass2.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestMissingElement2/TestMissingGenericClass2.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6639645
  * @summary Modeling type implementing missing interfaces
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @clean MissingGenericClass2
  * @build JavacTestingAbstractProcessor Generator
  * @compile -XprintRounds -processor Generator TestMissingGenericClass2.java
--- a/langtools/test/tools/javac/processing/model/element/TestMissingElement2/TestMissingGenericInterface1.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestMissingElement2/TestMissingGenericInterface1.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6639645
  * @summary Modeling type implementing missing interfaces
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @clean MissingGenericInterface1
  * @build JavacTestingAbstractProcessor Generator
  * @compile -XprintRounds -processor Generator TestMissingGenericInterface1.java
--- a/langtools/test/tools/javac/processing/model/element/TestMissingElement2/TestMissingGenericInterface2.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestMissingElement2/TestMissingGenericInterface2.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6639645
  * @summary Modeling type implementing missing interfaces
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @clean MissingGenericInterface2
  * @build JavacTestingAbstractProcessor Generator
  * @compile -XprintRounds -processor Generator TestMissingGenericInterface2.java
--- a/langtools/test/tools/javac/processing/model/element/TestMissingElement2/TestMissingInterface.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestMissingElement2/TestMissingInterface.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6639645
  * @summary Modeling type implementing missing interfaces
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor Generator
  * @compile -XprintRounds -processor Generator TestMissingInterface.java
  * @run main TestMissingInterface
--- a/langtools/test/tools/javac/processing/model/element/TestNames.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestNames.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6380016
  * @summary Test that the constraints guaranteed by the Filer and maintained
  * @author  Joseph D. Darcy
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor TestNames
  * @compile -processor TestNames -proc:only TestNames.java
  */
--- a/langtools/test/tools/javac/processing/model/element/TestPackageElement.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestPackageElement.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6449798 6399404
  * @summary Test basic workings of PackageElement
  * @author  Joseph D. Darcy
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor TestPackageElement
  * @compile -processor TestPackageElement -proc:only TestPackageElement.java
  */
--- a/langtools/test/tools/javac/processing/model/element/TestResourceElement.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestResourceElement.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6967842
  * @summary Element not returned from tree API for ARM resource variables.
  * @author A. Sundararajan
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor TestResourceElement
  * @compile -processor TestResourceElement -proc:only TestResourceElement.java
  */
--- a/langtools/test/tools/javac/processing/model/element/TestResourceVariable.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestResourceVariable.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug  6911256 6964740 6967842 6961571 7025809
  * @summary Test that the resource variable kind is appropriately set
  * @author  Joseph D. Darcy
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor TestResourceVariable
  * @compile -processor TestResourceVariable -proc:only TestResourceVariable.java
  */
--- a/langtools/test/tools/javac/processing/model/element/TestTypeParameter.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TestTypeParameter.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6505047
  * @summary javax.lang.model.element.Element.getEnclosingElement() doesn't return null for type parameter
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor TestTypeParameter
  * @compile -processor TestTypeParameter -proc:only TestTypeParameter.java
  */
--- a/langtools/test/tools/javac/processing/model/element/TypeParamBounds.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/element/TypeParamBounds.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6423972
  * @summary Tests TypeParameter.getBounds.
  * @author  Scott Seligman
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor TypeParamBounds
  * @compile -processor TypeParamBounds -proc:only TypeParamBounds.java
  */
--- a/langtools/test/tools/javac/processing/model/type/MirroredTypeEx/OverEager.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/type/MirroredTypeEx/OverEager.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6362178
  * @summary MirroredType[s]Exception shouldn't be created too eagerly
  * @author  Scott Seligman
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor
  * @compile -g OverEager.java
  * @compile -processor OverEager -proc:only OverEager.java
--- a/langtools/test/tools/javac/processing/model/type/MirroredTypeEx/Plurality.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/type/MirroredTypeEx/Plurality.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug     6519115
  * @summary Verify MirroredTypeException vs MirroredTypesException is thrown
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor
  * @compile Plurality.java
  * @compile -processor Plurality -proc:only Plurality.java
--- a/langtools/test/tools/javac/processing/model/type/NoTypes.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/type/NoTypes.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6418666 6423973 6453386 7025809
  * @summary Test the NoTypes: VOID, PACKAGE, NONE
  * @author  Scott Seligman
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor
  * @compile -g NoTypes.java
  * @compile -processor NoTypes -proc:only NoTypes.java
--- a/langtools/test/tools/javac/processing/model/type/TestUnionType.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/type/TestUnionType.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug     7029150 7025809
  * @summary Test support for union types
- * @library ../../../lib
+ * @library /tools/javac/lib
  */
 
 import java.net.URI;
--- a/langtools/test/tools/javac/processing/model/util/BinaryName.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/util/BinaryName.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6346251
  * @summary Test Elements.getBinaryName
  * @author  Scott Seligman
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor BinaryName
  * @compile -processor BinaryName -proc:only BinaryName.java
  */
--- a/langtools/test/tools/javac/processing/model/util/GetTypeElemBadArg.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/util/GetTypeElemBadArg.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6346506 6408241
  * @summary getTypeElement should tolerate a type that can't be found
  * @author  Scott Seligman
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor GetTypeElemBadArg
  * @compile -processor GetTypeElemBadArg -proc:only GetTypeElemBadArg.java
  */
--- a/langtools/test/tools/javac/processing/model/util/NoSupers.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/util/NoSupers.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6346453
  * @summary directSupertypes should return empty list if arg has no supertypes
  * @author  Scott Seligman
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor NoSupers
  * @compile -processor NoSupers -proc:only NoSupers.java
  */
--- a/langtools/test/tools/javac/processing/model/util/OverridesSpecEx.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/util/OverridesSpecEx.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6453386
  * @summary Verify that example code in Elements.overrides works as spec'ed.
  * @author  Scott Seligman
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor
  * @compile -g OverridesSpecEx.java
  * @compile -processor OverridesSpecEx -proc:only OverridesSpecEx.java
--- a/langtools/test/tools/javac/processing/model/util/TypesBadArg.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/util/TypesBadArg.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6345812
  * @summary Validate argument kinds in Types utilities
  * @author  Scott Seligman
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor TypesBadArg
  * @compile -processor TypesBadArg -proc:only TypesBadArg.java
  */
--- a/langtools/test/tools/javac/processing/model/util/deprecation/TestDeprecation.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/util/deprecation/TestDeprecation.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,7 +26,7 @@
  * @bug 6392818
  * @summary Tests Elements.isDeprecated(Element)
  * @author  Joseph D. Darcy
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor
  * @compile TestDeprecation.java
  * @compile -processor TestDeprecation -proc:only Dep1.java
--- a/langtools/test/tools/javac/processing/model/util/directSupersOfErr/DirectSupersOfErr.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/util/directSupersOfErr/DirectSupersOfErr.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug     6346973
  * @summary directSupertypes(t) should not return t
  * @author  Scott Seligman
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor DirectSupersOfErr
  * @compile -processor DirectSupersOfErr -proc:only C1.java
  */
--- a/langtools/test/tools/javac/processing/model/util/elements/TestGetConstantExpression.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/util/elements/TestGetConstantExpression.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6471577 6517779
  * @summary Test Elements.getConstantExpression
  * @author  Joseph D. Darcy
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor TestGetConstantExpression
  * @compile -processor TestGetConstantExpression Foo.java
  */
--- a/langtools/test/tools/javac/processing/model/util/elements/TestGetPackageOf.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/util/elements/TestGetPackageOf.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6453386
  * @summary Test Elements.getPackageOf
  * @author  Joseph D. Darcy
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor TestGetPackageOf
  * @compile -processor TestGetPackageOf -proc:only TestGetPackageOf.java
  */
--- a/langtools/test/tools/javac/processing/model/util/filter/TestIterables.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/model/util/filter/TestIterables.java	Tue Jan 22 11:54:16 2013 -0800
@@ -26,7 +26,7 @@
  * @bug 6406164
  * @summary Test that ElementFilter iterable methods behave properly.
  * @author  Joseph D. Darcy
- * @library ../../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor
  * @compile TestIterables.java
  * @compile -processor TestIterables -proc:only Foo1.java
--- a/langtools/test/tools/javac/processing/options/testCommandLineClasses/Test.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/options/testCommandLineClasses/Test.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6930508
  * @summary Passing nested class names on javac command line interfere with subsequent name -> class lookup
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor p.NestedExamples Test
  * @run main Test
  */
--- a/langtools/test/tools/javac/processing/options/testPrintProcessorInfo/Test.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/options/testPrintProcessorInfo/Test.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6987384
  * @summary -XprintProcessorRoundsInfo message printed with different timing than previous
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor Test
  * @compile/fail/ref=Test.out -XDrawDiagnostics -XprintProcessorInfo -Werror -proc:only -processor Test Test.java
  */
--- a/langtools/test/tools/javac/processing/options/testPrintProcessorInfo/TestWithXstdout.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/options/testPrintProcessorInfo/TestWithXstdout.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6987384
  * @summary -XprintProcessorRoundsInfo message printed with different timing than previous
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor Test TestWithXstdout
  * @run main TestWithXstdout
  */
--- a/langtools/test/tools/javac/processing/warnings/UseImplicit/TestProcUseImplicitWarning.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/warnings/UseImplicit/TestProcUseImplicitWarning.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6986892
  * @summary confusing warning given after errors in annotation processing
- * @library ../../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor TestProcUseImplicitWarning
  * @clean C1 p.C2
  * @compile/fail/ref=err.out -XDrawDiagnostics -processor TestProcUseImplicitWarning -Aerror C1.java
--- a/langtools/test/tools/javac/processing/werror/WError1.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/werror/WError1.java	Tue Jan 22 11:54:16 2013 -0800
@@ -24,7 +24,7 @@
 /*
  * @test 6403456
  * @summary -Werror should work with annotation processing
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile WError1.java
  * @compile -proc:only -processor WError1 WError1.java
--- a/langtools/test/tools/javac/processing/werror/WErrorGen.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/werror/WErrorGen.java	Tue Jan 22 11:54:16 2013 -0800
@@ -24,7 +24,7 @@
 /*
  * @test 6403456
  * @summary -Werror should work with annotation processing
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile WErrorGen.java
  * @compile -proc:only -processor WErrorGen WErrorGen.java
--- a/langtools/test/tools/javac/processing/werror/WErrorLast.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/processing/werror/WErrorLast.java	Tue Jan 22 11:54:16 2013 -0800
@@ -24,7 +24,7 @@
 /*
  * @test 6403456
  * @summary -Werror should work with annotation processing
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build   JavacTestingAbstractProcessor
  * @compile WErrorLast.java
  * @compile -proc:only -processor WErrorLast WErrorLast.java
--- a/langtools/test/tools/javac/resolve/ResolveHarness.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/resolve/ResolveHarness.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 7098660
  * @summary Write better overload resolution/inference tests
- * @library ../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor ResolveHarness
  * @run main ResolveHarness
  */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/tree/PrettySimpleStringTest.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,73 @@
+/*
+ * 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 8006033
+ * @summary bug in Pretty.toSimpleString
+ */
+
+import java.io.File;
+
+import javax.tools.StandardJavaFileManager;
+
+import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.util.JavacTask;
+import com.sun.tools.javac.api.JavacTool;
+import com.sun.tools.javac.tree.JCTree;
+import com.sun.tools.javac.tree.Pretty;
+
+public class PrettySimpleStringTest {
+    public static void main(String... args) throws Exception {
+        new PrettySimpleStringTest().run();
+    }
+
+    void run() throws Exception {
+        File testSrc = new File(System.getProperty("test.src"));
+        File thisFile = new File(testSrc, getClass().getName() + ".java");
+        JavacTool tool = JavacTool.create();
+        StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
+        JavacTask task = tool.getTask(null, fm, null, null, null,
+                fm.getJavaFileObjects(thisFile));
+        Iterable<? extends CompilationUnitTree> trees = task.parse();
+        CompilationUnitTree thisTree = trees.iterator().next();
+
+        {   // test default
+            String thisSrc = Pretty.toSimpleString((JCTree) thisTree);
+            System.err.println(thisSrc);
+            String expect = "import jav[...]} } }";
+            if (!thisSrc.equals(expect)) {
+                throw new Exception("unexpected result");
+            }
+        }
+
+        {   // test explicit length
+            String thisSrc = Pretty.toSimpleString((JCTree) thisTree, 32);
+            System.err.println(thisSrc);
+            String expect = "import java.io.Fil[...]; } } } }";
+            if (!thisSrc.equals(expect)) {
+                throw new Exception("unexpected result");
+            }
+        }
+    }
+}
--- a/langtools/test/tools/javac/util/T6597678.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/util/T6597678.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 6597678 6449184
  * @summary Ensure Messages propogated between rounds
- * @library ../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor T6597678
  * @run main T6597678
  */
--- a/langtools/test/tools/javac/util/context/T7021650.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/util/context/T7021650.java	Tue Jan 22 11:54:16 2013 -0800
@@ -25,7 +25,7 @@
  * @test
  * @bug 7021650
  * @summary Fix Context issues
- * @library ../../lib
+ * @library /tools/javac/lib
  * @build JavacTestingAbstractProcessor T7021650
  * @run main T7021650
  */
--- a/langtools/test/tools/javac/varargs/7042566/T7042566.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/varargs/7042566/T7042566.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,22 @@
  * @test
  * @bug 7042566
  * @summary Unambiguous varargs method calls flagged as ambiguous
+ * @library ../../lib
+ * @build JavacTestingAbstractThreadedTest
+ * @run main T7042566
  */
 
+import java.io.File;
+import java.net.URI;
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.concurrent.atomic.AtomicInteger;
+import javax.tools.Diagnostic;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileObject;
+import javax.tools.SimpleJavaFileObject;
+import javax.tools.ToolProvider;
+
 import com.sun.source.util.JavacTask;
 import com.sun.tools.classfile.Instruction;
 import com.sun.tools.classfile.Attribute;
@@ -34,44 +48,36 @@
 import com.sun.tools.classfile.Code_attribute;
 import com.sun.tools.classfile.ConstantPool.*;
 import com.sun.tools.classfile.Method;
-import com.sun.tools.javac.api.JavacTool;
 import com.sun.tools.javac.util.List;
 
-import java.io.File;
-import java.net.URI;
-import java.util.Arrays;
-import java.util.Locale;
-import javax.tools.Diagnostic;
-import javax.tools.JavaCompiler;
-import javax.tools.JavaFileObject;
-import javax.tools.SimpleJavaFileObject;
-import javax.tools.StandardJavaFileManager;
-import javax.tools.ToolProvider;
-
-public class T7042566 {
+public class T7042566
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     VarargsMethod m1;
     VarargsMethod m2;
     TypeConfiguration actuals;
 
-    T7042566(TypeConfiguration m1_conf, TypeConfiguration m2_conf, TypeConfiguration actuals) {
+    T7042566(TypeConfiguration m1_conf, TypeConfiguration m2_conf,
+            TypeConfiguration actuals) {
         this.m1 = new VarargsMethod(m1_conf);
         this.m2 = new VarargsMethod(m2_conf);
         this.actuals = actuals;
     }
 
-    void compileAndCheck() throws Exception {
+    @Override
+    public void run() {
+        int id = checkCount.incrementAndGet();
         final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
-        JavaSource source = new JavaSource();
+        JavaSource source = new JavaSource(id);
         ErrorChecker ec = new ErrorChecker();
-        JavacTask ct = (JavacTask)tool.getTask(null, fm, ec,
+        JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), ec,
                 null, null, Arrays.asList(source));
         ct.call();
-        check(source, ec);
+        check(source, ec, id);
     }
 
-    void check(JavaSource source, ErrorChecker ec) {
-        checkCount++;
+    void check(JavaSource source, ErrorChecker ec, int id) {
         boolean resolutionError = false;
         VarargsMethod selectedMethod = null;
 
@@ -99,13 +105,13 @@
                     "\nFound error: " + ec.errorFound +
                     "\nCompiler diagnostics:\n" + ec.printDiags());
         } else if (!resolutionError) {
-            verifyBytecode(selectedMethod, source);
+            verifyBytecode(selectedMethod, source, id);
         }
     }
 
-    void verifyBytecode(VarargsMethod selected, JavaSource source) {
-        bytecodeCheckCount++;
-        File compiledTest = new File("Test.class");
+    void verifyBytecode(VarargsMethod selected, JavaSource source, int id) {
+        bytecodeCheckCount.incrementAndGet();
+        File compiledTest = new File(String.format("Test%d.class", id));
         try {
             ClassFile cf = ClassFile.read(compiledTest);
             Method testMethod = null;
@@ -118,7 +124,8 @@
             if (testMethod == null) {
                 throw new Error("Test method not found");
             }
-            Code_attribute ea = (Code_attribute)testMethod.attributes.get(Attribute.Code);
+            Code_attribute ea =
+                (Code_attribute)testMethod.attributes.get(Attribute.Code);
             if (testMethod == null) {
                 throw new Error("Code attribute for test() method not found");
             }
@@ -127,11 +134,12 @@
                 if (i.getMnemonic().equals("invokevirtual")) {
                     int cp_entry = i.getUnsignedShort(1);
                     CONSTANT_Methodref_info methRef =
-                            (CONSTANT_Methodref_info)cf.constant_pool.get(cp_entry);
+                        (CONSTANT_Methodref_info)cf.constant_pool.get(cp_entry);
                     String type = methRef.getNameAndTypeInfo().getType();
                     String sig = selected.parameterTypes.bytecodeSigStr;
                     if (!type.contains(sig)) {
-                        throw new Error("Unexpected type method call: " + type + "" +
+                        throw new Error("Unexpected type method call: " +
+                                        type + "" +
                                         "\nfound: " + sig +
                                         "\n" + source.getCharContent(true));
                     }
@@ -146,7 +154,7 @@
 
     class JavaSource extends SimpleJavaFileObject {
 
-        static final String source_template = "class Test {\n" +
+        static final String source_template = "class Test#ID {\n" +
                 "   #V1\n" +
                 "   #V2\n" +
                 "   void test() { m(#E); }\n" +
@@ -154,11 +162,13 @@
 
         String source;
 
-        public JavaSource() {
-            super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
-            source = source_template.replaceAll("#V1", m1.toString()).
-                    replaceAll("#V2", m2.toString()).
-                    replaceAll("#E", actuals.expressionListStr);
+        public JavaSource(int id) {
+            super(URI.create(String.format("myfo:/Test%d.java", id)),
+                    JavaFileObject.Kind.SOURCE);
+            source = source_template.replaceAll("#V1", m1.toString())
+                    .replaceAll("#V2", m2.toString())
+                    .replaceAll("#E", actuals.expressionListStr)
+                    .replaceAll("#ID", String.valueOf(id));
         }
 
         @Override
@@ -167,26 +177,17 @@
         }
     }
 
-    /** global decls ***/
-
-    // Create a single file manager and reuse it for each compile to save time.
-    static StandardJavaFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);
-
-    //statistics
-    static int checkCount = 0;
-    static int bytecodeCheckCount = 0;
-
     public static void main(String... args) throws Exception {
         for (TypeConfiguration tconf1 : TypeConfiguration.values()) {
             for (TypeConfiguration tconf2 : TypeConfiguration.values()) {
                 for (TypeConfiguration tconf3 : TypeConfiguration.values()) {
-                    new T7042566(tconf1, tconf2, tconf3).compileAndCheck();
+                    pool.execute(new T7042566(tconf1, tconf2, tconf3));
                 }
             }
         }
 
-        System.out.println("Total checks made: " + checkCount);
-        System.out.println("Bytecode checks made: " + bytecodeCheckCount);
+        outWriter.println("Bytecode checks made: " + bytecodeCheckCount.get());
+        checkAfterExec();
     }
 
     enum TypeKind {
@@ -326,14 +327,16 @@
         }
     }
 
-    static class ErrorChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
+    static class ErrorChecker
+        implements javax.tools.DiagnosticListener<JavaFileObject> {
 
         boolean errorFound;
         List<String> errDiags = List.nil();
 
         public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
             if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
-                errDiags = errDiags.append(diagnostic.getMessage(Locale.getDefault()));
+                errDiags = errDiags
+                        .append(diagnostic.getMessage(Locale.getDefault()));
                 errorFound = true;
             }
         }
@@ -347,4 +350,8 @@
             return buf.toString();
         }
     }
+
+    //number of bytecode checks made while running combo tests
+    static AtomicInteger bytecodeCheckCount = new AtomicInteger();
+
 }
--- a/langtools/test/tools/javac/varargs/warning/Warn4.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/varargs/warning/Warn4.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,11 @@
  * @bug     6945418 6993978
  * @summary Project Coin: Simplified Varargs Method Invocation
  * @author  mcimadamore
+ * @library ../../lib
+ * @build JavacTestingAbstractThreadedTest
  * @run main Warn4
  */
-import com.sun.source.util.JavacTask;
-import com.sun.tools.javac.api.JavacTool;
+
 import java.net.URI;
 import java.util.Arrays;
 import java.util.Set;
@@ -38,16 +39,19 @@
 import javax.tools.JavaCompiler;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
-import javax.tools.StandardJavaFileManager;
 import javax.tools.ToolProvider;
+import com.sun.source.util.JavacTask;
 
-public class Warn4 {
+public class Warn4
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     final static Warning[] error = null;
     final static Warning[] none = new Warning[] {};
     final static Warning[] vararg = new Warning[] { Warning.VARARGS };
     final static Warning[] unchecked = new Warning[] { Warning.UNCHECKED };
-    final static Warning[] both = new Warning[] { Warning.VARARGS, Warning.UNCHECKED };
+    final static Warning[] both =
+            new Warning[] { Warning.VARARGS, Warning.UNCHECKED };
 
     enum Warning {
         UNCHECKED("generic.array.creation"),
@@ -59,8 +63,10 @@
             this.key = key;
         }
 
-        boolean isSuppressed(TrustMe trustMe, SourceLevel source, SuppressLevel suppressLevelClient,
-                SuppressLevel suppressLevelDecl, ModifierKind modKind) {
+        boolean isSuppressed(TrustMe trustMe, SourceLevel source,
+                SuppressLevel suppressLevelClient,
+                SuppressLevel suppressLevelDecl,
+                ModifierKind modKind) {
             switch(this) {
                 case VARARGS:
                     return source == SourceLevel.JDK_6 ||
@@ -68,7 +74,8 @@
                             trustMe == TrustMe.TRUST;
                 case UNCHECKED:
                     return suppressLevelClient == SuppressLevel.UNCHECKED ||
-                        (trustMe == TrustMe.TRUST && modKind != ModifierKind.NONE && source == SourceLevel.JDK_7);
+                        (trustMe == TrustMe.TRUST && modKind !=
+                            ModifierKind.NONE && source == SourceLevel.JDK_7);
             }
 
             SuppressLevel supLev = this == VARARGS ?
@@ -172,13 +179,13 @@
                             for (Signature vararg_meth : Signature.values()) {
                                 for (Signature client_meth : Signature.values()) {
                                     if (vararg_meth.isApplicableTo(client_meth)) {
-                                        test(sourceLevel,
+                                        pool.execute(new Warn4(sourceLevel,
                                                 trustMe,
                                                 suppressLevelClient,
                                                 suppressLevelDecl,
                                                 modKind,
                                                 vararg_meth,
-                                                client_meth);
+                                                client_meth));
                                     }
                                 }
                             }
@@ -187,63 +194,82 @@
                 }
             }
         }
+
+        checkAfterExec();
     }
 
-    // Create a single file manager and reuse it for each compile to save time.
-    static StandardJavaFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);
+    SourceLevel sourceLevel;
+    TrustMe trustMe;
+    SuppressLevel suppressLevelClient;
+    SuppressLevel suppressLevelDecl;
+    ModifierKind modKind;
+    Signature vararg_meth;
+    Signature client_meth;
+    DiagnosticChecker diagChecker;
 
-    static void test(SourceLevel sourceLevel, TrustMe trustMe, SuppressLevel suppressLevelClient,
-            SuppressLevel suppressLevelDecl, ModifierKind modKind, Signature vararg_meth, Signature client_meth) throws Exception {
+    public Warn4(SourceLevel sourceLevel, TrustMe trustMe,
+            SuppressLevel suppressLevelClient, SuppressLevel suppressLevelDecl,
+            ModifierKind modKind, Signature vararg_meth, Signature client_meth) {
+        this.sourceLevel = sourceLevel;
+        this.trustMe = trustMe;
+        this.suppressLevelClient = suppressLevelClient;
+        this.suppressLevelDecl = suppressLevelDecl;
+        this.modKind = modKind;
+        this.vararg_meth = vararg_meth;
+        this.client_meth = client_meth;
+        this.diagChecker = new DiagnosticChecker();
+    }
+
+    @Override
+    public void run() {
+        int id = checkCount.incrementAndGet();
         final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
-        JavaSource source = new JavaSource(trustMe, suppressLevelClient, suppressLevelDecl, modKind, vararg_meth, client_meth);
-        DiagnosticChecker dc = new DiagnosticChecker();
-        JavacTask ct = (JavacTask)tool.getTask(null, fm, dc,
+        JavaSource source = new JavaSource(id);
+        JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), diagChecker,
                 Arrays.asList("-Xlint:unchecked", "-source", sourceLevel.sourceKey),
                 null, Arrays.asList(source));
-        ct.generate(); //to get mandatory notes
-        check(dc.warnings, sourceLevel,
-                new boolean[] {vararg_meth.giveUnchecked(client_meth),
-                               vararg_meth.giveVarargs(client_meth)},
-                source, trustMe, suppressLevelClient, suppressLevelDecl, modKind);
+        ct.call(); //to get mandatory notes
+        check(source, new boolean[] {vararg_meth.giveUnchecked(client_meth),
+                               vararg_meth.giveVarargs(client_meth)});
     }
 
-    static void check(Set<Warning> warnings, SourceLevel sourceLevel, boolean[] warnArr, JavaSource source,
-            TrustMe trustMe, SuppressLevel suppressLevelClient, SuppressLevel suppressLevelDecl, ModifierKind modKind) {
+    void check(JavaSource source, boolean[] warnArr) {
         boolean badOutput = false;
         for (Warning wkind : Warning.values()) {
             boolean isSuppressed = wkind.isSuppressed(trustMe, sourceLevel,
                     suppressLevelClient, suppressLevelDecl, modKind);
             System.out.println("SUPPRESSED = " + isSuppressed);
-            badOutput |= (warnArr[wkind.ordinal()] && !isSuppressed) != warnings.contains(wkind);
+            badOutput |= (warnArr[wkind.ordinal()] && !isSuppressed) !=
+                    diagChecker.warnings.contains(wkind);
         }
         if (badOutput) {
             throw new Error("invalid diagnostics for source:\n" +
                     source.getCharContent(true) +
                     "\nExpected unchecked warning: " + warnArr[0] +
                     "\nExpected unsafe vararg warning: " + warnArr[1] +
-                    "\nWarnings: " + warnings +
+                    "\nWarnings: " + diagChecker.warnings +
                     "\nSource level: " + sourceLevel);
         }
     }
 
-    static class JavaSource extends SimpleJavaFileObject {
+    class JavaSource extends SimpleJavaFileObject {
 
         String source;
 
-        public JavaSource(TrustMe trustMe, SuppressLevel suppressLevelClient, SuppressLevel suppressLevelDecl,
-                ModifierKind modKind, Signature vararg_meth, Signature client_meth) {
-            super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
+        public JavaSource(int id) {
+            super(URI.create(String.format("myfo:/Test%d.java", id)),
+                    JavaFileObject.Kind.SOURCE);
             String meth1 = vararg_meth.template.replace("#arity", "...");
             meth1 = meth1.replace("#name", "m");
             meth1 = meth1.replace("#body", "");
-            meth1 = trustMe.anno + "\n" + suppressLevelDecl.getSuppressAnno() + modKind.mod + meth1;
+            meth1 = trustMe.anno + "\n" + suppressLevelDecl.getSuppressAnno() +
+                    modKind.mod + meth1;
             String meth2 = client_meth.template.replace("#arity", "");
             meth2 = meth2.replace("#name", "test");
             meth2 = meth2.replace("#body", "m(arg);");
             meth2 = suppressLevelClient.getSuppressAnno() + meth2;
-            source = "import java.util.List;\n" +
-                     "class Test {\n" + meth1 +
-                     "\n" + meth2 + "\n}\n";
+            source = String.format("import java.util.List;\n" +
+                     "class Test%s {\n %s \n %s \n } \n", id, meth1, meth2);
         }
 
         @Override
@@ -252,7 +278,8 @@
         }
     }
 
-    static class DiagnosticChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
+    static class DiagnosticChecker
+        implements javax.tools.DiagnosticListener<JavaFileObject> {
 
         Set<Warning> warnings = new HashSet<>();
 
@@ -267,4 +294,5 @@
             }
         }
     }
+
 }
--- a/langtools/test/tools/javac/varargs/warning/Warn5.java	Tue Jan 22 14:27:41 2013 -0500
+++ b/langtools/test/tools/javac/varargs/warning/Warn5.java	Tue Jan 22 11:54:16 2013 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,10 +26,10 @@
  * @bug     6993978 7097436
  * @summary Project Coin: Annotation to reduce varargs warnings
  * @author  mcimadamore
+ * @library ../../lib
+ * @build JavacTestingAbstractThreadedTest
  * @run main Warn5
  */
-import com.sun.source.util.JavacTask;
-import com.sun.tools.javac.api.JavacTool;
 import java.net.URI;
 import java.util.Arrays;
 import java.util.EnumSet;
@@ -37,10 +37,12 @@
 import javax.tools.JavaCompiler;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
-import javax.tools.StandardJavaFileManager;
 import javax.tools.ToolProvider;
+import com.sun.source.util.JavacTask;
 
-public class Warn5 {
+public class Warn5
+    extends JavacTestingAbstractThreadedTest
+    implements Runnable {
 
     enum XlintOption {
         NONE("none"),
@@ -161,9 +163,6 @@
         REDUNDANT_SAFEVARARGS;
     }
 
-    // Create a single file manager and reuse it for each compile to save time.
-    static StandardJavaFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);
-
     public static void main(String... args) throws Exception {
         for (SourceLevel sourceLevel : SourceLevel.values()) {
             for (XlintOption xlint : XlintOption.values()) {
@@ -173,14 +172,9 @@
                             for (MethodKind methKind : MethodKind.values()) {
                                 for (SignatureKind sig : SignatureKind.values()) {
                                     for (BodyKind body : BodyKind.values()) {
-                                        new Warn5(sourceLevel,
-                                                xlint,
-                                                trustMe,
-                                                suppressLevel,
-                                                modKind,
-                                                methKind,
-                                                sig,
-                                                body).test();
+                                        pool.execute(new Warn5(sourceLevel,
+                                                xlint, trustMe, suppressLevel,
+                                                modKind, methKind, sig, body));
                                     }
                                 }
                             }
@@ -189,6 +183,8 @@
                 }
             }
         }
+
+        checkAfterExec(false);
     }
 
     final SourceLevel sourceLevel;
@@ -202,7 +198,9 @@
     final JavaSource source;
     final DiagnosticChecker dc;
 
-    public Warn5(SourceLevel sourceLevel, XlintOption xlint, TrustMe trustMe, SuppressLevel suppressLevel, ModifierKind modKind, MethodKind methKind, SignatureKind sig, BodyKind body) {
+    public Warn5(SourceLevel sourceLevel, XlintOption xlint, TrustMe trustMe,
+            SuppressLevel suppressLevel, ModifierKind modKind,
+            MethodKind methKind, SignatureKind sig, BodyKind body) {
         this.sourceLevel = sourceLevel;
         this.xlint = xlint;
         this.trustMe = trustMe;
@@ -215,24 +213,36 @@
         this.dc = new DiagnosticChecker();
     }
 
-    void test() throws Exception {
+    @Override
+    public void run() {
         final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
-        JavacTask ct = (JavacTask)tool.getTask(null, fm, dc,
-                Arrays.asList(xlint.getXlintOption(), "-source", sourceLevel.sourceKey), null, Arrays.asList(source));
-        ct.analyze();
+        JavacTask ct = (JavacTask)tool.getTask(null, fm.get(), dc,
+                Arrays.asList(xlint.getXlintOption(),
+                    "-source", sourceLevel.sourceKey),
+                null, Arrays.asList(source));
+        try {
+            ct.analyze();
+        } catch (Throwable t) {
+            processException(t);
+        }
         check();
     }
 
     void check() {
 
-        EnumSet<WarningKind> expectedWarnings = EnumSet.noneOf(WarningKind.class);
+        EnumSet<WarningKind> expectedWarnings =
+                EnumSet.noneOf(WarningKind.class);
 
         if (sourceLevel == SourceLevel.JDK_7 &&
                 trustMe == TrustMe.TRUST &&
                 suppressLevel != SuppressLevel.VARARGS &&
                 xlint != XlintOption.NONE &&
-                sig.isVarargs && !sig.isReifiableArg && body.hasAliasing &&
-                (methKind == MethodKind.CONSTRUCTOR || (methKind == MethodKind.METHOD && modKind != ModifierKind.NONE))) {
+                sig.isVarargs &&
+                !sig.isReifiableArg &&
+                body.hasAliasing &&
+                (methKind == MethodKind.CONSTRUCTOR ||
+                (methKind == MethodKind.METHOD &&
+                modKind != ModifierKind.NONE))) {
             expectedWarnings.add(WarningKind.UNSAFE_BODY);
         }
 
@@ -247,7 +257,8 @@
         if (sourceLevel == SourceLevel.JDK_7 &&
                 trustMe == TrustMe.TRUST &&
                 (!sig.isVarargs ||
-                (modKind == ModifierKind.NONE && methKind == MethodKind.METHOD))) {
+                (modKind == ModifierKind.NONE &&
+                methKind == MethodKind.METHOD))) {
             expectedWarnings.add(WarningKind.MALFORMED_SAFEVARARGS);
         }
 
@@ -255,7 +266,8 @@
                 trustMe == TrustMe.TRUST &&
                 xlint != XlintOption.NONE &&
                 suppressLevel != SuppressLevel.VARARGS &&
-                (modKind != ModifierKind.NONE || methKind == MethodKind.CONSTRUCTOR) &&
+                (modKind != ModifierKind.NONE ||
+                methKind == MethodKind.CONSTRUCTOR) &&
                 sig.isVarargs &&
                 sig.isReifiableArg) {
             expectedWarnings.add(WarningKind.REDUNDANT_SAFEVARARGS);
@@ -297,19 +309,23 @@
         }
     }
 
-    class DiagnosticChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
+    class DiagnosticChecker
+        implements javax.tools.DiagnosticListener<JavaFileObject> {
 
         EnumSet<WarningKind> warnings = EnumSet.noneOf(WarningKind.class);
 
         public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
             if (diagnostic.getKind() == Diagnostic.Kind.WARNING) {
-                    if (diagnostic.getCode().contains("unsafe.use.varargs.param")) {
+                    if (diagnostic.getCode().
+                            contains("unsafe.use.varargs.param")) {
                         setWarning(WarningKind.UNSAFE_BODY);
-                    } else if (diagnostic.getCode().contains("redundant.trustme")) {
+                    } else if (diagnostic.getCode().
+                            contains("redundant.trustme")) {
                         setWarning(WarningKind.REDUNDANT_SAFEVARARGS);
                     }
             } else if (diagnostic.getKind() == Diagnostic.Kind.MANDATORY_WARNING &&
-                    diagnostic.getCode().contains("varargs.non.reifiable.type")) {
+                    diagnostic.getCode().
+                        contains("varargs.non.reifiable.type")) {
                 setWarning(WarningKind.UNSAFE_DECL);
             } else if (diagnostic.getKind() == Diagnostic.Kind.ERROR &&
                     diagnostic.getCode().contains("invalid.trustme")) {
@@ -319,7 +335,8 @@
 
         void setWarning(WarningKind wk) {
             if (!warnings.add(wk)) {
-                throw new AssertionError("Duplicate warning of kind " + wk + " in source:\n" + source);
+                throw new AssertionError("Duplicate warning of kind " +
+                        wk + " in source:\n" + source);
             }
         }
 
@@ -327,4 +344,5 @@
             return warnings.contains(wk);
         }
     }
+
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javadoc/MaxWarns.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8005644
+ * @summary set default max errs and max warns
+ */
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+
+public class MaxWarns {
+    public static void main(String... args) throws Exception {
+        new MaxWarns().run();
+    }
+
+    void run() throws Exception {
+        final int defaultMaxWarns = 100;
+        final int genWarns = 150;
+        File f = genSrc(genWarns);
+        String out = javadoc(f);
+        check(out, defaultMaxWarns);
+
+        if (errors > 0)
+            throw new Exception(errors + " errors occurred");
+    }
+
+    File genSrc(int count) throws IOException {
+        StringBuilder sb = new StringBuilder();
+        sb.append("package p;\n")
+            .append("public class C {\n")
+            .append("    /**\n");
+        for (int i = 0; i < count; i++)
+            sb.append("     * @param i").append(i).append(" does not exist!\n");
+        sb.append("     */\n")
+            .append("    public void m() { }\n")
+            .append("}\n");
+        File srcDir = new File("src");
+        srcDir.mkdirs();
+        File f = new File(srcDir, "C.java");
+        try (FileWriter fw = new FileWriter(f)) {
+            fw.write(sb.toString());
+        }
+        return f;
+    }
+
+    String javadoc(File f) {
+        StringWriter sw = new StringWriter();
+        PrintWriter pw = new PrintWriter(sw);
+        String[] args = { "-d", "api", f.getPath() };
+        int rc = com.sun.tools.javadoc.Main.execute("javadoc", pw, pw, pw,
+                com.sun.tools.doclets.standard.Standard.class.getName(), args);
+        pw.flush();
+        return sw.toString();
+    }
+
+    void check(String out, int count) {
+        System.err.println(out);
+        Pattern warn = Pattern.compile("warning - @param argument \"i[0-9]+\" is not a parameter name");
+        Matcher m = warn.matcher(out);
+        int n = 0;
+        for (int start = 0; m.find(start); start = m.start() + 1) {
+            n++;
+        }
+        if (n != count)
+            error("unexpected number of warnings reported: " + n + "; expected: " + count);
+
+        Pattern warnCount = Pattern.compile("(?ms).*^([0-9]+) warnings$.*");
+        m = warnCount.matcher(out);
+        if (m.matches()) {
+            n = Integer.parseInt(m.group(1));
+            if (n != count)
+                error("unexpected number of warnings reported: " + n + "; expected: " + count);
+        } else
+            error("total count not found");
+    }
+
+    void error(String msg) {
+        System.err.println("Error: " + msg);
+        errors++;
+    }
+
+    int errors;
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javap/MethodParameters.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8004727 8005647
+ * @summary javac should generate method parameters correctly.
+ */
+
+import java.io.*;
+import java.util.*;
+
+public class MethodParameters {
+
+    static final String Foo_name = "Foo";
+    static final String Foo_contents =
+        ("public class Foo {\n" +
+         "  Foo() {}\n" +
+         "  Foo(int i) {}\n" +
+         "  void foo0() {}\n" +
+         "  void foo2(int j, int k) {}\n" +
+         "}").replaceAll(" +", " ");
+    static final String Init0_expected =
+        ("  Foo();\n" +
+         "    flags: \n" +
+         "    Code:\n" +
+         "      stack=1, locals=1, args_size=1\n" +
+         "         0: aload_0       \n" +
+         "         1: invokespecial #1                  // Method java/lang/Object.\"<init>\":()V\n" +
+         "         4: return        \n" +
+         "      LineNumberTable:\n" +
+         "        line 2: 0").replaceAll(" +", " ");
+    static final String Init1_expected =
+        ("  Foo(int);\n" +
+         "    flags: \n" +
+         "    Code:\n" +
+         "      stack=1, locals=2, args_size=2\n" +
+         "         0: aload_0       \n" +
+         "         1: invokespecial #1                  // Method java/lang/Object.\"<init>\":()V\n" +
+         "         4: return        \n" +
+         "      LineNumberTable:\n" +
+         "        line 3: 0\n" +
+         "    MethodParameters:\n" +
+         "      Name                                Flags\n" +
+         "      i").replaceAll(" +", " ");
+    static final String foo0_expected =
+        ("  void foo0();\n" +
+         "    flags: \n" +
+         "    Code:\n" +
+         "      stack=0, locals=1, args_size=1\n" +
+         "         0: return        \n" +
+         "      LineNumberTable:\n" +
+         "        line 4: 0").replaceAll(" +", " ");
+    static final String foo2_expected =
+        ("  void foo2(int, int);\n" +
+         "    flags: \n" +
+         "    Code:\n" +
+         "      stack=0, locals=3, args_size=3\n" +
+         "         0: return        \n" +
+         "      LineNumberTable:\n" +
+         "        line 5: 0\n" +
+         "    MethodParameters:\n" +
+         "      Name                                Flags\n" +
+         "      j                              \n" +
+         "      k").replaceAll(" +", " ");
+
+    static final File classesdir = new File("methodparameters");
+    static final String separator = System.getProperty("line.separator");
+
+    public static void main(String... args) throws Exception {
+        new MethodParameters().run();
+    }
+
+    void run() throws Exception {
+        classesdir.mkdir();
+        final File Foo_java =
+            writeFile(classesdir, Foo_name + ".java", Foo_contents);
+        compile("-parameters", "-d", classesdir.getPath(), Foo_java.getPath());
+        System.out.println("Run javap");
+        String output =
+            javap("-c", "-verbose", "-classpath",
+                  classesdir.getPath(), Foo_name);
+        String normalized =
+            output.replaceAll(separator, "\n").replaceAll(" +", " ");
+
+        if (!normalized.contains(Init0_expected))
+            error("Bad output for zero-parameter constructor.  Expected\n" +
+                  Init0_expected + "\n" + "but got\n" + normalized);
+        if (!normalized.contains(Init1_expected))
+           error("Bad output for one-parameter constructor.  Expected\n" +
+                 Init1_expected + "\n" + "but got\n" + normalized);
+        if (!normalized.contains(foo0_expected))
+           error("Bad output for zero-parameter method.  Expected\n" +
+                 foo0_expected + "\n" + "but got\n" + normalized);
+        if (!normalized.contains(foo2_expected))
+           error("Bad output for two-parameter method  Expected\n" +
+                 foo2_expected + "\n" + "but got\n" + normalized);
+
+        if (0 != errors)
+            throw new Exception("MethodParameters test failed with " +
+                                errors + " errors");
+    }
+
+    String javap(String... args) {
+        StringWriter sw = new StringWriter();
+        PrintWriter out = new PrintWriter(sw);
+        //sun.tools.javap.Main.entry(args);
+        int rc = com.sun.tools.javap.Main.run(args, out);
+        if (rc != 0)
+            throw new Error("javap failed. rc=" + rc);
+        out.close();
+        System.out.println(sw);
+        return sw.toString();
+    }
+
+    String compile(String... args) throws Exception {
+        System.err.println("compile: " + Arrays.asList(args));
+        StringWriter sw = new StringWriter();
+        PrintWriter pw = new PrintWriter(sw);
+        int rc = com.sun.tools.javac.Main.compile(args, pw);
+        pw.close();
+        String out = sw.toString();
+        if (out.length() > 0)
+            System.err.println(out);
+        if (rc != 0)
+            error("compilation failed, rc=" + rc);
+        return out;
+    }
+
+    File writeFile(File dir, String path, String body) throws IOException {
+        File f = new File(dir, path);
+        f.getParentFile().mkdirs();
+        FileWriter out = new FileWriter(f);
+        out.write(body);
+        out.close();
+        return f;
+    }
+
+    void error(String msg) {
+        System.err.println("Error: " + msg);
+        errors++;
+    }
+
+    int errors;
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/jdeps/Basic.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,149 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8003562
+ * @summary Basic tests for jdeps tool
+ * @build Test p.Foo
+ * @run main Basic
+ */
+
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.*;
+import java.util.regex.*;
+
+public class Basic {
+    public static void main(String... args) throws Exception {
+        int errors = 0;
+
+        errors += new Basic().run();
+        if (errors > 0)
+            throw new Exception(errors + " errors found");
+    }
+
+    int run() throws IOException {
+        File testDir = new File(System.getProperty("test.classes", "."));
+        // test a .class file
+        test(new File(testDir, "Test.class"),
+             new String[] {"java.lang", "p"});
+        // test a directory
+        test(new File(testDir, "p"),
+             new String[] {"java.lang", "java.util"});
+        // test class-level dependency output
+        test(new File(testDir, "Test.class"),
+             new String[] {"java.lang.Object", "p.Foo"},
+             new String[] {"-V", "class"});
+        // test -p option
+        test(new File(testDir, "Test.class"),
+             new String[] {"p.Foo"},
+             new String[] {"--verbose-level=class", "-p", "p"});
+        // test -e option
+        test(new File(testDir, "Test.class"),
+             new String[] {"p.Foo"},
+             new String[] {"-V", "class", "-e", "p\\..*"});
+        test(new File(testDir, "Test.class"),
+             new String[] {"java.lang"},
+             new String[] {"-V", "package", "-e", "java\\.lang\\..*"});
+        // test -classpath and -all options
+        test(null,
+             new String[] {"com.sun.tools.jdeps", "java.lang", "java.util",
+                           "java.util.regex", "java.io", "p"},
+             new String[] {"--classpath", testDir.getPath(), "*"});
+        return errors;
+    }
+
+    void test(File file, String[] expect) {
+        test(file, expect, new String[0]);
+    }
+
+    void test(File file, String[] expect, String[] options) {
+        String[] args;
+        if (file != null) {
+            args = Arrays.copyOf(options, options.length+1);
+            args[options.length] = file.getPath();
+        } else {
+            args = options;
+        }
+        String[] deps = jdeps(args);
+        checkEqual("dependencies", expect, deps);
+    }
+
+    String[] jdeps(String... args) {
+        StringWriter sw = new StringWriter();
+        PrintWriter pw = new PrintWriter(sw);
+        System.err.println("jdeps " + Arrays.toString(args));
+        int rc = com.sun.tools.jdeps.Main.run(args, pw);
+        pw.close();
+        String out = sw.toString();
+        if (!out.isEmpty())
+            System.err.println(out);
+        if (rc != 0)
+            throw new Error("jdeps failed: rc=" + rc);
+        return findDeps(out);
+    }
+
+    // Pattern used to parse lines
+    private static Pattern linePattern = Pattern.compile(".*\r?\n");
+    private static Pattern pattern = Pattern.compile("\\s+ -> (\\S+) +.*");
+
+    // Use the linePattern to break the given String into lines, applying
+    // the pattern to each line to see if we have a match
+    private static String[] findDeps(String out) {
+        List<String> result = new ArrayList<>();
+        Matcher lm = linePattern.matcher(out);  // Line matcher
+        Matcher pm = null;                      // Pattern matcher
+        int lines = 0;
+        while (lm.find()) {
+            lines++;
+            CharSequence cs = lm.group();       // The current line
+            if (pm == null)
+                pm = pattern.matcher(cs);
+            else
+                pm.reset(cs);
+            if (pm.find())
+                result.add(pm.group(1));
+            if (lm.end() == out.length())
+                break;
+        }
+        return result.toArray(new String[0]);
+    }
+
+    void checkEqual(String label, String[] expect, String[] found) {
+        Set<String> s1 = new HashSet<>(Arrays.asList(expect));
+        Set<String> s2 = new HashSet<>(Arrays.asList(found));
+
+        if (!s1.equals(s2))
+            error("Unexpected " + label + " found: '" + s2 + "', expected: '" + s1 + "'");
+    }
+
+    void error(String msg) {
+        System.err.println("Error: " + msg);
+        errors++;
+    }
+
+    int errors;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/jdeps/Test.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+public class Test {
+    public void test() {
+        p.Foo f = new p.Foo();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/jdeps/p/Foo.java	Tue Jan 22 11:54:16 2013 -0800
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package p;
+
+import java.util.List;
+import java.util.Collections;
+public class Foo {
+    public static List foo() {
+        return Collections.emptyList();
+    }
+
+    public Foo() {
+    }
+}
--- a/make/install-rules.gmk	Tue Jan 22 14:27:41 2013 -0500
+++ b/make/install-rules.gmk	Tue Jan 22 11:54:16 2013 -0800
@@ -96,6 +96,9 @@
 combo_build:
 	@$(ECHO) $@ installer combo build started: `$(DATE) '+%y-%m-%d %H:%M'`
 	$(CD) $(INSTALL_TOPDIR)/make/installer/bundles/windows/ishield/wrapper/wrapper.jreboth ; $(MAKE) all
+	$(CD) $(INSTALL_TOPDIR)/make/installer/bundles/windows/ishield/wrapper/wrapper.new64jre ; $(MAKE) all
+	$(CD) $(INSTALL_TOPDIR)/make/installer/bundles/windows/ishield/jre ; $(MAKE) au_combo
+	$(CD) $(INSTALL_TOPDIR)/make/installer/bundles/windows/xmlinffile ; $(MAKE) all
 
 install-clobber:
 ifeq ($(BUILD_INSTALL), true)
--- a/make/jprt.properties	Tue Jan 22 14:27:41 2013 -0500
+++ b/make/jprt.properties	Tue Jan 22 11:54:16 2013 -0800
@@ -28,6 +28,9 @@
 # Locked down to jdk8
 jprt.tools.default.release=jdk8
 
+# Unix toolkit to use for building on windows
+jprt.windows.jdk8.build.unix.toolkit=cygwin
+
 # The different build flavors we want, we override here so we just get these 2
 jprt.build.flavors=product,fastdebug