Merge
authorlana
Fri, 15 Mar 2013 23:31:19 -0700
changeset 16483 443a7e5f9b91
parent 16482 cbc9c93df1fd (current diff)
parent 16128 1ee796f45a7f (diff)
child 16484 f24cb2927b7a
Merge
jdk/makefiles/CompileNativeLibraries.gmk
jdk/src/share/classes/java/util/logging/Logger.java
jdk/src/share/classes/sun/security/util/KeyLength.java
--- a/.hgtags	Fri Mar 15 19:30:28 2013 +0530
+++ b/.hgtags	Fri Mar 15 23:31:19 2013 -0700
@@ -201,3 +201,4 @@
 d17eb2e13e362085e866d46235314c50cc4661cc jdk8-b77
 6d3dcd34b5b962ea1ef9eed0dafdee9e812401bc jdk8-b78
 a1313a8d90d17d363a3b2a645dc4030ec204b168 jdk8-b79
+3fa21fbf9be7e6b482af43aacb6a09acfa30bdb6 jdk8-b80
--- a/.hgtags-top-repo	Fri Mar 15 19:30:28 2013 +0530
+++ b/.hgtags-top-repo	Fri Mar 15 23:31:19 2013 -0700
@@ -201,3 +201,4 @@
 3933eebc659d58c597aa8cb4b3e58f2250ce3e1a jdk8-b77
 fd1a5574cf68af24bfd52decc37ac6361afb278a jdk8-b78
 91d35211e74464dca5edf9b66ab01d0d0d8cded7 jdk8-b79
+907a926d3c96472f357617b48b6b968ea855c23c jdk8-b80
--- a/common/autoconf/generated-configure.sh	Fri Mar 15 19:30:28 2013 +0530
+++ b/common/autoconf/generated-configure.sh	Fri Mar 15 23:31:19 2013 -0700
@@ -1,6 +1,6 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.67 for OpenJDK jdk8.
+# Generated by GNU Autoconf 2.68 for OpenJDK jdk8.
 #
 # Report bugs to <build-dev@openjdk.java.net>.
 #
@@ -91,6 +91,7 @@
 IFS=" ""	$as_nl"
 
 # Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
 case $0 in #((
   *[\\/]* ) as_myself=$0 ;;
   *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
@@ -216,11 +217,18 @@
   # We cannot yet assume a decent shell, so we have to provide a
 	# neutralization value for shells without unset; and this also
 	# works around shells that cannot unset nonexistent variables.
+	# Preserve -v and -x to the replacement shell.
 	BASH_ENV=/dev/null
 	ENV=/dev/null
 	(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
 	export CONFIG_SHELL
-	exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
+	case $- in # ((((
+	  *v*x* | *x*v* ) as_opts=-vx ;;
+	  *v* ) as_opts=-v ;;
+	  *x* ) as_opts=-x ;;
+	  * ) as_opts= ;;
+	esac
+	exec "$CONFIG_SHELL" $as_opts "$as_myself" ${1+"$@"}
 fi
 
     if test x$as_have_required = xno; then :
@@ -725,6 +733,8 @@
 BUILD_CXX
 BUILD_CC
 MSVCR_DLL
+DXSDK_INCLUDE_PATH
+DXSDK_LIB_PATH
 VS_PATH
 VS_LIB
 VS_INCLUDE
@@ -985,6 +995,9 @@
 with_override_jdk
 with_import_hotspot
 with_msvcr_dll
+with_dxsdk
+with_dxsdk_lib
+with_dxsdk_include
 with_extra_cflags
 with_extra_cxxflags
 with_extra_ldflags
@@ -1435,7 +1448,7 @@
     $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
     expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
       $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
-    : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}
+    : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
     ;;
 
   esac
@@ -1736,6 +1749,11 @@
                           source
   --with-msvcr-dll        copy this msvcr100.dll into the built JDK (Windows
                           only) [probed]
+  --with-dxsdk            the DirectX SDK (Windows only) [probed]
+  --with-dxsdk-lib        the DirectX SDK lib directory (Windows only)
+                          [probed]
+  --with-dxsdk-include    the DirectX SDK include directory (Windows only)
+                          [probed]
   --with-extra-cflags     extra flags to be used when compiling jdk c-files
   --with-extra-cxxflags   extra flags to be used when compiling jdk c++-files
   --with-extra-ldflags    extra flags to be used when linking jdk
@@ -1862,7 +1880,7 @@
 if $ac_init_version; then
   cat <<\_ACEOF
 OpenJDK configure jdk8
-generated by GNU Autoconf 2.67
+generated by GNU Autoconf 2.68
 
 Copyright (C) 2010 Free Software Foundation, Inc.
 This configure script is free software; the Free Software Foundation
@@ -1908,7 +1926,7 @@
 
 	ac_retval=1
 fi
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
   as_fn_set_status $ac_retval
 
 } # ac_fn_c_try_compile
@@ -1946,7 +1964,7 @@
 
 	ac_retval=1
 fi
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
   as_fn_set_status $ac_retval
 
 } # ac_fn_cxx_try_compile
@@ -1984,7 +2002,7 @@
 
 	ac_retval=1
 fi
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
   as_fn_set_status $ac_retval
 
 } # ac_fn_objc_try_compile
@@ -2021,7 +2039,7 @@
 
     ac_retval=1
 fi
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
   as_fn_set_status $ac_retval
 
 } # ac_fn_c_try_cpp
@@ -2058,7 +2076,7 @@
 
     ac_retval=1
 fi
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
   as_fn_set_status $ac_retval
 
 } # ac_fn_cxx_try_cpp
@@ -2071,10 +2089,10 @@
 ac_fn_cxx_check_header_mongrel ()
 {
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if eval "test \"\${$3+set}\"" = set; then :
+  if eval \${$3+:} false; then :
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
 $as_echo_n "checking for $2... " >&6; }
-if eval "test \"\${$3+set}\"" = set; then :
+if eval \${$3+:} false; then :
   $as_echo_n "(cached) " >&6
 fi
 eval ac_res=\$$3
@@ -2141,7 +2159,7 @@
 esac
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
 $as_echo_n "checking for $2... " >&6; }
-if eval "test \"\${$3+set}\"" = set; then :
+if eval \${$3+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   eval "$3=\$ac_header_compiler"
@@ -2150,7 +2168,7 @@
 	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
 $as_echo "$ac_res" >&6; }
 fi
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
 
 } # ac_fn_cxx_check_header_mongrel
 
@@ -2191,7 +2209,7 @@
        ac_retval=$ac_status
 fi
   rm -rf conftest.dSYM conftest_ipa8_conftest.oo
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
   as_fn_set_status $ac_retval
 
 } # ac_fn_cxx_try_run
@@ -2205,7 +2223,7 @@
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
 $as_echo_n "checking for $2... " >&6; }
-if eval "test \"\${$3+set}\"" = set; then :
+if eval \${$3+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -2223,7 +2241,7 @@
 eval ac_res=\$$3
 	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
 $as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
 
 } # ac_fn_cxx_check_header_compile
 
@@ -2400,7 +2418,7 @@
 rm -f conftest.val
 
   fi
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
   as_fn_set_status $ac_retval
 
 } # ac_fn_cxx_compute_int
@@ -2446,7 +2464,7 @@
   # interfere with the next link command; also delete a directory that is
   # left behind by Apple's compiler.  We do this before executing the actions.
   rm -rf conftest.dSYM conftest_ipa8_conftest.oo
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
   as_fn_set_status $ac_retval
 
 } # ac_fn_cxx_try_link
@@ -2459,7 +2477,7 @@
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
 $as_echo_n "checking for $2... " >&6; }
-if eval "test \"\${$3+set}\"" = set; then :
+if eval \${$3+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -2514,7 +2532,7 @@
 eval ac_res=\$$3
 	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
 $as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
 
 } # ac_fn_cxx_check_func
 
@@ -2527,7 +2545,7 @@
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
 $as_echo_n "checking for $2... " >&6; }
-if eval "test \"\${$3+set}\"" = set; then :
+if eval \${$3+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -2545,7 +2563,7 @@
 eval ac_res=\$$3
 	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
 $as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
 
 } # ac_fn_c_check_header_compile
 cat >config.log <<_ACEOF
@@ -2553,7 +2571,7 @@
 running configure, to aid debugging if configure makes a mistake.
 
 It was created by OpenJDK $as_me jdk8, which was
-generated by GNU Autoconf 2.67.  Invocation command line was
+generated by GNU Autoconf 2.68.  Invocation command line was
 
   $ $0 $@
 
@@ -2811,7 +2829,7 @@
       || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "failed to load site script $ac_site_file
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
   fi
 done
 
@@ -3720,6 +3738,10 @@
 
 
 
+# Setup the DXSDK paths
+
+
+
 
 
 
@@ -3729,7 +3751,7 @@
 #CUSTOM_AUTOCONF_INCLUDE
 
 # Do not change or remove the following line, it is needed for consistency checks:
-DATE_WHEN_GENERATED=1362411827
+DATE_WHEN_GENERATED=1363150186
 
 ###############################################################################
 #
@@ -3767,7 +3789,7 @@
 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_BASENAME+set}" = set; then :
+if ${ac_cv_path_BASENAME+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $BASENAME in
@@ -3826,7 +3848,7 @@
 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_BASH+set}" = set; then :
+if ${ac_cv_path_BASH+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $BASH in
@@ -3885,7 +3907,7 @@
 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_CAT+set}" = set; then :
+if ${ac_cv_path_CAT+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $CAT in
@@ -3944,7 +3966,7 @@
 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_CHMOD+set}" = set; then :
+if ${ac_cv_path_CHMOD+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $CHMOD in
@@ -4003,7 +4025,7 @@
 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_CMP+set}" = set; then :
+if ${ac_cv_path_CMP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $CMP in
@@ -4062,7 +4084,7 @@
 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 :
+if ${ac_cv_path_COMM+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $COMM in
@@ -4121,7 +4143,7 @@
 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_CP+set}" = set; then :
+if ${ac_cv_path_CP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $CP in
@@ -4180,7 +4202,7 @@
 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 :
+if ${ac_cv_path_CPIO+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $CPIO in
@@ -4239,7 +4261,7 @@
 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_CUT+set}" = set; then :
+if ${ac_cv_path_CUT+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $CUT in
@@ -4298,7 +4320,7 @@
 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_DATE+set}" = set; then :
+if ${ac_cv_path_DATE+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $DATE in
@@ -4357,7 +4379,7 @@
 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_DIFF+set}" = set; then :
+if ${ac_cv_path_DIFF+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $DIFF in
@@ -4416,7 +4438,7 @@
 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_DIRNAME+set}" = set; then :
+if ${ac_cv_path_DIRNAME+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $DIRNAME in
@@ -4475,7 +4497,7 @@
 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_ECHO+set}" = set; then :
+if ${ac_cv_path_ECHO+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $ECHO in
@@ -4534,7 +4556,7 @@
 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_EXPR+set}" = set; then :
+if ${ac_cv_path_EXPR+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $EXPR in
@@ -4593,7 +4615,7 @@
 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_FILE+set}" = set; then :
+if ${ac_cv_path_FILE+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $FILE in
@@ -4652,7 +4674,7 @@
 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_FIND+set}" = set; then :
+if ${ac_cv_path_FIND+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $FIND in
@@ -4711,7 +4733,7 @@
 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_HEAD+set}" = set; then :
+if ${ac_cv_path_HEAD+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $HEAD in
@@ -4770,7 +4792,7 @@
 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_LN+set}" = set; then :
+if ${ac_cv_path_LN+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $LN in
@@ -4829,7 +4851,7 @@
 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_LS+set}" = set; then :
+if ${ac_cv_path_LS+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $LS in
@@ -4888,7 +4910,7 @@
 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_MKDIR+set}" = set; then :
+if ${ac_cv_path_MKDIR+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $MKDIR in
@@ -4947,7 +4969,7 @@
 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_MKTEMP+set}" = set; then :
+if ${ac_cv_path_MKTEMP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $MKTEMP in
@@ -5006,7 +5028,7 @@
 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_MV+set}" = set; then :
+if ${ac_cv_path_MV+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $MV in
@@ -5065,7 +5087,7 @@
 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_PRINTF+set}" = set; then :
+if ${ac_cv_path_PRINTF+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $PRINTF in
@@ -5124,7 +5146,7 @@
 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_THEPWDCMD+set}" = set; then :
+if ${ac_cv_path_THEPWDCMD+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $THEPWDCMD in
@@ -5183,7 +5205,7 @@
 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_RM+set}" = set; then :
+if ${ac_cv_path_RM+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $RM in
@@ -5242,7 +5264,7 @@
 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_SH+set}" = set; then :
+if ${ac_cv_path_SH+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $SH in
@@ -5301,7 +5323,7 @@
 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_SORT+set}" = set; then :
+if ${ac_cv_path_SORT+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $SORT in
@@ -5360,7 +5382,7 @@
 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_TAIL+set}" = set; then :
+if ${ac_cv_path_TAIL+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $TAIL in
@@ -5419,7 +5441,7 @@
 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_TAR+set}" = set; then :
+if ${ac_cv_path_TAR+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $TAR in
@@ -5478,7 +5500,7 @@
 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_TEE+set}" = set; then :
+if ${ac_cv_path_TEE+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $TEE in
@@ -5537,7 +5559,7 @@
 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_TOUCH+set}" = set; then :
+if ${ac_cv_path_TOUCH+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $TOUCH in
@@ -5596,7 +5618,7 @@
 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_TR+set}" = set; then :
+if ${ac_cv_path_TR+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $TR in
@@ -5655,7 +5677,7 @@
 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_UNAME+set}" = set; then :
+if ${ac_cv_path_UNAME+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $UNAME in
@@ -5714,7 +5736,7 @@
 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_UNIQ+set}" = set; then :
+if ${ac_cv_path_UNIQ+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $UNIQ in
@@ -5773,7 +5795,7 @@
 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_WC+set}" = set; then :
+if ${ac_cv_path_WC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $WC in
@@ -5832,7 +5854,7 @@
 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_WHICH+set}" = set; then :
+if ${ac_cv_path_WHICH+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $WHICH in
@@ -5891,7 +5913,7 @@
 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_XARGS+set}" = set; then :
+if ${ac_cv_path_XARGS+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $XARGS in
@@ -5951,7 +5973,7 @@
 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_prog_AWK+set}" = set; then :
+if ${ac_cv_prog_AWK+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$AWK"; then
@@ -6001,7 +6023,7 @@
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
 $as_echo_n "checking for grep that handles long lines and -e... " >&6; }
-if test "${ac_cv_path_GREP+set}" = set; then :
+if ${ac_cv_path_GREP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -z "$GREP"; then
@@ -6076,7 +6098,7 @@
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
 $as_echo_n "checking for egrep... " >&6; }
-if test "${ac_cv_path_EGREP+set}" = set; then :
+if ${ac_cv_path_EGREP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
@@ -6155,7 +6177,7 @@
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5
 $as_echo_n "checking for fgrep... " >&6; }
-if test "${ac_cv_path_FGREP+set}" = set; then :
+if ${ac_cv_path_FGREP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1
@@ -6234,7 +6256,7 @@
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5
 $as_echo_n "checking for a sed that does not truncate output... " >&6; }
-if test "${ac_cv_path_SED+set}" = set; then :
+if ${ac_cv_path_SED+:} false; then :
   $as_echo_n "(cached) " >&6
 else
             ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/
@@ -6320,7 +6342,7 @@
 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_NAWK+set}" = set; then :
+if ${ac_cv_path_NAWK+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $NAWK in
@@ -6380,7 +6402,7 @@
 set dummy cygpath; 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_CYGPATH+set}" = set; then :
+if ${ac_cv_path_CYGPATH+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $CYGPATH in
@@ -6420,7 +6442,7 @@
 set dummy readlink; 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_READLINK+set}" = set; then :
+if ${ac_cv_path_READLINK+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $READLINK in
@@ -6460,7 +6482,7 @@
 set dummy df; 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_DF+set}" = set; then :
+if ${ac_cv_path_DF+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $DF in
@@ -6500,7 +6522,7 @@
 set dummy SetFile; 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_SETFILE+set}" = set; then :
+if ${ac_cv_path_SETFILE+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $SETFILE in
@@ -6546,7 +6568,7 @@
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5
 $as_echo_n "checking build system type... " >&6; }
-if test "${ac_cv_build+set}" = set; then :
+if ${ac_cv_build+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_build_alias=$build_alias
@@ -6562,7 +6584,7 @@
 $as_echo "$ac_cv_build" >&6; }
 case $ac_cv_build in
 *-*-*) ;;
-*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5 ;;
+*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;;
 esac
 build=$ac_cv_build
 ac_save_IFS=$IFS; IFS='-'
@@ -6580,7 +6602,7 @@
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5
 $as_echo_n "checking host system type... " >&6; }
-if test "${ac_cv_host+set}" = set; then :
+if ${ac_cv_host+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test "x$host_alias" = x; then
@@ -6595,7 +6617,7 @@
 $as_echo "$ac_cv_host" >&6; }
 case $ac_cv_host in
 *-*-*) ;;
-*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5 ;;
+*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;;
 esac
 host=$ac_cv_host
 ac_save_IFS=$IFS; IFS='-'
@@ -6613,7 +6635,7 @@
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking target system type" >&5
 $as_echo_n "checking target system type... " >&6; }
-if test "${ac_cv_target+set}" = set; then :
+if ${ac_cv_target+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test "x$target_alias" = x; then
@@ -6628,7 +6650,7 @@
 $as_echo "$ac_cv_target" >&6; }
 case $ac_cv_target in
 *-*-*) ;;
-*) as_fn_error $? "invalid value of canonical target" "$LINENO" 5 ;;
+*) as_fn_error $? "invalid value of canonical target" "$LINENO" 5;;
 esac
 target=$ac_cv_target
 ac_save_IFS=$IFS; IFS='-'
@@ -8094,7 +8116,7 @@
 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_prog_PKGHANDLER+set}" = set; then :
+if ${ac_cv_prog_PKGHANDLER+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$PKGHANDLER"; then
@@ -8459,7 +8481,7 @@
 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_CHECK_GMAKE+set}" = set; then :
+if ${ac_cv_path_CHECK_GMAKE+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $CHECK_GMAKE in
@@ -8813,7 +8835,7 @@
 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_CHECK_MAKE+set}" = set; then :
+if ${ac_cv_path_CHECK_MAKE+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $CHECK_MAKE in
@@ -9172,7 +9194,7 @@
 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_CHECK_TOOLSDIR_GMAKE+set}" = set; then :
+if ${ac_cv_path_CHECK_TOOLSDIR_GMAKE+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $CHECK_TOOLSDIR_GMAKE in
@@ -9525,7 +9547,7 @@
 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_CHECK_TOOLSDIR_MAKE+set}" = set; then :
+if ${ac_cv_path_CHECK_TOOLSDIR_MAKE+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $CHECK_TOOLSDIR_MAKE in
@@ -9921,7 +9943,7 @@
 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_UNZIP+set}" = set; then :
+if ${ac_cv_path_UNZIP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $UNZIP in
@@ -9980,7 +10002,7 @@
 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_ZIP+set}" = set; then :
+if ${ac_cv_path_ZIP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $ZIP in
@@ -10039,7 +10061,7 @@
 set dummy ldd; 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_LDD+set}" = set; then :
+if ${ac_cv_path_LDD+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $LDD in
@@ -10085,7 +10107,7 @@
 set dummy otool; 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_OTOOL+set}" = set; then :
+if ${ac_cv_path_OTOOL+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $OTOOL in
@@ -10130,7 +10152,7 @@
 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_READELF+set}" = set; then :
+if ${ac_cv_path_READELF+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $READELF in
@@ -10173,7 +10195,7 @@
 set dummy hg; 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_HG+set}" = set; then :
+if ${ac_cv_path_HG+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $HG in
@@ -10213,7 +10235,7 @@
 set dummy stat; 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_STAT+set}" = set; then :
+if ${ac_cv_path_STAT+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $STAT in
@@ -10253,7 +10275,7 @@
 set dummy time; 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_TIME+set}" = set; then :
+if ${ac_cv_path_TIME+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $TIME in
@@ -10298,7 +10320,7 @@
 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 :
+if ${ac_cv_path_COMM+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $COMM in
@@ -10362,7 +10384,7 @@
 set dummy ${ac_tool_prefix}pkg-config; 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_PKG_CONFIG+set}" = set; then :
+if ${ac_cv_path_PKG_CONFIG+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $PKG_CONFIG in
@@ -10405,7 +10427,7 @@
 set dummy pkg-config; 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_ac_pt_PKG_CONFIG+set}" = set; then :
+if ${ac_cv_path_ac_pt_PKG_CONFIG+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $ac_pt_PKG_CONFIG in
@@ -10578,7 +10600,7 @@
 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_prog_BDEPS_UNZIP+set}" = set; then :
+if ${ac_cv_prog_BDEPS_UNZIP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$BDEPS_UNZIP"; then
@@ -10624,7 +10646,7 @@
 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_prog_BDEPS_FTP+set}" = set; then :
+if ${ac_cv_prog_BDEPS_FTP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$BDEPS_FTP"; then
@@ -11891,7 +11913,7 @@
 set dummy javac; 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_JAVAC_CHECK+set}" = set; then :
+if ${ac_cv_path_JAVAC_CHECK+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $JAVAC_CHECK in
@@ -11931,7 +11953,7 @@
 set dummy java; 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_JAVA_CHECK+set}" = set; then :
+if ${ac_cv_path_JAVA_CHECK+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $JAVA_CHECK in
@@ -15990,7 +16012,7 @@
 set dummy link; 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_CYGWIN_LINK+set}" = set; then :
+if ${ac_cv_path_CYGWIN_LINK+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $CYGWIN_LINK in
@@ -16952,6 +16974,432 @@
   fi
 
 
+
+
+# Check whether --with-dxsdk was given.
+if test "${with_dxsdk+set}" = set; then :
+  withval=$with_dxsdk;
+fi
+
+
+# Check whether --with-dxsdk-lib was given.
+if test "${with_dxsdk_lib+set}" = set; then :
+  withval=$with_dxsdk_lib;
+fi
+
+
+# Check whether --with-dxsdk-include was given.
+if test "${with_dxsdk_include+set}" = set; then :
+  withval=$with_dxsdk_include;
+fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for DirectX SDK" >&5
+$as_echo_n "checking for DirectX SDK... " >&6; }
+
+  if test "x$with_dxsdk" != x; then
+    dxsdk_path="$with_dxsdk"
+  elif test "x$DXSDK_DIR" != x; then
+    dxsdk_path="$DXSDK_DIR"
+  elif test -d "C:/DXSDK"; then
+    dxsdk_path="C:/DXSDK"
+  else
+    as_fn_error $? "Could not find the DirectX SDK" "$LINENO" 5
+  fi
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $dxsdk_path" >&5
+$as_echo "$dxsdk_path" >&6; }
+
+  if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then
+
+  # Input might be given as Windows format, start by converting to
+  # unix format.
+  path="$dxsdk_path"
+  new_path=`$CYGPATH -u "$path"`
+
+  # Cygwin tries to hide some aspects of the Windows file system, such that binaries are
+  # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered
+  # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then
+  # "foo.exe" is OK but "foo" is an error.
+  #
+  # This test is therefore slightly more accurate than "test -f" to check for file precense.
+  # It is also a way to make sure we got the proper file name for the real test later on.
+  test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null`
+  if test "x$test_shortpath" = x; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: The path of dxsdk_path, which resolves as \"$path\", is invalid." >&5
+$as_echo "$as_me: The path of dxsdk_path, which resolves as \"$path\", is invalid." >&6;}
+    as_fn_error $? "Cannot locate the the path of dxsdk_path" "$LINENO" 5
+  fi
+
+  # Call helper function which possibly converts this using DOS-style short mode.
+  # If so, the updated path is stored in $new_path.
+
+  input_path="$new_path"
+  # Check if we need to convert this using DOS-style short mode. If the path
+  # contains just simple characters, use it. Otherwise (spaces, weird characters),
+  # take no chances and rewrite it.
+  # Note: m4 eats our [], so we need to use [ and ] instead.
+  has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]`
+  if test "x$has_forbidden_chars" != x; then
+    # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \)
+    shortmode_path=`$CYGPATH -s -m -a "$input_path"`
+    path_after_shortmode=`$CYGPATH -u "$shortmode_path"`
+    if test "x$path_after_shortmode" != "x$input_to_shortpath"; then
+      # Going to short mode and back again did indeed matter. Since short mode is
+      # case insensitive, let's make it lowercase to improve readability.
+      shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+      # Now convert it back to Unix-stile (cygpath)
+      input_path=`$CYGPATH -u "$shortmode_path"`
+      new_path="$input_path"
+    fi
+  fi
+
+  test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/`
+  if test "x$test_cygdrive_prefix" = x; then
+    # As a simple fix, exclude /usr/bin since it's not a real path.
+    if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then
+      # The path is in a Cygwin special directory (e.g. /home). We need this converted to
+      # a path prefixed by /cygdrive for fixpath to work.
+      new_path="$CYGWIN_ROOT_PATH$input_path"
+    fi
+  fi
+
+
+  if test "x$path" != "x$new_path"; then
+    dxsdk_path="$new_path"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting dxsdk_path to \"$new_path\"" >&5
+$as_echo "$as_me: Rewriting dxsdk_path to \"$new_path\"" >&6;}
+  fi
+
+  elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then
+
+  path="$dxsdk_path"
+  has_colon=`$ECHO $path | $GREP ^.:`
+  new_path="$path"
+  if test "x$has_colon" = x; then
+    # Not in mixed or Windows style, start by that.
+    new_path=`cmd //c echo $path`
+  fi
+
+
+  input_path="$new_path"
+  # Check if we need to convert this using DOS-style short mode. If the path
+  # contains just simple characters, use it. Otherwise (spaces, weird characters),
+  # take no chances and rewrite it.
+  # Note: m4 eats our [], so we need to use [ and ] instead.
+  has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]`
+  if test "x$has_forbidden_chars" != x; then
+    # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \)
+    new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+  fi
+
+
+  windows_path="$new_path"
+  if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then
+    unix_path=`$CYGPATH -u "$windows_path"`
+    new_path="$unix_path"
+  elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then
+    unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'`
+    new_path="$unix_path"
+  fi
+
+  if test "x$path" != "x$new_path"; then
+    dxsdk_path="$new_path"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting dxsdk_path to \"$new_path\"" >&5
+$as_echo "$as_me: Rewriting dxsdk_path to \"$new_path\"" >&6;}
+  fi
+
+  # Save the first 10 bytes of this path to the storage, so fixpath can work.
+  all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}")
+
+  else
+    # We're on a posix platform. Hooray! :)
+    path="$dxsdk_path"
+
+    if test ! -f "$path" && test ! -d "$path"; then
+      as_fn_error $? "The path of dxsdk_path, which resolves as \"$path\", is not found." "$LINENO" 5
+    fi
+
+    has_space=`$ECHO "$path" | $GREP " "`
+    if test "x$has_space" != x; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: The path of dxsdk_path, which resolves as \"$path\", is invalid." >&5
+$as_echo "$as_me: The path of dxsdk_path, which resolves as \"$path\", is invalid." >&6;}
+      as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5
+    fi
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for DirectX SDK lib dir" >&5
+$as_echo_n "checking for DirectX SDK lib dir... " >&6; }
+  if test "x$with_dxsdk_lib" != x; then
+    DXSDK_LIB_PATH="$with_dxsdk_lib"
+  elif test "x$OPENJDK_TARGET_CPU" = "xx86_64"; then
+    DXSDK_LIB_PATH="$dxsdk_path/Lib/x64"
+  else
+    DXSDK_LIB_PATH="$dxsdk_path/Lib"
+  fi
+  # dsound.lib is linked to in jsoundds
+  if test ! -f "$DXSDK_LIB_PATH/dsound.lib"; then
+    as_fn_error $? "Invalid DirectX SDK lib dir" "$LINENO" 5
+  fi
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DXSDK_LIB_PATH" >&5
+$as_echo "$DXSDK_LIB_PATH" >&6; }
+
+  if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then
+
+  # Input might be given as Windows format, start by converting to
+  # unix format.
+  path="$DXSDK_LIB_PATH"
+  new_path=`$CYGPATH -u "$path"`
+
+  # Cygwin tries to hide some aspects of the Windows file system, such that binaries are
+  # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered
+  # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then
+  # "foo.exe" is OK but "foo" is an error.
+  #
+  # This test is therefore slightly more accurate than "test -f" to check for file precense.
+  # It is also a way to make sure we got the proper file name for the real test later on.
+  test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null`
+  if test "x$test_shortpath" = x; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: The path of DXSDK_LIB_PATH, which resolves as \"$path\", is invalid." >&5
+$as_echo "$as_me: The path of DXSDK_LIB_PATH, which resolves as \"$path\", is invalid." >&6;}
+    as_fn_error $? "Cannot locate the the path of DXSDK_LIB_PATH" "$LINENO" 5
+  fi
+
+  # Call helper function which possibly converts this using DOS-style short mode.
+  # If so, the updated path is stored in $new_path.
+
+  input_path="$new_path"
+  # Check if we need to convert this using DOS-style short mode. If the path
+  # contains just simple characters, use it. Otherwise (spaces, weird characters),
+  # take no chances and rewrite it.
+  # Note: m4 eats our [], so we need to use [ and ] instead.
+  has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]`
+  if test "x$has_forbidden_chars" != x; then
+    # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \)
+    shortmode_path=`$CYGPATH -s -m -a "$input_path"`
+    path_after_shortmode=`$CYGPATH -u "$shortmode_path"`
+    if test "x$path_after_shortmode" != "x$input_to_shortpath"; then
+      # Going to short mode and back again did indeed matter. Since short mode is
+      # case insensitive, let's make it lowercase to improve readability.
+      shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+      # Now convert it back to Unix-stile (cygpath)
+      input_path=`$CYGPATH -u "$shortmode_path"`
+      new_path="$input_path"
+    fi
+  fi
+
+  test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/`
+  if test "x$test_cygdrive_prefix" = x; then
+    # As a simple fix, exclude /usr/bin since it's not a real path.
+    if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then
+      # The path is in a Cygwin special directory (e.g. /home). We need this converted to
+      # a path prefixed by /cygdrive for fixpath to work.
+      new_path="$CYGWIN_ROOT_PATH$input_path"
+    fi
+  fi
+
+
+  if test "x$path" != "x$new_path"; then
+    DXSDK_LIB_PATH="$new_path"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting DXSDK_LIB_PATH to \"$new_path\"" >&5
+$as_echo "$as_me: Rewriting DXSDK_LIB_PATH to \"$new_path\"" >&6;}
+  fi
+
+  elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then
+
+  path="$DXSDK_LIB_PATH"
+  has_colon=`$ECHO $path | $GREP ^.:`
+  new_path="$path"
+  if test "x$has_colon" = x; then
+    # Not in mixed or Windows style, start by that.
+    new_path=`cmd //c echo $path`
+  fi
+
+
+  input_path="$new_path"
+  # Check if we need to convert this using DOS-style short mode. If the path
+  # contains just simple characters, use it. Otherwise (spaces, weird characters),
+  # take no chances and rewrite it.
+  # Note: m4 eats our [], so we need to use [ and ] instead.
+  has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]`
+  if test "x$has_forbidden_chars" != x; then
+    # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \)
+    new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+  fi
+
+
+  windows_path="$new_path"
+  if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then
+    unix_path=`$CYGPATH -u "$windows_path"`
+    new_path="$unix_path"
+  elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then
+    unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'`
+    new_path="$unix_path"
+  fi
+
+  if test "x$path" != "x$new_path"; then
+    DXSDK_LIB_PATH="$new_path"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting DXSDK_LIB_PATH to \"$new_path\"" >&5
+$as_echo "$as_me: Rewriting DXSDK_LIB_PATH to \"$new_path\"" >&6;}
+  fi
+
+  # Save the first 10 bytes of this path to the storage, so fixpath can work.
+  all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}")
+
+  else
+    # We're on a posix platform. Hooray! :)
+    path="$DXSDK_LIB_PATH"
+
+    if test ! -f "$path" && test ! -d "$path"; then
+      as_fn_error $? "The path of DXSDK_LIB_PATH, which resolves as \"$path\", is not found." "$LINENO" 5
+    fi
+
+    has_space=`$ECHO "$path" | $GREP " "`
+    if test "x$has_space" != x; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: The path of DXSDK_LIB_PATH, which resolves as \"$path\", is invalid." >&5
+$as_echo "$as_me: The path of DXSDK_LIB_PATH, which resolves as \"$path\", is invalid." >&6;}
+      as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5
+    fi
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for DirectX SDK include dir" >&5
+$as_echo_n "checking for DirectX SDK include dir... " >&6; }
+  if test "x$with_dxsdk_include" != x; then
+    DXSDK_INCLUDE_PATH="$with_dxsdk_include"
+  else
+    DXSDK_INCLUDE_PATH="$dxsdk_path/Include"
+  fi
+  # dsound.h is included in jsoundds
+  if test ! -f "$DXSDK_INCLUDE_PATH/dsound.h"; then
+    as_fn_error $? "Invalid DirectX SDK lib dir" "$LINENO" 5
+  fi
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DXSDK_INCLUDE_PATH" >&5
+$as_echo "$DXSDK_INCLUDE_PATH" >&6; }
+
+  if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then
+
+  # Input might be given as Windows format, start by converting to
+  # unix format.
+  path="$DXSDK_INCLUDE_PATH"
+  new_path=`$CYGPATH -u "$path"`
+
+  # Cygwin tries to hide some aspects of the Windows file system, such that binaries are
+  # named .exe but called without that suffix. Therefore, "foo" and "foo.exe" are considered
+  # the same file, most of the time (as in "test -f"). But not when running cygpath -s, then
+  # "foo.exe" is OK but "foo" is an error.
+  #
+  # This test is therefore slightly more accurate than "test -f" to check for file precense.
+  # It is also a way to make sure we got the proper file name for the real test later on.
+  test_shortpath=`$CYGPATH -s -m "$new_path" 2> /dev/null`
+  if test "x$test_shortpath" = x; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: The path of DXSDK_INCLUDE_PATH, which resolves as \"$path\", is invalid." >&5
+$as_echo "$as_me: The path of DXSDK_INCLUDE_PATH, which resolves as \"$path\", is invalid." >&6;}
+    as_fn_error $? "Cannot locate the the path of DXSDK_INCLUDE_PATH" "$LINENO" 5
+  fi
+
+  # Call helper function which possibly converts this using DOS-style short mode.
+  # If so, the updated path is stored in $new_path.
+
+  input_path="$new_path"
+  # Check if we need to convert this using DOS-style short mode. If the path
+  # contains just simple characters, use it. Otherwise (spaces, weird characters),
+  # take no chances and rewrite it.
+  # Note: m4 eats our [], so we need to use [ and ] instead.
+  has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-._/a-zA-Z0-9]`
+  if test "x$has_forbidden_chars" != x; then
+    # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \)
+    shortmode_path=`$CYGPATH -s -m -a "$input_path"`
+    path_after_shortmode=`$CYGPATH -u "$shortmode_path"`
+    if test "x$path_after_shortmode" != "x$input_to_shortpath"; then
+      # Going to short mode and back again did indeed matter. Since short mode is
+      # case insensitive, let's make it lowercase to improve readability.
+      shortmode_path=`$ECHO "$shortmode_path" | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+      # Now convert it back to Unix-stile (cygpath)
+      input_path=`$CYGPATH -u "$shortmode_path"`
+      new_path="$input_path"
+    fi
+  fi
+
+  test_cygdrive_prefix=`$ECHO $input_path | $GREP ^/cygdrive/`
+  if test "x$test_cygdrive_prefix" = x; then
+    # As a simple fix, exclude /usr/bin since it's not a real path.
+    if test "x`$ECHO $new_path | $GREP ^/usr/bin/`" = x; then
+      # The path is in a Cygwin special directory (e.g. /home). We need this converted to
+      # a path prefixed by /cygdrive for fixpath to work.
+      new_path="$CYGWIN_ROOT_PATH$input_path"
+    fi
+  fi
+
+
+  if test "x$path" != "x$new_path"; then
+    DXSDK_INCLUDE_PATH="$new_path"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting DXSDK_INCLUDE_PATH to \"$new_path\"" >&5
+$as_echo "$as_me: Rewriting DXSDK_INCLUDE_PATH to \"$new_path\"" >&6;}
+  fi
+
+  elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then
+
+  path="$DXSDK_INCLUDE_PATH"
+  has_colon=`$ECHO $path | $GREP ^.:`
+  new_path="$path"
+  if test "x$has_colon" = x; then
+    # Not in mixed or Windows style, start by that.
+    new_path=`cmd //c echo $path`
+  fi
+
+
+  input_path="$new_path"
+  # Check if we need to convert this using DOS-style short mode. If the path
+  # contains just simple characters, use it. Otherwise (spaces, weird characters),
+  # take no chances and rewrite it.
+  # Note: m4 eats our [], so we need to use [ and ] instead.
+  has_forbidden_chars=`$ECHO "$input_path" | $GREP [^-_/:a-zA-Z0-9]`
+  if test "x$has_forbidden_chars" != x; then
+    # Now convert it to mixed DOS-style, short mode (no spaces, and / instead of \)
+    new_path=`cmd /c "for %A in (\"$input_path\") do @echo %~sA"|$TR \\\\\\\\ / | $TR 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+  fi
+
+
+  windows_path="$new_path"
+  if test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.cygwin"; then
+    unix_path=`$CYGPATH -u "$windows_path"`
+    new_path="$unix_path"
+  elif test "x$OPENJDK_BUILD_OS_ENV" = "xwindows.msys"; then
+    unix_path=`$ECHO "$windows_path" | $SED -e 's,^\\(.\\):,/\\1,g' -e 's,\\\\,/,g'`
+    new_path="$unix_path"
+  fi
+
+  if test "x$path" != "x$new_path"; then
+    DXSDK_INCLUDE_PATH="$new_path"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: Rewriting DXSDK_INCLUDE_PATH to \"$new_path\"" >&5
+$as_echo "$as_me: Rewriting DXSDK_INCLUDE_PATH to \"$new_path\"" >&6;}
+  fi
+
+  # Save the first 10 bytes of this path to the storage, so fixpath can work.
+  all_fixpath_prefixes=("${all_fixpath_prefixes[@]}" "${new_path:0:10}")
+
+  else
+    # We're on a posix platform. Hooray! :)
+    path="$DXSDK_INCLUDE_PATH"
+
+    if test ! -f "$path" && test ! -d "$path"; then
+      as_fn_error $? "The path of DXSDK_INCLUDE_PATH, which resolves as \"$path\", is not found." "$LINENO" 5
+    fi
+
+    has_space=`$ECHO "$path" | $GREP " "`
+    if test "x$has_space" != x; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: The path of DXSDK_INCLUDE_PATH, which resolves as \"$path\", is invalid." >&5
+$as_echo "$as_me: The path of DXSDK_INCLUDE_PATH, which resolves as \"$path\", is invalid." >&6;}
+      as_fn_error $? "Spaces are not allowed in this path." "$LINENO" 5
+    fi
+  fi
+
+
+
+
+  LDFLAGS_JDK="$LDFLAGS_JDK -libpath:$DXSDK_LIB_PATH"
+
 fi
 
 
@@ -16979,7 +17427,7 @@
 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_BUILD_CC+set}" = set; then :
+if ${ac_cv_path_BUILD_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $BUILD_CC in
@@ -17290,7 +17738,7 @@
 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_BUILD_CXX+set}" = set; then :
+if ${ac_cv_path_BUILD_CXX+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $BUILD_CXX in
@@ -17599,7 +18047,7 @@
 set dummy ld; 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_BUILD_LD+set}" = set; then :
+if ${ac_cv_path_BUILD_LD+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $BUILD_LD in
@@ -18111,7 +18559,7 @@
 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_TOOLS_DIR_CC+set}" = set; then :
+if ${ac_cv_path_TOOLS_DIR_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $TOOLS_DIR_CC in
@@ -18163,7 +18611,7 @@
 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_POTENTIAL_CC+set}" = set; then :
+if ${ac_cv_path_POTENTIAL_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $POTENTIAL_CC in
@@ -18576,7 +19024,7 @@
 set dummy $ac_tool_prefix$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_prog_PROPER_COMPILER_CC+set}" = set; then :
+if ${ac_cv_prog_PROPER_COMPILER_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$PROPER_COMPILER_CC"; then
@@ -18620,7 +19068,7 @@
 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_prog_ac_ct_PROPER_COMPILER_CC+set}" = set; then :
+if ${ac_cv_prog_ac_ct_PROPER_COMPILER_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_PROPER_COMPILER_CC"; then
@@ -19070,7 +19518,7 @@
 set dummy $ac_tool_prefix$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_prog_CC+set}" = set; then :
+if ${ac_cv_prog_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$CC"; then
@@ -19114,7 +19562,7 @@
 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_prog_ac_ct_CC+set}" = set; then :
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_CC"; then
@@ -19167,7 +19615,7 @@
 test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "no acceptable C compiler found in \$PATH
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
 
 # Provide some information about the compiler.
 $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
@@ -19282,7 +19730,7 @@
 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error 77 "C compiler cannot create executables
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
 $as_echo "yes" >&6; }
@@ -19325,7 +19773,7 @@
   { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "cannot compute suffix of executables: cannot compile and link
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
 fi
 rm -f conftest conftest$ac_cv_exeext
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
@@ -19384,7 +19832,7 @@
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "cannot run C compiled programs.
 If you meant to cross compile, use \`--host'.
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
     fi
   fi
 fi
@@ -19395,7 +19843,7 @@
 ac_clean_files=$ac_clean_files_save
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
 $as_echo_n "checking for suffix of object files... " >&6; }
-if test "${ac_cv_objext+set}" = set; then :
+if ${ac_cv_objext+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -19436,7 +19884,7 @@
 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "cannot compute suffix of object files: cannot compile
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
 fi
 rm -f conftest.$ac_cv_objext conftest.$ac_ext
 fi
@@ -19446,7 +19894,7 @@
 ac_objext=$OBJEXT
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
-if test "${ac_cv_c_compiler_gnu+set}" = set; then :
+if ${ac_cv_c_compiler_gnu+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -19483,7 +19931,7 @@
 ac_save_CFLAGS=$CFLAGS
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
 $as_echo_n "checking whether $CC accepts -g... " >&6; }
-if test "${ac_cv_prog_cc_g+set}" = set; then :
+if ${ac_cv_prog_cc_g+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_save_c_werror_flag=$ac_c_werror_flag
@@ -19561,7 +20009,7 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
-if test "${ac_cv_prog_cc_c89+set}" = set; then :
+if ${ac_cv_prog_cc_c89+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_cv_prog_cc_c89=no
@@ -19680,7 +20128,7 @@
 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_TOOLS_DIR_CXX+set}" = set; then :
+if ${ac_cv_path_TOOLS_DIR_CXX+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $TOOLS_DIR_CXX in
@@ -19732,7 +20180,7 @@
 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_POTENTIAL_CXX+set}" = set; then :
+if ${ac_cv_path_POTENTIAL_CXX+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $POTENTIAL_CXX in
@@ -20145,7 +20593,7 @@
 set dummy $ac_tool_prefix$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_prog_PROPER_COMPILER_CXX+set}" = set; then :
+if ${ac_cv_prog_PROPER_COMPILER_CXX+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$PROPER_COMPILER_CXX"; then
@@ -20189,7 +20637,7 @@
 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_prog_ac_ct_PROPER_COMPILER_CXX+set}" = set; then :
+if ${ac_cv_prog_ac_ct_PROPER_COMPILER_CXX+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_PROPER_COMPILER_CXX"; then
@@ -20643,7 +21091,7 @@
 set dummy $ac_tool_prefix$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_prog_CXX+set}" = set; then :
+if ${ac_cv_prog_CXX+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$CXX"; then
@@ -20687,7 +21135,7 @@
 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_prog_ac_ct_CXX+set}" = set; then :
+if ${ac_cv_prog_ac_ct_CXX+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_CXX"; then
@@ -20765,7 +21213,7 @@
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C++ compiler" >&5
 $as_echo_n "checking whether we are using the GNU C++ compiler... " >&6; }
-if test "${ac_cv_cxx_compiler_gnu+set}" = set; then :
+if ${ac_cv_cxx_compiler_gnu+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -20802,7 +21250,7 @@
 ac_save_CXXFLAGS=$CXXFLAGS
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts -g" >&5
 $as_echo_n "checking whether $CXX accepts -g... " >&6; }
-if test "${ac_cv_prog_cxx_g+set}" = set; then :
+if ${ac_cv_prog_cxx_g+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_save_cxx_werror_flag=$ac_cxx_werror_flag
@@ -20900,7 +21348,7 @@
 set dummy $ac_tool_prefix$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_prog_OBJC+set}" = set; then :
+if ${ac_cv_prog_OBJC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$OBJC"; then
@@ -20944,7 +21392,7 @@
 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_prog_ac_ct_OBJC+set}" = set; then :
+if ${ac_cv_prog_ac_ct_OBJC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_OBJC"; then
@@ -21020,7 +21468,7 @@
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU Objective C compiler" >&5
 $as_echo_n "checking whether we are using the GNU Objective C compiler... " >&6; }
-if test "${ac_cv_objc_compiler_gnu+set}" = set; then :
+if ${ac_cv_objc_compiler_gnu+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -21057,7 +21505,7 @@
 ac_save_OBJCFLAGS=$OBJCFLAGS
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $OBJC accepts -g" >&5
 $as_echo_n "checking whether $OBJC accepts -g... " >&6; }
-if test "${ac_cv_prog_objc_g+set}" = set; then :
+if ${ac_cv_prog_objc_g+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_save_objc_werror_flag=$ac_objc_werror_flag
@@ -21433,7 +21881,7 @@
 set dummy ${ac_tool_prefix}ar; 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_prog_AR+set}" = set; then :
+if ${ac_cv_prog_AR+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$AR"; then
@@ -21473,7 +21921,7 @@
 set dummy ar; 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_prog_ac_ct_AR+set}" = set; then :
+if ${ac_cv_prog_ac_ct_AR+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_AR"; then
@@ -21815,7 +22263,7 @@
 set dummy link; 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_prog_WINLD+set}" = set; then :
+if ${ac_cv_prog_WINLD+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$WINLD"; then
@@ -22154,7 +22602,7 @@
 set dummy mt; 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_prog_MT+set}" = set; then :
+if ${ac_cv_prog_MT+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$MT"; then
@@ -22475,7 +22923,7 @@
 set dummy rc; 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_prog_RC+set}" = set; then :
+if ${ac_cv_prog_RC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$RC"; then
@@ -22866,7 +23314,7 @@
 set dummy lib; 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_prog_WINAR+set}" = set; then :
+if ${ac_cv_prog_WINAR+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$WINAR"; then
@@ -23172,7 +23620,7 @@
 set dummy dumpbin; 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_prog_DUMPBIN+set}" = set; then :
+if ${ac_cv_prog_DUMPBIN+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$DUMPBIN"; then
@@ -23491,7 +23939,7 @@
   CPP=
 fi
 if test -z "$CPP"; then
-  if test "${ac_cv_prog_CPP+set}" = set; then :
+  if ${ac_cv_prog_CPP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
       # Double quotes because CPP needs to be expanded
@@ -23607,7 +24055,7 @@
   { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
 fi
 
 ac_ext=cpp
@@ -23891,7 +24339,7 @@
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C++ preprocessor" >&5
 $as_echo_n "checking how to run the C++ preprocessor... " >&6; }
 if test -z "$CXXCPP"; then
-  if test "${ac_cv_prog_CXXCPP+set}" = set; then :
+  if ${ac_cv_prog_CXXCPP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
       # Double quotes because CXXCPP needs to be expanded
@@ -24007,7 +24455,7 @@
   { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "C++ preprocessor \"$CXXCPP\" fails sanity check
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
 fi
 
 ac_ext=cpp
@@ -24309,7 +24757,7 @@
 set dummy as; 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_AS+set}" = set; then :
+if ${ac_cv_path_AS+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $AS in
@@ -24623,7 +25071,7 @@
 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_NM+set}" = set; then :
+if ${ac_cv_path_NM+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $NM in
@@ -24932,7 +25380,7 @@
 set dummy strip; 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_STRIP+set}" = set; then :
+if ${ac_cv_path_STRIP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $STRIP in
@@ -25238,7 +25686,7 @@
 set dummy mcs; 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_MCS+set}" = set; then :
+if ${ac_cv_path_MCS+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $MCS in
@@ -25546,7 +25994,7 @@
 set dummy ${ac_tool_prefix}nm; 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_prog_NM+set}" = set; then :
+if ${ac_cv_prog_NM+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$NM"; then
@@ -25586,7 +26034,7 @@
 set dummy nm; 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_prog_ac_ct_NM+set}" = set; then :
+if ${ac_cv_prog_ac_ct_NM+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_NM"; then
@@ -25904,7 +26352,7 @@
 set dummy ${ac_tool_prefix}strip; 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_prog_STRIP+set}" = set; then :
+if ${ac_cv_prog_STRIP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$STRIP"; then
@@ -25944,7 +26392,7 @@
 set dummy strip; 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_prog_ac_ct_STRIP+set}" = set; then :
+if ${ac_cv_prog_ac_ct_STRIP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_STRIP"; then
@@ -26269,7 +26717,7 @@
 set dummy $ac_tool_prefix$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_prog_OBJCOPY+set}" = set; then :
+if ${ac_cv_prog_OBJCOPY+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$OBJCOPY"; then
@@ -26313,7 +26761,7 @@
 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_prog_ac_ct_OBJCOPY+set}" = set; then :
+if ${ac_cv_prog_ac_ct_OBJCOPY+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_OBJCOPY"; then
@@ -26640,7 +27088,7 @@
 set dummy $ac_tool_prefix$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_prog_OBJDUMP+set}" = set; then :
+if ${ac_cv_prog_OBJDUMP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$OBJDUMP"; then
@@ -26684,7 +27132,7 @@
 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_prog_ac_ct_OBJDUMP+set}" = set; then :
+if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_OBJDUMP"; then
@@ -27008,7 +27456,7 @@
 set dummy lipo; 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_LIPO+set}" = set; then :
+if ${ac_cv_path_LIPO+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $LIPO in
@@ -27323,7 +27771,7 @@
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
 $as_echo_n "checking for ANSI C header files... " >&6; }
-if test "${ac_cv_header_stdc+set}" = set; then :
+if ${ac_cv_header_stdc+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -27499,7 +27947,7 @@
 for ac_header in stdio.h
 do :
   ac_fn_cxx_check_header_mongrel "$LINENO" "stdio.h" "ac_cv_header_stdio_h" "$ac_includes_default"
-if test "x$ac_cv_header_stdio_h" = x""yes; then :
+if test "x$ac_cv_header_stdio_h" = xyes; then :
   cat >>confdefs.h <<_ACEOF
 #define HAVE_STDIO_H 1
 _ACEOF
@@ -27528,7 +27976,7 @@
 # This bug is HP SR number 8606223364.
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking size of int *" >&5
 $as_echo_n "checking size of int *... " >&6; }
-if test "${ac_cv_sizeof_int_p+set}" = set; then :
+if ${ac_cv_sizeof_int_p+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if ac_fn_cxx_compute_int "$LINENO" "(long int) (sizeof (int *))" "ac_cv_sizeof_int_p"        "$ac_includes_default"; then :
@@ -27538,7 +27986,7 @@
      { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error 77 "cannot compute sizeof (int *)
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
    else
      ac_cv_sizeof_int_p=0
    fi
@@ -27585,7 +28033,7 @@
 #
  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5
 $as_echo_n "checking whether byte ordering is bigendian... " >&6; }
-if test "${ac_cv_c_bigendian+set}" = set; then :
+if ${ac_cv_c_bigendian+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_cv_c_bigendian=unknown
@@ -28596,8 +29044,8 @@
   have_x=disabled
 else
   case $x_includes,$x_libraries in #(
-    *\'*) as_fn_error $? "cannot use X directory names containing '" "$LINENO" 5 ;; #(
-    *,NONE | NONE,*) if test "${ac_cv_have_x+set}" = set; then :
+    *\'*) as_fn_error $? "cannot use X directory names containing '" "$LINENO" 5;; #(
+    *,NONE | NONE,*) if ${ac_cv_have_x+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   # One or both of the vars are not set, and there is no cached value.
@@ -28874,7 +29322,7 @@
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dnet_ntoa in -ldnet" >&5
 $as_echo_n "checking for dnet_ntoa in -ldnet... " >&6; }
-if test "${ac_cv_lib_dnet_dnet_ntoa+set}" = set; then :
+if ${ac_cv_lib_dnet_dnet_ntoa+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -28908,14 +29356,14 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dnet_dnet_ntoa" >&5
 $as_echo "$ac_cv_lib_dnet_dnet_ntoa" >&6; }
-if test "x$ac_cv_lib_dnet_dnet_ntoa" = x""yes; then :
+if test "x$ac_cv_lib_dnet_dnet_ntoa" = xyes; then :
   X_EXTRA_LIBS="$X_EXTRA_LIBS -ldnet"
 fi
 
     if test $ac_cv_lib_dnet_dnet_ntoa = no; then
       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dnet_ntoa in -ldnet_stub" >&5
 $as_echo_n "checking for dnet_ntoa in -ldnet_stub... " >&6; }
-if test "${ac_cv_lib_dnet_stub_dnet_ntoa+set}" = set; then :
+if ${ac_cv_lib_dnet_stub_dnet_ntoa+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -28949,7 +29397,7 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dnet_stub_dnet_ntoa" >&5
 $as_echo "$ac_cv_lib_dnet_stub_dnet_ntoa" >&6; }
-if test "x$ac_cv_lib_dnet_stub_dnet_ntoa" = x""yes; then :
+if test "x$ac_cv_lib_dnet_stub_dnet_ntoa" = xyes; then :
   X_EXTRA_LIBS="$X_EXTRA_LIBS -ldnet_stub"
 fi
 
@@ -28968,14 +29416,14 @@
     # The functions gethostbyname, getservbyname, and inet_addr are
     # in -lbsd on LynxOS 3.0.1/i386, according to Lars Hecking.
     ac_fn_cxx_check_func "$LINENO" "gethostbyname" "ac_cv_func_gethostbyname"
-if test "x$ac_cv_func_gethostbyname" = x""yes; then :
+if test "x$ac_cv_func_gethostbyname" = xyes; then :
 
 fi
 
     if test $ac_cv_func_gethostbyname = no; then
       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gethostbyname in -lnsl" >&5
 $as_echo_n "checking for gethostbyname in -lnsl... " >&6; }
-if test "${ac_cv_lib_nsl_gethostbyname+set}" = set; then :
+if ${ac_cv_lib_nsl_gethostbyname+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -29009,14 +29457,14 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nsl_gethostbyname" >&5
 $as_echo "$ac_cv_lib_nsl_gethostbyname" >&6; }
-if test "x$ac_cv_lib_nsl_gethostbyname" = x""yes; then :
+if test "x$ac_cv_lib_nsl_gethostbyname" = xyes; then :
   X_EXTRA_LIBS="$X_EXTRA_LIBS -lnsl"
 fi
 
       if test $ac_cv_lib_nsl_gethostbyname = no; then
 	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for gethostbyname in -lbsd" >&5
 $as_echo_n "checking for gethostbyname in -lbsd... " >&6; }
-if test "${ac_cv_lib_bsd_gethostbyname+set}" = set; then :
+if ${ac_cv_lib_bsd_gethostbyname+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -29050,7 +29498,7 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bsd_gethostbyname" >&5
 $as_echo "$ac_cv_lib_bsd_gethostbyname" >&6; }
-if test "x$ac_cv_lib_bsd_gethostbyname" = x""yes; then :
+if test "x$ac_cv_lib_bsd_gethostbyname" = xyes; then :
   X_EXTRA_LIBS="$X_EXTRA_LIBS -lbsd"
 fi
 
@@ -29065,14 +29513,14 @@
     # must be given before -lnsl if both are needed.  We assume that
     # if connect needs -lnsl, so does gethostbyname.
     ac_fn_cxx_check_func "$LINENO" "connect" "ac_cv_func_connect"
-if test "x$ac_cv_func_connect" = x""yes; then :
+if test "x$ac_cv_func_connect" = xyes; then :
 
 fi
 
     if test $ac_cv_func_connect = no; then
       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for connect in -lsocket" >&5
 $as_echo_n "checking for connect in -lsocket... " >&6; }
-if test "${ac_cv_lib_socket_connect+set}" = set; then :
+if ${ac_cv_lib_socket_connect+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -29106,7 +29554,7 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_socket_connect" >&5
 $as_echo "$ac_cv_lib_socket_connect" >&6; }
-if test "x$ac_cv_lib_socket_connect" = x""yes; then :
+if test "x$ac_cv_lib_socket_connect" = xyes; then :
   X_EXTRA_LIBS="-lsocket $X_EXTRA_LIBS"
 fi
 
@@ -29114,14 +29562,14 @@
 
     # Guillermo Gomez says -lposix is necessary on A/UX.
     ac_fn_cxx_check_func "$LINENO" "remove" "ac_cv_func_remove"
-if test "x$ac_cv_func_remove" = x""yes; then :
+if test "x$ac_cv_func_remove" = xyes; then :
 
 fi
 
     if test $ac_cv_func_remove = no; then
       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for remove in -lposix" >&5
 $as_echo_n "checking for remove in -lposix... " >&6; }
-if test "${ac_cv_lib_posix_remove+set}" = set; then :
+if ${ac_cv_lib_posix_remove+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -29155,7 +29603,7 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_posix_remove" >&5
 $as_echo "$ac_cv_lib_posix_remove" >&6; }
-if test "x$ac_cv_lib_posix_remove" = x""yes; then :
+if test "x$ac_cv_lib_posix_remove" = xyes; then :
   X_EXTRA_LIBS="$X_EXTRA_LIBS -lposix"
 fi
 
@@ -29163,14 +29611,14 @@
 
     # BSDI BSD/OS 2.1 needs -lipc for XOpenDisplay.
     ac_fn_cxx_check_func "$LINENO" "shmat" "ac_cv_func_shmat"
-if test "x$ac_cv_func_shmat" = x""yes; then :
+if test "x$ac_cv_func_shmat" = xyes; then :
 
 fi
 
     if test $ac_cv_func_shmat = no; then
       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shmat in -lipc" >&5
 $as_echo_n "checking for shmat in -lipc... " >&6; }
-if test "${ac_cv_lib_ipc_shmat+set}" = set; then :
+if ${ac_cv_lib_ipc_shmat+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -29204,7 +29652,7 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ipc_shmat" >&5
 $as_echo "$ac_cv_lib_ipc_shmat" >&6; }
-if test "x$ac_cv_lib_ipc_shmat" = x""yes; then :
+if test "x$ac_cv_lib_ipc_shmat" = xyes; then :
   X_EXTRA_LIBS="$X_EXTRA_LIBS -lipc"
 fi
 
@@ -29222,7 +29670,7 @@
   # John Interrante, Karl Berry
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for IceConnectionNumber in -lICE" >&5
 $as_echo_n "checking for IceConnectionNumber in -lICE... " >&6; }
-if test "${ac_cv_lib_ICE_IceConnectionNumber+set}" = set; then :
+if ${ac_cv_lib_ICE_IceConnectionNumber+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -29256,7 +29704,7 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ICE_IceConnectionNumber" >&5
 $as_echo "$ac_cv_lib_ICE_IceConnectionNumber" >&6; }
-if test "x$ac_cv_lib_ICE_IceConnectionNumber" = x""yes; then :
+if test "x$ac_cv_lib_ICE_IceConnectionNumber" = xyes; then :
   X_PRE_LIBS="$X_PRE_LIBS -lSM -lICE"
 fi
 
@@ -30269,7 +30717,7 @@
             LDFLAGS="$FREETYPE2_LIBS"
             { $as_echo "$as_me:${as_lineno-$LINENO}: checking for FT_Init_FreeType in -lfreetype" >&5
 $as_echo_n "checking for FT_Init_FreeType in -lfreetype... " >&6; }
-if test "${ac_cv_lib_freetype_FT_Init_FreeType+set}" = set; then :
+if ${ac_cv_lib_freetype_FT_Init_FreeType+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -30303,7 +30751,7 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_freetype_FT_Init_FreeType" >&5
 $as_echo "$ac_cv_lib_freetype_FT_Init_FreeType" >&6; }
-if test "x$ac_cv_lib_freetype_FT_Init_FreeType" = x""yes; then :
+if test "x$ac_cv_lib_freetype_FT_Init_FreeType" = xyes; then :
   FREETYPE2_FOUND=true
 else
   as_fn_error $? "Could not find freetype2! $HELP_MSG " "$LINENO" 5
@@ -30591,7 +31039,7 @@
 	    for ac_header in alsa/asoundlib.h
 do :
   ac_fn_cxx_check_header_mongrel "$LINENO" "alsa/asoundlib.h" "ac_cv_header_alsa_asoundlib_h" "$ac_includes_default"
-if test "x$ac_cv_header_alsa_asoundlib_h" = x""yes; then :
+if test "x$ac_cv_header_alsa_asoundlib_h" = xyes; then :
   cat >>confdefs.h <<_ACEOF
 #define HAVE_ALSA_ASOUNDLIB_H 1
 _ACEOF
@@ -30650,7 +31098,7 @@
 USE_EXTERNAL_LIBJPEG=true
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ljpeg" >&5
 $as_echo_n "checking for main in -ljpeg... " >&6; }
-if test "${ac_cv_lib_jpeg_main+set}" = set; then :
+if ${ac_cv_lib_jpeg_main+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -30678,7 +31126,7 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_jpeg_main" >&5
 $as_echo "$ac_cv_lib_jpeg_main" >&6; }
-if test "x$ac_cv_lib_jpeg_main" = x""yes; then :
+if test "x$ac_cv_lib_jpeg_main" = xyes; then :
   cat >>confdefs.h <<_ACEOF
 #define HAVE_LIBJPEG 1
 _ACEOF
@@ -30702,7 +31150,7 @@
 USE_EXTERNAL_LIBJPEG=true
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -lgif" >&5
 $as_echo_n "checking for main in -lgif... " >&6; }
-if test "${ac_cv_lib_gif_main+set}" = set; then :
+if ${ac_cv_lib_gif_main+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -30730,7 +31178,7 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gif_main" >&5
 $as_echo "$ac_cv_lib_gif_main" >&6; }
-if test "x$ac_cv_lib_gif_main" = x""yes; then :
+if test "x$ac_cv_lib_gif_main" = xyes; then :
   cat >>confdefs.h <<_ACEOF
 #define HAVE_LIBGIF 1
 _ACEOF
@@ -30760,7 +31208,7 @@
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for compress in -lz" >&5
 $as_echo_n "checking for compress in -lz... " >&6; }
-if test "${ac_cv_lib_z_compress+set}" = set; then :
+if ${ac_cv_lib_z_compress+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -30794,7 +31242,7 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_z_compress" >&5
 $as_echo "$ac_cv_lib_z_compress" >&6; }
-if test "x$ac_cv_lib_z_compress" = x""yes; then :
+if test "x$ac_cv_lib_z_compress" = xyes; then :
    ZLIB_FOUND=yes
 else
    ZLIB_FOUND=no
@@ -30887,7 +31335,7 @@
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for cos in -lm" >&5
 $as_echo_n "checking for cos in -lm... " >&6; }
-if test "${ac_cv_lib_m_cos+set}" = set; then :
+if ${ac_cv_lib_m_cos+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -30921,7 +31369,7 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_m_cos" >&5
 $as_echo "$ac_cv_lib_m_cos" >&6; }
-if test "x$ac_cv_lib_m_cos" = x""yes; then :
+if test "x$ac_cv_lib_m_cos" = xyes; then :
   cat >>confdefs.h <<_ACEOF
 #define HAVE_LIBM 1
 _ACEOF
@@ -30945,7 +31393,7 @@
 LIBS=""
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
 $as_echo_n "checking for dlopen in -ldl... " >&6; }
-if test "${ac_cv_lib_dl_dlopen+set}" = set; then :
+if ${ac_cv_lib_dl_dlopen+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=$LIBS
@@ -30979,7 +31427,7 @@
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
 $as_echo "$ac_cv_lib_dl_dlopen" >&6; }
-if test "x$ac_cv_lib_dl_dlopen" = x""yes; then :
+if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
   cat >>confdefs.h <<_ACEOF
 #define HAVE_LIBDL 1
 _ACEOF
@@ -31653,7 +32101,7 @@
 set dummy ccache; 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_CCACHE+set}" = set; then :
+if ${ac_cv_path_CCACHE+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   case $CCACHE in
@@ -31914,10 +32362,21 @@
      :end' >>confcache
 if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
   if test -w "$cache_file"; then
-    test "x$cache_file" != "x/dev/null" &&
+    if test "x$cache_file" != "x/dev/null"; then
       { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
 $as_echo "$as_me: updating cache $cache_file" >&6;}
-    cat confcache >$cache_file
+      if test ! -f "$cache_file" || test -h "$cache_file"; then
+	cat confcache >"$cache_file"
+      else
+        case $cache_file in #(
+        */* | ?:*)
+	  mv -f confcache "$cache_file"$$ &&
+	  mv -f "$cache_file"$$ "$cache_file" ;; #(
+        *)
+	  mv -f confcache "$cache_file" ;;
+	esac
+      fi
+    fi
   else
     { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
@@ -31949,7 +32408,7 @@
 
 
 
-: ${CONFIG_STATUS=./config.status}
+: "${CONFIG_STATUS=./config.status}"
 ac_write_fail=0
 ac_clean_files_save=$ac_clean_files
 ac_clean_files="$ac_clean_files $CONFIG_STATUS"
@@ -32050,6 +32509,7 @@
 IFS=" ""	$as_nl"
 
 # Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
 case $0 in #((
   *[\\/]* ) as_myself=$0 ;;
   *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
@@ -32357,7 +32817,7 @@
 # values after options handling.
 ac_log="
 This file was extended by OpenJDK $as_me jdk8, which was
-generated by GNU Autoconf 2.67.  Invocation command line was
+generated by GNU Autoconf 2.68.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
   CONFIG_HEADERS  = $CONFIG_HEADERS
@@ -32420,7 +32880,7 @@
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
 OpenJDK config.status jdk8
-configured by $0, generated by GNU Autoconf 2.67,
+configured by $0, generated by GNU Autoconf 2.68,
   with options \\"\$ac_cs_config\\"
 
 Copyright (C) 2010 Free Software Foundation, Inc.
@@ -32549,7 +33009,7 @@
     "$OUTPUT_ROOT/spec.sh") CONFIG_FILES="$CONFIG_FILES $OUTPUT_ROOT/spec.sh:$AUTOCONF_DIR/spec.sh.in" ;;
     "$OUTPUT_ROOT/Makefile") CONFIG_FILES="$CONFIG_FILES $OUTPUT_ROOT/Makefile:$AUTOCONF_DIR/Makefile.in" ;;
 
-  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5 ;;
+  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
   esac
 done
 
@@ -32571,9 +33031,10 @@
 # after its creation but before its name has been assigned to `$tmp'.
 $debug ||
 {
-  tmp=
+  tmp= ac_tmp=
   trap 'exit_status=$?
-  { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
+  : "${ac_tmp:=$tmp}"
+  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
 ' 0
   trap 'as_fn_exit 1' 1 2 13 15
 }
@@ -32581,12 +33042,13 @@
 
 {
   tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
-  test -n "$tmp" && test -d "$tmp"
+  test -d "$tmp"
 }  ||
 {
   tmp=./conf$$-$RANDOM
   (umask 077 && mkdir "$tmp")
 } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
+ac_tmp=$tmp
 
 # Set up the scripts for CONFIG_FILES section.
 # No need to generate them if there are no CONFIG_FILES.
@@ -32608,7 +33070,7 @@
   ac_cs_awk_cr=$ac_cr
 fi
 
-echo 'BEGIN {' >"$tmp/subs1.awk" &&
+echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
 _ACEOF
 
 
@@ -32636,7 +33098,7 @@
 rm -f conf$$subs.sh
 
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-cat >>"\$tmp/subs1.awk" <<\\_ACAWK &&
+cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
 _ACEOF
 sed -n '
 h
@@ -32684,7 +33146,7 @@
 rm -f conf$$subs.awk
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 _ACAWK
-cat >>"\$tmp/subs1.awk" <<_ACAWK &&
+cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
   for (key in S) S_is_set[key] = 1
   FS = ""
 
@@ -32716,7 +33178,7 @@
   sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
 else
   cat
-fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \
+fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
   || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
 _ACEOF
 
@@ -32750,7 +33212,7 @@
 # No need to generate them if there are no CONFIG_HEADERS.
 # This happens for instance with `./config.status Makefile'.
 if test -n "$CONFIG_HEADERS"; then
-cat >"$tmp/defines.awk" <<\_ACAWK ||
+cat >"$ac_tmp/defines.awk" <<\_ACAWK ||
 BEGIN {
 _ACEOF
 
@@ -32762,8 +33224,8 @@
 # handling of long lines.
 ac_delim='%!_!# '
 for ac_last_try in false false :; do
-  ac_t=`sed -n "/$ac_delim/p" confdefs.h`
-  if test -z "$ac_t"; then
+  ac_tt=`sed -n "/$ac_delim/p" confdefs.h`
+  if test -z "$ac_tt"; then
     break
   elif $ac_last_try; then
     as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5
@@ -32864,7 +33326,7 @@
   esac
   case $ac_mode$ac_tag in
   :[FHL]*:*);;
-  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5 ;;
+  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
   :[FH]-) ac_tag=-:-;;
   :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
   esac
@@ -32883,7 +33345,7 @@
     for ac_f
     do
       case $ac_f in
-      -) ac_f="$tmp/stdin";;
+      -) ac_f="$ac_tmp/stdin";;
       *) # Look for the file first in the build tree, then in the source tree
 	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
 	 # because $ac_f cannot contain `:'.
@@ -32892,7 +33354,7 @@
 	   [\\/$]*) false;;
 	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
 	   esac ||
-	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5 ;;
+	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
       esac
       case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
       as_fn_append ac_file_inputs " '$ac_f'"
@@ -32918,8 +33380,8 @@
     esac
 
     case $ac_tag in
-    *:-:* | *:-) cat >"$tmp/stdin" \
-      || as_fn_error $? "could not create $ac_file" "$LINENO" 5  ;;
+    *:-:* | *:-) cat >"$ac_tmp/stdin" \
+      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
     esac
     ;;
   esac
@@ -33044,21 +33506,22 @@
 s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
 $ac_datarootdir_hack
 "
-eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \
-  || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
+  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
 
 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
-  { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
-  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' \
+      "$ac_tmp/out"`; test -z "$ac_out"; } &&
   { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
 which seems to be undefined.  Please make sure it is defined" >&5
 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
 which seems to be undefined.  Please make sure it is defined" >&2;}
 
-  rm -f "$tmp/stdin"
+  rm -f "$ac_tmp/stdin"
   case $ac_file in
-  -) cat "$tmp/out" && rm -f "$tmp/out";;
-  *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";;
+  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
+  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
   esac \
   || as_fn_error $? "could not create $ac_file" "$LINENO" 5
  ;;
@@ -33069,20 +33532,20 @@
   if test x"$ac_file" != x-; then
     {
       $as_echo "/* $configure_input  */" \
-      && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs"
-    } >"$tmp/config.h" \
+      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs"
+    } >"$ac_tmp/config.h" \
       || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-    if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then
+    if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then
       { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
 $as_echo "$as_me: $ac_file is unchanged" >&6;}
     else
       rm -f "$ac_file"
-      mv "$tmp/config.h" "$ac_file" \
+      mv "$ac_tmp/config.h" "$ac_file" \
 	|| as_fn_error $? "could not create $ac_file" "$LINENO" 5
     fi
   else
     $as_echo "/* $configure_input  */" \
-      && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \
+      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \
       || as_fn_error $? "could not create -" "$LINENO" 5
   fi
  ;;
--- a/common/autoconf/spec.gmk.in	Fri Mar 15 19:30:28 2013 +0530
+++ b/common/autoconf/spec.gmk.in	Fri Mar 15 23:31:19 2013 -0700
@@ -285,6 +285,10 @@
 X_LIBS:=@X_LIBS@
 OPENWIN_HOME:=@OPENWIN_HOME@
 
+# DirectX SDK
+DXSDK_LIB_PATH=@DXSDK_LIB_PATH@
+DXSDK_INCLUDE_PATH=@DXSDK_INCLUDE_PATH@
+
 # The lowest required version of macosx to enforce compatiblity for
 MACOSX_VERSION_MIN=@MACOSX_VERSION_MIN@
 
--- a/common/autoconf/toolchain.m4	Fri Mar 15 19:30:28 2013 +0530
+++ b/common/autoconf/toolchain.m4	Fri Mar 15 23:31:19 2013 -0700
@@ -176,6 +176,7 @@
 [
 if test "x$OPENJDK_TARGET_OS" = "xwindows"; then
   TOOLCHAIN_SETUP_VISUAL_STUDIO_ENV
+  TOOLCHAIN_SETUP_DXSDK
 fi
 
 AC_SUBST(MSVCR_DLL)
--- a/common/autoconf/toolchain_windows.m4	Fri Mar 15 19:30:28 2013 +0530
+++ b/common/autoconf/toolchain_windows.m4	Fri Mar 15 23:31:19 2013 -0700
@@ -262,3 +262,61 @@
   AC_MSG_RESULT([$MSVCR_DLL])
   BASIC_FIXUP_PATH(MSVCR_DLL)
 ])
+
+
+# Setup the DXSDK paths
+AC_DEFUN([TOOLCHAIN_SETUP_DXSDK],
+[
+  AC_ARG_WITH(dxsdk, [AS_HELP_STRING([--with-dxsdk],
+      [the DirectX SDK (Windows only) @<:@probed@:>@])])
+  AC_ARG_WITH(dxsdk-lib, [AS_HELP_STRING([--with-dxsdk-lib],
+      [the DirectX SDK lib directory (Windows only) @<:@probed@:>@])])
+  AC_ARG_WITH(dxsdk-include, [AS_HELP_STRING([--with-dxsdk-include],
+      [the DirectX SDK include directory (Windows only) @<:@probed@:>@])])
+
+  AC_MSG_CHECKING([for DirectX SDK])
+
+  if test "x$with_dxsdk" != x; then
+    dxsdk_path="$with_dxsdk"
+  elif test "x$DXSDK_DIR" != x; then
+    dxsdk_path="$DXSDK_DIR"
+  elif test -d "C:/DXSDK"; then
+    dxsdk_path="C:/DXSDK"
+  else
+    AC_MSG_ERROR([Could not find the DirectX SDK])
+  fi
+  AC_MSG_RESULT([$dxsdk_path])
+  BASIC_FIXUP_PATH(dxsdk_path)
+
+  AC_MSG_CHECKING([for DirectX SDK lib dir])
+  if test "x$with_dxsdk_lib" != x; then
+    DXSDK_LIB_PATH="$with_dxsdk_lib"
+  elif test "x$OPENJDK_TARGET_CPU" = "xx86_64"; then
+    DXSDK_LIB_PATH="$dxsdk_path/Lib/x64"
+  else
+    DXSDK_LIB_PATH="$dxsdk_path/Lib"
+  fi
+  # dsound.lib is linked to in jsoundds
+  if test ! -f "$DXSDK_LIB_PATH/dsound.lib"; then
+    AC_MSG_ERROR([Invalid DirectX SDK lib dir])
+  fi
+  AC_MSG_RESULT([$DXSDK_LIB_PATH])
+  BASIC_FIXUP_PATH(DXSDK_LIB_PATH)
+
+  AC_MSG_CHECKING([for DirectX SDK include dir])
+  if test "x$with_dxsdk_include" != x; then
+    DXSDK_INCLUDE_PATH="$with_dxsdk_include"
+  else
+    DXSDK_INCLUDE_PATH="$dxsdk_path/Include"
+  fi
+  # dsound.h is included in jsoundds
+  if test ! -f "$DXSDK_INCLUDE_PATH/dsound.h"; then
+    AC_MSG_ERROR([Invalid DirectX SDK lib dir])
+  fi
+  AC_MSG_RESULT([$DXSDK_INCLUDE_PATH])
+  BASIC_FIXUP_PATH(DXSDK_INCLUDE_PATH)
+
+  AC_SUBST(DXSDK_LIB_PATH)
+  AC_SUBST(DXSDK_INCLUDE_PATH)
+  LDFLAGS_JDK="$LDFLAGS_JDK -libpath:$DXSDK_LIB_PATH"
+])
--- a/corba/.hgtags	Fri Mar 15 19:30:28 2013 +0530
+++ b/corba/.hgtags	Fri Mar 15 23:31:19 2013 -0700
@@ -201,3 +201,4 @@
 35684a40c5845782324dbcc9ac8969528020ff61 jdk8-b77
 27d6368ae8ba570c31c2f0e696d39c99fa2f4538 jdk8-b78
 e41fb1aa0329767b2737303c994e38bede1baa07 jdk8-b79
+5f3d4a6bdd027a1631d97e2dfff63fd5e46987a4 jdk8-b80
--- a/hotspot/.hgtags	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/.hgtags	Fri Mar 15 23:31:19 2013 -0700
@@ -320,3 +320,5 @@
 555ec35a250783110aa070dbc8a8603f6cabe41f hs25-b20
 6691814929b606fe0e7954fd6e485dd876505c83 jdk8-b79
 df5396524152118535c36da5801d828b560d19a2 hs25-b21
+4a198b201f3ce84433fa94a3ca65d061473e7c4c jdk8-b80
+dd6350b4abc4a6c19c89dd982cc0e4f3d119885c hs25-b22
--- a/hotspot/agent/src/os/bsd/MacosxDebuggerLocal.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/agent/src/os/bsd/MacosxDebuggerLocal.m	Fri Mar 15 23:31:19 2013 -0700
@@ -160,7 +160,7 @@
   CHECK_EXCEPTION_(0);
 
   unsigned long alignedAddress;
-  unsigned long alignedLength;
+  unsigned long alignedLength = 0;
   kern_return_t result;
   vm_offset_t *pages;
   int *mapped;
@@ -630,7 +630,7 @@
     /* Couldn't find entry point.  error_message should contain some
      * platform dependent error message.
      */
-    THROW_NEW_DEBUGGER_EXCEPTION(error_message);
+    THROW_NEW_DEBUGGER_EXCEPTION_(error_message, (jlong)func);
   }
   return (jlong)func;
 }
--- a/hotspot/agent/src/os/linux/LinuxDebuggerLocal.c	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/agent/src/os/linux/LinuxDebuggerLocal.c	Fri Mar 15 23:31:19 2013 -0700
@@ -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
@@ -25,6 +25,13 @@
 #include <jni.h>
 #include "libproc.h"
 
+#include <elf.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <string.h>
+#include <limits.h>
+
 #if defined(x86_64) && !defined(amd64)
 #define amd64 1
 #endif
@@ -154,6 +161,39 @@
   }
 }
 
+
+/*
+ * Verify that a named ELF binary file (core or executable) has the same
+ * bitness as ourselves.
+ * Throw an exception if there is a mismatch or other problem.
+ *
+ * If we proceed using a mismatched debugger/debuggee, the best to hope
+ * for is a missing symbol, the worst is a crash searching for debug symbols.
+ */
+void verifyBitness(JNIEnv *env, const char *binaryName) {
+  int fd = open(binaryName, O_RDONLY);
+  if (fd < 0) {
+    THROW_NEW_DEBUGGER_EXCEPTION("cannot open binary file");
+  }
+  unsigned char elf_ident[EI_NIDENT];
+  int i = read(fd, &elf_ident, sizeof(elf_ident));
+  close(fd);
+
+  if (i < 0) {
+    THROW_NEW_DEBUGGER_EXCEPTION("cannot read binary file");
+  }
+#ifndef _LP64
+  if (elf_ident[EI_CLASS] == ELFCLASS64) {
+    THROW_NEW_DEBUGGER_EXCEPTION("debuggee is 64 bit, use 64-bit java for debugger");
+  }
+#else
+  if (elf_ident[EI_CLASS] != ELFCLASS64) {
+    THROW_NEW_DEBUGGER_EXCEPTION("debuggee is 32 bit, use 32 bit java for debugger");
+  }
+#endif
+}
+
+
 /*
  * Class:     sun_jvm_hotspot_debugger_linux_LinuxDebuggerLocal
  * Method:    attach0
@@ -162,6 +202,12 @@
 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_linux_LinuxDebuggerLocal_attach0__I
   (JNIEnv *env, jobject this_obj, jint jpid) {
 
+  // For bitness checking, locate binary at /proc/jpid/exe
+  char buf[PATH_MAX];
+  snprintf((char *) &buf, PATH_MAX, "/proc/%d/exe", jpid);
+  verifyBitness(env, (char *) &buf);
+  CHECK_EXCEPTION;
+
   struct ps_prochandle* ph;
   if ( (ph = Pgrab(jpid)) == NULL) {
     THROW_NEW_DEBUGGER_EXCEPTION("Can't attach to the process");
@@ -187,6 +233,9 @@
   coreName_cstr = (*env)->GetStringUTFChars(env, coreName, &isCopy);
   CHECK_EXCEPTION;
 
+  verifyBitness(env, execName_cstr);
+  CHECK_EXCEPTION;
+
   if ( (ph = Pgrab_core(execName_cstr, coreName_cstr)) == NULL) {
     (*env)->ReleaseStringUTFChars(env, execName, execName_cstr);
     (*env)->ReleaseStringUTFChars(env, coreName, coreName_cstr);
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/amd64/LinuxAMD64CFrame.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/amd64/LinuxAMD64CFrame.java	Fri Mar 15 23:31:19 2013 -0700
@@ -60,8 +60,13 @@
         return null;
       }
 
+      // Check alignment of rbp
+      if ( dbg.getAddressValue(rbp) % ADDRESS_SIZE != 0) {
+        return null;
+      }
+
       Address nextRBP = rbp.getAddressAt( 0 * ADDRESS_SIZE);
-      if (nextRBP == null) {
+      if (nextRBP == null || nextRBP.lessThanOrEqual(rbp)) {
         return null;
       }
       Address nextPC  = rbp.getAddressAt( 1 * ADDRESS_SIZE);
--- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/x86/LinuxX86CFrame.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/x86/LinuxX86CFrame.java	Fri Mar 15 23:31:19 2013 -0700
@@ -61,8 +61,13 @@
         return null;
       }
 
+      // Check alignment of ebp
+      if ( dbg.getAddressValue(ebp) % ADDRESS_SIZE != 0) {
+        return null;
+      }
+
       Address nextEBP = ebp.getAddressAt( 0 * ADDRESS_SIZE);
-      if (nextEBP == null) {
+      if (nextEBP == null || nextEBP.lessThanOrEqual(ebp)) {
         return null;
       }
       Address nextPC  = ebp.getAddressAt( 1 * ADDRESS_SIZE);
--- a/hotspot/make/bsd/makefiles/gcc.make	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/make/bsd/makefiles/gcc.make	Fri Mar 15 23:31:19 2013 -0700
@@ -229,6 +229,20 @@
 CFLAGS += -DDONT_USE_PRECOMPILED_HEADER
 endif
 
+ifeq ($(OS_VENDOR), Darwin)
+  # Setting these parameters makes it an error to link to macosx APIs that are 
+  # newer than the given OS version and makes the linked binaries compatible even
+  # if built on a newer version of the OS.
+  # The expected format is X.Y.Z
+  ifeq ($(MACOSX_VERSION_MIN),)
+    MACOSX_VERSION_MIN=10.7.0
+  endif
+  # The macro takes the version with no dots, ex: 1070
+  CFLAGS += -DMAC_OS_X_VERSION_MAX_ALLOWED=$(subst .,,$(MACOSX_VERSION_MIN)) \
+            -mmacosx-version-min=$(MACOSX_VERSION_MIN)
+  LDFLAGS += -mmacosx-version-min=$(MACOSX_VERSION_MIN)
+endif
+
 #------------------------------------------------------------------------
 # Linker flags
 
--- a/hotspot/make/hotspot_version	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/make/hotspot_version	Fri Mar 15 23:31:19 2013 -0700
@@ -35,7 +35,7 @@
 
 HS_MAJOR_VER=25
 HS_MINOR_VER=0
-HS_BUILD_NUMBER=21
+HS_BUILD_NUMBER=22
 
 JDK_MAJOR_VER=1
 JDK_MINOR_VER=8
--- a/hotspot/src/os/bsd/vm/os_bsd.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os/bsd/vm/os_bsd.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -2695,7 +2695,7 @@
   assert(thread->is_VM_thread(), "Must be VMThread");
   // read current suspend action
   int action = osthread->sr.suspend_action();
-  if (action == SR_SUSPEND) {
+  if (action == os::Bsd::SuspendResume::SR_SUSPEND) {
     suspend_save_context(osthread, siginfo, context);
 
     // Notify the suspend action is about to be completed. do_suspend()
@@ -2717,12 +2717,12 @@
     do {
       sigsuspend(&suspend_set);
       // ignore all returns until we get a resume signal
-    } while (osthread->sr.suspend_action() != SR_CONTINUE);
+    } while (osthread->sr.suspend_action() != os::Bsd::SuspendResume::SR_CONTINUE);
 
     resume_clear_context(osthread);
 
   } else {
-    assert(action == SR_CONTINUE, "unexpected sr action");
+    assert(action == os::Bsd::SuspendResume::SR_CONTINUE, "unexpected sr action");
     // nothing special to do - just leave the handler
   }
 
@@ -2776,7 +2776,7 @@
 // but this seems the normal response to library errors
 static bool do_suspend(OSThread* osthread) {
   // mark as suspended and send signal
-  osthread->sr.set_suspend_action(SR_SUSPEND);
+  osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_SUSPEND);
   int status = pthread_kill(osthread->pthread_id(), SR_signum);
   assert_status(status == 0, status, "pthread_kill");
 
@@ -2785,18 +2785,18 @@
     for (int i = 0; !osthread->sr.is_suspended(); i++) {
       os::yield_all(i);
     }
-    osthread->sr.set_suspend_action(SR_NONE);
+    osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_NONE);
     return true;
   }
   else {
-    osthread->sr.set_suspend_action(SR_NONE);
+    osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_NONE);
     return false;
   }
 }
 
 static void do_resume(OSThread* osthread) {
   assert(osthread->sr.is_suspended(), "thread should be suspended");
-  osthread->sr.set_suspend_action(SR_CONTINUE);
+  osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_CONTINUE);
 
   int status = pthread_kill(osthread->pthread_id(), SR_signum);
   assert_status(status == 0, status, "pthread_kill");
@@ -2806,7 +2806,7 @@
       os::yield_all(i);
     }
   }
-  osthread->sr.set_suspend_action(SR_NONE);
+  osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_NONE);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -3903,15 +3903,27 @@
 jlong os::current_thread_cpu_time() {
 #ifdef __APPLE__
   return os::thread_cpu_time(Thread::current(), true /* user + sys */);
+#else
+  Unimplemented();
+  return 0;
 #endif
 }
 
 jlong os::thread_cpu_time(Thread* thread) {
+#ifdef __APPLE__
+  return os::thread_cpu_time(thread, true /* user + sys */);
+#else
+  Unimplemented();
+  return 0;
+#endif
 }
 
 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
 #ifdef __APPLE__
   return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
+#else
+  Unimplemented();
+  return 0;
 #endif
 }
 
@@ -3935,6 +3947,9 @@
   } else {
     return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
   }
+#else
+  Unimplemented();
+  return 0;
 #endif
 }
 
--- a/hotspot/src/os/bsd/vm/os_bsd.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os/bsd/vm/os_bsd.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -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
@@ -151,36 +151,25 @@
   // for BsdThreads are no longer needed.
   class SuspendResume {
   private:
-    volatile int _suspend_action;
+    volatile int  _suspend_action;
+    volatile jint _state;
+  public:
     // values for suspend_action:
-    #define SR_NONE               (0x00)
-    #define SR_SUSPEND            (0x01)  // suspend request
-    #define SR_CONTINUE           (0x02)  // resume request
+    enum {
+      SR_NONE              = 0x00,
+      SR_SUSPEND           = 0x01,  // suspend request
+      SR_CONTINUE          = 0x02,  // resume request
+      SR_SUSPENDED         = 0x20   // values for _state: + SR_NONE
+    };
 
-    volatile jint _state;
-    // values for _state: + SR_NONE
-    #define SR_SUSPENDED          (0x20)
-  public:
     SuspendResume() { _suspend_action = SR_NONE; _state = SR_NONE; }
 
     int suspend_action() const     { return _suspend_action; }
     void set_suspend_action(int x) { _suspend_action = x;    }
 
     // atomic updates for _state
-    void set_suspended()           {
-      jint temp, temp2;
-      do {
-        temp = _state;
-        temp2 = Atomic::cmpxchg(temp | SR_SUSPENDED, &_state, temp);
-      } while (temp2 != temp);
-    }
-    void clear_suspended()        {
-      jint temp, temp2;
-      do {
-        temp = _state;
-        temp2 = Atomic::cmpxchg(temp & ~SR_SUSPENDED, &_state, temp);
-      } while (temp2 != temp);
-    }
+    inline void set_suspended();
+    inline void clear_suspended();
     bool is_suspended()            { return _state & SR_SUSPENDED;       }
 
     #undef SR_SUSPENDED
--- a/hotspot/src/os/bsd/vm/os_bsd.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os/bsd/vm/os_bsd.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -25,7 +25,6 @@
 #ifndef OS_BSD_VM_OS_BSD_INLINE_HPP
 #define OS_BSD_VM_OS_BSD_INLINE_HPP
 
-#include "runtime/atomic.hpp"
 #include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 
@@ -286,4 +285,21 @@
                             const char* optval, socklen_t optlen) {
   return ::setsockopt(fd, level, optname, optval, optlen);
 }
+
+inline void os::Bsd::SuspendResume::set_suspended()           {
+  jint temp, temp2;
+  do {
+    temp = _state;
+    temp2 = Atomic::cmpxchg(temp | SR_SUSPENDED, &_state, temp);
+  } while (temp2 != temp);
+}
+
+inline void os::Bsd::SuspendResume::clear_suspended()        {
+  jint temp, temp2;
+  do {
+    temp = _state;
+    temp2 = Atomic::cmpxchg(temp & ~SR_SUSPENDED, &_state, temp);
+  } while (temp2 != temp);
+}
+
 #endif // OS_BSD_VM_OS_BSD_INLINE_HPP
--- a/hotspot/src/os/linux/vm/os_linux.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os/linux/vm/os_linux.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -3461,7 +3461,7 @@
   assert(thread->is_VM_thread(), "Must be VMThread");
   // read current suspend action
   int action = osthread->sr.suspend_action();
-  if (action == SR_SUSPEND) {
+  if (action == os::Linux::SuspendResume::SR_SUSPEND) {
     suspend_save_context(osthread, siginfo, context);
 
     // Notify the suspend action is about to be completed. do_suspend()
@@ -3483,12 +3483,12 @@
     do {
       sigsuspend(&suspend_set);
       // ignore all returns until we get a resume signal
-    } while (osthread->sr.suspend_action() != SR_CONTINUE);
+    } while (osthread->sr.suspend_action() != os::Linux::SuspendResume::SR_CONTINUE);
 
     resume_clear_context(osthread);
 
   } else {
-    assert(action == SR_CONTINUE, "unexpected sr action");
+    assert(action == os::Linux::SuspendResume::SR_CONTINUE, "unexpected sr action");
     // nothing special to do - just leave the handler
   }
 
@@ -3542,7 +3542,7 @@
 // but this seems the normal response to library errors
 static bool do_suspend(OSThread* osthread) {
   // mark as suspended and send signal
-  osthread->sr.set_suspend_action(SR_SUSPEND);
+  osthread->sr.set_suspend_action(os::Linux::SuspendResume::SR_SUSPEND);
   int status = pthread_kill(osthread->pthread_id(), SR_signum);
   assert_status(status == 0, status, "pthread_kill");
 
@@ -3551,18 +3551,18 @@
     for (int i = 0; !osthread->sr.is_suspended(); i++) {
       os::yield_all(i);
     }
-    osthread->sr.set_suspend_action(SR_NONE);
+    osthread->sr.set_suspend_action(os::Linux::SuspendResume::SR_NONE);
     return true;
   }
   else {
-    osthread->sr.set_suspend_action(SR_NONE);
+    osthread->sr.set_suspend_action(os::Linux::SuspendResume::SR_NONE);
     return false;
   }
 }
 
 static void do_resume(OSThread* osthread) {
   assert(osthread->sr.is_suspended(), "thread should be suspended");
-  osthread->sr.set_suspend_action(SR_CONTINUE);
+  osthread->sr.set_suspend_action(os::Linux::SuspendResume::SR_CONTINUE);
 
   int status = pthread_kill(osthread->pthread_id(), SR_signum);
   assert_status(status == 0, status, "pthread_kill");
@@ -3572,7 +3572,7 @@
       os::yield_all(i);
     }
   }
-  osthread->sr.set_suspend_action(SR_NONE);
+  osthread->sr.set_suspend_action(os::Linux::SuspendResume::SR_NONE);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
--- a/hotspot/src/os/linux/vm/os_linux.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os/linux/vm/os_linux.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -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
@@ -209,39 +209,27 @@
   // for LinuxThreads are no longer needed.
   class SuspendResume {
   private:
-    volatile int _suspend_action;
+    volatile int  _suspend_action;
+    volatile jint _state;
+  public:
     // values for suspend_action:
-    #define SR_NONE               (0x00)
-    #define SR_SUSPEND            (0x01)  // suspend request
-    #define SR_CONTINUE           (0x02)  // resume request
+    enum {
+      SR_NONE              = 0x00,
+      SR_SUSPEND           = 0x01,  // suspend request
+      SR_CONTINUE          = 0x02,  // resume request
+      SR_SUSPENDED         = 0x20   // values for _state: + SR_NONE
+    };
 
-    volatile jint _state;
-    // values for _state: + SR_NONE
-    #define SR_SUSPENDED          (0x20)
-  public:
     SuspendResume() { _suspend_action = SR_NONE; _state = SR_NONE; }
 
     int suspend_action() const     { return _suspend_action; }
     void set_suspend_action(int x) { _suspend_action = x;    }
 
     // atomic updates for _state
-    void set_suspended()           {
-      jint temp, temp2;
-      do {
-        temp = _state;
-        temp2 = Atomic::cmpxchg(temp | SR_SUSPENDED, &_state, temp);
-      } while (temp2 != temp);
-    }
-    void clear_suspended()        {
-      jint temp, temp2;
-      do {
-        temp = _state;
-        temp2 = Atomic::cmpxchg(temp & ~SR_SUSPENDED, &_state, temp);
-      } while (temp2 != temp);
-    }
+    inline void set_suspended();
+    inline void clear_suspended();
     bool is_suspended()            { return _state & SR_SUSPENDED;       }
 
-    #undef SR_SUSPENDED
   };
 
 private:
--- a/hotspot/src/os/linux/vm/os_linux.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os/linux/vm/os_linux.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -25,7 +25,6 @@
 #ifndef OS_LINUX_VM_OS_LINUX_INLINE_HPP
 #define OS_LINUX_VM_OS_LINUX_INLINE_HPP
 
-#include "runtime/atomic.hpp"
 #include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 
@@ -288,4 +287,21 @@
                             const char* optval, socklen_t optlen) {
   return ::setsockopt(fd, level, optname, optval, optlen);
 }
+
+inline void os::Linux::SuspendResume::set_suspended() {
+  jint temp, temp2;
+  do {
+    temp = _state;
+    temp2 = Atomic::cmpxchg(temp | SR_SUSPENDED, &_state, temp);
+  } while (temp2 != temp);
+}
+
+inline void os::Linux::SuspendResume::clear_suspended()        {
+  jint temp, temp2;
+  do {
+    temp = _state;
+    temp2 = Atomic::cmpxchg(temp & ~SR_SUSPENDED, &_state, temp);
+  } while (temp2 != temp);
+}
+
 #endif // OS_LINUX_VM_OS_LINUX_INLINE_HPP
--- a/hotspot/src/os/solaris/vm/os_solaris.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os/solaris/vm/os_solaris.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -25,7 +25,6 @@
 #ifndef OS_SOLARIS_VM_OS_SOLARIS_INLINE_HPP
 #define OS_SOLARIS_VM_OS_SOLARIS_INLINE_HPP
 
-#include "runtime/atomic.hpp"
 #include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 
--- a/hotspot/src/os/windows/vm/decoder_windows.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os/windows/vm/decoder_windows.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "prims/jvm.h"
+#include "runtime/arguments.hpp"
 #include "decoder_windows.hpp"
 
 WindowsDecoder::WindowsDecoder() {
--- a/hotspot/src/os/windows/vm/os_windows.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os/windows/vm/os_windows.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -25,7 +25,6 @@
 #ifndef OS_WINDOWS_VM_OS_WINDOWS_INLINE_HPP
 #define OS_WINDOWS_VM_OS_WINDOWS_INLINE_HPP
 
-#include "runtime/atomic.hpp"
 #include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 
--- a/hotspot/src/os_cpu/bsd_x86/vm/atomic_bsd_x86.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os_cpu/bsd_x86/vm/atomic_bsd_x86.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 #ifndef OS_CPU_BSD_X86_VM_ATOMIC_BSD_X86_INLINE_HPP
 #define OS_CPU_BSD_X86_VM_ATOMIC_BSD_X86_INLINE_HPP
 
-#include "orderAccess_bsd_x86.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
--- a/hotspot/src/os_cpu/bsd_x86/vm/orderAccess_bsd_x86.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os_cpu/bsd_x86/vm/orderAccess_bsd_x86.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,9 @@
 #ifndef OS_CPU_BSD_X86_VM_ORDERACCESS_BSD_X86_INLINE_HPP
 #define OS_CPU_BSD_X86_VM_ORDERACCESS_BSD_X86_INLINE_HPP
 
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/orderAccess.hpp"
+#include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
 
 // Implementation of class OrderAccess.
--- a/hotspot/src/os_cpu/bsd_zero/vm/atomic_bsd_zero.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os_cpu/bsd_zero/vm/atomic_bsd_zero.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2007, 2008, 2011 Red Hat, Inc.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -26,7 +26,6 @@
 #ifndef OS_CPU_BSD_ZERO_VM_ATOMIC_BSD_ZERO_INLINE_HPP
 #define OS_CPU_BSD_ZERO_VM_ATOMIC_BSD_ZERO_INLINE_HPP
 
-#include "orderAccess_bsd_zero.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_zero.hpp"
--- a/hotspot/src/os_cpu/linux_sparc/vm/atomic_linux_sparc.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os_cpu/linux_sparc/vm/atomic_linux_sparc.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 #ifndef OS_CPU_LINUX_SPARC_VM_ATOMIC_LINUX_SPARC_INLINE_HPP
 #define OS_CPU_LINUX_SPARC_VM_ATOMIC_LINUX_SPARC_INLINE_HPP
 
-#include "orderAccess_linux_sparc.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_sparc.hpp"
--- a/hotspot/src/os_cpu/linux_x86/vm/atomic_linux_x86.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os_cpu/linux_x86/vm/atomic_linux_x86.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 #ifndef OS_CPU_LINUX_X86_VM_ATOMIC_LINUX_X86_INLINE_HPP
 #define OS_CPU_LINUX_X86_VM_ATOMIC_LINUX_X86_INLINE_HPP
 
-#include "orderAccess_linux_x86.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
--- a/hotspot/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,9 @@
 #ifndef OS_CPU_LINUX_X86_VM_ORDERACCESS_LINUX_X86_INLINE_HPP
 #define OS_CPU_LINUX_X86_VM_ORDERACCESS_LINUX_X86_INLINE_HPP
 
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/orderAccess.hpp"
+#include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
 
 // Implementation of class OrderAccess.
--- a/hotspot/src/os_cpu/linux_zero/vm/atomic_linux_zero.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os_cpu/linux_zero/vm/atomic_linux_zero.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2007, 2008, 2011 Red Hat, Inc.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -26,7 +26,6 @@
 #ifndef OS_CPU_LINUX_ZERO_VM_ATOMIC_LINUX_ZERO_INLINE_HPP
 #define OS_CPU_LINUX_ZERO_VM_ATOMIC_LINUX_ZERO_INLINE_HPP
 
-#include "orderAccess_linux_zero.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_zero.hpp"
--- a/hotspot/src/os_cpu/solaris_sparc/vm/atomic_solaris_sparc.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/atomic_solaris_sparc.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 #ifndef OS_CPU_SOLARIS_SPARC_VM_ATOMIC_SOLARIS_SPARC_INLINE_HPP
 #define OS_CPU_SOLARIS_SPARC_VM_ATOMIC_SOLARIS_SPARC_INLINE_HPP
 
-#include "orderAccess_solaris_sparc.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_sparc.hpp"
--- a/hotspot/src/os_cpu/solaris_sparc/vm/orderAccess_solaris_sparc.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os_cpu/solaris_sparc/vm/orderAccess_solaris_sparc.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
 #ifndef OS_CPU_SOLARIS_SPARC_VM_ORDERACCESS_SOLARIS_SPARC_INLINE_HPP
 #define OS_CPU_SOLARIS_SPARC_VM_ORDERACCESS_SOLARIS_SPARC_INLINE_HPP
 
+#include "runtime/atomic.inline.hpp"
 #include "runtime/orderAccess.hpp"
 #include "vm_version_sparc.hpp"
 
--- a/hotspot/src/os_cpu/solaris_x86/vm/atomic_solaris_x86.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os_cpu/solaris_x86/vm/atomic_solaris_x86.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 #ifndef OS_CPU_SOLARIS_X86_VM_ATOMIC_SOLARIS_X86_INLINE_HPP
 #define OS_CPU_SOLARIS_X86_VM_ATOMIC_SOLARIS_X86_INLINE_HPP
 
-#include "orderAccess_solaris_x86.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
--- a/hotspot/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,7 @@
 #ifndef OS_CPU_SOLARIS_X86_VM_ORDERACCESS_SOLARIS_X86_INLINE_HPP
 #define OS_CPU_SOLARIS_X86_VM_ORDERACCESS_SOLARIS_X86_INLINE_HPP
 
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/orderAccess.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
--- a/hotspot/src/os_cpu/windows_x86/vm/atomic_windows_x86.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os_cpu/windows_x86/vm/atomic_windows_x86.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 #ifndef OS_CPU_WINDOWS_X86_VM_ATOMIC_WINDOWS_X86_INLINE_HPP
 #define OS_CPU_WINDOWS_X86_VM_ATOMIC_WINDOWS_X86_INLINE_HPP
 
-#include "orderAccess_windows_x86.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
--- a/hotspot/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,12 +25,11 @@
 #ifndef OS_CPU_WINDOWS_X86_VM_ORDERACCESS_WINDOWS_X86_INLINE_HPP
 #define OS_CPU_WINDOWS_X86_VM_ORDERACCESS_WINDOWS_X86_INLINE_HPP
 
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/orderAccess.hpp"
+#include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
 
-#pragma warning(disable: 4035) // Disables warnings reporting missing return statement
-
 // Implementation of class OrderAccess.
 
 inline void OrderAccess::loadload()   { acquire(); }
@@ -214,6 +213,4 @@
 #endif // AMD64
 }
 
-#pragma warning(default: 4035) // Enables warnings reporting missing return statement
-
 #endif // OS_CPU_WINDOWS_X86_VM_ORDERACCESS_WINDOWS_X86_INLINE_HPP
--- a/hotspot/src/share/vm/c1/c1_FrameMap.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/c1/c1_FrameMap.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -308,27 +308,6 @@
   return sp_offset_for_monitor_base(index) + in_ByteSize(BasicObjectLock::obj_offset_in_bytes());
 }
 
-void FrameMap::print_frame_layout() const {
-  int svar;
-  tty->print_cr("#####################################");
-  tty->print_cr("Frame size in words %d", framesize());
-
-  if( _num_monitors > 0) {
-    tty->print_cr("monitor [0]:%d | [%2d]:%d",
-                  in_bytes(sp_offset_for_monitor_base(0)),
-                  in_bytes(sp_offset_for_monitor_base(_num_monitors)));
-  }
-  if( _num_spills > 0) {
-    svar = _num_spills - 1;
-    if(svar == 0)
-      tty->print_cr("spill   [0]:%d", in_bytes(sp_offset_for_spill(0)));
-    else
-      tty->print_cr("spill   [0]:%d | [%2d]:%d", in_bytes(sp_offset_for_spill(0)),
-                    svar,
-                    in_bytes(sp_offset_for_spill(svar)));
-  }
-}
-
 
 // For OopMaps, map a local variable or spill index to an VMReg.
 // This is the offset from sp() in the frame of the slot for the index,
--- a/hotspot/src/share/vm/c1/c1_FrameMap.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/c1/c1_FrameMap.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -226,8 +226,6 @@
     return make_new_address(sp_offset_for_monitor_object(monitor_index));
   }
 
-  void print_frame_layout() const;
-
   // Creates Location describing desired slot and returns it via pointer
   // to Location object. Returns true if the stack frame offset was legal
   // (as defined by Location::legal_offset_in_bytes()), false otherwise.
--- a/hotspot/src/share/vm/classfile/classLoaderData.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/classfile/classLoaderData.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -234,6 +234,7 @@
   void add_to_deallocate_list(Metadata* m);
 
   static ClassLoaderData* class_loader_data(oop loader);
+  static ClassLoaderData* class_loader_data_or_null(oop loader);
   static ClassLoaderData* anonymous_class_loader_data(oop loader, TRAPS);
   static void print_loader(ClassLoaderData *loader_data, outputStream *out);
 
--- a/hotspot/src/share/vm/classfile/classLoaderData.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/classfile/classLoaderData.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -25,9 +25,15 @@
 #include "classfile/classLoaderData.hpp"
 #include "classfile/javaClasses.hpp"
 
+inline ClassLoaderData* ClassLoaderData::class_loader_data_or_null(oop loader) {
+  if (loader == NULL) {
+    return ClassLoaderData::the_null_class_loader_data();
+  }
+  return java_lang_ClassLoader::loader_data(loader);
+}
+
 inline ClassLoaderData* ClassLoaderData::class_loader_data(oop loader) {
-  if (loader == NULL) return ClassLoaderData::the_null_class_loader_data();
-  ClassLoaderData* loader_data = java_lang_ClassLoader::loader_data(loader);
+  ClassLoaderData* loader_data = class_loader_data_or_null(loader);
   assert(loader_data != NULL, "Must be");
   return loader_data;
 }
--- a/hotspot/src/share/vm/classfile/dictionary.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/classfile/dictionary.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -347,6 +347,7 @@
   assert_locked_or_safepoint(SystemDictionary_lock);
   assert(obj() != NULL, "adding NULL obj");
   assert(obj()->name() == class_name, "sanity check on name");
+  assert(loader_data != NULL, "Must be non-NULL");
 
   unsigned int hash = compute_hash(class_name, loader_data);
   int index = hash_to_index(hash);
--- a/hotspot/src/share/vm/classfile/systemDictionary.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/classfile/systemDictionary.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -866,16 +866,22 @@
 // the new entry.
 
 Klass* SystemDictionary::find(Symbol* class_name,
-                                Handle class_loader,
-                                Handle protection_domain,
-                                TRAPS) {
+                              Handle class_loader,
+                              Handle protection_domain,
+                              TRAPS) {
 
   // UseNewReflection
   // The result of this call should be consistent with the result
   // of the call to resolve_instance_class_or_null().
   // See evaluation 6790209 and 4474172 for more details.
   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
-  ClassLoaderData* loader_data = register_loader(class_loader, CHECK_NULL);
+  ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());
+
+  if (loader_data == NULL) {
+    // If the ClassLoaderData has not been setup,
+    // then the class loader has no entries in the dictionary.
+    return NULL;
+  }
 
   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
   int d_index = dictionary()->hash_to_index(d_hash);
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -300,8 +300,7 @@
   }
 }
 
-// Wait until the next synchronous GC, a concurrent full gc request,
-// or a timeout, whichever is earlier.
+// Wait until any cms_lock event
 void ConcurrentMarkSweepThread::wait_on_cms_lock(long t_millis) {
   MutexLockerEx x(CGC_lock,
                   Mutex::_no_safepoint_check_flag);
@@ -315,15 +314,100 @@
          "Should not be set");
 }
 
+// Wait until the next synchronous GC, a concurrent full gc request,
+// or a timeout, whichever is earlier.
+void ConcurrentMarkSweepThread::wait_on_cms_lock_for_scavenge(long t_millis) {
+  // Wait time in millis or 0 value representing infinite wait for a scavenge
+  assert(t_millis >= 0, "Wait time for scavenge should be 0 or positive");
+
+  GenCollectedHeap* gch = GenCollectedHeap::heap();
+  double start_time_secs = os::elapsedTime();
+  double end_time_secs = start_time_secs + (t_millis / ((double) MILLIUNITS));
+
+  // Total collections count before waiting loop
+  unsigned int before_count;
+  {
+    MutexLockerEx hl(Heap_lock, Mutex::_no_safepoint_check_flag);
+    before_count = gch->total_collections();
+  }
+
+  unsigned int loop_count = 0;
+
+  while(!_should_terminate) {
+    double now_time = os::elapsedTime();
+    long wait_time_millis;
+
+    if(t_millis != 0) {
+      // New wait limit
+      wait_time_millis = (long) ((end_time_secs - now_time) * MILLIUNITS);
+      if(wait_time_millis <= 0) {
+        // Wait time is over
+        break;
+      }
+    } else {
+      // No wait limit, wait if necessary forever
+      wait_time_millis = 0;
+    }
+
+    // Wait until the next event or the remaining timeout
+    {
+      MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
+
+      if (_should_terminate || _collector->_full_gc_requested) {
+        return;
+      }
+      set_CMS_flag(CMS_cms_wants_token);   // to provoke notifies
+      assert(t_millis == 0 || wait_time_millis > 0, "Sanity");
+      CGC_lock->wait(Mutex::_no_safepoint_check_flag, wait_time_millis);
+      clear_CMS_flag(CMS_cms_wants_token);
+      assert(!CMS_flag_is_set(CMS_cms_has_token | CMS_cms_wants_token),
+             "Should not be set");
+    }
+
+    // Extra wait time check before entering the heap lock to get the collection count
+    if(t_millis != 0 && os::elapsedTime() >= end_time_secs) {
+      // Wait time is over
+      break;
+    }
+
+    // Total collections count after the event
+    unsigned int after_count;
+    {
+      MutexLockerEx hl(Heap_lock, Mutex::_no_safepoint_check_flag);
+      after_count = gch->total_collections();
+    }
+
+    if(before_count != after_count) {
+      // There was a collection - success
+      break;
+    }
+
+    // Too many loops warning
+    if(++loop_count == 0) {
+      warning("wait_on_cms_lock_for_scavenge() has looped %u times", loop_count - 1);
+    }
+  }
+}
+
 void ConcurrentMarkSweepThread::sleepBeforeNextCycle() {
   while (!_should_terminate) {
     if (CMSIncrementalMode) {
       icms_wait();
+      if(CMSWaitDuration >= 0) {
+        // Wait until the next synchronous GC, a concurrent full gc
+        // request or a timeout, whichever is earlier.
+        wait_on_cms_lock_for_scavenge(CMSWaitDuration);
+      }
       return;
     } else {
-      // Wait until the next synchronous GC, a concurrent full gc
-      // request or a timeout, whichever is earlier.
-      wait_on_cms_lock(CMSWaitDuration);
+      if(CMSWaitDuration >= 0) {
+        // Wait until the next synchronous GC, a concurrent full gc
+        // request or a timeout, whichever is earlier.
+        wait_on_cms_lock_for_scavenge(CMSWaitDuration);
+      } else {
+        // Wait until any cms_lock event or check interval not to call shouldConcurrentCollect permanently
+        wait_on_cms_lock(CMSCheckInterval);
+      }
     }
     // Check if we should start a CMS collection cycle
     if (_collector->shouldConcurrentCollect()) {
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -130,6 +130,12 @@
   // A concurrent full gc request terminates the wait.
   void wait_on_cms_lock(long t_millis);
 
+  // Wait on CMS lock until the next synchronous GC
+  // or given timeout, whichever is earlier. A timeout value
+  // of 0 indicates that there is no upper bound on the wait time.
+  // A concurrent full gc request terminates the wait.
+  void wait_on_cms_lock_for_scavenge(long t_millis);
+
   // The CMS thread will yield during the work portion of its cycle
   // only when requested to.  Both synchronous and asychronous requests
   // are provided:
--- a/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -146,43 +146,6 @@
   verify();
 }
 
-uint CollectionSetChooser::calc_min_old_cset_length() {
-  // The min old CSet region bound is based on the maximum desired
-  // number of mixed GCs after a cycle. I.e., even if some old regions
-  // look expensive, we should add them to the CSet anyway to make
-  // sure we go through the available old regions in no more than the
-  // maximum desired number of mixed GCs.
-  //
-  // The calculation is based on the number of marked regions we added
-  // to the CSet chooser in the first place, not how many remain, so
-  // that the result is the same during all mixed GCs that follow a cycle.
-
-  const size_t region_num = (size_t) _length;
-  const size_t gc_num = (size_t) G1MixedGCCountTarget;
-  size_t result = region_num / gc_num;
-  // emulate ceiling
-  if (result * gc_num < region_num) {
-    result += 1;
-  }
-  return (uint) result;
-}
-
-uint CollectionSetChooser::calc_max_old_cset_length() {
-  // The max old CSet region bound is based on the threshold expressed
-  // as a percentage of the heap size. I.e., it should bound the
-  // number of old regions added to the CSet irrespective of how many
-  // of them are available.
-
-  G1CollectedHeap* g1h = G1CollectedHeap::heap();
-  const size_t region_num = g1h->n_regions();
-  const size_t perc = (size_t) G1OldCSetRegionThresholdPercent;
-  size_t result = region_num * perc / 100;
-  // emulate ceiling
-  if (100 * result < region_num * perc) {
-    result += 1;
-  }
-  return (uint) result;
-}
 
 void CollectionSetChooser::add_region(HeapRegion* hr) {
   assert(!hr->isHumongous(),
--- a/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/gc_implementation/g1/collectionSetChooser.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -51,6 +51,8 @@
   uint _curr_index;
 
   // The number of candidate old regions added to the CSet chooser.
+  // Note: this is not updated when removing a region using
+  // remove_and_move_to_next() below.
   uint _length;
 
   // Keeps track of the start of the next array chunk to be claimed by
@@ -111,13 +113,8 @@
             hr->live_bytes() < _region_live_threshold_bytes;
   }
 
-  // Calculate the minimum number of old regions we'll add to the CSet
-  // during a mixed GC.
-  uint calc_min_old_cset_length();
-
-  // Calculate the maximum number of old regions we'll add to the CSet
-  // during a mixed GC.
-  uint calc_max_old_cset_length();
+  // Returns the number candidate old regions added
+  uint length() { return _length; }
 
   // Serial version.
   void add_region(HeapRegion *hr);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1806,6 +1806,14 @@
 }
 #endif // !PRODUCT
 
+double G1CollectorPolicy::reclaimable_bytes_perc(size_t reclaimable_bytes) {
+  // Returns the given amount of reclaimable bytes (that represents
+  // the amount of reclaimable space still to be collected) as a
+  // percentage of the current heap capacity.
+  size_t capacity_bytes = _g1->capacity();
+  return (double) reclaimable_bytes * 100.0 / (double) capacity_bytes;
+}
+
 bool G1CollectorPolicy::next_gc_should_be_mixed(const char* true_action_str,
                                                 const char* false_action_str) {
   CollectionSetChooser* cset_chooser = _collectionSetChooser;
@@ -1815,19 +1823,21 @@
                   ergo_format_reason("candidate old regions not available"));
     return false;
   }
+
+  // Is the amount of uncollected reclaimable space above G1HeapWastePercent?
   size_t reclaimable_bytes = cset_chooser->remaining_reclaimable_bytes();
-  size_t capacity_bytes = _g1->capacity();
-  double perc = (double) reclaimable_bytes * 100.0 / (double) capacity_bytes;
+  double reclaimable_perc = reclaimable_bytes_perc(reclaimable_bytes);
   double threshold = (double) G1HeapWastePercent;
-  if (perc < threshold) {
+  if (reclaimable_perc <= threshold) {
     ergo_verbose4(ErgoMixedGCs,
               false_action_str,
-              ergo_format_reason("reclaimable percentage lower than threshold")
+              ergo_format_reason("reclaimable percentage not over threshold")
               ergo_format_region("candidate old regions")
               ergo_format_byte_perc("reclaimable")
               ergo_format_perc("threshold"),
               cset_chooser->remaining_regions(),
-              reclaimable_bytes, perc, threshold);
+              reclaimable_bytes,
+              reclaimable_perc, threshold);
     return false;
   }
 
@@ -1838,10 +1848,50 @@
                 ergo_format_byte_perc("reclaimable")
                 ergo_format_perc("threshold"),
                 cset_chooser->remaining_regions(),
-                reclaimable_bytes, perc, threshold);
+                reclaimable_bytes,
+                reclaimable_perc, threshold);
   return true;
 }
 
+uint G1CollectorPolicy::calc_min_old_cset_length() {
+  // The min old CSet region bound is based on the maximum desired
+  // number of mixed GCs after a cycle. I.e., even if some old regions
+  // look expensive, we should add them to the CSet anyway to make
+  // sure we go through the available old regions in no more than the
+  // maximum desired number of mixed GCs.
+  //
+  // The calculation is based on the number of marked regions we added
+  // to the CSet chooser in the first place, not how many remain, so
+  // that the result is the same during all mixed GCs that follow a cycle.
+
+  const size_t region_num = (size_t) _collectionSetChooser->length();
+  const size_t gc_num = (size_t) MAX2(G1MixedGCCountTarget, (uintx) 1);
+  size_t result = region_num / gc_num;
+  // emulate ceiling
+  if (result * gc_num < region_num) {
+    result += 1;
+  }
+  return (uint) result;
+}
+
+uint G1CollectorPolicy::calc_max_old_cset_length() {
+  // The max old CSet region bound is based on the threshold expressed
+  // as a percentage of the heap size. I.e., it should bound the
+  // number of old regions added to the CSet irrespective of how many
+  // of them are available.
+
+  G1CollectedHeap* g1h = G1CollectedHeap::heap();
+  const size_t region_num = g1h->n_regions();
+  const size_t perc = (size_t) G1OldCSetRegionThresholdPercent;
+  size_t result = region_num * perc / 100;
+  // emulate ceiling
+  if (100 * result < region_num * perc) {
+    result += 1;
+  }
+  return (uint) result;
+}
+
+
 void G1CollectorPolicy::finalize_cset(double target_pause_time_ms) {
   double young_start_time_sec = os::elapsedTime();
 
@@ -1855,7 +1905,7 @@
 
   double base_time_ms = predict_base_elapsed_time_ms(_pending_cards);
   double predicted_pause_time_ms = base_time_ms;
-  double time_remaining_ms = target_pause_time_ms - base_time_ms;
+  double time_remaining_ms = MAX2(target_pause_time_ms - base_time_ms, 0.0);
 
   ergo_verbose4(ErgoCSetConstruction | ErgoHigh,
                 "start choosing CSet",
@@ -1893,7 +1943,7 @@
 
   _collection_set = _inc_cset_head;
   _collection_set_bytes_used_before = _inc_cset_bytes_used_before;
-  time_remaining_ms -= _inc_cset_predicted_elapsed_time_ms;
+  time_remaining_ms = MAX2(time_remaining_ms - _inc_cset_predicted_elapsed_time_ms, 0.0);
   predicted_pause_time_ms += _inc_cset_predicted_elapsed_time_ms;
 
   ergo_verbose3(ErgoCSetConstruction | ErgoHigh,
@@ -1917,8 +1967,8 @@
   if (!gcs_are_young()) {
     CollectionSetChooser* cset_chooser = _collectionSetChooser;
     cset_chooser->verify();
-    const uint min_old_cset_length = cset_chooser->calc_min_old_cset_length();
-    const uint max_old_cset_length = cset_chooser->calc_max_old_cset_length();
+    const uint min_old_cset_length = calc_min_old_cset_length();
+    const uint max_old_cset_length = calc_max_old_cset_length();
 
     uint expensive_region_num = 0;
     bool check_time_remaining = adaptive_young_list_length();
@@ -1936,6 +1986,30 @@
         break;
       }
 
+
+      // Stop adding regions if the remaining reclaimable space is
+      // not above G1HeapWastePercent.
+      size_t reclaimable_bytes = cset_chooser->remaining_reclaimable_bytes();
+      double reclaimable_perc = reclaimable_bytes_perc(reclaimable_bytes);
+      double threshold = (double) G1HeapWastePercent;
+      if (reclaimable_perc <= threshold) {
+        // We've added enough old regions that the amount of uncollected
+        // reclaimable space is at or below the waste threshold. Stop
+        // adding old regions to the CSet.
+        ergo_verbose5(ErgoCSetConstruction,
+                      "finish adding old regions to CSet",
+                      ergo_format_reason("reclaimable percentage not over threshold")
+                      ergo_format_region("old")
+                      ergo_format_region("max")
+                      ergo_format_byte_perc("reclaimable")
+                      ergo_format_perc("threshold"),
+                      old_cset_region_length(),
+                      max_old_cset_length,
+                      reclaimable_bytes,
+                      reclaimable_perc, threshold);
+        break;
+      }
+
       double predicted_time_ms = predict_region_elapsed_time_ms(hr, gcs_are_young());
       if (check_time_remaining) {
         if (predicted_time_ms > time_remaining_ms) {
@@ -1975,7 +2049,7 @@
       }
 
       // We will add this region to the CSet.
-      time_remaining_ms -= predicted_time_ms;
+      time_remaining_ms = MAX2(time_remaining_ms - predicted_time_ms, 0.0);
       predicted_pause_time_ms += predicted_time_ms;
       cset_chooser->remove_and_move_to_next(hr);
       _g1->old_set_remove(hr);
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -619,6 +619,18 @@
   bool predict_will_fit(uint young_length, double base_time_ms,
                         uint base_free_regions, double target_pause_time_ms);
 
+  // Calculate the minimum number of old regions we'll add to the CSet
+  // during a mixed GC.
+  uint calc_min_old_cset_length();
+
+  // Calculate the maximum number of old regions we'll add to the CSet
+  // during a mixed GC.
+  uint calc_max_old_cset_length();
+
+  // Returns the given amount of uncollected reclaimable space
+  // as a percentage of the current heap capacity.
+  double reclaimable_bytes_perc(size_t reclaimable_bytes);
+
 public:
 
   G1CollectorPolicy();
--- a/hotspot/src/share/vm/gc_implementation/parNew/parCardTableModRefBS.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/gc_implementation/parNew/parCardTableModRefBS.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -373,6 +373,8 @@
                          " does not exceed used.end() = " PTR_FORMAT ","
                          " yet last_chunk_index_to_check " INTPTR_FORMAT
                          " exceeds last_chunk_index " INTPTR_FORMAT,
+                         last_block, last_block + last_block_size,
+                         used.end(),
                          last_chunk_index_to_check, last_chunk_index));
           assert(sp->used_region().end() > used.end(),
                  err_msg("Expansion did not happen: "
--- a/hotspot/src/share/vm/memory/allocation.inline.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/memory/allocation.inline.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
 #ifndef SHARE_VM_MEMORY_ALLOCATION_INLINE_HPP
 #define SHARE_VM_MEMORY_ALLOCATION_INLINE_HPP
 
+#include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 
 // Explicit C-heap memory management
--- a/hotspot/src/share/vm/memory/cardTableModRefBS.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/memory/cardTableModRefBS.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -694,7 +694,7 @@
     if (failed) {
       if (!failures) {
         tty->cr();
-        tty->print_cr("== CT verification failed: ["PTR_FORMAT","PTR_FORMAT"]");
+        tty->print_cr("== CT verification failed: ["PTR_FORMAT","PTR_FORMAT"]", start, end);
         tty->print_cr("==   %sexpecting value: %d",
                       (val_equals) ? "" : "not ", val);
         failures = true;
--- a/hotspot/src/share/vm/memory/cardTableRS.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/memory/cardTableRS.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -353,7 +353,7 @@
     assert(jp >= _begin && jp < _end,
            err_msg("Error: jp " PTR_FORMAT " should be within "
                    "[_begin, _end) = [" PTR_FORMAT "," PTR_FORMAT ")",
-                   _begin, _end));
+                   jp, _begin, _end));
     oop obj = oopDesc::load_decode_heap_oop(p);
     guarantee(obj == NULL || (HeapWord*)obj >= _boundary,
               err_msg("pointer " PTR_FORMAT " at " PTR_FORMAT " on "
--- a/hotspot/src/share/vm/memory/metaspaceCounters.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/memory/metaspaceCounters.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -25,12 +25,14 @@
 #include "precompiled.hpp"
 #include "memory/metaspaceCounters.hpp"
 #include "memory/resourceArea.hpp"
-
-#define METASPACE_NAME "perm"
+#include "utilities/exceptions.hpp"
 
 MetaspaceCounters* MetaspaceCounters::_metaspace_counters = NULL;
 
-MetaspaceCounters::MetaspaceCounters() {
+MetaspaceCounters::MetaspaceCounters() :
+    _capacity(NULL),
+    _used(NULL),
+    _max_capacity(NULL) {
   if (UsePerfData) {
     size_t min_capacity = MetaspaceAux::min_chunk_size();
     size_t max_capacity = MetaspaceAux::reserved_in_bytes();
@@ -41,6 +43,25 @@
   }
 }
 
+static PerfVariable* create_ms_variable(const char *ns,
+                                        const char *name,
+                                        size_t value,
+                                        TRAPS) {
+  const char *path = PerfDataManager::counter_name(ns, name);
+  PerfVariable *result =
+      PerfDataManager::create_variable(SUN_GC, path, PerfData::U_Bytes, value,
+                                       CHECK_NULL);
+  return result;
+}
+
+static void create_ms_constant(const char *ns,
+                               const char *name,
+                               size_t value,
+                               TRAPS) {
+  const char *path = PerfDataManager::counter_name(ns, name);
+  PerfDataManager::create_constant(SUN_GC, path, PerfData::U_Bytes, value, CHECK);
+}
+
 void MetaspaceCounters::initialize(size_t min_capacity,
                                    size_t max_capacity,
                                    size_t curr_capacity,
@@ -50,93 +71,32 @@
     EXCEPTION_MARK;
     ResourceMark rm;
 
-    // Create a name that will be recognized by jstat tools as
-    // the perm gen.  Change this to a Metaspace name when the
-    // tools are fixed.
-    // name to recognize "sun.gc.generation.2.*"
-
-    const char* name = METASPACE_NAME;
-    const int ordinal = 2;
-    const int spaces = 1;
-
-    const char* cns = PerfDataManager::name_space("generation", ordinal);
-
-    _name_space = NEW_C_HEAP_ARRAY(char, strlen(cns)+1, mtClass);
-    strcpy(_name_space, cns);
-
-    const char* cname = PerfDataManager::counter_name(_name_space, "name");
-    PerfDataManager::create_string_constant(SUN_GC, cname, name, CHECK);
-
-    // End of perm gen like name creation
-
-    cname = PerfDataManager::counter_name(_name_space, "spaces");
-    PerfDataManager::create_constant(SUN_GC, cname, PerfData::U_None,
-                                     spaces, CHECK);
-
-    cname = PerfDataManager::counter_name(_name_space, "minCapacity");
-    PerfDataManager::create_constant(SUN_GC, cname, PerfData::U_Bytes,
-                                     min_capacity, CHECK);
-
-    cname = PerfDataManager::counter_name(_name_space, "maxCapacity");
-    PerfDataManager::create_constant(SUN_GC, cname, PerfData::U_Bytes,
-                                     max_capacity, CHECK);
+    const char *ms = "metaspace";
 
-    cname = PerfDataManager::counter_name(_name_space, "capacity");
-    _current_size =
-      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
-                                       curr_capacity, CHECK);
-
-    // SpaceCounter like counters
-    // name to recognize "sun.gc.generation.2.space.0.*"
-    {
-      const int space_ordinal = 0;
-      const char* cns = PerfDataManager::name_space(_name_space, "space",
-                                                    space_ordinal);
-
-      char* space_name_space = NEW_C_HEAP_ARRAY(char, strlen(cns)+1, mtClass);
-      strcpy(space_name_space, cns);
-
-      const char* cname = PerfDataManager::counter_name(space_name_space, "name");
-      PerfDataManager::create_string_constant(SUN_GC, cname, name, CHECK);
-
-      cname = PerfDataManager::counter_name(space_name_space, "maxCapacity");
-      _max_capacity = PerfDataManager::create_variable(SUN_GC, cname,
-                                                       PerfData::U_Bytes,
-                                                       (jlong)max_capacity, CHECK);
-
-      cname = PerfDataManager::counter_name(space_name_space, "capacity");
-      _capacity = PerfDataManager::create_variable(SUN_GC, cname,
-                                                   PerfData::U_Bytes,
-                                                   curr_capacity, CHECK);
-
-      cname = PerfDataManager::counter_name(space_name_space, "used");
-      _used = PerfDataManager::create_variable(SUN_GC,
-                                               cname,
-                                               PerfData::U_Bytes,
-                                               used,
-                                               CHECK);
-
-    cname = PerfDataManager::counter_name(space_name_space, "initCapacity");
-    PerfDataManager::create_constant(SUN_GC, cname, PerfData::U_Bytes,
-                                     min_capacity, CHECK);
-    }
+    create_ms_constant(ms, "minCapacity", min_capacity, CHECK);
+    _max_capacity = create_ms_variable(ms, "maxCapacity", max_capacity, CHECK);
+    _capacity = create_ms_variable(ms, "capacity", curr_capacity, CHECK);
+    _used = create_ms_variable(ms, "used", used, CHECK);
   }
 }
 
 void MetaspaceCounters::update_capacity() {
   assert(UsePerfData, "Should not be called unless being used");
+  assert(_capacity != NULL, "Should be initialized");
   size_t capacity_in_bytes = MetaspaceAux::capacity_in_bytes();
   _capacity->set_value(capacity_in_bytes);
 }
 
 void MetaspaceCounters::update_used() {
   assert(UsePerfData, "Should not be called unless being used");
+  assert(_used != NULL, "Should be initialized");
   size_t used_in_bytes = MetaspaceAux::used_in_bytes();
   _used->set_value(used_in_bytes);
 }
 
 void MetaspaceCounters::update_max_capacity() {
   assert(UsePerfData, "Should not be called unless being used");
+  assert(_max_capacity != NULL, "Should be initialized");
   size_t reserved_in_bytes = MetaspaceAux::reserved_in_bytes();
   _max_capacity->set_value(reserved_in_bytes);
 }
@@ -146,18 +106,19 @@
     update_used();
     update_capacity();
     update_max_capacity();
-    _current_size->set_value(MetaspaceAux::reserved_in_bytes());
   }
 }
 
 void MetaspaceCounters::initialize_performance_counters() {
   if (UsePerfData) {
+    assert(_metaspace_counters == NULL, "Should only be initialized once");
     _metaspace_counters = new MetaspaceCounters();
   }
 }
 
 void MetaspaceCounters::update_performance_counters() {
   if (UsePerfData) {
+    assert(_metaspace_counters != NULL, "Should be initialized");
     _metaspace_counters->update_all();
   }
 }
--- a/hotspot/src/share/vm/memory/metaspaceCounters.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/memory/metaspaceCounters.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -29,11 +29,9 @@
 
 class MetaspaceCounters: public CHeapObj<mtClass> {
   friend class VMStructs;
-  PerfVariable*      _current_size;
   PerfVariable*      _capacity;
   PerfVariable*      _used;
   PerfVariable*      _max_capacity;
-  char*              _name_space;
   static MetaspaceCounters* _metaspace_counters;
   void initialize(size_t min_capacity,
                   size_t max_capacity,
--- a/hotspot/src/share/vm/oops/instanceKlass.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/oops/instanceKlass.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -2170,7 +2170,11 @@
       if (impl != NULL) {
         if (!impl->is_loader_alive(is_alive)) {
           // remove this guy
-          *adr_implementor() = NULL;
+          Klass** klass = adr_implementor();
+          assert(klass != NULL, "null klass");
+          if (klass != NULL) {
+            *klass = NULL;
+          }
         }
       }
     }
@@ -3151,9 +3155,10 @@
   if (protection_domain() != NULL) {
     guarantee(protection_domain()->is_oop(), "should be oop");
   }
-  if (host_klass() != NULL) {
-    guarantee(host_klass()->is_metadata(), "should be in metaspace");
-    guarantee(host_klass()->is_klass(), "should be klass");
+  const Klass* host = host_klass();
+  if (host != NULL) {
+    guarantee(host->is_metadata(), "should be in metaspace");
+    guarantee(host->is_klass(), "should be klass");
   }
   if (signers() != NULL) {
     guarantee(signers()->is_objArray(), "should be obj array");
--- a/hotspot/src/share/vm/oops/instanceKlass.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/oops/instanceKlass.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -536,7 +536,9 @@
     assert(is_anonymous(), "not anonymous");
     Klass** addr = (Klass**)adr_host_klass();
     assert(addr != NULL, "no reversed space");
-    *addr = host;
+    if (addr != NULL) {
+      *addr = host;
+    }
   }
   bool is_anonymous() const                {
     return (_misc_flags & _misc_is_anonymous) != 0;
@@ -758,7 +760,10 @@
   void set_implementor(Klass* k) {
     assert(is_interface(), "not interface");
     Klass** addr = adr_implementor();
-    *addr = k;
+    assert(addr != NULL, "null addr");
+    if (addr != NULL) {
+      *addr = k;
+    }
   }
 
   int  nof_implementors() const       {
--- a/hotspot/src/share/vm/oops/symbol.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/oops/symbol.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 #include "classfile/altHashing.hpp"
 #include "classfile/classLoaderData.hpp"
 #include "oops/symbol.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 #include "memory/allocation.inline.hpp"
 #include "memory/resourceArea.hpp"
@@ -210,6 +211,28 @@
   return AltHashing::murmur3_32(seed, (const jbyte*)as_C_string(), utf8_length());
 }
 
+void Symbol::increment_refcount() {
+  // Only increment the refcount if positive.  If negative either
+  // overflow has occurred or it is a permanent symbol in a read only
+  // shared archive.
+  if (_refcount >= 0) {
+    Atomic::inc(&_refcount);
+    NOT_PRODUCT(Atomic::inc(&_total_count);)
+  }
+}
+
+void Symbol::decrement_refcount() {
+  if (_refcount >= 0) {
+    Atomic::dec(&_refcount);
+#ifdef ASSERT
+    if (_refcount < 0) {
+      print();
+      assert(false, "reference count underflow for symbol");
+    }
+#endif
+  }
+}
+
 void Symbol::print_on(outputStream* st) const {
   if (this == NULL) {
     st->print_cr("NULL");
--- a/hotspot/src/share/vm/oops/symbol.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/oops/symbol.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,7 +27,6 @@
 
 #include "utilities/utf8.hpp"
 #include "memory/allocation.hpp"
-#include "runtime/atomic.hpp"
 
 // A Symbol is a canonicalized string.
 // All Symbols reside in global SymbolTable and are reference counted.
@@ -150,8 +149,8 @@
 
   // Reference counting.  See comments above this class for when to use.
   int refcount() const      { return _refcount; }
-  inline void increment_refcount();
-  inline void decrement_refcount();
+  void increment_refcount();
+  void decrement_refcount();
 
   int byte_at(int index) const {
     assert(index >=0 && index < _length, "symbol index overflow");
@@ -232,26 +231,4 @@
  return (((uintptr_t)this < (uintptr_t)other) ? -1
    : ((uintptr_t)this == (uintptr_t) other) ? 0 : 1);
 }
-
-inline void Symbol::increment_refcount() {
-  // Only increment the refcount if positive.  If negative either
-  // overflow has occurred or it is a permanent symbol in a read only
-  // shared archive.
-  if (_refcount >= 0) {
-    Atomic::inc(&_refcount);
-    NOT_PRODUCT(Atomic::inc(&_total_count);)
-  }
-}
-
-inline void Symbol::decrement_refcount() {
-  if (_refcount >= 0) {
-    Atomic::dec(&_refcount);
-#ifdef ASSERT
-    if (_refcount < 0) {
-      print();
-      assert(false, "reference count underflow for symbol");
-    }
-#endif
-  }
-}
 #endif // SHARE_VM_OOPS_SYMBOL_HPP
--- a/hotspot/src/share/vm/opto/c2_globals.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/opto/c2_globals.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -54,6 +54,12 @@
 
 #define C2_FLAGS(develop, develop_pd, product, product_pd, diagnostic, experimental, notproduct) \
                                                                             \
+  develop(bool, StressLCM, false,                                           \
+          "Randomize instruction scheduling in LCM")                        \
+                                                                            \
+  develop(bool, StressGCM, false,                                           \
+          "Randomize instruction scheduling in GCM")                        \
+                                                                            \
   notproduct(intx, CompileZapFirst, 0,                                      \
           "If +ZapDeadCompiledLocals, "                                     \
           "skip this many before compiling in zap calls")                   \
--- a/hotspot/src/share/vm/opto/compile.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/opto/compile.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -2899,6 +2899,13 @@
       }
     }
     break;
+  case Op_MemBarStoreStore:
+    // Break the link with AllocateNode: it is no longer useful and
+    // confuses register allocation.
+    if (n->req() > MemBarNode::Precedent) {
+      n->set_req(MemBarNode::Precedent, top());
+    }
+    break;
   default:
     assert( !n->is_Call(), "" );
     assert( !n->is_Mem(), "" );
@@ -3669,3 +3676,38 @@
     n->set_req(0, NULL);
   }
 }
+
+// Auxiliary method to support randomized stressing/fuzzing.
+//
+// This method can be called the arbitrary number of times, with current count
+// as the argument. The logic allows selecting a single candidate from the
+// running list of candidates as follows:
+//    int count = 0;
+//    Cand* selected = null;
+//    while(cand = cand->next()) {
+//      if (randomized_select(++count)) {
+//        selected = cand;
+//      }
+//    }
+//
+// Including count equalizes the chances any candidate is "selected".
+// This is useful when we don't have the complete list of candidates to choose
+// from uniformly. In this case, we need to adjust the randomicity of the
+// selection, or else we will end up biasing the selection towards the latter
+// candidates.
+//
+// Quick back-envelope calculation shows that for the list of n candidates
+// the equal probability for the candidate to persist as "best" can be
+// achieved by replacing it with "next" k-th candidate with the probability
+// of 1/k. It can be easily shown that by the end of the run, the
+// probability for any candidate is converged to 1/n, thus giving the
+// uniform distribution among all the candidates.
+//
+// We don't care about the domain size as long as (RANDOMIZED_DOMAIN / count) is large.
+#define RANDOMIZED_DOMAIN_POW 29
+#define RANDOMIZED_DOMAIN (1 << RANDOMIZED_DOMAIN_POW)
+#define RANDOMIZED_DOMAIN_MASK ((1 << (RANDOMIZED_DOMAIN_POW + 1)) - 1)
+bool Compile::randomized_select(int count) {
+  assert(count > 0, "only positive");
+  return (os::random() & RANDOMIZED_DOMAIN_MASK) < (RANDOMIZED_DOMAIN / count);
+}
--- a/hotspot/src/share/vm/opto/compile.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/opto/compile.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -678,6 +678,7 @@
   void         record_dead_node(uint idx)  { if (_dead_node_list.test_set(idx)) return;
                                              _dead_node_count++;
                                            }
+  bool         is_dead_node(uint idx)      { return _dead_node_list.test(idx) != 0; }
   uint         dead_node_count()           { return _dead_node_count; }
   void         reset_dead_node_list()      { _dead_node_list.Reset();
                                              _dead_node_count = 0;
@@ -1086,6 +1087,9 @@
 
   // Definitions of pd methods
   static void pd_compiler2_init();
+
+  // Auxiliary method for randomized fuzzing/stressing
+  static bool randomized_select(int count);
 };
 
 #endif // SHARE_VM_OPTO_COMPILE_HPP
--- a/hotspot/src/share/vm/opto/gcm.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/opto/gcm.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1046,6 +1046,8 @@
   }
 #endif
 
+  int cand_cnt = 0;  // number of candidates tried
+
   // Walk up the dominator tree from LCA (Lowest common ancestor) to
   // the earliest legal location.  Capture the least execution frequency.
   while (LCA != early) {
@@ -1071,8 +1073,11 @@
         LCA->_pre_order, LCA->_nodes[0]->_idx, start_lat, end_idx, end_lat, LCA_freq);
     }
 #endif
+    cand_cnt++;
     if (LCA_freq < least_freq              || // Better Frequency
-        ( !in_latency                   &&    // No block containing latency
+        (StressGCM && Compile::randomized_select(cand_cnt)) || // Should be randomly accepted in stress mode
+         (!StressGCM                    &&    // Otherwise, choose with latency
+          !in_latency                   &&    // No block containing latency
           LCA_freq < least_freq * delta &&    // No worse frequency
           target >= end_lat             &&    // within latency range
           !self->is_iteratively_computed() )  // But don't hoist IV increments
@@ -1210,7 +1215,8 @@
     }
 
     // If there is no opportunity to hoist, then we're done.
-    bool try_to_hoist = (LCA != early);
+    // In stress mode, try to hoist even the single operations.
+    bool try_to_hoist = StressGCM || (LCA != early);
 
     // Must clone guys stay next to use; no hoisting allowed.
     // Also cannot hoist guys that alter memory or are otherwise not
--- a/hotspot/src/share/vm/opto/lcm.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/opto/lcm.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -421,6 +421,7 @@
   uint latency = 0; // Bigger is scheduled first
   uint score   = 0; // Bigger is better
   int idx = -1;     // Index in worklist
+  int cand_cnt = 0; // Candidate count
 
   for( uint i=0; i<cnt; i++ ) { // Inspect entire worklist
     // Order in worklist is used to break ties.
@@ -503,11 +504,14 @@
     uint n_score   = n->req();   // Many inputs get high score to break ties
 
     // Keep best latency found
-    if( choice < n_choice ||
-        ( choice == n_choice &&
-          ( latency < n_latency ||
-            ( latency == n_latency &&
-              ( score < n_score ))))) {
+    cand_cnt++;
+    if (choice < n_choice ||
+        (choice == n_choice &&
+         ((StressLCM && Compile::randomized_select(cand_cnt)) ||
+          (!StressLCM &&
+           (latency < n_latency ||
+            (latency == n_latency &&
+             (score < n_score))))))) {
       choice  = n_choice;
       latency = n_latency;
       score   = n_score;
--- a/hotspot/src/share/vm/opto/macro.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/opto/macro.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1101,12 +1101,6 @@
   Node* klass_node        = alloc->in(AllocateNode::KlassNode);
   Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
 
-  Node* storestore = alloc->storestore();
-  if (storestore != NULL) {
-    // Break this link that is no longer useful and confuses register allocation
-    storestore->set_req(MemBarNode::Precedent, top());
-  }
-
   assert(ctrl != NULL, "must have control");
   // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
   // they will not be used if "always_slow" is set
@@ -1324,7 +1318,7 @@
         // No InitializeNode or no stores captured by zeroing
         // elimination. Simply add the MemBarStoreStore after object
         // initialization.
-        MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot, fast_oop_rawmem);
+        MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
         transform_later(mb);
 
         mb->init_req(TypeFunc::Memory, fast_oop_rawmem);
--- a/hotspot/src/share/vm/opto/memnode.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/opto/memnode.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -238,7 +238,7 @@
     return this;
   ctl = in(MemNode::Control);
   // Don't bother trying to transform a dead node
-  if( ctl && ctl->is_top() )  return NodeSentinel;
+  if (ctl && ctl->is_top())  return NodeSentinel;
 
   PhaseIterGVN *igvn = phase->is_IterGVN();
   // Wait if control on the worklist.
@@ -262,8 +262,8 @@
   }
   // Ignore if memory is dead, or self-loop
   Node *mem = in(MemNode::Memory);
-  if( phase->type( mem ) == Type::TOP ) return NodeSentinel; // caller will return NULL
-  assert( mem != this, "dead loop in MemNode::Ideal" );
+  if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return NULL
+  assert(mem != this, "dead loop in MemNode::Ideal");
 
   if (can_reshape && igvn != NULL && igvn->_worklist.member(mem)) {
     // This memory slice may be dead.
@@ -273,12 +273,12 @@
   }
 
   Node *address = in(MemNode::Address);
-  const Type *t_adr = phase->type( address );
-  if( t_adr == Type::TOP )              return NodeSentinel; // caller will return NULL
-
-  if( can_reshape && igvn != NULL &&
+  const Type *t_adr = phase->type(address);
+  if (t_adr == Type::TOP)              return NodeSentinel; // caller will return NULL
+
+  if (can_reshape && igvn != NULL &&
       (igvn->_worklist.member(address) ||
-       igvn->_worklist.size() > 0 && (phase->type(address) != adr_type())) ) {
+       igvn->_worklist.size() > 0 && (t_adr != adr_type())) ) {
     // The address's base and type may change when the address is processed.
     // Delay this mem node transformation until the address is processed.
     phase->is_IterGVN()->_worklist.push(this);
@@ -288,7 +288,7 @@
   // Do NOT remove or optimize the next lines: ensure a new alias index
   // is allocated for an oop pointer type before Escape Analysis.
   // Note: C++ will not remove it since the call has side effect.
-  if ( t_adr->isa_oopptr() ) {
+  if (t_adr->isa_oopptr()) {
     int alias_idx = phase->C->get_alias_index(t_adr->is_ptr());
   }
 
@@ -296,6 +296,26 @@
   Node* base = NULL;
   if (address->is_AddP())
     base = address->in(AddPNode::Base);
+  if (base != NULL && phase->type(base)->higher_equal(TypePtr::NULL_PTR) &&
+      !t_adr->isa_rawptr()) {
+    // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true.
+    Compile* C = phase->C;
+    tty->cr();
+    tty->print_cr("===== NULL+offs not RAW address =====");
+    if (C->is_dead_node(this->_idx))    tty->print_cr("'this' is dead");
+    if ((ctl != NULL) && C->is_dead_node(ctl->_idx)) tty->print_cr("'ctl' is dead");
+    if (C->is_dead_node(mem->_idx))     tty->print_cr("'mem' is dead");
+    if (C->is_dead_node(address->_idx)) tty->print_cr("'address' is dead");
+    if (C->is_dead_node(base->_idx))    tty->print_cr("'base' is dead");
+    tty->cr();
+    base->dump(1);
+    tty->cr();
+    this->dump(2);
+    tty->print("this->adr_type():     "); adr_type()->dump(); tty->cr();
+    tty->print("phase->type(address): "); t_adr->dump(); tty->cr();
+    tty->print("phase->type(base):    "); phase->type(address)->dump(); tty->cr();
+    tty->cr();
+  }
   assert(base == NULL || t_adr->isa_rawptr() ||
         !phase->type(base)->higher_equal(TypePtr::NULL_PTR), "NULL+offs not RAW address?");
 #endif
--- a/hotspot/src/share/vm/prims/jvmtiEnter.xsl	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/prims/jvmtiEnter.xsl	Fri Mar 15 23:31:19 2013 -0700
@@ -773,7 +773,7 @@
 </xsl:text>
     <xsl:apply-templates select=".." mode="traceError">     
       <xsl:with-param name="err">JVMTI_ERROR_INVALID_THREAD</xsl:with-param>
-      <xsl:with-param name="comment"> - jthread resolved to NULL - jthread = %0x%x</xsl:with-param>
+      <xsl:with-param name="comment"> - jthread resolved to NULL - jthread = 0x%x</xsl:with-param>
       <xsl:with-param name="extraValue">, <xsl:value-of select="$name"/></xsl:with-param>
     </xsl:apply-templates>
     <xsl:text>
@@ -782,7 +782,7 @@
 </xsl:text>
     <xsl:apply-templates select=".." mode="traceError">     
       <xsl:with-param name="err">JVMTI_ERROR_INVALID_THREAD</xsl:with-param>
-      <xsl:with-param name="comment"> - oop is not a thread - jthread = %0x%x</xsl:with-param>
+      <xsl:with-param name="comment"> - oop is not a thread - jthread = 0x%x</xsl:with-param>
       <xsl:with-param name="extraValue">, <xsl:value-of select="$name"/></xsl:with-param>
     </xsl:apply-templates>
     <xsl:text>
@@ -794,7 +794,7 @@
       <xsl:with-param name="err">
         <xsl:text>JVMTI_ERROR_THREAD_NOT_ALIVE</xsl:text>
       </xsl:with-param>
-      <xsl:with-param name="comment"> - not a Java thread - jthread = %0x%x</xsl:with-param>
+      <xsl:with-param name="comment"> - not a Java thread - jthread = 0x%x</xsl:with-param>
       <xsl:with-param name="extraValue">, <xsl:value-of select="$name"/></xsl:with-param>
     </xsl:apply-templates>
     <xsl:text>
@@ -838,7 +838,7 @@
 </xsl:text>
     <xsl:apply-templates select=".." mode="traceError">     
       <xsl:with-param name="err">JVMTI_ERROR_ILLEGAL_ARGUMENT</xsl:with-param>
-      <xsl:with-param name="comment"> - negative depth - jthread = %0x%x</xsl:with-param>
+      <xsl:with-param name="comment"> - negative depth - jthread = 0x%x</xsl:with-param>
       <xsl:with-param name="extraValue">, <xsl:value-of select="$name"/></xsl:with-param>
     </xsl:apply-templates>
     <xsl:text>
--- a/hotspot/src/share/vm/prims/jvmtiEnvBase.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/prims/jvmtiEnvBase.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -997,13 +997,19 @@
       // move our object at this point. However, our owner value is safe
       // since it is either the Lock word on a stack or a JavaThread *.
       owning_thread = Threads::owning_thread_from_monitor_owner(owner, !at_safepoint);
-      assert(owning_thread != NULL, "sanity check");
-      if (owning_thread != NULL) {  // robustness
+      // Cannot assume (owning_thread != NULL) here because this function
+      // may not have been called at a safepoint and the owning_thread
+      // might not be suspended.
+      if (owning_thread != NULL) {
         // The monitor's owner either has to be the current thread, at safepoint
         // or it has to be suspended. Any of these conditions will prevent both
         // contending and waiting threads from modifying the state of
         // the monitor.
         if (!at_safepoint && !JvmtiEnv::is_thread_fully_suspended(owning_thread, true, &debug_bits)) {
+          // Don't worry! This return of JVMTI_ERROR_THREAD_NOT_SUSPENDED
+          // will not make it back to the JVM/TI agent. The error code will
+          // get intercepted in JvmtiEnv::GetObjectMonitorUsage() which
+          // will retry the call via a VM_GetObjectMonitorUsage VM op.
           return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
         }
         HandleMark hm;
--- a/hotspot/src/share/vm/runtime/frame.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/runtime/frame.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1070,7 +1070,12 @@
 
   // First consult the ADLC on where it puts parameter 0 for this signature.
   VMReg reg = SharedRuntime::name_for_receiver();
-  oop r = *caller.oopmapreg_to_location(reg, reg_map);
+  oop* oop_adr = caller.oopmapreg_to_location(reg, reg_map);
+  if (oop_adr == NULL) {
+    guarantee(oop_adr != NULL, "bad register save location");
+    return NULL;
+  }
+  oop r = *oop_adr;
   assert(Universe::heap()->is_in_or_null(r), err_msg("bad receiver: " INTPTR_FORMAT " (" INTX_FORMAT ")", (intptr_t) r, (intptr_t) r));
   return r;
 }
--- a/hotspot/src/share/vm/runtime/globals.hpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/runtime/globals.hpp	Fri Mar 15 23:31:19 2013 -0700
@@ -1751,6 +1751,10 @@
   manageable(intx, CMSWaitDuration, 2000,                                   \
           "Time in milliseconds that CMS thread waits for young GC")        \
                                                                             \
+  develop(uintx, CMSCheckInterval, 1000,                                    \
+          "Interval in milliseconds that CMS thread checks if it "          \
+          "should start a collection cycle")                                \
+                                                                            \
   product(bool, CMSYield, true,                                             \
           "Yield between steps of concurrent mark & sweep")                 \
                                                                             \
--- a/hotspot/src/share/vm/runtime/synchronizer.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/runtime/synchronizer.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -813,6 +813,7 @@
   }
 
   if (owner != NULL) {
+    // owning_thread_from_monitor_owner() may also return NULL here
     return Threads::owning_thread_from_monitor_owner(owner, doLock);
   }
 
--- a/hotspot/src/share/vm/runtime/thread.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/runtime/thread.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -4285,7 +4285,9 @@
       if (owner == (address)p) return p;
     }
   }
-  assert(UseHeavyMonitors == false, "Did not find owning Java thread with UseHeavyMonitors enabled");
+  // Cannot assert on lack of success here since this function may be
+  // used by code that is trying to report useful problem information
+  // like deadlock detection.
   if (UseHeavyMonitors) return NULL;
 
   //
@@ -4303,7 +4305,7 @@
       }
     }
   }
-  assert(the_owner != NULL, "Did not find owning Java thread for lock word address");
+  // cannot assert on lack of success here; see above comment
   return the_owner;
 }
 
--- a/hotspot/src/share/vm/services/memReporter.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/services/memReporter.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -419,7 +419,7 @@
       _output->print_cr("[" PTR_FORMAT "] %s+0x%x", pc, buf, offset);
       _output->print("%28s", " ");
     } else {
-      _output->print("[" PTR_FORMAT "]%18s", " ");
+      _output->print("[" PTR_FORMAT "]%18s", pc, " ");
     }
 
     _output->print_cr("(mmap: reserved=%d%s, committed=%d%s)",
@@ -596,7 +596,7 @@
         _output->print_cr("[" PTR_FORMAT "] %s+0x%x", pc, buf, offset);
         _output->print("%28s", " ");
       } else {
-        _output->print("[" PTR_FORMAT "]%18s", " ");
+        _output->print("[" PTR_FORMAT "]%18s", pc, " ");
       }
     }
 
--- a/hotspot/src/share/vm/services/threadService.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/services/threadService.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -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
@@ -327,8 +327,28 @@
     while (waitingToLockMonitor != NULL || waitingToLockBlocker != NULL) {
       cycle->add_thread(currentThread);
       if (waitingToLockMonitor != NULL) {
-        currentThread = Threads::owning_thread_from_monitor_owner((address)waitingToLockMonitor->owner(),
-                                                                  false /* no locking needed */);
+        currentThread = Threads::owning_thread_from_monitor_owner(
+                          (address)waitingToLockMonitor->owner(),
+                          false /* no locking needed */);
+        if (currentThread == NULL) {
+          // This function is called at a safepoint so the JavaThread
+          // that owns waitingToLockMonitor should be findable, but
+          // if it is not findable, then the previous currentThread is
+          // blocked permanently. We record this as a deadlock.
+          num_deadlocks++;
+
+          cycle->set_deadlock(true);
+
+          // add this cycle to the deadlocks list
+          if (deadlocks == NULL) {
+            deadlocks = cycle;
+          } else {
+            last->set_next(cycle);
+          }
+          last = cycle;
+          cycle = new DeadlockCycle();
+          break;
+        }
       } else {
         if (concurrent_locks) {
           if (waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass())) {
@@ -841,7 +861,17 @@
         owner_desc = " (JVMTI raw monitor),\n  which is held by";
       }
       currentThread = Threads::owning_thread_from_monitor_owner(
-        (address)waitingToLockMonitor->owner(), false /* no locking needed */);
+                        (address)waitingToLockMonitor->owner(),
+                        false /* no locking needed */);
+      if (currentThread == NULL) {
+        // The deadlock was detected at a safepoint so the JavaThread
+        // that owns waitingToLockMonitor should be findable, but
+        // if it is not findable, then the previous currentThread is
+        // blocked permanently.
+        st->print("%s UNKNOWN_owner_addr=" PTR_FORMAT, owner_desc,
+                  (address)waitingToLockMonitor->owner());
+        continue;
+      }
     } else {
       st->print("  waiting for ownable synchronizer " INTPTR_FORMAT ", (a %s)",
                 (address)waitingToLockBlocker,
--- a/hotspot/src/share/vm/utilities/numberSeq.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/src/share/vm/utilities/numberSeq.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -245,7 +245,7 @@
 
 void NumberSeq::dump_on(outputStream* s) {
   AbsSeq::dump_on(s);
-  s->print_cr("\t\t _last = %7.3f, _maximum = %7.3f");
+  s->print_cr("\t\t _last = %7.3f, _maximum = %7.3f", _last, _maximum);
 }
 
 void TruncatedSeq::dump_on(outputStream* s) {
--- a/hotspot/test/compiler/6431242/Test.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/test/compiler/6431242/Test.java	Fri Mar 15 23:31:19 2013 -0700
@@ -25,7 +25,7 @@
 /*
  * @test
  * @bug 6431242
- * @run main/othervm -server -XX:+PrintCompilation Test
+ * @run main Test
  */
 
 public class Test{
--- a/hotspot/test/compiler/6589834/Test_ia32.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/test/compiler/6589834/Test_ia32.java	Fri Mar 15 23:31:19 2013 -0700
@@ -26,7 +26,7 @@
  * @bug 6589834
  * @summary deoptimization problem with -XX:+DeoptimizeALot
  *
- * @run main/othervm -server Test_ia32
+ * @run main Test_ia32
  */
 
 /***************************************************************************************
--- a/hotspot/test/compiler/6636138/Test1.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/test/compiler/6636138/Test1.java	Fri Mar 15 23:31:19 2013 -0700
@@ -26,7 +26,7 @@
  * @bug 6636138
  * @summary SuperWord::co_locate_pack(Node_List* p) generates memory graph that leads to memory order violation.
  *
- * @run main/othervm -server -Xbatch -XX:CompileOnly=Test1.init Test1
+ * @run main/othervm -Xbatch -XX:CompileOnly=Test1.init Test1
  */
 
 public class Test1 {
--- a/hotspot/test/compiler/6636138/Test2.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/test/compiler/6636138/Test2.java	Fri Mar 15 23:31:19 2013 -0700
@@ -26,7 +26,7 @@
  * @bug 6636138
  * @summary SuperWord::co_locate_pack(Node_List* p) generates memory graph that leads to memory order violation.
  *
- * @run main/othervm -server -Xbatch -XX:CompileOnly=Test2.shift Test2
+ * @run main/othervm -Xbatch -XX:CompileOnly=Test2.shift Test2
  */
 
 public class Test2 {
--- a/hotspot/test/compiler/6795161/Test.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/test/compiler/6795161/Test.java	Fri Mar 15 23:31:19 2013 -0700
@@ -26,7 +26,7 @@
  * @test
  * @bug 6795161
  * @summary Escape analysis leads to data corruption
- * @run main/othervm -server  -XX:+IgnoreUnrecognizedVMOptions -Xcomp -XX:CompileOnly=Test -XX:+DoEscapeAnalysis Test
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -Xcomp -XX:CompileOnly=Test -XX:+DoEscapeAnalysis Test
  */
 
 class Test_Class_1 {
--- a/hotspot/test/compiler/6946040/TestCharShortByteSwap.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/test/compiler/6946040/TestCharShortByteSwap.java	Fri Mar 15 23:31:19 2013 -0700
@@ -26,7 +26,7 @@
  * @test
  * @bug 6946040
  * @summary Tests Character/Short.reverseBytes and their intrinsics implementation in the server compiler
- * @run main/othervm -Xbatch -server -XX:CompileOnly=.testChar,.testShort TestCharShortByteSwap
+ * @run main/othervm -Xbatch -XX:CompileOnly=.testChar,.testShort TestCharShortByteSwap
  */
 
 // This test must run without any command line arguments.
--- a/hotspot/test/compiler/7068051/Test7068051.sh	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/test/compiler/7068051/Test7068051.sh	Fri Mar 15 23:31:19 2013 -0700
@@ -45,5 +45,5 @@
 
 ${TESTJAVA}/bin/javac -d . Test7068051.java
 
-${TESTJAVA}/bin/java -showversion -Xbatch ${TESTVMOPTS} Test7068051 foo.jar
+${TESTJAVA}/bin/java ${TESTVMOPTS} -showversion -Xbatch Test7068051 foo.jar
 
--- a/hotspot/test/compiler/8000805/Test8000805.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/hotspot/test/compiler/8000805/Test8000805.java	Fri Mar 15 23:31:19 2013 -0700
@@ -26,7 +26,7 @@
  * @bug 8000805
  * @summary JMM issue: short loads are non-atomic
  *
- * @run main/othervm -server -XX:-TieredCompilation -Xcomp -XX:+PrintCompilation -XX:CompileOnly=Test8000805.loadS2LmaskFF,Test8000805.loadS2Lmask16,Test8000805.loadS2Lmask13,Test8000805.loadUS_signExt,Test8000805.loadB2L_mask8 Test8000805
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -Xcomp -XX:+PrintCompilation -XX:CompileOnly=Test8000805.loadS2LmaskFF,Test8000805.loadS2Lmask16,Test8000805.loadS2Lmask13,Test8000805.loadUS_signExt,Test8000805.loadB2L_mask8 Test8000805
  */
 
 public class Test8000805 {
--- a/jaxp/.hgtags	Fri Mar 15 19:30:28 2013 +0530
+++ b/jaxp/.hgtags	Fri Mar 15 23:31:19 2013 -0700
@@ -201,3 +201,4 @@
 573e789c187a69a3ae00bffd26eb35c0f4a60636 jdk8-b77
 00958c5a7070bd578aa8b70773cb3f204a9c1be1 jdk8-b78
 58fa065dd5d663d62f85402461388fb7a92656fa jdk8-b79
+4873a0499bc3bd263b7dd3b551a2b4e275ab5a0b jdk8-b80
--- a/jaxws/.hgtags	Fri Mar 15 19:30:28 2013 +0530
+++ b/jaxws/.hgtags	Fri Mar 15 23:31:19 2013 -0700
@@ -201,3 +201,4 @@
 64dfba1bad16433f609f17a42c3c5990367c5c0b jdk8-b77
 391de4c992d1960a09cdd340362ff936bac69323 jdk8-b78
 70d8658d2a3063bc13127f3452af017d838f1362 jdk8-b79
+b0224010e2f0c2474055ac592c8d3f37b9264690 jdk8-b80
--- a/jdk/.hgtags	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/.hgtags	Fri Mar 15 23:31:19 2013 -0700
@@ -201,3 +201,5 @@
 b2fc8e31cecc35b76188e821d4c5dc0e0b74ac24 jdk8-b77
 00b7535d743f83eda763c10b3c9ea19ba4b67f55 jdk8-b78
 c933505d75c2a0a671f06d6dac5d2237a9228d2d jdk8-b79
+dfb40f066c6ce129822f0f5dc2ac89173808781a jdk8-b80
+c0f8022eba536dcdc8aae659005b33f3982b9368 jdk8-b81
--- a/jdk/make/common/shared/Defs-utils.gmk	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/make/common/shared/Defs-utils.gmk	Fri Mar 15 23:31:19 2013 -0700
@@ -74,24 +74,24 @@
   UTILS_DEVTOOL_PATH=$(DEVTOOLS_PATH)
 endif
 
-# Utilities
-ifdef CROSS_COMPILE_ARCH
-  AR             = $(COMPILER_PATH)ar
-  AS             = $(COMPILER_PATH)as
-  LD             = $(COMPILER_PATH)ld
-  MCS            = $(COMPILER_PATH)mcs
-  NM             = $(COMPILER_PATH)nm
-  STRIP          = $(COMPILER_PATH)strip
-endif
-
-ifeq ($(PLATFORM),solaris)
-  AR             = $(UTILS_CCS_BIN_PATH)ar
-  AS             = $(UTILS_CCS_BIN_PATH)as
-  LD             = $(UTILS_CCS_BIN_PATH)ld
-  MCS            = $(UTILS_CCS_BIN_PATH)mcs
-  NM             = $(UTILS_CCS_BIN_PATH)nm
-  STRIP          = $(UTILS_CCS_BIN_PATH)strip
-endif
+ifndef CONFIGURE_BUILD
+  # Utilities
+  ifdef CROSS_COMPILE_ARCH
+    AR             = $(COMPILER_PATH)ar
+    AS             = $(COMPILER_PATH)as
+    LD             = $(COMPILER_PATH)ld
+    MCS            = $(COMPILER_PATH)mcs
+    NM             = $(COMPILER_PATH)nm
+    STRIP          = $(COMPILER_PATH)strip
+  else
+    AR             = $(UTILS_CCS_BIN_PATH)ar
+    AS             = $(UTILS_CCS_BIN_PATH)as
+    LD             = $(UTILS_CCS_BIN_PATH)ld
+    MCS            = $(UTILS_CCS_BIN_PATH)mcs
+    NM             = $(UTILS_CCS_BIN_PATH)nm
+    STRIP          = $(UTILS_CCS_BIN_PATH)strip
+  endif
+endif # CONFIGURE_BUILD
 
 ADB            = $(UTILS_COMMAND_PATH)adb
 BASENAME       = $(UTILS_COMMAND_PATH)basename
--- a/jdk/make/sun/cmm/lcms/Makefile	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/make/sun/cmm/lcms/Makefile	Fri Mar 15 23:31:19 2013 -0700
@@ -28,6 +28,9 @@
 LIBRARY = lcms
 PRODUCT = sun
 
+# Use highest level of optimization on this library
+OPTIMIZATION_LEVEL = HIGHEST
+
 include $(BUILDDIR)/common/Defs.gmk
 
 #
--- a/jdk/make/sun/cmm/lcms/mapfile-vers	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/make/sun/cmm/lcms/mapfile-vers	Fri Mar 15 23:31:19 2013 -0700
@@ -27,13 +27,12 @@
 
 SUNWprivate_1.1 {
 	global:
-        Java_sun_java2d_cmm_lcms_LCMS_loadProfile;
-        Java_sun_java2d_cmm_lcms_LCMS_freeProfile;
+        Java_sun_java2d_cmm_lcms_LCMS_loadProfileNative;
+        Java_sun_java2d_cmm_lcms_LCMS_freeProfileNative;
         Java_sun_java2d_cmm_lcms_LCMS_getProfileSize;
         Java_sun_java2d_cmm_lcms_LCMS_getProfileData;
-        Java_sun_java2d_cmm_lcms_LCMS_getTagSize;
-        Java_sun_java2d_cmm_lcms_LCMS_getTagData;
-        Java_sun_java2d_cmm_lcms_LCMS_setTagData;
+        Java_sun_java2d_cmm_lcms_LCMS_getTagNative;
+        Java_sun_java2d_cmm_lcms_LCMS_setTagDataNative;
         Java_sun_java2d_cmm_lcms_LCMS_colorConvert;
         Java_sun_java2d_cmm_lcms_LCMS_getProfileID;
         Java_sun_java2d_cmm_lcms_LCMS_initLCMS;
--- a/jdk/makefiles/CompileNativeLibraries.gmk	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/makefiles/CompileNativeLibraries.gmk	Fri Mar 15 23:31:19 2013 -0700
@@ -464,12 +464,13 @@
 	$(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/sun/windows \
 	$(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/sun/java2d/windows \
 	$(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/sun/java2d/d3d
+    LIBAWT_CFLAGS+=-I$(DXSDK_INCLUDE_PATH)
 else
     LIBAWT_DIRS+=\
 	$(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/sun/java2d/x11
 endif
 
-LIBAWT_CFLAGS:=-D__MEDIALIB_OLD_NAMES -D__USE_J2D_NAMES \
+LIBAWT_CFLAGS+=-D__MEDIALIB_OLD_NAMES -D__USE_J2D_NAMES \
 	$(X_CFLAGS) \
 	$(foreach dir,$(LIBAWT_DIRS),-I$(dir))
 
@@ -1218,7 +1219,7 @@
                 OUTPUT_DIR:=$(INSTALL_LIBRARIES_HERE),\
                 SRC:=$(JDK_TOPDIR)/src/share/native/sun/java2d/cmm/lcms,\
 		LANG:=C,\
-		OPTIMIZATION:=LOW, \
+		OPTIMIZATION:=HIGHEST, \
 		CFLAGS:=$(filter-out -xc99=%none,$(CFLAGS_JDKLIB)) \
 			$(SHARED_LIBRARY_FLAGS) \
 			-I$(JDK_TOPDIR)/src/share/native/sun/java2d \
@@ -1461,7 +1462,8 @@
 		        -I$(JDK_TOPDIR)/src/share/native/sun/awt/debug \
 		        -I$(JDK_TOPDIR)/src/share/native/sun/java2d \
 			-I$(JDK_TOPDIR)/src/share/native/sun/awt/image/cvutils \
-			-I$(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/sun/java2d/windows, \
+			-I$(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/sun/java2d/windows \
+			-I$(DXSDK_INCLUDE_PATH), \
 		LDFLAGS:=$(LDFLAGS_JDKLIB) $(KERNEL32_LIB) $(LDFLAGS_CXX_JDK) \
 			 advapi32.lib $(WIN_AWT_LIB),\
 		LDFLAGS_SUFFIX:=$(LDFLAGS_JDKLIB_SUFFIX),\
@@ -2905,7 +2907,8 @@
 		OPTIMIZATION:=LOW, \
 		CFLAGS:=$(CFLAGS_JDKLIB) \
 			$(LIBJSOUND_CFLAGS) \
-			-DUSE_DAUDIO=TRUE, \
+			-DUSE_DAUDIO=TRUE \
+                        -I$(DXSDK_INCLUDE_PATH), \
 		LDFLAGS:=$(LDFLAGS_JDKLIB) $(LDFLAGS_CXX_JDK) \
 			 $(call SET_SHARED_LIBRARY_ORIGIN),\
 		LDFLAGS_SUFFIX:=$(LDFLAGS_JDKLIB_SUFFIX) dsound.lib winmm.lib user32.lib ole32.lib,\
--- a/jdk/makefiles/Images.gmk	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/makefiles/Images.gmk	Fri Mar 15 23:31:19 2013 -0700
@@ -264,6 +264,13 @@
 $(foreach f,$(filter $(JDK_OUTPUTDIR)/lib$(OPENJDK_TARGET_CPU_ISADIR)/%,$(JDKJRE_JDKOUT_LIB_LIST)),\
     $(eval $(call AddFileToCopy,$(JDK_OUTPUTDIR),$(JDK_OVERLAY_IMAGE_DIR)/jre,$f,JDKJRE_OVERLAY_LIB_TARGETS)))
 
+ifneq ($(PROFILE),)
+# Files in lib$(PROFILE) are excluded from the generic copying routines so 
+# we have to add them back in here
+$(foreach f,$(CUSTOM_PROFILE_JARS),\
+    $(eval $(call AddFileToCopy,$(IMAGES_OUTPUTDIR)/lib$(PROFILE),$(JRE_IMAGE_DIR)/lib,$f,JRE_LIB_TARGETS)))
+endif
+
 # CTE plugin security change require new empty directory lib/applet
 $(JRE_IMAGE_DIR)/lib/applet: 
 	$(ECHO) $(LOG_INFO) Creating $(patsubst $(OUTPUT_ROOT)/%,%,$@)
@@ -739,11 +746,6 @@
 	$(JDKJRE_OVERLAY_STRIP_LIST) $(JDK_OVERLAY_BIN_STRIP_LIST) 
 
 ifneq ($(PROFILE),)
-# Files in lib$(PROFILE) are excluded from the generic copying routines so
-# we have to add them back in here
-$(foreach f,$(CUSTOM_PROFILE_JARS),\
-    $(eval $(call AddFileToCopy,$(IMAGES_OUTPUTDIR)/lib$(PROFILE),$(JRE_IMAGE_DIR)/lib,$f,JRE_LIB_TARGETS)))
-
 PROFILE_IMAGE_JARS := $(filter %.jar, $(JRE_LIB_TARGETS))
 
 PROFILE_IMAGE_JARS_CHECKED := $(IMAGES_OUTPUTDIR)/lib$(PROFILE)/_jars_checked
--- a/jdk/makefiles/mapfiles/liblcms/mapfile-vers	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/makefiles/mapfiles/liblcms/mapfile-vers	Fri Mar 15 23:31:19 2013 -0700
@@ -27,13 +27,12 @@
 
 SUNWprivate_1.1 {
 	global:
-        Java_sun_java2d_cmm_lcms_LCMS_loadProfile;
-        Java_sun_java2d_cmm_lcms_LCMS_freeProfile;
+        Java_sun_java2d_cmm_lcms_LCMS_loadProfileNative;
+        Java_sun_java2d_cmm_lcms_LCMS_freeProfileNative;
         Java_sun_java2d_cmm_lcms_LCMS_getProfileSize;
         Java_sun_java2d_cmm_lcms_LCMS_getProfileData;
-        Java_sun_java2d_cmm_lcms_LCMS_getTagSize;
-        Java_sun_java2d_cmm_lcms_LCMS_getTagData;
-        Java_sun_java2d_cmm_lcms_LCMS_setTagData;
+        Java_sun_java2d_cmm_lcms_LCMS_getTagNative;
+        Java_sun_java2d_cmm_lcms_LCMS_setTagDataNative;
         Java_sun_java2d_cmm_lcms_LCMS_colorConvert;
         Java_sun_java2d_cmm_lcms_LCMS_getProfileID;
         Java_sun_java2d_cmm_lcms_LCMS_initLCMS;
--- a/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxUI.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/com/apple/laf/AquaComboBoxUI.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,7 +34,6 @@
 import javax.swing.event.*;
 import javax.swing.plaf.*;
 import javax.swing.plaf.basic.*;
-import com.apple.laf.ClientPropertyApplicator;
 import com.apple.laf.ClientPropertyApplicator.Property;
 import apple.laf.JRSUIConstants.Size;
 
@@ -142,35 +141,46 @@
         return new AquaComboBoxEditor();
     }
 
-    class AquaComboBoxEditor extends BasicComboBoxEditor implements UIResource, DocumentListener {
-        protected AquaComboBoxEditor() {
+    final class AquaComboBoxEditor extends BasicComboBoxEditor
+            implements UIResource, DocumentListener {
+
+        AquaComboBoxEditor() {
             super();
             editor = new AquaCustomComboTextField();
             editor.addFocusListener(this);
             editor.getDocument().addDocumentListener(this);
         }
 
+        @Override
         public void focusGained(final FocusEvent e) {
-            arrowButton.repaint();
+            if (arrowButton != null) {
+                arrowButton.repaint();
+            }
         }
 
+        @Override
         public void focusLost(final FocusEvent e) {
-            arrowButton.repaint();
+            if (arrowButton != null) {
+                arrowButton.repaint();
+            }
         }
 
+        @Override
         public void changedUpdate(final DocumentEvent e) {
             editorTextChanged();
         }
 
+        @Override
         public void insertUpdate(final DocumentEvent e) {
             editorTextChanged();
         }
 
+        @Override
         public void removeUpdate(final DocumentEvent e) {
             editorTextChanged();
         }
 
-        protected void editorTextChanged() {
+        private void editorTextChanged() {
             if (!popup.isVisible()) return;
 
             final Object text = editor.getText();
--- a/jdk/src/macosx/classes/sun/awt/CGraphicsConfig.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/awt/CGraphicsConfig.java	Fri Mar 15 23:31:19 2013 -0700
@@ -53,7 +53,7 @@
 
     @Override
     public Rectangle getBounds() {
-        final Rectangle2D nativeBounds = nativeGetBounds(device.getCoreGraphicsScreen());
+        final Rectangle2D nativeBounds = nativeGetBounds(device.getCGDisplayID());
         return nativeBounds.getBounds(); // does integer rounding
     }
 
--- a/jdk/src/macosx/classes/sun/awt/CGraphicsDevice.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/awt/CGraphicsDevice.java	Fri Mar 15 23:31:19 2013 -0700
@@ -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,11 +25,12 @@
 
 package sun.awt;
 
+import java.awt.AWTPermission;
+import java.awt.DisplayMode;
 import java.awt.GraphicsConfiguration;
 import java.awt.GraphicsDevice;
+import java.awt.Insets;
 import java.awt.Window;
-import java.awt.AWTPermission;
-import java.awt.DisplayMode;
 import java.util.Objects;
 
 import sun.java2d.opengl.CGLGraphicsConfig;
@@ -58,9 +59,12 @@
     }
 
     /**
+     * Returns CGDirectDisplayID, which is the same id as @"NSScreenNumber" in
+     * NSScreen.
+     *
      * @return CoreGraphics display id.
      */
-    public int getCoreGraphicsScreen() {
+    public int getCGDisplayID() {
         return displayID;
     }
 
@@ -107,8 +111,9 @@
         return nativeGetYResolution(displayID);
     }
 
-    private static native double nativeGetXResolution(int displayID);
-    private static native double nativeGetYResolution(int displayID);
+    public Insets getScreenInsets() {
+        return nativeGetScreenInsets(displayID);
+    }
 
     /**
      * Enters full-screen mode, or returns to windowed mode.
@@ -214,9 +219,15 @@
         return nativeGetDisplayModes(displayID);
     }
 
-    private native void nativeSetDisplayMode(int displayID, int w, int h, int bpp, int refrate);
+    private static native void nativeSetDisplayMode(int displayID, int w, int h, int bpp, int refrate);
+
+    private static native DisplayMode nativeGetDisplayMode(int displayID);
+
+    private static native DisplayMode[] nativeGetDisplayModes(int displayID);
 
-    private native DisplayMode nativeGetDisplayMode(int displayID);
+    private static native double nativeGetXResolution(int displayID);
 
-    private native DisplayMode[] nativeGetDisplayModes(int displayID);
+    private static native double nativeGetYResolution(int displayID);
+
+    private static native Insets nativeGetScreenInsets(int displayID);
 }
--- a/jdk/src/macosx/classes/sun/font/CStrike.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/font/CStrike.java	Fri Mar 15 23:31:19 2013 -0700
@@ -500,7 +500,10 @@
                 final Iterator<Long> i = generalCache.values().iterator();
                 while (i.hasNext()) {
                     final long longValue = i.next().longValue();
-                    if (longValue != -1 && longValue != 0) StrikeCache.freeLongPointer(longValue);
+                    if (longValue != -1 && longValue != 0) {
+                        removeGlyphInfoFromCache(longValue);
+                        StrikeCache.freeLongPointer(longValue);
+                    }
                 }
             }
 
@@ -512,7 +515,10 @@
         private static void disposeLongArray(final long[] longArray) {
             for (int i = 0; i < longArray.length; i++) {
                 final long ptr = longArray[i];
-                if (ptr != 0 && ptr != -1) StrikeCache.freeLongPointer(ptr); // free's the native struct pointer
+                if (ptr != 0 && ptr != -1) {
+                    removeGlyphInfoFromCache(ptr);
+                    StrikeCache.freeLongPointer(ptr); // free's the native struct pointer
+                }
             }
         }
 
--- a/jdk/src/macosx/classes/sun/font/CStrikeDisposer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/font/CStrikeDisposer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -85,4 +85,6 @@
     }
 
     private native void freeNativeScalerContext(long pContext);
+
+    protected static native void removeGlyphInfoFromCache(long glyphInfo);
 }
--- a/jdk/src/macosx/classes/sun/java2d/opengl/CGLGraphicsConfig.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/java2d/opengl/CGLGraphicsConfig.java	Fri Mar 15 23:31:19 2013 -0700
@@ -80,10 +80,8 @@
     private ContextCapabilities oglCaps;
     private OGLContext context;
     private final Object disposerReferent = new Object();
-
-    public static native int getDefaultPixFmt(int screennum);
     private static native boolean initCGL();
-    private static native long getCGLConfigInfo(int screennum, int visualnum,
+    private static native long getCGLConfigInfo(int displayID, int visualnum,
                                                 int swapInterval);
     private static native int getOGLCapabilities(long configInfo);
 
@@ -137,15 +135,16 @@
             // Java-level context and flush the queue...
             OGLContext.invalidateCurrentContext();
 
-            cfginfo = getCGLConfigInfo(device.getCoreGraphicsScreen(), pixfmt,
+            cfginfo = getCGLConfigInfo(device.getCGDisplayID(), pixfmt,
                                        kOpenGLSwapInterval);
-
-            OGLContext.setScratchSurface(cfginfo);
-            rq.flushAndInvokeNow(new Runnable() {
-                public void run() {
-                    ids[0] = OGLContext.getOGLIdString();
-                }
-            });
+            if (cfginfo != 0L) {
+                OGLContext.setScratchSurface(cfginfo);
+                rq.flushAndInvokeNow(new Runnable() {
+                    public void run() {
+                        ids[0] = OGLContext.getOGLIdString();
+                    }
+                });
+            }
         } finally {
             rq.unlock();
         }
@@ -253,8 +252,8 @@
 
     @Override
     public String toString() {
-        int screen = getDevice().getCoreGraphicsScreen();
-        return ("CGLGraphicsConfig[dev="+screen+",pixfmt="+pixfmt+"]");
+        int displayID = getDevice().getCGDisplayID();
+        return ("CGLGraphicsConfig[dev="+displayID+",pixfmt="+pixfmt+"]");
     }
 
     @Override
@@ -413,8 +412,8 @@
 
     @Override
     public void addDeviceEventListener(AccelDeviceEventListener l) {
-        int screen = getDevice().getCoreGraphicsScreen();
-        AccelDeviceEventNotifier.addListener(l, screen);
+        int displayID = getDevice().getCGDisplayID();
+        AccelDeviceEventNotifier.addListener(l, displayID);
     }
 
     @Override
--- a/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/lwawt/LWComponentPeer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -439,7 +439,7 @@
     }
 
     @Override
-    public final Graphics getGraphics() {
+    public Graphics getGraphics() {
         final Graphics g = getOnscreenGraphics();
         if (g != null) {
             synchronized (getPeerTreeLock()){
@@ -1227,10 +1227,10 @@
     }
 
     protected void sendEventToDelegate(final AWTEvent e) {
+        if (getDelegate() == null || !isShowing() || !isEnabled()) {
+            return;
+        }
         synchronized (getDelegateLock()) {
-            if (getDelegate() == null || !isShowing() || !isEnabled()) {
-                return;
-            }
             AWTEvent delegateEvent = createDelegateEvent(e);
             if (delegateEvent != null) {
                 AWTAccessor.getComponentAccessor()
@@ -1244,7 +1244,12 @@
         }
     }
 
-    protected AWTEvent createDelegateEvent(AWTEvent e) {
+    /**
+     * Changes the target of the AWTEvent from awt component to appropriate
+     * swing delegate.
+     */
+    private AWTEvent createDelegateEvent(final AWTEvent e) {
+        // TODO modifiers should be changed to getModifiers()|getModifiersEx()?
         AWTEvent delegateEvent = null;
         if (e instanceof MouseWheelEvent) {
             MouseWheelEvent me = (MouseWheelEvent) e;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/macosx/classes/sun/lwawt/LWLightweightFramePeer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.lwawt;
+
+import java.awt.Graphics;
+import java.awt.Insets;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.Window;
+import java.awt.dnd.DropTarget;
+
+import sun.awt.CausedFocusEvent;
+import sun.awt.LightweightFrame;
+
+public class LWLightweightFramePeer extends LWWindowPeer {
+
+    public LWLightweightFramePeer(LightweightFrame target,
+                                  PlatformComponent platformComponent,
+                                  PlatformWindow platformWindow)
+    {
+        super(target, platformComponent, platformWindow, LWWindowPeer.PeerType.LW_FRAME);
+    }
+
+    private LightweightFrame getLwTarget() {
+        return (LightweightFrame)getTarget();
+    }
+
+    @Override
+    public Graphics getGraphics() {
+        return getLwTarget().getGraphics();
+    }
+
+    @Override
+    protected void setVisibleImpl(final boolean visible) {
+    }
+
+    @Override
+    public boolean requestWindowFocus(CausedFocusEvent.Cause cause) {
+        if (!focusAllowedFor()) {
+            return false;
+        }
+        if (getPlatformWindow().rejectFocusRequest(cause)) {
+            return false;
+        }
+
+        Window opposite = LWKeyboardFocusManagerPeer.getInstance().
+            getCurrentFocusedWindow();
+
+        changeFocusedWindow(true, opposite);
+
+        return true;
+    }
+
+    @Override
+    public Point getLocationOnScreen() {
+        Rectangle bounds = getBounds();
+        return new Point(bounds.x, bounds.y); // todo
+    }
+
+    @Override
+    public Insets getInsets() {
+        return new Insets(0, 0, 0, 0);
+    }
+
+    @Override
+    public void setBounds(int x, int y, int w, int h, int op) {
+        setBounds(x, y, w, h, op, true, false);
+    }
+
+    @Override
+    public void updateCursorImmediately() {
+        // TODO: tries to switch to the awt/fx toolkit thread and causes a deadlock on macosx
+    }
+
+    @Override
+    public void addDropTarget(DropTarget dt) {
+    }
+
+    @Override
+    public void removeDropTarget(DropTarget dt) {
+    }
+
+    @Override
+    public void grab() {
+        getLwTarget().grabFocus();
+    }
+
+    @Override
+    public void ungrab() {
+        getLwTarget().ungrabFocus();
+    }
+}
--- a/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/lwawt/LWToolkit.java	Fri Mar 15 23:31:19 2013 -0700
@@ -218,6 +218,23 @@
         return peer;
     }
 
+    private LWLightweightFramePeer createDelegatedLwPeer(LightweightFrame target,
+                                                         PlatformComponent platformComponent,
+                                                         PlatformWindow platformWindow)
+    {
+        LWLightweightFramePeer peer = new LWLightweightFramePeer(target, platformComponent, platformWindow);
+        targetCreatedPeer(target, peer);
+        peer.initialize();
+        return peer;
+    }
+
+    @Override
+    public FramePeer createLightweightFrame(LightweightFrame target) {
+        PlatformComponent platformComponent = createLwPlatformComponent();
+        PlatformWindow platformWindow = createPlatformWindow(LWWindowPeer.PeerType.LW_FRAME);
+        return createDelegatedLwPeer(target, platformComponent, platformWindow);
+    }
+
     @Override
     public WindowPeer createWindow(Window target) {
         PlatformComponent platformComponent = createPlatformComponent();
@@ -502,6 +519,8 @@
 
     protected abstract PlatformComponent createPlatformComponent();
 
+    protected abstract PlatformComponent createLwPlatformComponent();
+
     protected abstract FileDialogPeer createFileDialogPeer(FileDialog target);
 
     // ---- UTILITY METHODS ---- //
--- a/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -48,7 +48,8 @@
         FRAME,
         DIALOG,
         EMBEDDED_FRAME,
-        VIEW_EMBEDDED_FRAME
+        VIEW_EMBEDDED_FRAME,
+        LW_FRAME
     }
 
     private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.lwawt.focus.LWWindowPeer");
@@ -1090,7 +1091,7 @@
         return platformWindow.requestWindowFocus();
     }
 
-    private boolean focusAllowedFor() {
+    protected boolean focusAllowedFor() {
         Window window = getTarget();
         // TODO: check if modal blocked
         return window.isVisible() && window.isEnabled() && isFocusableWindow();
@@ -1113,10 +1114,15 @@
         return !(window instanceof Dialog || window instanceof Frame);
     }
 
+    @Override
+    public void emulateActivation(boolean activate) {
+        changeFocusedWindow(activate, null);
+    }
+
     /*
      * Changes focused window on java level.
      */
-    private void changeFocusedWindow(boolean becomesFocused, Window opposite) {
+    protected void changeFocusedWindow(boolean becomesFocused, Window opposite) {
         if (focusLog.isLoggable(PlatformLogger.FINE)) {
             focusLog.fine((becomesFocused?"gaining":"loosing") + " focus window: " + this);
         }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTargetContextPeer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDropTargetContextPeer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -128,6 +128,15 @@
         }
     }
 
+    @Override
+    protected int postDropTargetEvent(Component component, int x, int y, int dropAction,
+                                      int actions, long[] formats, long nativeCtxt, int eventID,
+                                      boolean dispatchType) {
+        // On MacOS X all the DnD events should be synchronous
+        return super.postDropTargetEvent(component, x, y, dropAction, actions, formats, nativeCtxt,
+                eventID, SunDropTargetContextPeer.DISPATCH_SYNC);
+    }
+
     // Signal drop complete:
     protected void doDropDone(boolean success, int dropAction, boolean isLocal) {
         long nativeDropTarget = this.getNativeDragContext();
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformComponent.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformComponent.java	Fri Mar 15 23:31:19 2013 -0700
@@ -35,7 +35,7 @@
  * On OSX {@code CPlatformComponent} stores pointer to the native CAlayer which
  * can be used from JAWT.
  */
-final class CPlatformComponent extends CFRetainedResource
+class CPlatformComponent extends CFRetainedResource
         implements PlatformComponent {
 
     private volatile PlatformWindow platformWindow;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformLWComponent.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+package sun.lwawt.macosx;
+
+import sun.lwawt.PlatformWindow;
+
+class CPlatformLWComponent extends CPlatformComponent {
+
+    CPlatformLWComponent() {
+        super();
+    }
+
+    @Override
+    public long getPointer() {
+        return 0;
+    }
+
+    @Override
+    public void initialize(final PlatformWindow platformWindow) {
+    }
+
+    @Override
+    public void setBounds(final int x, final int y, final int w, final int h) {
+    }
+
+    @Override
+    public void dispose() {
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformLWView.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.lwawt.macosx;
+
+import sun.lwawt.LWWindowPeer;
+import sun.java2d.SurfaceData;
+
+public class CPlatformLWView extends CPlatformView {
+
+    public CPlatformLWView() {
+        super();
+    }
+
+    @Override
+    public void initialize(LWWindowPeer peer, CPlatformResponder responder) {
+        initializeBase(peer, responder);
+    }
+
+    @Override
+    public long getAWTView() {
+        return 0;
+    }
+
+    @Override
+    public boolean isOpaque() {
+        return true;
+    }
+
+    @Override
+    public void setBounds(int x, int y, int width, int height) {
+    }
+
+    @Override
+    public void enterFullScreenMode() {
+    }
+
+    @Override
+    public void exitFullScreenMode() {
+    }
+
+    @Override
+    public SurfaceData replaceSurfaceData() {
+        return null;
+    }
+
+    @Override
+    public SurfaceData getSurfaceData() {
+        return null;
+    }
+
+    @Override
+    public void dispose() {
+    }
+
+    @Override
+    public long getWindowLayerPtr() {
+        return 0;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformLWWindow.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,202 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.lwawt.macosx;
+
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Graphics;
+import java.awt.GraphicsDevice;
+import java.awt.Insets;
+import java.awt.MenuBar;
+import java.awt.Point;
+import java.awt.Window;
+import sun.awt.CausedFocusEvent;
+import sun.java2d.SurfaceData;
+import sun.lwawt.LWWindowPeer;
+import sun.lwawt.PlatformWindow;
+
+public class CPlatformLWWindow extends CPlatformWindow {
+
+    @Override
+    public void initialize(Window target, LWWindowPeer peer, PlatformWindow owner) {
+        initializeBase(target, peer, owner, new CPlatformLWView());
+    }
+
+    @Override
+    public void toggleFullScreen() {
+    }
+
+    @Override
+    public void setMenuBar(MenuBar mb) {
+    }
+
+    @Override
+    public void dispose() {
+    }
+
+    @Override
+    public FontMetrics getFontMetrics(Font f) {
+        return null;
+    }
+
+    @Override
+    public Insets getInsets() {
+        return new Insets(0, 0, 0, 0);
+    }
+
+    @Override
+    public Point getLocationOnScreen() {
+        return null;
+    }
+
+    @Override
+    public GraphicsDevice getGraphicsDevice() {
+        return null;
+    }
+
+    @Override
+    public SurfaceData getScreenSurface() {
+        return null;
+    }
+
+    @Override
+    public SurfaceData replaceSurfaceData() {
+        return null;
+    }
+
+    @Override
+    public void setBounds(int x, int y, int w, int h) {
+        if (getPeer() != null) {
+            getPeer().notifyReshape(x, y, w, h);
+        }
+    }
+
+    @Override
+    public void setVisible(boolean visible) {
+    }
+
+    @Override
+    public void setTitle(String title) {
+    }
+
+    @Override
+    public void updateIconImages() {
+    }
+
+    @Override
+    public long getNSWindowPtr() {
+        return 0;
+    }
+
+    @Override
+    public SurfaceData getSurfaceData() {
+        return null;
+    }
+
+    @Override
+    public void toBack() {
+    }
+
+    @Override
+    public void toFront() {
+    }
+
+    @Override
+    public void setResizable(final boolean resizable) {
+    }
+
+    @Override
+    public void setSizeConstraints(int minW, int minH, int maxW, int maxH) {
+    }
+
+    @Override
+    public boolean rejectFocusRequest(CausedFocusEvent.Cause cause) {
+        return false;
+    }
+
+    @Override
+    public boolean requestWindowFocus() {
+        return true;
+    }
+
+    @Override
+    public boolean isActive() {
+        return true;
+    }
+
+    @Override
+    public void updateFocusableWindowState() {
+    }
+
+    @Override
+    public Graphics transformGraphics(Graphics g) {
+        return null;
+    }
+
+    @Override
+    public void setAlwaysOnTop(boolean isAlwaysOnTop) {
+    }
+
+    @Override
+    public PlatformWindow getTopmostPlatformWindowUnderMouse(){
+        return null;
+    }
+
+    @Override
+    public void setOpacity(float opacity) {
+    }
+
+    @Override
+    public void setOpaque(boolean isOpaque) {
+    }
+
+    @Override
+    public void enterFullScreenMode() {
+    }
+
+    @Override
+    public void exitFullScreenMode() {
+    }
+
+    @Override
+    public void setWindowState(int windowState) {
+    }
+
+    @Override
+    public LWWindowPeer getPeer() {
+        return super.getPeer();
+    }
+
+    @Override
+    public CPlatformView getContentView() {
+        return super.getContentView();
+    }
+
+    @Override
+    public long getLayerPtr() {
+        return 0;
+    }
+}
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java	Fri Mar 15 23:31:19 2013 -0700
@@ -54,8 +54,7 @@
     }
 
     public void initialize(LWWindowPeer peer, CPlatformResponder responder) {
-        this.peer = peer;
-        this.responder = responder;
+        initializeBase(peer, responder);
 
         if (!LWCToolkit.getSunAwtDisableCALayers()) {
             this.windowLayer = new CGLLayer(peer);
@@ -63,6 +62,11 @@
         setPtr(nativeCreateView(0, 0, 0, 0, getWindowLayerPtr()));
     }
 
+    protected void initializeBase(LWWindowPeer peer, CPlatformResponder responder) {
+        this.peer = peer;
+        this.responder = responder;
+    }
+
     public long getAWTView() {
         return ptr;
         }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Fri Mar 15 23:31:19 2013 -0700
@@ -30,6 +30,7 @@
 import java.awt.event.*;
 import java.awt.peer.WindowPeer;
 import java.beans.*;
+import java.lang.reflect.InvocationTargetException;
 import java.util.List;
 
 import javax.swing.*;
@@ -44,7 +45,7 @@
 import com.apple.laf.ClientPropertyApplicator.Property;
 import com.sun.awt.AWTUtilities;
 
-public final class CPlatformWindow extends CFRetainedResource implements PlatformWindow {
+public class CPlatformWindow extends CFRetainedResource implements PlatformWindow {
     private native long nativeCreateNSWindow(long nsViewPtr, long styleBits, double x, double y, double w, double h);
     private static native void nativeSetNSWindowStyleBits(long nsWindowPtr, int mask, int data);
     private static native void nativeSetNSWindowMenuBar(long nsWindowPtr, long menuBarPtr);
@@ -218,11 +219,7 @@
      */
     @Override // PlatformWindow
     public void initialize(Window _target, LWWindowPeer _peer, PlatformWindow _owner) {
-        this.peer = _peer;
-        this.target = _target;
-        if (_owner instanceof CPlatformWindow) {
-            this.owner = (CPlatformWindow)_owner;
-        }
+        initializeBase(_target, _peer, _owner, new CPlatformView());
 
         final int styleBits = getInitialStyleBits();
 
@@ -231,7 +228,6 @@
         String warningString = target.getWarningString();
 
         responder = new CPlatformResponder(peer, false);
-        contentView = new CPlatformView();
         contentView.initialize(peer, responder);
 
         final long nativeWindowPtr = nativeCreateNSWindow(contentView.getAWTView(), styleBits, 0, 0, 0, 0);
@@ -253,6 +249,15 @@
         validateSurface();
     }
 
+    protected void initializeBase(Window target, LWWindowPeer peer, PlatformWindow owner, CPlatformView view) {
+        this.peer = peer;
+        this.target = target;
+        if (owner instanceof CPlatformWindow) {
+            this.owner = (CPlatformWindow)owner;
+        }
+        this.contentView = view;
+    }
+
     private int getInitialStyleBits() {
         // defaults style bits
         int styleBits = DECORATED | HAS_SHADOW | CLOSEABLE | MINIMIZABLE | ZOOMABLE | RESIZABLE;
@@ -857,7 +862,16 @@
 
     private void flushBuffers() {
         if (isVisible() && !nativeBounds.isEmpty()) {
-            LWCToolkit.getLWCToolkit().flushPendingEventsOnAppkit(target);
+            try {
+                LWCToolkit.invokeAndWait(new Runnable() {
+                    @Override
+                    public void run() {
+                        //Posting an empty to flush the EventQueue without blocking the main thread
+                    }
+                }, target);
+            } catch (InterruptedException | InvocationTargetException e) {
+                e.printStackTrace();
+            }
         }
     }
 
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CRobot.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CRobot.java	Fri Mar 15 23:31:19 2013 -0700
@@ -65,7 +65,7 @@
         mouseLastX = x;
         mouseLastY = y;
 
-        mouseEvent(fDevice.getCoreGraphicsScreen(), mouseLastX, mouseLastY,
+        mouseEvent(fDevice.getCGDisplayID(), mouseLastX, mouseLastY,
                    mouseButtonsState, true, true);
     }
 
@@ -79,7 +79,7 @@
     public void mousePress(int buttons) {
         mouseButtonsState |= buttons;
 
-        mouseEvent(fDevice.getCoreGraphicsScreen(), mouseLastX, mouseLastY,
+        mouseEvent(fDevice.getCGDisplayID(), mouseLastX, mouseLastY,
                    buttons, true, false);
     }
 
@@ -93,7 +93,7 @@
     public void mouseRelease(int buttons) {
         mouseButtonsState &= ~buttons;
 
-        mouseEvent(fDevice.getCoreGraphicsScreen(), mouseLastX, mouseLastY,
+        mouseEvent(fDevice.getCGDisplayID(), mouseLastX, mouseLastY,
                    buttons, false, false);
     }
 
@@ -163,7 +163,7 @@
     }
 
     private native void initRobot();
-    private native void mouseEvent(int screen, int lastX, int lastY,
+    private native void mouseEvent(int displayID, int lastX, int lastY,
                                    int buttonsState,
                                    boolean isButtonsDownState,
                                    boolean isMouseMove);
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CToolkitThreadBlockedHandler.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CToolkitThreadBlockedHandler.java	Fri Mar 15 23:31:19 2013 -0700
@@ -25,27 +25,33 @@
 
 package sun.lwawt.macosx;
 
+import sun.awt.Mutex;
 import sun.awt.datatransfer.ToolkitThreadBlockedHandler;
 
-final class CToolkitThreadBlockedHandler implements ToolkitThreadBlockedHandler {
-    private final LWCToolkit toolkit = (LWCToolkit)java.awt.Toolkit.getDefaultToolkit();
-
-    public void lock() {
-    }
+final class CToolkitThreadBlockedHandler extends Mutex implements ToolkitThreadBlockedHandler {
+    private long awtRunLoopMediator = 0;
+    private final boolean processEvents;
 
-    public void unlock() {
-    }
-
-    protected boolean isOwned() {
-       return false;
+    CToolkitThreadBlockedHandler() {
+        super();
+        this.processEvents = true;
     }
 
     public void enter() {
-        // Execute the next AppKit event while we are waiting for system to
-        // finish our request - this will save us from biting our own tail
-        toolkit.executeNextAppKitEvent();
+        if (!isOwned()) {
+            throw new IllegalMonitorStateException();
+        }
+        awtRunLoopMediator = LWCToolkit.createAWTRunLoopMediator();
+        unlock();
+        LWCToolkit.doAWTRunLoop(awtRunLoopMediator, processEvents);
+        lock();
     }
 
     public void exit() {
+        if (!isOwned()) {
+            throw new IllegalMonitorStateException();
+        }
+        LWCToolkit.stopAWTRunLoop(awtRunLoopMediator);
+        awtRunLoopMediator = 0;
     }
 }
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/LWCToolkit.java	Fri Mar 15 23:31:19 2013 -0700
@@ -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
@@ -63,8 +63,6 @@
 
     private static native void initIDs();
 
-    static native void executeNextAppKitEvent();
-
     private static CInputMethodDescriptor sInputMethodDescriptor;
 
     static {
@@ -160,6 +158,8 @@
             return new CPlatformEmbeddedFrame();
         } else if (peerType == PeerType.VIEW_EMBEDDED_FRAME) {
             return new CViewPlatformEmbeddedFrame();
+        } else if (peerType == PeerType.LW_FRAME) {
+            return new CPlatformLWWindow();
         } else {
             assert (peerType == PeerType.SIMPLEWINDOW || peerType == PeerType.DIALOG || peerType == PeerType.FRAME);
             return new CPlatformWindow();
@@ -172,6 +172,11 @@
     }
 
     @Override
+    protected PlatformComponent createLwPlatformComponent() {
+        return new CPlatformLWComponent();
+    }
+
+    @Override
     protected FileDialogPeer createFileDialogPeer(FileDialog target) {
         return new CFileDialog(target);
     }
@@ -346,22 +351,7 @@
 
     @Override
     public Insets getScreenInsets(final GraphicsConfiguration gc) {
-        final CGraphicsConfig cgc = (CGraphicsConfig) gc;
-        final int displayId = cgc.getDevice().getCoreGraphicsScreen();
-        Rectangle fullScreen, workArea;
-        final long screen = CWrapper.NSScreen.screenByDisplayId(displayId);
-        try {
-            fullScreen = CWrapper.NSScreen.frame(screen).getBounds();
-            workArea = CWrapper.NSScreen.visibleFrame(screen).getBounds();
-        } finally {
-            CWrapper.NSObject.release(screen);
-        }
-        // Convert between Cocoa's coordinate system and Java.
-        int bottom = workArea.y - fullScreen.y;
-        int top = fullScreen.height - workArea.height - bottom;
-        int left = workArea.x - fullScreen.x;
-        int right = fullScreen.width - workArea.width - left;
-        return  new Insets(top, left, bottom, right);
+        return ((CGraphicsConfig) gc).getDevice().getScreenInsets();
     }
 
     @Override
@@ -495,30 +485,6 @@
         synchronized(ret) { return ret[0]; }
     }
 
-    /**
-     * Just a wrapper for LWCToolkit.invokeAndWait. Posts an empty event to the
-     * appropriate event queue and waits for it to finish.
-     */
-    public static void flushPendingEventsOnAppkit(final Component component) {
-        try {
-            invokeAndWait(new Runnable() {
-                @Override
-                public void run() {
-                }
-            }, component);
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
-
-    // Kicks an event over to the appropriate eventqueue and waits for it to finish
-    // To avoid deadlocking, we manually run the NSRunLoop while waiting
-    // Any selector invoked using ThreadUtilities performOnMainThread will be processed in doAWTRunLoop
-    // The CInvocationEvent will call LWCToolkit.stopAWTRunLoop() when finished, which will stop our manual runloop
-    public static void invokeAndWait(Runnable event, Component component) throws InterruptedException, InvocationTargetException {
-        invokeAndWait(event, component, true);
-    }
-
     public static <T> T invokeAndWait(final Callable<T> callable, Component component) throws Exception {
         final CallableWrapper<T> wrapper = new CallableWrapper<T>(callable);
         invokeAndWait(wrapper, component);
@@ -548,10 +514,27 @@
         }
     }
 
-    public static void invokeAndWait(Runnable event, Component component, boolean detectDeadlocks) throws InterruptedException, InvocationTargetException {
-        long mediator = createAWTRunLoopMediator();
+    // Kicks an event over to the appropriate eventqueue and waits for it to finish
+    // To avoid deadlocking, we manually run the NSRunLoop while waiting
+    // Any selector invoked using ThreadUtilities performOnMainThread will be processed in doAWTRunLoop
+    // The InvocationEvent will call LWCToolkit.stopAWTRunLoop() when finished, which will stop our manual runloop
+    // Does not dispatch native events while in the loop
+    public static void invokeAndWait(Runnable event, Component component) throws InterruptedException, InvocationTargetException {
+        final long mediator = createAWTRunLoopMediator();
 
-        InvocationEvent invocationEvent = new CPeerEvent(event, mediator);
+        InvocationEvent invocationEvent =
+                new InvocationEvent(component != null ? component : Toolkit.getDefaultToolkit(), event) {
+                    @Override
+                    public void dispatch() {
+                        try {
+                            super.dispatch();
+                        } finally {
+                            if (mediator != 0) {
+                                stopAWTRunLoop(mediator);
+                            }
+                        }
+                    }
+                };
 
         if (component != null) {
             AppContext appContext = SunToolkit.targetToAppContext(component);
@@ -564,7 +547,7 @@
             ((LWCToolkit)Toolkit.getDefaultToolkit()).getSystemEventQueueForInvokeAndWait().postEvent(invocationEvent);
         }
 
-        doAWTRunLoop(mediator, true, detectDeadlocks);
+        doAWTRunLoop(mediator, false);
 
         Throwable eventException = invocationEvent.getException();
         if (eventException != null) {
@@ -576,7 +559,8 @@
     }
 
     public static void invokeLater(Runnable event, Component component) throws InvocationTargetException {
-        final InvocationEvent invocationEvent = new CPeerEvent(event, 0);
+        final InvocationEvent invocationEvent =
+                new InvocationEvent(component != null ? component : Toolkit.getDefaultToolkit(), event);
 
         if (component != null) {
             final AppContext appContext = SunToolkit.targetToAppContext(component);
@@ -681,31 +665,6 @@
         return false;
     }
 
-    // Extends PeerEvent because we want to pass long an ObjC mediator object and because we want these events to be posted early
-    // Typically, rather than relying on the notifier to call notifyAll(), we use the mediator to stop the runloop
-    public static class CPeerEvent extends PeerEvent {
-        private long _mediator = 0;
-
-        public CPeerEvent(Runnable runnable, long mediator) {
-            super(Toolkit.getDefaultToolkit(), runnable, null, true, 0);
-            _mediator = mediator;
-        }
-
-        public void dispatch() {
-            try {
-                super.dispatch();
-            } finally {
-                if (_mediator != 0) {
-                    LWCToolkit.stopAWTRunLoop(_mediator);
-                }
-            }
-        }
-    }
-
-    // Call through to native methods
-    public static void doAWTRunLoop(long mediator, boolean awtMode) { doAWTRunLoop(mediator, awtMode, true); }
-    public static void doAWTRunLoop(long mediator) { doAWTRunLoop(mediator, true); }
-
     private static Boolean sunAwtDisableCALayers = null;
 
     /**
@@ -730,12 +689,20 @@
      * Native methods section
      ************************/
 
-    // These are public because they are accessed from WebKitPluginObject in JavaDeploy
-    // Basic usage:
-    // createAWTRunLoopMediator. Start client code on another thread. doAWTRunLoop. When client code is finished, stopAWTRunLoop.
-    public static native long createAWTRunLoopMediator();
-    public static native void doAWTRunLoop(long mediator, boolean awtMode, boolean detectDeadlocks);
-    public static native void stopAWTRunLoop(long mediator);
+    static native long createAWTRunLoopMediator();
+    /**
+     * Method to run a nested run-loop. The nested loop is spinned in the javaRunLoop mode, so selectors sent
+     * by [JNFRunLoop performOnMainThreadWaiting] are processed.
+     * @param mediator a native pointer to the mediator object created by createAWTRunLoopMediator
+     * @param processEvents if true - dispatches event while in the nested loop. Used in DnD.
+     *                      Additional attention is needed when using this feature as we short-circuit normal event
+     *                      processing which could break Appkit.
+     *                      (One known example is when the window is resized with the mouse)
+     *
+     *                      if false - all events come after exit form the nested loop
+     */
+    static native void doAWTRunLoop(long mediator, boolean processEvents);
+    static native void stopAWTRunLoop(long mediator);
 
     private native boolean nativeSyncQueue(long timeout);
 
--- a/jdk/src/macosx/native/sun/awt/AWTView.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/awt/AWTView.m	Fri Mar 15 23:31:19 2013 -0700
@@ -227,7 +227,7 @@
 
 - (void) mouseMoved: (NSEvent *)event {
     // TODO: better way to redirect move events to the "under" view
-
+    
     NSPoint eventLocation = [event locationInWindow];
     NSPoint localPoint = [self convertPoint: eventLocation fromView: nil];
 
@@ -668,7 +668,7 @@
 
 - (void) setDropTarget:(CDropTarget *)target {
     self._dropTarget = target;
-    [ThreadUtilities performOnMainThread:@selector(controlModelControlValid) onObject:self._dropTarget withObject:nil waitUntilDone:YES awtMode:YES];
+    [ThreadUtilities performOnMainThread:@selector(controlModelControlValid) on:self._dropTarget withObject:nil waitUntilDone:YES];
 }
 
 /********************************  BEGIN NSDraggingSource Interface  ********************************/
@@ -1215,7 +1215,7 @@
     fprintf(stderr, "AWTView InputMethod Selector Called : [abandonInput]\n");
 #endif // IM_DEBUG
 
-    [ThreadUtilities performOnMainThread:@selector(markedTextAbandoned:) onObject:[NSInputManager currentInputManager] withObject:self waitUntilDone:YES awtMode:YES];
+    [ThreadUtilities performOnMainThread:@selector(markedTextAbandoned:) on:[NSInputManager currentInputManager] withObject:self waitUntilDone:YES];
     [self unmarkText];
 }
 
--- a/jdk/src/macosx/native/sun/awt/ApplicationDelegate.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/awt/ApplicationDelegate.m	Fri Mar 15 23:31:19 2013 -0700
@@ -567,10 +567,9 @@
 {
 JNF_COCOA_ENTER(env);
     [ThreadUtilities performOnMainThread:@selector(_registerForNotification:)
-                                onObject:[ApplicationDelegate class]
+                                      on:[ApplicationDelegate class]
                               withObject:[NSNumber numberWithInt:notificationType]
-                           waitUntilDone:NO
-                                 awtMode:NO]; // AWT_THREADING Safe (non-blocking)
+                           waitUntilDone:NO]; // AWT_THREADING Safe (non-blocking)
 JNF_COCOA_EXIT(env);
 }
 
--- a/jdk/src/macosx/native/sun/awt/CClipboard.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/awt/CClipboard.m	Fri Mar 15 23:31:19 2013 -0700
@@ -120,7 +120,7 @@
             fClipboardOwner = JNFNewGlobalRef(inEnv, inClipboard);
         }
     }
-    [ThreadUtilities performOnMainThread:@selector(_nativeDeclareTypes:) onObject:self withObject:inTypes waitUntilDone:YES awtMode:YES];
+    [ThreadUtilities performOnMainThread:@selector(_nativeDeclareTypes:) on:self withObject:inTypes waitUntilDone:YES];
 }
 
 - (void) _nativeDeclareTypes:(NSArray *)inTypes {
@@ -135,7 +135,7 @@
 - (NSArray *) javaGetTypes {
 
     NSMutableArray *args = [NSMutableArray arrayWithCapacity:1];
-    [ThreadUtilities performOnMainThread:@selector(_nativeGetTypes:) onObject:self withObject:args waitUntilDone:YES awtMode:YES];
+    [ThreadUtilities performOnMainThread:@selector(_nativeGetTypes:) on:self withObject:args waitUntilDone:YES];
 
     //NSLog(@"CClipboard getTypes returns %@", [args lastObject]);
     return [args lastObject];
@@ -152,7 +152,7 @@
 - (void) javaSetData:(NSData *)inData forType:(NSString *) inFormat {
 
     CClipboardUpdate *newUpdate = [[CClipboardUpdate alloc] initWithData:inData withFormat:inFormat];
-    [ThreadUtilities performOnMainThread:@selector(_nativeSetData:) onObject:self withObject:newUpdate waitUntilDone:YES awtMode:YES];
+    [ThreadUtilities performOnMainThread:@selector(_nativeSetData:) on:self withObject:newUpdate waitUntilDone:YES];
     [newUpdate release];
 
     //NSLog(@"CClipboard javaSetData forType %@", inFormat);
@@ -170,7 +170,7 @@
 - (NSData *) javaGetDataForType:(NSString *) inFormat {
 
     NSMutableArray *args = [NSMutableArray arrayWithObject:inFormat];
-    [ThreadUtilities performOnMainThread:@selector(_nativeGetDataForType:) onObject:self withObject:args waitUntilDone:YES awtMode:YES];
+    [ThreadUtilities performOnMainThread:@selector(_nativeGetDataForType:) on:self withObject:args waitUntilDone:YES];
 
     //NSLog(@"CClipboard javaGetDataForType %@ returns an NSData", inFormat);
     return [args lastObject];
--- a/jdk/src/macosx/native/sun/awt/CDropTarget.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/awt/CDropTarget.m	Fri Mar 15 23:31:19 2013 -0700
@@ -390,8 +390,7 @@
 
     // Release dragging data if any when Java's AWT event thread is all finished.
     // Make sure dragging data is released on the native event thread.
-    [ThreadUtilities performOnMainThread:@selector(safeReleaseDraggingData:) onObject:self
-                              withObject:draggingSequenceNumberID waitUntilDone:NO awtMode:NO];
+    [ThreadUtilities performOnMainThread:@selector(safeReleaseDraggingData:) on:self withObject:draggingSequenceNumberID waitUntilDone:NO];
 }
 
 - (jint)currentJavaActions {
--- a/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/awt/CGraphicsDevice.m	Fri Mar 15 23:31:19 2013 -0700
@@ -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,8 @@
  * questions.
  */
 
-#include "LWCToolkit.h"
+#import "LWCToolkit.h"
+#import "ThreadUtilities.h"
 
 /*
  * Convert the mode string to the more convinient bits per pixel value
@@ -148,6 +149,47 @@
 
 /*
  * Class:     sun_awt_CGraphicsDevice
+ * Method:    nativeGetScreenInsets
+ * Signature: (I)D
+ */
+JNIEXPORT jobject JNICALL
+Java_sun_awt_CGraphicsDevice_nativeGetScreenInsets
+  (JNIEnv *env, jclass class, jint displayID)
+{
+    jobject ret = NULL;
+    __block NSRect frame = NSZeroRect;
+    __block NSRect visibleFrame = NSZeroRect;
+JNF_COCOA_ENTER(env);
+    
+    [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
+        NSArray *screens = [NSScreen screens];
+        for (NSScreen *screen in screens) {
+            NSDictionary *screenInfo = [screen deviceDescription];
+            NSNumber *screenID = [screenInfo objectForKey:@"NSScreenNumber"];
+            if ([screenID pointerValue] == displayID){
+                frame = [screen frame];
+                visibleFrame = [screen visibleFrame];
+                break;
+            }
+        }
+    }];
+    // Convert between Cocoa's coordinate system and Java.
+    jint bottom = visibleFrame.origin.y - frame.origin.y;
+    jint top = frame.size.height - visibleFrame.size.height - bottom;
+    jint left = visibleFrame.origin.x - frame.origin.x;
+    jint right = frame.size.width - visibleFrame.size.width - left;
+    
+    static JNF_CLASS_CACHE(jc_Insets, "java/awt/Insets");
+    static JNF_CTOR_CACHE(jc_Insets_ctor, jc_Insets, "(IIII)V");
+    ret = JNFNewObject(env, jc_Insets_ctor, top, left, bottom, right);
+
+JNF_COCOA_EXIT(env);
+
+    return ret;
+}
+
+/*
+ * Class:     sun_awt_CGraphicsDevice
  * Method:    nativeSetDisplayMode
  * Signature: (IIIII)V
  */
--- a/jdk/src/macosx/native/sun/awt/CMenu.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/awt/CMenu.m	Fri Mar 15 23:31:19 2013 -0700
@@ -55,11 +55,11 @@
 //- (void)finalize { [super finalize]; }
 
 - (void)addJavaSubmenu:(CMenu *)submenu {
-    [ThreadUtilities performOnMainThread:@selector(addNativeItem_OnAppKitThread:) onObject:self withObject:submenu waitUntilDone:YES awtMode:YES];
+    [ThreadUtilities performOnMainThread:@selector(addNativeItem_OnAppKitThread:) on:self withObject:submenu waitUntilDone:YES];
 }
 
 - (void)addJavaMenuItem:(CMenuItem *)theMenuItem {
-    [ThreadUtilities performOnMainThread:@selector(addNativeItem_OnAppKitThread:) onObject:self withObject:theMenuItem waitUntilDone:YES awtMode:YES];
+    [ThreadUtilities performOnMainThread:@selector(addNativeItem_OnAppKitThread:) on:self withObject:theMenuItem waitUntilDone:YES];
 }
 
 - (void)addNativeItem_OnAppKitThread:(CMenuItem *)itemModified {
@@ -70,7 +70,7 @@
 - (void)setJavaMenuTitle:(NSString *)title {
 
     if (title) {
-        [ThreadUtilities performOnMainThread:@selector(setNativeMenuTitle_OnAppKitThread:) onObject:self withObject:title waitUntilDone:YES awtMode:YES];
+        [ThreadUtilities performOnMainThread:@selector(setNativeMenuTitle_OnAppKitThread:) on:self withObject:title waitUntilDone:YES];
     }
 }
 
@@ -93,7 +93,7 @@
 
 - (void)deleteJavaItem:(jint)index {
 
-    [ThreadUtilities performOnMainThread:@selector(deleteNativeJavaItem_OnAppKitThread:) onObject:self withObject:[NSNumber numberWithInt:index] waitUntilDone:YES awtMode:YES];
+    [ThreadUtilities performOnMainThread:@selector(deleteNativeJavaItem_OnAppKitThread:) on:self withObject:[NSNumber numberWithInt:index] waitUntilDone:YES];
 }
 
 - (void)deleteNativeJavaItem_OnAppKitThread:(NSNumber *)number {
@@ -139,7 +139,7 @@
     // We use an array here only to be able to get a return value
     NSMutableArray *args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], nil];
 
-    [ThreadUtilities performOnMainThread:@selector(_create_OnAppKitThread:) onObject:[CMenu alloc] withObject:args waitUntilDone:YES awtMode:YES];
+    [ThreadUtilities performOnMainThread:@selector(_create_OnAppKitThread:) on:[CMenu alloc] withObject:args waitUntilDone:YES];
 
     aCMenu = (CMenu *)[args objectAtIndex: 0];
 
--- a/jdk/src/macosx/native/sun/awt/CMenuBar.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/awt/CMenuBar.m	Fri Mar 15 23:31:19 2013 -0700
@@ -197,7 +197,7 @@
 
     if (self == sActiveMenuBar) {
         NSArray *args = [[NSArray alloc] initWithObjects:theMenu, [NSNumber numberWithInt:-1], nil];
-        [ThreadUtilities performOnMainThread:@selector(nativeAddMenuAtIndex_OnAppKitThread:) onObject:self withObject:args waitUntilDone:YES awtMode:YES];
+        [ThreadUtilities performOnMainThread:@selector(nativeAddMenuAtIndex_OnAppKitThread:) on:self withObject:args waitUntilDone:YES];
         [args release];
     }
 }
@@ -216,7 +216,7 @@
 
     if (self == sActiveMenuBar) {
         NSArray *args = [[NSArray alloc] initWithObjects:theMenu, [NSNumber numberWithInt:index], nil];
-        [ThreadUtilities performOnMainThread:@selector(nativeAddMenuAtIndex_OnAppKitThread:) onObject:self withObject:args waitUntilDone:YES awtMode:YES];
+        [ThreadUtilities performOnMainThread:@selector(nativeAddMenuAtIndex_OnAppKitThread:) on:self withObject:args waitUntilDone:YES];
         [args release];
     }
 }
@@ -286,7 +286,7 @@
 
 - (void) javaDeleteMenu: (jint)index {
     if (self == sActiveMenuBar) {
-        [ThreadUtilities performOnMainThread:@selector(nativeDeleteMenu_OnAppKitThread:) onObject:self withObject:[NSNumber numberWithInt:index] waitUntilDone:YES awtMode:YES];
+        [ThreadUtilities performOnMainThread:@selector(nativeDeleteMenu_OnAppKitThread:) on:self withObject:[NSNumber numberWithInt:index] waitUntilDone:YES];
     }
 
     @synchronized(self) {
@@ -388,7 +388,7 @@
     // We use an array here only to be able to get a return value
     NSMutableArray *args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], nil];
 
-    [ThreadUtilities performOnMainThread:@selector(_create_OnAppKitThread:) onObject:[CMenuBar alloc] withObject:args waitUntilDone:YES awtMode:YES];
+    [ThreadUtilities performOnMainThread:@selector(_create_OnAppKitThread:) on:[CMenuBar alloc] withObject:args waitUntilDone:YES];
 
     aCMenuBar = (CMenuBar *)[args objectAtIndex: 0];
 
--- a/jdk/src/macosx/native/sun/awt/CMenuItem.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/awt/CMenuItem.m	Fri Mar 15 23:31:19 2013 -0700
@@ -386,7 +386,7 @@
         args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], [NSNumber numberWithBool:NO],  nil];
     }
 
-    [ThreadUtilities performOnMainThread:@selector(_createMenuItem_OnAppKitThread:) onObject:[CMenuItem alloc] withObject:args waitUntilDone:YES awtMode:YES];
+    [ThreadUtilities performOnMainThread:@selector(_createMenuItem_OnAppKitThread:) on:[CMenuItem alloc] withObject:args waitUntilDone:YES];
 
     aCMenuItem = (CMenuItem *)[args objectAtIndex: 0];
 
--- a/jdk/src/macosx/native/sun/awt/CRobot.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/awt/CRobot.m	Fri Mar 15 23:31:19 2013 -0700
@@ -135,7 +135,7 @@
 JNIEXPORT void JNICALL
 Java_sun_lwawt_macosx_CRobot_mouseEvent
 (JNIEnv *env, jobject peer,
- jint screenIndex, jint mouseLastX, jint mouseLastY, jint buttonsState,
+ jint displayID, jint mouseLastX, jint mouseLastY, jint buttonsState,
  jboolean isButtonsDownState, jboolean isMouseMove)
 {
     JNF_COCOA_ENTER(env);
@@ -149,8 +149,6 @@
 
     CGError err = kCGErrorSuccess;
 
-    CGDirectDisplayID displayID =
-    FindCGDirectDisplayIDForScreenIndex(screenIndex);
     CGRect globalDeviceBounds = CGDisplayBounds(displayID);
 
     // Set unknown mouse location, if needed.
--- a/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.m	Fri Mar 15 23:31:19 2013 -0700
@@ -1113,18 +1113,10 @@
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     id value = nil;
 
-    // This code frequently gets called indirectly by Java when VoiceOver is active.
-    // Basically, we just have to know when we going to be a bad state, and do something "special".
-    // Note that while NSApplication isn't technically correct, we post a focus changed notification
-    // (which will call this method, but with the correct codepath) shortly afterwards. See +postFocusChanged.
-    if (sInPerformFromJava) {
-        return [NSApplication sharedApplication];
-    } else {
-        jobject focused = JNFCallStaticObjectMethod(env, jm_getFocusOwner, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-        if (focused != NULL) {
-            if (JNFIsInstanceOf(env, focused, &sjc_Accessible)) {
-                value = [JavaComponentAccessibility createWithAccessible:focused withEnv:env withView:fView];
-            }
+    jobject focused = JNFCallStaticObjectMethod(env, jm_getFocusOwner, fComponent); // AWT_THREADING Safe (AWTRunLoop)
+    if (focused != NULL) {
+        if (JNFIsInstanceOf(env, focused, &sjc_Accessible)) {
+            value = [JavaComponentAccessibility createWithAccessible:focused withEnv:env withView:fView];
         }
     }
 
@@ -1149,7 +1141,7 @@
 {
 
 JNF_COCOA_ENTER(env);
-    [ThreadUtilities performOnMainThread:@selector(postFocusChanged:) onObject:[JavaComponentAccessibility class] withObject:nil waitUntilDone:NO awtMode:NO];
+    [ThreadUtilities performOnMainThread:@selector(postFocusChanged:) on:[JavaComponentAccessibility class] withObject:nil waitUntilDone:NO];
 JNF_COCOA_EXIT(env);
 }
 
@@ -1164,7 +1156,7 @@
 (JNIEnv *env, jclass jklass, jlong element)
 {
 JNF_COCOA_ENTER(env);
-    [ThreadUtilities performOnMainThread:@selector(postValueChanged) onObject:(JavaComponentAccessibility *)jlong_to_ptr(element) withObject:nil waitUntilDone:NO awtMode:NO];
+    [ThreadUtilities performOnMainThread:@selector(postValueChanged) on:(JavaComponentAccessibility *)jlong_to_ptr(element) withObject:nil waitUntilDone:NO];
 JNF_COCOA_EXIT(env);
 }
 
@@ -1177,7 +1169,7 @@
 (JNIEnv *env, jclass jklass, jlong element)
 {
 JNF_COCOA_ENTER(env);
-    [ThreadUtilities performOnMainThread:@selector(postSelectionChanged) onObject:(JavaComponentAccessibility *)jlong_to_ptr(element) withObject:nil waitUntilDone:NO awtMode:NO];
+    [ThreadUtilities performOnMainThread:@selector(postSelectionChanged) on:(JavaComponentAccessibility *)jlong_to_ptr(element) withObject:nil waitUntilDone:NO];
 JNF_COCOA_EXIT(env);
 }
 
@@ -1191,7 +1183,7 @@
 (JNIEnv *env, jclass jklass, jlong element)
 {
 JNF_COCOA_ENTER(env);
-    [ThreadUtilities performOnMainThread:@selector(unregisterFromCocoaAXSystem) onObject:(JavaComponentAccessibility *)jlong_to_ptr(element) withObject:nil waitUntilDone:NO awtMode:NO];
+    [ThreadUtilities performOnMainThread:@selector(unregisterFromCocoaAXSystem) on:(JavaComponentAccessibility *)jlong_to_ptr(element) withObject:nil waitUntilDone:NO];
 JNF_COCOA_EXIT(env);
 }
 
--- a/jdk/src/macosx/native/sun/awt/LWCToolkit.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/awt/LWCToolkit.h	Fri Mar 15 23:31:19 2013 -0700
@@ -44,8 +44,6 @@
 + (void) eventCountPlusPlus;
 @end
 
-CGDirectDisplayID FindCGDirectDisplayIDForScreenIndex(jint screenIndex);
-
 /*
  * Utility Macros
  */
--- a/jdk/src/macosx/native/sun/awt/LWCToolkit.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/awt/LWCToolkit.m	Fri Mar 15 23:31:19 2013 -0700
@@ -177,39 +177,6 @@
     NSBeep(); // produces both sound and visual flash, if configured in System Preferences
 }
 
-CGDirectDisplayID
-FindCGDirectDisplayIDForScreenIndex(jint screenIndex)
-{
-    // most common case - just one monitor
-    CGDirectDisplayID screenID = CGMainDisplayID();
-
-    CGDisplayCount displayCount = 0;
-    CGGetOnlineDisplayList(0, NULL, &displayCount);
-
-    if ((displayCount > 1) &&
-        (screenIndex >= 0) &&
-        (screenIndex < (jint)displayCount))
-    {
-        if (displayCount < 10) {
-            // stack allocated optimization for less than 10 monitors
-            CGDirectDisplayID onlineDisplays[displayCount];
-            CGGetOnlineDisplayList(displayCount, onlineDisplays, &displayCount);
-            screenID = (CGDirectDisplayID)onlineDisplays[screenIndex];
-        } else {
-            CGDirectDisplayID *onlineDisplays =
-            malloc(displayCount*sizeof(CGDirectDisplayID));
-            if (onlineDisplays != NULL) {
-                CGGetOnlineDisplayList(displayCount, onlineDisplays,
-                                       &displayCount);
-                screenID = (CGDirectDisplayID)onlineDisplays[screenIndex];
-                free(onlineDisplays);
-            }
-        }
-    }
-
-    return screenID;
-}
-
 /*
  * Class:     sun_lwawt_macosx_LWCToolkit
  * Method:    initIDs
@@ -332,7 +299,7 @@
  * Signature: (JZZ)V
  */
 JNIEXPORT void JNICALL Java_sun_lwawt_macosx_LWCToolkit_doAWTRunLoop
-(JNIEnv *env, jclass clz, jlong mediator, jboolean awtMode, jboolean detectDeadlocks)
+(JNIEnv *env, jclass clz, jlong mediator, jboolean processEvents)
 {
 AWT_ASSERT_APPKIT_THREAD;
 JNF_COCOA_ENTER(env);
@@ -341,26 +308,25 @@
 
     if (mediatorObject == nil) return;
 
-    if (!sInPerformFromJava || !detectDeadlocks) {
-
-        NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
-        NSDate *distantFuture = [NSDate distantFuture];
-        NSString *mode = (awtMode) ? [JNFRunLoop javaRunLoopMode] : NSDefaultRunLoopMode;
+    // Don't use acceptInputForMode because that doesn't setup autorelease pools properly
+    BOOL isRunning = true;
+    while (![mediatorObject shouldEndRunLoop] && isRunning) {
+        isRunning = [[NSRunLoop currentRunLoop] runMode:[JNFRunLoop javaRunLoopMode]
+                                             beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.010]];
+        if (processEvents) {
+            //We do not spin a runloop here as date is nil, so does not matter which mode to use
+            NSEvent *event;
+            if ((event = [NSApp nextEventMatchingMask:NSAnyEventMask
+                                           untilDate:nil
+                                              inMode:NSDefaultRunLoopMode
+                                             dequeue:YES]) != nil) {
+                [NSApp sendEvent:event];
+            }
 
-        BOOL isRunning = YES;
-        while (isRunning && ![mediatorObject shouldEndRunLoop]) {
-            // Don't use acceptInputForMode because that doesn't setup autorelease pools properly
-            isRunning = [currentRunLoop runMode:mode beforeDate:distantFuture];
         }
-
     }
-#ifndef PRODUCT_BUILD
-    if (sInPerformFromJava) {
-        NSLog(@"Apple AWT: Short-circuiting CToolkit.invokeAndWait trampoline deadlock!!!!!");
-        NSLog(@"\tPlease file a bug report with this message and a reproducible test case.");
-    }
-#endif
 
+   
     CFRelease(mediatorObject);
 
 JNF_COCOA_EXIT(env);
@@ -379,7 +345,7 @@
 
     AWTRunLoopObject* mediatorObject = (AWTRunLoopObject*)jlong_to_ptr(mediator);
 
-    [ThreadUtilities performOnMainThread:@selector(endRunLoop) onObject:mediatorObject withObject:nil waitUntilDone:NO awtMode:YES];
+    [ThreadUtilities performOnMainThread:@selector(endRunLoop) on:mediatorObject withObject:nil waitUntilDone:NO];
 
     CFRelease(mediatorObject);
 
@@ -463,20 +429,3 @@
 
 }
 
-/*
- * Class:     sun_lwawt_macosx_LWCToolkit
- * Method:    executeNextAppKitEvent
- * Signature: ()V
- */
-JNIEXPORT void JNICALL Java_sun_lwawt_macosx_LWCToolkit_executeNextAppKitEvent
-(JNIEnv *env, jclass cls)
-{
-    // Simply get the next event in native loop and pass it to execution
-    // We'll be called repeatedly so there's no need to block here
-    NSRunLoop *theRL = [NSRunLoop currentRunLoop];
-    NSApplication * app = [NSApplication sharedApplication];
-    NSEvent * event = [app nextEventMatchingMask: 0xFFFFFFFF untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES];
-    if (event != nil) {
-        [app sendEvent: event];
-    }
-}
--- a/jdk/src/macosx/native/sun/font/AWTStrike.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/font/AWTStrike.m	Fri Mar 15 23:31:19 2013 -0700
@@ -27,11 +27,13 @@
 #import "java_awt_geom_PathIterator.h"
 #import "sun_awt_SunHints.h"
 #import "sun_font_CStrike.h"
+#import "sun_font_CStrikeDisposer.h"
 #import "CGGlyphImages.h"
 #import "CGGlyphOutlines.h"
 #import "AWTStrike.h"
 #import "CoreTextSupport.h"
 //#import "jni_util.h"
+#include "fontscalerdefs.h"
 
 /* Use THIS_FILE when it is available. */
 #ifndef THIS_FILE
@@ -423,3 +425,19 @@
 
     return metrics;
 }
+
+extern void AccelGlyphCache_RemoveAllInfos(GlyphInfo* glyph);
+/*
+ * Class:     sun_font_CStrikeDisposer
+ * Method:    removeGlyphInfoFromCache
+ * Signature: (J)V
+ */
+JNIEXPORT void JNICALL Java_sun_font_CStrikeDisposer_removeGlyphInfoFromCache
+(JNIEnv *env, jclass cls, jlong glyphInfo)
+{
+    JNF_COCOA_ENTER(env);
+
+    AccelGlyphCache_RemoveAllCellInfos((GlyphInfo*)jlong_to_ptr(glyphInfo));
+
+    JNF_COCOA_EXIT(env);
+}
--- a/jdk/src/macosx/native/sun/java2d/opengl/CGLGraphicsConfig.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/java2d/opengl/CGLGraphicsConfig.m	Fri Mar 15 23:31:19 2013 -0700
@@ -192,12 +192,12 @@
 JNIEXPORT jlong JNICALL
 Java_sun_java2d_opengl_CGLGraphicsConfig_getCGLConfigInfo
     (JNIEnv *env, jclass cglgc,
-     jint screennum, jint pixfmt, jint swapInterval)
+     jint displayID, jint pixfmt, jint swapInterval)
 {
   jlong ret = 0L;
   JNF_COCOA_ENTER(env);
   NSMutableArray * retArray = [NSMutableArray arrayWithCapacity:3];
-  [retArray addObject: [NSNumber numberWithInt: (int)screennum]];
+  [retArray addObject: [NSNumber numberWithInt: (int)displayID]];
   [retArray addObject: [NSNumber numberWithInt: (int)pixfmt]];
   [retArray addObject: [NSNumber numberWithInt: (int)swapInterval]];
   if ([NSThread isMainThread]) {
@@ -217,7 +217,7 @@
 + (void) _getCGLConfigInfo: (NSMutableArray *)argValue {
     AWT_ASSERT_APPKIT_THREAD;
 
-    jint screennum = (jint)[(NSNumber *)[argValue objectAtIndex: 0] intValue];
+    jint displayID = (jint)[(NSNumber *)[argValue objectAtIndex: 0] intValue];
     jint pixfmt = (jint)[(NSNumber *)[argValue objectAtIndex: 1] intValue];
     jint swapInterval = (jint)[(NSNumber *)[argValue objectAtIndex: 2] intValue];
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
@@ -230,16 +230,11 @@
     CGOpenGLDisplayMask glMask = (CGOpenGLDisplayMask)pixfmt;
     if (sharedContext == NULL) {
         if (glMask == 0) {
-            CGDirectDisplayID id =
-                FindCGDirectDisplayIDForScreenIndex(screennum);
-            glMask = CGDisplayIDToOpenGLDisplayMask(id);
+            glMask = CGDisplayIDToOpenGLDisplayMask(displayID);
         }
 
         NSOpenGLPixelFormatAttribute attrs[] = {
             NSOpenGLPFAClosestPolicy,
-            NSOpenGLPFANoRecovery,
-            NSOpenGLPFAAccelerated,
-            NSOpenGLPFAFullScreen,
             NSOpenGLPFAWindow,
             NSOpenGLPFAPixelBuffer,
             NSOpenGLPFADoubleBuffer,
@@ -412,7 +407,7 @@
         return;
     }
     memset(cglinfo, 0, sizeof(CGLGraphicsConfigInfo));
-    cglinfo->screen = screennum;
+    cglinfo->screen = displayID;
     cglinfo->pixfmt = sharedPixelFormat;
     cglinfo->context = oglc;
 
@@ -422,17 +417,6 @@
 }
 @end //GraphicsConfigUtil
 
-
-JNIEXPORT jint JNICALL
-Java_sun_java2d_opengl_CGLGraphicsConfig_getDefaultPixFmt
-    (JNIEnv *env, jclass cglgc, jint screennum)
-{
-    J2dTraceLn(J2D_TRACE_INFO, "CGLGraphicsConfig_getDefaultPixFmt");
-
-    CGDirectDisplayID id = FindCGDirectDisplayIDForScreenIndex(screennum);
-    return (jint)CGDisplayIDToOpenGLDisplayMask(id);
-}
-
 JNIEXPORT jint JNICALL
 Java_sun_java2d_opengl_CGLGraphicsConfig_getOGLCapabilities
     (JNIEnv *env, jclass cglgc, jlong configInfo)
--- a/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.h	Fri Mar 15 23:31:19 2013 -0700
@@ -122,19 +122,12 @@
 #endif /* AWT_THREAD_ASSERTS */
 // --------------------------------------------------------------------------
 
-// This tracks if we are current inside of a performOnMainThread that is both waiting and in the AWTRunLoopMode
-extern BOOL sInPerformFromJava;
-
-// This is an empty Obj-C object just so that -performSelectorOnMainThread
-// can be used, and to use the Obj-C +initialize feature.
 __attribute__((visibility("default")))
-@interface ThreadUtilities : NSObject { }
+@interface ThreadUtilities { }
 
 + (JNIEnv*)getJNIEnv;
 + (JNIEnv*)getJNIEnvUncached;
 
-+ (void)performOnMainThread:(SEL)aSelector onObject:(id)target withObject:(id)arg waitUntilDone:(BOOL)wait awtMode:(BOOL)inAWT;
-
 //Wrappers for the corresponding JNFRunLoop methods with a check for main thread
 + (void)performOnMainThreadWaiting:(BOOL)wait block:(void (^)())block;
 + (void)performOnMainThread:(SEL)aSelector on:(id)target withObject:(id)arg waitUntilDone:(BOOL)wait;
--- a/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.m	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/macosx/native/sun/osxapp/ThreadUtilities.m	Fri Mar 15 23:31:19 2013 -0700
@@ -34,85 +34,6 @@
 JavaVM *jvm = NULL;
 static JNIEnv *appKitEnv = NULL;
 
-static NSArray *sPerformModes = nil;
-static NSArray *sAWTPerformModes = nil;
-
-static BOOL sLoggingEnabled = YES;
-
-#ifdef AWT_THREAD_ASSERTS_ENV_ASSERT
-int sAWTThreadAsserts = 0;
-#endif /* AWT_THREAD_ASSERTS_ENV_ASSERT */
-
-BOOL sInPerformFromJava = NO;
-
-// This class is used so that performSelectorOnMainThread can be
-// controlled a little more easily by us.  It has 2 roles.
-// The first is to set/unset a flag (sInPerformFromJava) that code can
-// check to see if we are in a synchronous perform initiated by a java thread.
-// The second is to implement the CocoaComponent backward compatibility mode.
-@interface CPerformer : NSObject {
-    id fTarget;
-    SEL fSelector;
-    id fArg;
-    BOOL fWait;
-}
-
-- (id) initWithTarget:(id)target selector:(SEL)selector arg:(id)arg wait:(BOOL)wait;
-- (void) perform;
-@end
-
-
-@implementation CPerformer
-
-- (id) initWithTarget:(id)target selector:(SEL)selector arg:(id)arg {
-    return [self initWithTarget:target selector:selector arg:arg wait:YES];
-}
-
-- (id) initWithTarget:(id)target selector:(SEL)selector arg:(id)arg wait:(BOOL)wait {
-    self = [super init];
-    if (self != nil) {
-        fTarget = [target retain];
-        fSelector = selector;
-        fArg = [arg retain];
-        // Only set sInPerformFromJava if this is a synchronous perform
-        fWait = wait;
-    }
-    return self;
-}
-
-- (void) dealloc {
-    [fTarget release];
-    [fArg release];
-    [super dealloc];
-}
-//- (void)finalize { [super finalize]; }
-
-- (void) perform {
-    AWT_ASSERT_APPKIT_THREAD;
-
-    // If this is the first time we're going from java thread -> appkit thread,
-    // set sInPerformFromJava for the duration of the invocation
-    BOOL nestedPerform = sInPerformFromJava;
-    if (fWait) {
-        sInPerformFromJava = YES;
-    }
-
-    // Actually do the work (cheat to avoid a method call)
-    @try {
-        objc_msgSend(fTarget, fSelector, fArg);
-        //[fTarget performSelector:fSelector withObject:fArg];
-    } @catch (NSException *e) {
-        NSLog(@"*** CPerformer: ignoring exception '%@' raised during perform of selector '%@' on target '%@' with args '%@'", e, NSStringFromSelector(fSelector), fTarget, fArg);
-    } @finally {
-        // If we actually set sInPerformFromJava, unset it now
-        if (!nestedPerform && fWait) {
-            sInPerformFromJava = NO;
-        }
-    }
-}
-@end
-
-
 @implementation ThreadUtilities
 
 + (JNIEnv*)getJNIEnv {
@@ -129,36 +50,6 @@
     return env;
 }
 
-+ (void)initialize {
-    // Headless: BOTH
-    // Embedded: BOTH
-    // Multiple Calls: NO
-    // Caller: Obj-C class initialization
-    // Thread: ?
-
-    if (sPerformModes == nil) {
-        // Create list of Run Loop modes to perform on
-        // The default performSelector, with no mode argument, runs in Default,
-        // ModalPanel, and EventTracking modes
-        sPerformModes =    [[NSArray alloc] initWithObjects:NSDefaultRunLoopMode, NSModalPanelRunLoopMode, nil];
-        sAWTPerformModes = [[NSArray alloc] initWithObjects:NSDefaultRunLoopMode, NSModalPanelRunLoopMode, NSEventTrackingRunLoopMode, [JNFRunLoop javaRunLoopMode], nil];
-
-#ifdef AWT_THREAD_ASSERTS_ENV_ASSERT
-        sAWTThreadAsserts = (getenv("COCOA_AWT_DISABLE_THREAD_ASSERTS") == NULL);
-#endif /* AWT_THREAD_ASSERTS_ENV_ASSERT */
-    }
-}
-
-// These methods can behave slightly differently than the normal
-// performSelector...  In particular, we define a special runloop mode
-// (AWTRunLoopMode) so that we can "block" the main thread against the
-// java event thread without deadlocking. See CToolkit.invokeAndWait.
-+ (void)performOnMainThread:(SEL)aSelector onObject:(id)target withObject:(id)arg waitUntilDone:(BOOL)wait awtMode:(BOOL)inAWT {
-    CPerformer *performer = [[CPerformer alloc] initWithTarget:target selector:aSelector arg:arg wait:wait];
-    [performer performSelectorOnMainThread:@selector(perform) withObject:nil waitUntilDone:wait modes:((inAWT) ? sAWTPerformModes : sPerformModes)]; // AWT_THREADING Safe (cover method)
-    [performer release];
-}
-
 + (void)performOnMainThreadWaiting:(BOOL)wait block:(void (^)())block {
     if ([NSThread isMainThread] && wait == YES) {
         block(); 
--- a/jdk/src/share/bin/jli_util.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/bin/jli_util.h	Fri Mar 15 23:31:19 2013 -0700
@@ -66,7 +66,7 @@
 #include <io.h>
 #define JLI_StrCaseCmp(p1, p2)          stricmp((p1), (p2))
 #define JLI_StrNCaseCmp(p1, p2, p3)     strnicmp((p1), (p2), (p3))
-#define JLI_Snprintf                    _snprintf
+int  JLI_Snprintf(char *buffer, size_t size, const char *format, ...);
 void JLI_CmdToArgs(char *cmdline);
 #define JLI_Lseek                       _lseeki64
 #else  /* NIXES */
--- a/jdk/src/share/bin/parse_manifest.c	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/bin/parse_manifest.c	Fri Mar 15 23:31:19 2013 -0700
@@ -569,9 +569,9 @@
 #ifdef O_BINARY
         | O_BINARY /* use binary mode on windows */
 #endif
-        )) == -1)
+        )) == -1) {
         return (-1);
-
+    }
     info->manifest_version = NULL;
     info->main_class = NULL;
     info->jre_version = NULL;
@@ -618,15 +618,17 @@
     zentry  entry;
     void    *data = NULL;
 
-    fd = open(jarfile, O_RDONLY
+    if ((fd = open(jarfile, O_RDONLY
 #ifdef O_LARGEFILE
         | O_LARGEFILE /* large file mode */
 #endif
 #ifdef O_BINARY
         | O_BINARY /* use binary mode on windows */
 #endif
-        );
-    if (fd != -1 && find_file(fd, &entry, filename) == 0) {
+        )) == -1) {
+        return NULL;
+    }
+    if (find_file(fd, &entry, filename) == 0) {
         data = inflate_file(fd, &entry, size);
     }
     close(fd);
@@ -671,8 +673,9 @@
 #ifdef O_BINARY
         | O_BINARY /* use binary mode on windows */
 #endif
-        )) == -1)
+        )) == -1) {
         return (-1);
+    }
 
     if (rc = find_file(fd, &entry, manifest_name) != 0) {
         close(fd);
--- a/jdk/src/share/classes/com/sun/beans/finder/MethodFinder.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/com/sun/beans/finder/MethodFinder.java	Fri Mar 15 23:31:19 2013 -0700
@@ -66,11 +66,14 @@
         Signature signature = new Signature(type, name, args);
 
         Method method = CACHE.get(signature);
-        if (method != null) {
+        boolean cached = method != null;
+        if (cached && isPackageAccessible(method.getDeclaringClass())) {
             return method;
         }
         method = findAccessibleMethod(new MethodFinder(name, args).find(type.getMethods()));
-        CACHE.put(signature, method);
+        if (!cached) {
+            CACHE.put(signature, method);
+        }
         return method;
     }
 
--- a/jdk/src/share/classes/com/sun/crypto/provider/DHKeyAgreement.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyAgreement.java	Fri Mar 15 23:31:19 2013 -0700
@@ -41,6 +41,8 @@
 import javax.crypto.SecretKey;
 import javax.crypto.spec.*;
 
+import sun.security.util.KeyUtil;
+
 /**
  * This class implements the Diffie-Hellman key agreement protocol between
  * any number of parties.
@@ -200,6 +202,9 @@
             throw new InvalidKeyException("Incompatible parameters");
         }
 
+        // validate the Diffie-Hellman public key
+        KeyUtil.validate(dhPubKey);
+
         // store the y value
         this.y = dhPubKey.getY();
 
--- a/jdk/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/com/sun/java/util/jar/pack/BandStructure.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1000,7 +1000,6 @@
 
         /** Write a constant pool reference. */
         public void putRef(Entry e) {
-            assert(index != null);
             addValue(encodeRefOrNull(e, index));
         }
         public void putRef(Entry e, Index index) {
@@ -1052,6 +1051,8 @@
 
 
     int encodeRef(Entry e, Index ix) {
+        if (ix == null)
+            throw new RuntimeException("null index for " + e.stringValue());
         int coding = ix.indexOf(e);
         if (verbose > 2)
             Utils.log.fine("putRef "+coding+" => "+e);
--- a/jdk/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/com/sun/java/util/jar/pack/ConstantPool.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1409,6 +1409,8 @@
 
         /** Index of all CP entries of a given tag and class. */
         public Index getMemberIndex(byte tag, ClassEntry classRef) {
+            if (classRef == null)
+                throw new RuntimeException("missing class reference for " + tagName(tag));
             if (indexByTagAndClass == null)
                 indexByTagAndClass = new Index[CONSTANT_Limit][];
             Index allClasses =  getIndexByTag(CONSTANT_Class);
--- a/jdk/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/com/sun/java/util/jar/pack/NativeUnpack.java	Fri Mar 15 23:31:19 2013 -0700
@@ -109,6 +109,10 @@
         return (p200 == null)? null: p200._nunp;
     }
 
+    private synchronized long getUnpackerPtr() {
+        return unpackerPtr;
+    }
+
     // Callback from the unpacker engine to get more data.
     private long readInputFn(ByteBuffer pbuf, long minlen) throws IOException {
         if (in == null)  return 0;  // nothing is readable
--- a/jdk/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/com/sun/java/util/jar/pack/PackerImpl.java	Fri Mar 15 23:31:19 2013 -0700
@@ -83,7 +83,7 @@
      * @param out an OutputStream
      * @exception IOException if an error is encountered.
      */
-    public void pack(JarFile in, OutputStream out) throws IOException {
+    public synchronized void pack(JarFile in, OutputStream out) throws IOException {
         assert(Utils.currentInstance.get() == null);
         TimeZone tz = (props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE))
                       ? null
@@ -118,7 +118,7 @@
      * @param out an OutputStream
      * @exception IOException if an error is encountered.
      */
-    public void pack(JarInputStream in, OutputStream out) throws IOException {
+    public synchronized void pack(JarInputStream in, OutputStream out) throws IOException {
         assert(Utils.currentInstance.get() == null);
         TimeZone tz = (props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE)) ? null :
             TimeZone.getDefault();
--- a/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, 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
@@ -106,7 +106,7 @@
      * @param out a JarOutputStream.
      * @exception IOException if an error is encountered.
      */
-    public void unpack(InputStream in, JarOutputStream out) throws IOException {
+    public synchronized void unpack(InputStream in, JarOutputStream out) throws IOException {
         if (in == null) {
             throw new NullPointerException("null input");
         }
@@ -151,7 +151,7 @@
      * @param out a JarOutputStream.
      * @exception IOException if an error is encountered.
      */
-    public void unpack(File in, JarOutputStream out) throws IOException {
+    public synchronized void unpack(File in, JarOutputStream out) throws IOException {
         if (in == null) {
             throw new NullPointerException("null input");
         }
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/ClassLoaderRepositorySupport.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/ClassLoaderRepositorySupport.java	Fri Mar 15 23:31:19 2013 -0700
@@ -36,6 +36,7 @@
 
 import javax.management.ObjectName;
 import javax.management.loading.PrivateClassLoader;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * This class keeps the list of Class Loaders registered in the MBean Server.
@@ -192,6 +193,7 @@
                                final ClassLoader without,
                                final ClassLoader stop)
             throws ClassNotFoundException {
+        ReflectUtil.checkPackageAccess(className);
         final int size = list.length;
         for(int i=0; i<size; i++) {
             try {
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java	Fri Mar 15 23:31:19 2013 -0700
@@ -54,6 +54,8 @@
 import java.lang.reflect.InvocationTargetException;
 import javax.management.AttributeNotFoundException;
 import javax.management.openmbean.CompositeData;
+import sun.reflect.misc.MethodUtil;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * This class contains the methods for performing all the tests needed to verify
@@ -526,8 +528,10 @@
                     // to locate method
                     readMethod = SimpleIntrospector.getReadMethod(clazz, element);
                 }
-                if (readMethod != null)
-                    return readMethod.invoke(complex);
+                if (readMethod != null) {
+                    ReflectUtil.checkPackageAccess(readMethod.getDeclaringClass());
+                    return MethodUtil.invoke(readMethod, complex, new Class[0]);
+                }
 
                 throw new AttributeNotFoundException(
                     "Could not find the getter method for the property " +
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/JmxMBeanServer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/JmxMBeanServer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -51,6 +51,7 @@
 import javax.management.MBeanRegistrationException;
 import javax.management.MBeanServer;
 import javax.management.MBeanServerDelegate;
+import javax.management.MBeanServerPermission;
 import javax.management.NotCompliantMBeanException;
 import javax.management.NotificationFilter;
 import javax.management.NotificationListener;
@@ -1409,6 +1410,8 @@
         // Default is true.
         final boolean fairLock = DEFAULT_FAIR_LOCK_POLICY;
 
+        checkNewMBeanServerPermission();
+
         // This constructor happens to disregard the value of the interceptors
         // flag - that is, it always uses the default value - false.
         // This is admitedly a bug, but we chose not to fix it for now
@@ -1494,4 +1497,11 @@
         }
     }
 
+    private static void checkNewMBeanServerPermission() {
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            Permission perm = new MBeanServerPermission("newMBeanServer");
+            sm.checkPermission(perm);
+        }
+    }
 }
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanInstantiator.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanInstantiator.java	Fri Mar 15 23:31:19 2013 -0700
@@ -32,11 +32,13 @@
 import java.io.ObjectInputStream;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
+import java.security.Permission;
 import java.util.Map;
 import java.util.logging.Level;
 
 import javax.management.InstanceNotFoundException;
 import javax.management.MBeanException;
+import javax.management.MBeanPermission;
 import javax.management.NotCompliantMBeanException;
 import javax.management.ObjectName;
 import javax.management.OperationsException;
@@ -44,7 +46,7 @@
 import javax.management.RuntimeErrorException;
 import javax.management.RuntimeMBeanException;
 import javax.management.RuntimeOperationsException;
-
+import sun.reflect.misc.ConstructorUtil;
 import sun.reflect.misc.ReflectUtil;
 
 /**
@@ -56,7 +58,6 @@
  * @since 1.5
  */
 public class MBeanInstantiator {
-
     private final ModifiableClassLoaderRepository clr;
     //    private MetaData meta = null;
 
@@ -88,6 +89,7 @@
                              "Exception occurred during object instantiation");
         }
 
+        ReflectUtil.checkPackageAccess(className);
         try {
             if (clr == null) throw new ClassNotFoundException(className);
             theClass = clr.loadClass(className);
@@ -162,6 +164,7 @@
                     continue;
                 }
 
+                ReflectUtil.checkPackageAccess(signature[i]);
                 // Ok we do not have a primitive type ! We need to build
                 // the signature of the method
                 //
@@ -205,6 +208,9 @@
      */
     public Object instantiate(Class<?> theClass)
         throws ReflectionException, MBeanException {
+
+        checkMBeanPermission(theClass, null, null, "instantiate");
+
         Object moi;
 
 
@@ -260,6 +266,9 @@
     public Object instantiate(Class<?> theClass, Object params[],
                               String signature[], ClassLoader loader)
         throws ReflectionException, MBeanException {
+
+        checkMBeanPermission(theClass, null, null, "instantiate");
+
         // Instantiate the new object
 
         // ------------------------------
@@ -407,6 +416,8 @@
             throw new  RuntimeOperationsException(new
              IllegalArgumentException(), "Null className passed in parameter");
         }
+
+        ReflectUtil.checkPackageAccess(className);
         Class<?> theClass;
         if (loaderName == null) {
             // Load the class using the agent class loader
@@ -619,13 +630,13 @@
      **/
     static Class<?> loadClass(String className, ClassLoader loader)
         throws ReflectionException {
-
         Class<?> theClass;
         if (className == null) {
             throw new RuntimeOperationsException(new
                 IllegalArgumentException("The class name cannot be null"),
                               "Exception occurred during object instantiation");
         }
+        ReflectUtil.checkPackageAccess(className);
         try {
             if (loader == null)
                 loader = MBeanInstantiator.class.getClassLoader();
@@ -676,6 +687,7 @@
                 // We need to load the class through the class
                 // loader of the target object.
                 //
+                ReflectUtil.checkPackageAccess(signature[i]);
                 tab[i] = Class.forName(signature[i], false, aLoader);
             }
         } catch (ClassNotFoundException e) {
@@ -701,7 +713,7 @@
 
     private Constructor<?> findConstructor(Class<?> c, Class<?>[] params) {
         try {
-            return c.getConstructor(params);
+            return ConstructorUtil.getConstructor(c, params);
         } catch (Exception e) {
             return null;
         }
@@ -715,4 +727,18 @@
                                           char.class, boolean.class})
             primitiveClasses.put(c.getName(), c);
     }
+
+    private static void checkMBeanPermission(Class<?> clazz,
+                                             String member,
+                                             ObjectName objectName,
+                                             String actions) {
+        SecurityManager sm = System.getSecurityManager();
+        if (clazz != null && sm != null) {
+            Permission perm = new MBeanPermission(clazz.getName(),
+                                                  member,
+                                                  objectName,
+                                                  actions);
+            sm.checkPermission(perm);
+        }
+    }
 }
--- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanSupport.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanSupport.java	Fri Mar 15 23:31:19 2013 -0700
@@ -38,6 +38,7 @@
 import javax.management.ObjectName;
 import javax.management.ReflectionException;
 import com.sun.jmx.mbeanserver.MXBeanMappingFactory;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * Base class for MBeans.  There is one instance of this class for
@@ -131,6 +132,7 @@
                 " is not an instance of " + mbeanInterfaceType.getName();
             throw new NotCompliantMBeanException(msg);
         }
+        ReflectUtil.checkPackageAccess(mbeanInterfaceType);
         this.resource = resource;
         MBeanIntrospector<M> introspector = getMBeanIntrospector();
         this.perInterface = introspector.getPerInterface(mbeanInterfaceType);
--- a/jdk/src/share/classes/java/awt/CheckboxMenuItem.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/CheckboxMenuItem.java	Fri Mar 15 23:31:19 2013 -0700
@@ -277,7 +277,7 @@
      * @since 1.4
      */
     public synchronized ItemListener[] getItemListeners() {
-        return (ItemListener[])(getListeners(ItemListener.class));
+        return getListeners(ItemListener.class);
     }
 
     /**
--- a/jdk/src/share/classes/java/awt/Cursor.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/Cursor.java	Fri Mar 15 23:31:19 2013 -0700
@@ -163,11 +163,11 @@
      * hashtable, filesystem dir prefix, filename, and properties for custom cursors support
      */
 
-    private static final Hashtable  systemCustomCursors         = new Hashtable(1);
+    private static final Hashtable<String,Cursor> systemCustomCursors = new Hashtable<>(1);
     private static final String systemCustomCursorDirPrefix = initCursorDir();
 
     private static String initCursorDir() {
-        String jhome =  (String) java.security.AccessController.doPrivileged(
+        String jhome = java.security.AccessController.doPrivileged(
                new sun.security.action.GetPropertyAction("java.home"));
         return jhome +
             File.separator + "lib" + File.separator + "images" +
@@ -298,7 +298,7 @@
     static public Cursor getSystemCustomCursor(final String name)
         throws AWTException, HeadlessException {
         GraphicsEnvironment.checkHeadless();
-        Cursor cursor = (Cursor)systemCustomCursors.get(name);
+        Cursor cursor = systemCustomCursors.get(name);
 
         if (cursor == null) {
             synchronized(systemCustomCursors) {
@@ -319,11 +319,11 @@
             final String fileName =
                 systemCustomCursorProperties.getProperty(key);
 
-            String localized = (String)systemCustomCursorProperties.getProperty(prefix + DotNameSuffix);
+            String localized = systemCustomCursorProperties.getProperty(prefix + DotNameSuffix);
 
             if (localized == null) localized = name;
 
-            String hotspot = (String)systemCustomCursorProperties.getProperty(prefix + DotHotspotSuffix);
+            String hotspot = systemCustomCursorProperties.getProperty(prefix + DotHotspotSuffix);
 
             if (hotspot == null)
                 throw new AWTException("no hotspot property defined for cursor: " + name);
@@ -348,9 +348,9 @@
                 final int fy = y;
                 final String flocalized = localized;
 
-                cursor = (Cursor) java.security.AccessController.doPrivileged(
-                    new java.security.PrivilegedExceptionAction() {
-                    public Object run() throws Exception {
+                cursor = java.security.AccessController.<Cursor>doPrivileged(
+                    new java.security.PrivilegedExceptionAction<Cursor>() {
+                    public Cursor run() throws Exception {
                         Toolkit toolkit = Toolkit.getDefaultToolkit();
                         Image image = toolkit.getImage(
                            systemCustomCursorDirPrefix + fileName);
@@ -447,8 +447,8 @@
             systemCustomCursorProperties = new Properties();
 
             try {
-                AccessController.doPrivileged(
-                      new java.security.PrivilegedExceptionAction() {
+                AccessController.<Object>doPrivileged(
+                      new java.security.PrivilegedExceptionAction<Object>() {
                     public Object run() throws Exception {
                         FileInputStream fis = null;
                         try {
--- a/jdk/src/share/classes/java/awt/Dialog.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/Dialog.java	Fri Mar 15 23:31:19 2013 -0700
@@ -39,6 +39,7 @@
 import sun.awt.util.IdentityArrayList;
 import sun.awt.util.IdentityLinkedList;
 import sun.security.util.SecurityConstants;
+import java.security.AccessControlException;
 
 /**
  * A Dialog is a top-level window with a title and a border
@@ -128,6 +129,8 @@
      */
     boolean undecorated = false;
 
+    private transient boolean initialized = false;
+
     /**
      * Modal dialogs block all input to some top-level windows.
      * Whether a particular window is blocked depends on dialog's type
@@ -671,6 +674,7 @@
         this.title = title;
         setModalityType(modalityType);
         SunToolkit.checkAndSetPolicy(this);
+        initialized = true;
     }
 
     /**
@@ -722,6 +726,7 @@
         this.title = title;
         setModalityType(modalityType);
         SunToolkit.checkAndSetPolicy(this);
+        initialized = true;
     }
 
     /**
@@ -851,12 +856,9 @@
         if (modalityType == type) {
             return;
         }
-        if (type == ModalityType.TOOLKIT_MODAL) {
-            SecurityManager sm = System.getSecurityManager();
-            if (sm != null) {
-                sm.checkPermission(SecurityConstants.AWT.TOOLKIT_MODALITY_PERMISSION);
-            }
-        }
+
+        checkModalityPermission(type);
+
         modalityType = type;
         modal = (modalityType != ModalityType.MODELESS);
     }
@@ -1025,6 +1027,11 @@
      */
     @Deprecated
     public void show() {
+        if (!initialized) {
+            throw new IllegalStateException("The dialog component " +
+                "has not been initialized properly");
+        }
+
         beforeFirstShow = false;
         if (!isModal()) {
             conditionalShow(null, null);
@@ -1600,18 +1607,51 @@
         }
     }
 
+    private void checkModalityPermission(ModalityType mt) {
+        if (mt == ModalityType.TOOLKIT_MODAL) {
+            SecurityManager sm = System.getSecurityManager();
+            if (sm != null) {
+                sm.checkPermission(
+                    SecurityConstants.AWT.TOOLKIT_MODALITY_PERMISSION
+                );
+            }
+        }
+    }
+
     private void readObject(ObjectInputStream s)
         throws ClassNotFoundException, IOException, HeadlessException
     {
         GraphicsEnvironment.checkHeadless();
-        s.defaultReadObject();
+
+        java.io.ObjectInputStream.GetField fields =
+            s.readFields();
+
+        ModalityType localModalityType = (ModalityType)fields.get("modalityType", null);
+
+        try {
+            checkModalityPermission(localModalityType);
+        } catch (AccessControlException ace) {
+            localModalityType = DEFAULT_MODALITY_TYPE;
+        }
 
         // in 1.5 or earlier modalityType was absent, so use "modal" instead
-        if (modalityType == null) {
+        if (localModalityType == null) {
+            this.modal = fields.get("modal", false);
             setModal(modal);
+        } else {
+            this.modalityType = localModalityType;
         }
 
+        this.resizable = fields.get("resizable", true);
+        this.undecorated = fields.get("undecorated", false);
+        this.title = (String)fields.get("title", "");
+
         blockedWindows = new IdentityArrayList<>();
+
+        SunToolkit.checkAndSetPolicy(this);
+
+        initialized = true;
+
     }
 
     /*
--- a/jdk/src/share/classes/java/awt/EventQueue.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/EventQueue.java	Fri Mar 15 23:31:19 2013 -0700
@@ -171,7 +171,7 @@
      * The modifiers field of the current event, if the current event is an
      * InputEvent or ActionEvent.
      */
-    private WeakReference currentEvent;
+    private WeakReference<AWTEvent> currentEvent;
 
     /*
      * Non-zero if a thread is waiting in getNextEvent(int) for an event of
@@ -194,7 +194,8 @@
                 }
                 public void removeSourceEvents(EventQueue eventQueue,
                                                Object source,
-                                               boolean removeAllEvents) {
+                                               boolean removeAllEvents)
+                {
                     eventQueue.removeSourceEvents(source, removeAllEvents);
                 }
                 public boolean noEvents(EventQueue eventQueue) {
@@ -203,6 +204,11 @@
                 public void wakeup(EventQueue eventQueue, boolean isShutdown) {
                     eventQueue.wakeup(isShutdown);
                 }
+                public void invokeAndWait(Object source, Runnable r)
+                    throws InterruptedException, InvocationTargetException
+                {
+                    EventQueue.invokeAndWait(source, r);
+                }
             });
     }
 
@@ -809,7 +815,7 @@
         pushPopLock.lock();
         try {
                 return (Thread.currentThread() == dispatchThread)
-                ? ((AWTEvent)currentEvent.get())
+                ? currentEvent.get()
                 : null;
         } finally {
             pushPopLock.unlock();
@@ -1167,7 +1173,7 @@
                 return;
             }
 
-            currentEvent = new WeakReference(e);
+            currentEvent = new WeakReference<>(e);
 
             // This series of 'instanceof' checks should be replaced with a
             // polymorphic type (for example, an interface which declares a
@@ -1245,8 +1251,14 @@
      * @since           1.2
      */
     public static void invokeAndWait(Runnable runnable)
-             throws InterruptedException, InvocationTargetException {
+        throws InterruptedException, InvocationTargetException
+    {
+        invokeAndWait(Toolkit.getDefaultToolkit(), runnable);
+    }
 
+    static void invokeAndWait(Object source, Runnable runnable)
+        throws InterruptedException, InvocationTargetException
+    {
         if (EventQueue.isDispatchThread()) {
             throw new Error("Cannot call invokeAndWait from the event dispatcher thread");
         }
@@ -1255,8 +1267,7 @@
         Object lock = new AWTInvocationLock();
 
         InvocationEvent event =
-            new InvocationEvent(Toolkit.getDefaultToolkit(), runnable, lock,
-                                true);
+            new InvocationEvent(source, runnable, lock, true);
 
         synchronized (lock) {
             Toolkit.getEventQueue().postEvent(event);
--- a/jdk/src/share/classes/java/awt/Menu.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/Menu.java	Fri Mar 15 23:31:19 2013 -0700
@@ -66,7 +66,7 @@
 
         AWTAccessor.setMenuAccessor(
             new AWTAccessor.MenuAccessor() {
-                public Vector getItems(Menu menu) {
+                public Vector<MenuComponent> getItems(Menu menu) {
                     return menu.items;
                 }
             });
@@ -78,7 +78,7 @@
      * @serial
      * @see #countItems()
      */
-    Vector              items = new Vector();
+    Vector<MenuComponent> items = new Vector<>();
 
     /**
      * This field indicates whether the menu has the
@@ -313,7 +313,7 @@
             }
 
             int nitems = getItemCount();
-            Vector tempItems = new Vector();
+            Vector<MenuItem> tempItems = new Vector<>();
 
             /* Remove the item at index, nitems-index times
                storing them in a temporary vector in the
@@ -330,7 +330,7 @@
                already in the correct order in the temp vector.
             */
             for (int i = 0; i < tempItems.size()  ; i++) {
-                add((MenuItem)tempItems.elementAt(i));
+                add(tempItems.elementAt(i));
             }
         }
     }
@@ -379,7 +379,7 @@
             }
 
             int nitems = getItemCount();
-            Vector tempItems = new Vector();
+            Vector<MenuItem> tempItems = new Vector<>();
 
             /* Remove the item at index, nitems-index times
                storing them in a temporary vector in the
@@ -396,7 +396,7 @@
                already in the correct order in the temp vector.
             */
             for (int i = 0; i < tempItems.size()  ; i++) {
-                add((MenuItem)tempItems.elementAt(i));
+                add(tempItems.elementAt(i));
             }
         }
     }
@@ -475,13 +475,13 @@
         return null;
     }
 
-    synchronized Enumeration shortcuts() {
-        Vector shortcuts = new Vector();
+    synchronized Enumeration<MenuShortcut> shortcuts() {
+        Vector<MenuShortcut> shortcuts = new Vector<>();
         int nitems = getItemCount();
         for (int i = 0 ; i < nitems ; i++) {
             MenuItem mi = getItem(i);
             if (mi instanceof Menu) {
-                Enumeration e = ((Menu)mi).shortcuts();
+                Enumeration<MenuShortcut> e = ((Menu)mi).shortcuts();
                 while (e.hasMoreElements()) {
                     shortcuts.addElement(e.nextElement());
                 }
--- a/jdk/src/share/classes/java/awt/MenuBar.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/MenuBar.java	Fri Mar 15 23:31:19 2013 -0700
@@ -81,7 +81,7 @@
                     return menuBar.helpMenu;
                 }
 
-                public Vector getMenus(MenuBar menuBar) {
+                public Vector<Menu> getMenus(MenuBar menuBar) {
                     return menuBar.menus;
                 }
             });
@@ -94,7 +94,7 @@
      * @serial
      * @see #countMenus()
      */
-    Vector menus = new Vector();
+    Vector<Menu> menus = new Vector<>();
 
     /**
      * This menu is a special menu dedicated to
@@ -309,7 +309,7 @@
      * be called on the toolkit thread.
      */
     final Menu getMenuImpl(int i) {
-        return (Menu)menus.elementAt(i);
+        return menus.elementAt(i);
     }
 
     /**
@@ -321,10 +321,10 @@
      * @since       JDK1.1
      */
     public synchronized Enumeration<MenuShortcut> shortcuts() {
-        Vector shortcuts = new Vector();
+        Vector<MenuShortcut> shortcuts = new Vector<>();
         int nmenus = getMenuCount();
         for (int i = 0 ; i < nmenus ; i++) {
-            Enumeration e = getMenu(i).shortcuts();
+            Enumeration<MenuShortcut> e = getMenu(i).shortcuts();
             while (e.hasMoreElements()) {
                 shortcuts.addElement(e.nextElement());
             }
@@ -438,7 +438,7 @@
       // HeadlessException will be thrown from MenuComponent's readObject
       s.defaultReadObject();
       for (int i = 0; i < menus.size(); i++) {
-        Menu m = (Menu)menus.elementAt(i);
+        Menu m = menus.elementAt(i);
         m.parent = this;
       }
     }
--- a/jdk/src/share/classes/java/awt/MenuComponent.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/MenuComponent.java	Fri Mar 15 23:31:19 2013 -0700
@@ -290,7 +290,7 @@
     public void setFont(Font f) {
         font = f;
         //Fixed 6312943: NullPointerException in method MenuComponent.setFont(Font)
-        MenuComponentPeer peer = (MenuComponentPeer)this.peer;
+        MenuComponentPeer peer = this.peer;
         if (peer != null) {
             peer.setFont(f);
         }
@@ -303,7 +303,7 @@
      */
     public void removeNotify() {
         synchronized (getTreeLock()) {
-            MenuComponentPeer p = (MenuComponentPeer)this.peer;
+            MenuComponentPeer p = this.peer;
             if (p != null) {
                 Toolkit.getEventQueue().removeSourceEvents(this, true);
                 this.peer = null;
--- a/jdk/src/share/classes/java/awt/MenuItem.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/MenuItem.java	Fri Mar 15 23:31:19 2013 -0700
@@ -564,7 +564,7 @@
      * @since 1.4
      */
     public synchronized ActionListener[] getActionListeners() {
-        return (ActionListener[])(getListeners(ActionListener.class));
+        return getListeners(ActionListener.class);
     }
 
     /**
--- a/jdk/src/share/classes/java/awt/RenderingHints.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/RenderingHints.java	Fri Mar 15 23:31:19 2013 -0700
@@ -92,7 +92,7 @@
      * {@code equals()} method.
      */
     public abstract static class Key {
-        private static HashMap identitymap = new HashMap(17);
+        private static HashMap<Object,Object> identitymap = new HashMap<>(17);
 
         private String getIdentity() {
             // Note that the identity string is dependent on 3 variables:
@@ -138,7 +138,7 @@
             }
             // Note: Use a weak reference to avoid holding on to extra
             // objects and classes after they should be unloaded.
-            identitymap.put(identity, new WeakReference(k));
+            identitymap.put(identity, new WeakReference<Key>(k));
         }
 
         private int privatekey;
@@ -195,7 +195,7 @@
         }
     }
 
-    HashMap hintmap = new HashMap(7);
+    HashMap<Object,Object> hintmap = new HashMap<>(7);
 
     /**
      * Antialiasing hint key.
@@ -1267,12 +1267,13 @@
      * object.
      * @return a clone of this instance.
      */
+    @SuppressWarnings("unchecked")
     public Object clone() {
         RenderingHints rh;
         try {
             rh = (RenderingHints) super.clone();
             if (hintmap != null) {
-                rh.hintmap = (HashMap) hintmap.clone();
+                rh.hintmap = (HashMap<Object,Object>) hintmap.clone();
             }
         } catch (CloneNotSupportedException e) {
             // this shouldn't happen, since we are Cloneable
--- a/jdk/src/share/classes/java/awt/TextComponent.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/TextComponent.java	Fri Mar 15 23:31:19 2013 -0700
@@ -109,12 +109,6 @@
     // the background color of non-editable TextComponents.
     boolean backgroundSetByClientCode = false;
 
-    /**
-     * True if this <code>TextComponent</code> has access
-     * to the System clipboard.
-     */
-    transient private boolean canAccessClipboard;
-
     transient protected TextListener textListener;
 
     /*
@@ -139,7 +133,6 @@
         GraphicsEnvironment.checkHeadless();
         this.text = (text != null) ? text : "";
         setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
-        checkSystemClipboardAccess();
     }
 
     private void enableInputMethodsIfNecessary() {
@@ -734,17 +727,14 @@
     /**
      * Assigns a valid value to the canAccessClipboard instance variable.
      */
-    private void checkSystemClipboardAccess() {
-        canAccessClipboard = true;
+    private boolean canAccessClipboard() {
         SecurityManager sm = System.getSecurityManager();
-        if (sm != null) {
-            try {
-                sm.checkSystemClipboardAccess();
-            }
-            catch (SecurityException e) {
-                canAccessClipboard = false;
-            }
-        }
+        if (sm == null) return true;
+        try {
+            sm.checkSystemClipboardAccess();
+            return true;
+        } catch (SecurityException e) {}
+        return false;
     }
 
     /*
@@ -827,7 +817,6 @@
             }
         }
         enableInputMethodsIfNecessary();
-        checkSystemClipboardAccess();
     }
 
 
--- a/jdk/src/share/classes/java/awt/Window.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/Window.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1206,7 +1206,7 @@
         }
         else {
             try {
-                EventQueue.invokeAndWait(action);
+                EventQueue.invokeAndWait(this, action);
             }
             catch (InterruptedException e) {
                 System.err.println("Disposal was interrupted:");
--- a/jdk/src/share/classes/java/awt/datatransfer/Clipboard.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/datatransfer/Clipboard.java	Fri Mar 15 23:31:19 2013 -0700
@@ -71,7 +71,7 @@
      *
      * @since 1.5
      */
-    private Set currentDataFlavors;
+    private Set<DataFlavor> currentDataFlavors;
 
     /**
      * Creates a clipboard object.
@@ -313,7 +313,7 @@
         if (flavorListeners == null) {
             return;
         }
-        Set prevDataFlavors = currentDataFlavors;
+        Set<DataFlavor> prevDataFlavors = currentDataFlavors;
         currentDataFlavors = getAvailableDataFlavorSet();
         if (prevDataFlavors.equals(currentDataFlavors)) {
             return;
@@ -339,8 +339,8 @@
      *
      * @since 1.5
      */
-    private Set getAvailableDataFlavorSet() {
-        Set set = new HashSet();
+    private Set<DataFlavor> getAvailableDataFlavorSet() {
+        Set<DataFlavor> set = new HashSet<>();
         Transferable contents = getContents(null);
         if (contents != null) {
             DataFlavor[] flavors = contents.getTransferDataFlavors();
--- a/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java	Fri Mar 15 23:31:19 2013 -0700
@@ -165,7 +165,7 @@
      * <P>
      * @return an Iterator for the events comprising the gesture
      */
-
+    @SuppressWarnings("unchecked")
     public Iterator<InputEvent> iterator() { return events.iterator(); }
 
     /**
@@ -184,7 +184,7 @@
      * <P>
      * @return an array of the events comprising the gesture
      */
-
+    @SuppressWarnings("unchecked")
     public Object[] toArray(Object[] array) { return events.toArray(array); }
 
     /**
@@ -333,7 +333,6 @@
         component = (Component)f.get("component", null);
         origin = (Point)f.get("origin", null);
         action = f.get("action", 0);
-
         // Pre-1.4 support. 'events' was previously non-transient
         try {
             events = (List)f.get("events", null);
@@ -351,7 +350,7 @@
     /*
      * fields
      */
-
+    @SuppressWarnings("rawtypes")
     private transient List events;
 
     /**
--- a/jdk/src/share/classes/java/awt/dnd/DragGestureRecognizer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/dnd/DragGestureRecognizer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -297,7 +297,7 @@
      * @return the initial event that triggered the drag gesture
      */
 
-    public InputEvent getTriggerEvent() { return events.isEmpty() ? null : (InputEvent)events.get(0); }
+    public InputEvent getTriggerEvent() { return events.isEmpty() ? null : events.get(0); }
 
     /**
      * Reset the Recognizer, if its currently recognizing a gesture, ignore
--- a/jdk/src/share/classes/java/awt/dnd/DragSource.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/dnd/DragSource.java	Fri Mar 15 23:31:19 2013 -0700
@@ -600,7 +600,7 @@
      * @since    1.4
      */
     public DragSourceListener[] getDragSourceListeners() {
-        return (DragSourceListener[])getListeners(DragSourceListener.class);
+        return getListeners(DragSourceListener.class);
     }
 
     /**
@@ -660,8 +660,7 @@
      * @since    1.4
      */
     public DragSourceMotionListener[] getDragSourceMotionListeners() {
-        return (DragSourceMotionListener[])
-            getListeners(DragSourceMotionListener.class);
+        return getListeners(DragSourceMotionListener.class);
     }
 
     /**
@@ -896,8 +895,8 @@
      * @since 1.5
      */
     public static int getDragThreshold() {
-        int ts = ((Integer)AccessController.doPrivileged(
-                new GetIntegerAction("awt.dnd.drag.threshold", 0))).intValue();
+        int ts = AccessController.doPrivileged(
+                new GetIntegerAction("awt.dnd.drag.threshold", 0)).intValue();
         if (ts > 0) {
             return ts;
         } else {
--- a/jdk/src/share/classes/java/awt/dnd/InvalidDnDOperationException.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/dnd/InvalidDnDOperationException.java	Fri Mar 15 23:31:19 2013 -0700
@@ -36,6 +36,8 @@
 
 public class InvalidDnDOperationException extends IllegalStateException {
 
+    private static final long serialVersionUID = 5156676500247816278L;
+
     static private String dft_msg = "The operation requested cannot be performed by the DnD system since it is not in the appropriate state";
 
     /**
--- a/jdk/src/share/classes/java/awt/geom/AffineTransform.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/geom/AffineTransform.java	Fri Mar 15 23:31:19 2013 -0700
@@ -876,6 +876,7 @@
      * they have not been cached.
      * @see #getType
      */
+    @SuppressWarnings("fallthrough")
     private void calculateType() {
         int ret = TYPE_IDENTITY;
         boolean sgn0, sgn1;
@@ -1038,6 +1039,7 @@
      * @see #TYPE_UNIFORM_SCALE
      * @since 1.2
      */
+    @SuppressWarnings("fallthrough")
     public double getDeterminant() {
         switch (state) {
         default:
@@ -1250,6 +1252,7 @@
         default:
             stateError();
             /* NOTREACHED */
+            return;
         case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
             m02 = tx * m00 + ty * m01 + m02;
             m12 = tx * m10 + ty * m11 + m12;
@@ -1631,6 +1634,7 @@
      * Y axis direction
      * @since 1.2
      */
+    @SuppressWarnings("fallthrough")
     public void scale(double sx, double sy) {
         int state = this.state;
         switch (state) {
@@ -1705,6 +1709,7 @@
         default:
             stateError();
             /* NOTREACHED */
+            return;
         case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
         case (APPLY_SHEAR | APPLY_SCALE):
             double M0, M1;
@@ -2224,6 +2229,7 @@
      * @see #preConcatenate
      * @since 1.2
      */
+    @SuppressWarnings("fallthrough")
     public void concatenate(AffineTransform Tx) {
         double M0, M1;
         double T00, T01, T10, T11;
@@ -2432,6 +2438,7 @@
      * @see #concatenate
      * @since 1.2
      */
+    @SuppressWarnings("fallthrough")
     public void preConcatenate(AffineTransform Tx) {
         double M0, M1;
         double T00, T01, T10, T11;
@@ -2655,6 +2662,7 @@
         default:
             stateError();
             /* NOTREACHED */
+            return null;
         case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
             det = m00 * m11 - m01 * m10;
             if (Math.abs(det) <= Double.MIN_VALUE) {
@@ -2751,6 +2759,7 @@
         default:
             stateError();
             /* NOTREACHED */
+            return;
         case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
             M00 = m00; M01 = m01; M02 = m02;
             M10 = m10; M11 = m11; M12 = m12;
@@ -2885,6 +2894,7 @@
         default:
             stateError();
             /* NOTREACHED */
+            return null;
         case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
             ptDst.setLocation(x * m00 + y * m01 + m02,
                               x * m10 + y * m11 + m12);
@@ -2968,6 +2978,7 @@
             default:
                 stateError();
                 /* NOTREACHED */
+                return;
             case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
                 dst.setLocation(x * m00 + y * m01 + m02,
                                 x * m10 + y * m11 + m12);
@@ -3043,6 +3054,7 @@
         default:
             stateError();
             /* NOTREACHED */
+            return;
         case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
             M00 = m00; M01 = m01; M02 = m02;
             M10 = m10; M11 = m11; M12 = m12;
@@ -3157,6 +3169,7 @@
         default:
             stateError();
             /* NOTREACHED */
+            return;
         case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
             M00 = m00; M01 = m01; M02 = m02;
             M10 = m10; M11 = m11; M12 = m12;
@@ -3252,6 +3265,7 @@
         default:
             stateError();
             /* NOTREACHED */
+            return;
         case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
             M00 = m00; M01 = m01; M02 = m02;
             M10 = m10; M11 = m11; M12 = m12;
@@ -3347,6 +3361,7 @@
         default:
             stateError();
             /* NOTREACHED */
+            return;
         case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
             M00 = m00; M01 = m01; M02 = m02;
             M10 = m10; M11 = m11; M12 = m12;
@@ -3436,6 +3451,7 @@
      *                                         inverted.
      * @since 1.2
      */
+    @SuppressWarnings("fallthrough")
     public Point2D inverseTransform(Point2D ptSrc, Point2D ptDst)
         throws NoninvertibleTransformException
     {
@@ -3547,6 +3563,7 @@
         default:
             stateError();
             /* NOTREACHED */
+            return;
         case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
             M00 = m00; M01 = m01; M02 = m02;
             M10 = m10; M11 = m11; M12 = m12;
@@ -3679,6 +3696,7 @@
         default:
             stateError();
             /* NOTREACHED */
+            return null;
         case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
         case (APPLY_SHEAR | APPLY_SCALE):
             ptDst.setLocation(x * m00 + y * m01, x * m10 + y * m11);
@@ -3754,6 +3772,7 @@
         default:
             stateError();
             /* NOTREACHED */
+            return;
         case (APPLY_SHEAR | APPLY_SCALE | APPLY_TRANSLATE):
         case (APPLY_SHEAR | APPLY_SCALE):
             M00 = m00; M01 = m01;
--- a/jdk/src/share/classes/java/awt/peer/FramePeer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/peer/FramePeer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -125,4 +125,10 @@
     // into an EmbeddedFramePeer which would extend FramePeer
     Rectangle getBoundsPrivate();
 
+    /**
+     * Requests the peer to emulate window activation.
+     *
+     * @param activate activate or deactivate the window
+     */
+    void emulateActivation(boolean activate);
 }
--- a/jdk/src/share/classes/java/awt/peer/WindowPeer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/awt/peer/WindowPeer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -27,8 +27,6 @@
 
 import java.awt.*;
 
-import java.awt.image.BufferedImage;
-
 /**
  * The peer interface for {@link Window}.
  *
--- a/jdk/src/share/classes/java/beans/PropertyDescriptor.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/beans/PropertyDescriptor.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -109,10 +109,6 @@
         if (writeMethodName != null && getWriteMethod() == null) {
             throw new IntrospectionException("Method not found: " + writeMethodName);
         }
-        boundInitialization(beanClass);
-    }
-
-    private void boundInitialization(Class<?> beanClass) {
         // If this class or one of its base classes allow PropertyChangeListener,
         // then we assume that any properties we discover are "bound".
         // See Introspector.getTargetPropertyInfo() method.
@@ -163,7 +159,6 @@
         setReadMethod(read);
         setWriteMethod(write);
         this.baseName = base;
-        boundInitialization(bean);
     }
 
     /**
--- a/jdk/src/share/classes/java/io/ObjectInputStream.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/io/ObjectInputStream.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1752,6 +1752,12 @@
         ObjectStreamClass desc = readClassDesc(false);
         desc.checkDeserialize();
 
+        Class<?> cl = desc.forClass();
+        if (cl == String.class || cl == Class.class
+                || cl == ObjectStreamClass.class) {
+            throw new InvalidClassException("invalid class descriptor");
+        }
+
         Object obj;
         try {
             obj = desc.isInstantiable() ? desc.newInstance() : null;
--- a/jdk/src/share/classes/java/lang/Class.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/lang/Class.java	Fri Mar 15 23:31:19 2013 -0700
@@ -64,7 +64,9 @@
 import sun.reflect.generics.scope.ClassScope;
 import sun.security.util.SecurityConstants;
 import java.lang.annotation.Annotation;
+import java.lang.reflect.Proxy;
 import sun.reflect.annotation.*;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * Instances of the class {@code Class} represent classes and
@@ -251,11 +253,11 @@
                                    ClassLoader loader)
         throws ClassNotFoundException
     {
-        if (loader == null) {
+        if (sun.misc.VM.isSystemDomainLoader(loader)) {
             SecurityManager sm = System.getSecurityManager();
             if (sm != null) {
                 ClassLoader ccl = ClassLoader.getCallerClassLoader();
-                if (ccl != null) {
+                if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
                     sm.checkPermission(
                         SecurityConstants.GET_CLASSLOADER_PERMISSION);
                 }
@@ -320,7 +322,7 @@
         throws InstantiationException, IllegalAccessException
     {
         if (System.getSecurityManager() != null) {
-            checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
+            checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), false);
         }
         return newInstance0();
     }
@@ -1300,7 +1302,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), false);
 
         // Privileged so this implementation can look at DECLARED classes,
         // something the caller might not have privilege to do.  The code here
@@ -1375,7 +1377,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true);
         return copyFields(privateGetPublicFields(null));
     }
 
@@ -1426,7 +1428,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true);
         return copyMethods(privateGetPublicMethods());
     }
 
@@ -1475,7 +1477,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true);
         return copyConstructors(privateGetDeclaredConstructors(true));
     }
 
@@ -1534,7 +1536,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true);
         Field field = getField0(name);
         if (field == null) {
             throw new NoSuchFieldException(name);
@@ -1619,7 +1621,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true);
         Method method = getMethod0(name, parameterTypes);
         if (method == null) {
             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
@@ -1673,7 +1675,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader(), true);
         return getConstructor0(parameterTypes, Member.PUBLIC);
     }
 
@@ -1715,7 +1717,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), false);
         return getDeclaredClasses0();
     }
 
@@ -1759,7 +1761,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true);
         return copyFields(privateGetDeclaredFields(false));
     }
 
@@ -1807,7 +1809,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true);
         return copyMethods(privateGetDeclaredMethods(false));
     }
 
@@ -1852,7 +1854,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true);
         return copyConstructors(privateGetDeclaredConstructors(false));
     }
 
@@ -1896,7 +1898,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true);
         Field field = searchFields(privateGetDeclaredFields(false), name);
         if (field == null) {
             throw new NoSuchFieldException(name);
@@ -1951,7 +1953,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true);
         Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
         if (method == null) {
             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
@@ -2001,7 +2003,7 @@
         // be very careful not to change the stack depth of this
         // checkMemberAccess call for security reasons
         // see java.lang.SecurityManager.checkMemberAccess
-        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader());
+        checkMemberAccess(Member.DECLARED, ClassLoader.getCallerClassLoader(), true);
         return getConstructor0(parameterTypes, Member.DECLARED);
     }
 
@@ -2171,18 +2173,26 @@
      * <p> Default policy: allow all clients access with normal Java access
      * control.
      */
-    private void checkMemberAccess(int which, ClassLoader ccl) {
+    private void checkMemberAccess(int which, ClassLoader ccl, boolean checkProxyInterfaces) {
         SecurityManager s = System.getSecurityManager();
         if (s != null) {
             s.checkMemberAccess(this, which);
             ClassLoader cl = getClassLoader0();
-            if (sun.reflect.misc.ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
+            if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
                 String name = this.getName();
                 int i = name.lastIndexOf('.');
                 if (i != -1) {
-                    s.checkPackageAccess(name.substring(0, i));
+                    // skip the package access check on a proxy class in default proxy package
+                    String pkg = name.substring(0, i);
+                    if (!Proxy.isProxyClass(this) || !pkg.equals(ReflectUtil.PROXY_PACKAGE)) {
+                        s.checkPackageAccess(pkg);
+                    }
                 }
             }
+            // check package access on the proxy interfaces
+            if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
+                ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
+            }
         }
     }
 
--- a/jdk/src/share/classes/java/lang/invoke/DirectMethodHandle.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/lang/invoke/DirectMethodHandle.java	Fri Mar 15 23:31:19 2013 -0700
@@ -51,6 +51,16 @@
     private DirectMethodHandle(MethodType mtype, LambdaForm form, MemberName member) {
         super(mtype, form);
         if (!member.isResolved())  throw new InternalError();
+
+        if (member.getDeclaringClass().isInterface() && !member.isAbstract()) {
+            // Check for corner case: invokeinterface of Object method
+            MemberName m = new MemberName(Object.class, member.getName(), member.getMethodType(), member.getReferenceKind());
+            m = MemberName.getFactory().resolveOrNull(m.getReferenceKind(), m, null);
+            if (m != null && m.isPublic()) {
+                member = m;
+            }
+        }
+
         this.member = member;
     }
 
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java	Fri Mar 15 23:31:19 2013 -0700
@@ -807,12 +807,11 @@
         static
         MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
             // Do not use this function to inject calls into system classes.
-            if (hostClass == null) {
-                hostClass = C_Trampoline;
-            } else if (hostClass.isArray() ||
+            if (hostClass == null
+                ||    (hostClass.isArray() ||
                        hostClass.isPrimitive() ||
                        hostClass.getName().startsWith("java.") ||
-                       hostClass.getName().startsWith("sun.")) {
+                       hostClass.getName().startsWith("sun."))) {
                 throw new InternalError();  // does not happen, and should not anyway
             }
             // For simplicity, convert mh to a varargs-like method.
@@ -822,23 +821,6 @@
             return restoreToType(bccInvoker.bindTo(vamh), mh.type());
         }
 
-        // This class ("Trampoline") is known to be inside a dead-end class loader.
-        // Inject all doubtful calls into this class.
-        private static Class<?> C_Trampoline;
-        static {
-            Class<?> tramp = null;
-            try {
-                final int FRAME_COUNT_ARG = 1;  // [0] Reflection [1] Trampoline
-                java.lang.reflect.Method gcc = sun.reflect.Reflection.class.getMethod("getCallerClass", int.class);
-                tramp = (Class<?>) sun.reflect.misc.MethodUtil.invoke(gcc, null, new Object[]{ FRAME_COUNT_ARG });
-                if (tramp.getClassLoader() == BindCaller.class.getClassLoader())
-                    throw new RuntimeException(tramp.getName()+" class loader");
-            } catch (Throwable ex) {
-                throw new InternalError(ex);
-            }
-            C_Trampoline = tramp;
-        }
-
         private static MethodHandle makeInjectedInvoker(Class<?> hostClass) {
             Class<?> bcc = UNSAFE.defineAnonymousClass(hostClass, T_BYTES, null);
             if (hostClass.getClassLoader() != bcc.getClassLoader())
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandleNatives.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandleNatives.java	Fri Mar 15 23:31:19 2013 -0700
@@ -393,15 +393,33 @@
      */
     // FIXME: Replace this pattern match by an annotation @sun.reflect.CallerSensitive.
     static boolean isCallerSensitive(MemberName mem) {
-        assert(mem.isInvocable());
+        if (!mem.isInvocable())  return false;  // fields are not caller sensitive
         Class<?> defc = mem.getDeclaringClass();
         switch (mem.getName()) {
         case "doPrivileged":
+        case "doPrivilegedWithCombiner":
             return defc == java.security.AccessController.class;
+        case "checkMemberAccess":
+            return canBeCalledVirtual(mem, java.lang.SecurityManager.class);
         case "getUnsafe":
             return defc == sun.misc.Unsafe.class;
         case "lookup":
             return defc == java.lang.invoke.MethodHandles.class;
+        case "findStatic":
+        case "findVirtual":
+        case "findConstructor":
+        case "findSpecial":
+        case "findGetter":
+        case "findSetter":
+        case "findStaticGetter":
+        case "findStaticSetter":
+        case "bind":
+        case "unreflect":
+        case "unreflectSpecial":
+        case "unreflectConstructor":
+        case "unreflectGetter":
+        case "unreflectSetter":
+            return defc == java.lang.invoke.MethodHandles.Lookup.class;
         case "invoke":
             return defc == java.lang.reflect.Method.class;
         case "get":
@@ -455,7 +473,7 @@
             if (defc == java.util.concurrent.atomic.AtomicReferenceFieldUpdater.class)  return true;
             break;
         case "getContextClassLoader":
-            return defc == java.lang.Thread.class;
+            return canBeCalledVirtual(mem, java.lang.Thread.class);
         case "getPackage":
         case "getPackages":
             return defc == java.lang.Package.class;
@@ -473,9 +491,13 @@
             break;
         case "getCallerClassLoader":
             return defc == java.lang.ClassLoader.class;
+        case "registerAsParallelCapable":
+            return canBeCalledVirtual(mem, java.lang.ClassLoader.class);
         case "getProxyClass":
         case "newProxyInstance":
             return defc == java.lang.reflect.Proxy.class;
+        case "asInterfaceInstance":
+            return defc == java.lang.invoke.MethodHandleProxies.class;
         case "getBundle":
         case "clearCache":
             return defc == java.util.ResourceBundle.class;
@@ -492,4 +514,11 @@
             throw new InternalError(e);
         }
     }
+    static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) {
+        Class<?> symbolicRefClass = symbolicRef.getDeclaringClass();
+        if (symbolicRefClass == definingClass)  return true;
+        if (symbolicRef.isStatic() || symbolicRef.isPrivate())  return false;
+        return (definingClass.isAssignableFrom(symbolicRefClass) ||  // Msym overrides Mdef
+                symbolicRefClass.isInterface());                     // Mdef implements Msym
+    }
 }
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandleProxies.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandleProxies.java	Fri Mar 15 23:31:19 2013 -0700
@@ -26,8 +26,12 @@
 package java.lang.invoke;
 
 import java.lang.reflect.*;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 import sun.invoke.WrapperInstance;
 import java.util.ArrayList;
+import sun.reflect.Reflection;
+import sun.reflect.misc.ReflectUtil;
 
 /**
  * This class consists exclusively of static methods that help adapt
@@ -137,6 +141,21 @@
     <T> T asInterfaceInstance(final Class<T> intfc, final MethodHandle target) {
         if (!intfc.isInterface() || !Modifier.isPublic(intfc.getModifiers()))
             throw new IllegalArgumentException("not a public interface: "+intfc.getName());
+        final MethodHandle mh;
+        if (System.getSecurityManager() != null) {
+            final int CALLER_FRAME = 2; // 0: Reflection, 1: asInterfaceInstance, 2: caller
+            final Class<?> caller = Reflection.getCallerClass(CALLER_FRAME);
+            final ClassLoader ccl = caller != null ? caller.getClassLoader() : null;
+            ReflectUtil.checkProxyPackageAccess(ccl, intfc);
+            mh = ccl != null ? bindCaller(target, caller) : target;
+        } else {
+            mh = target;
+        }
+        ClassLoader proxyLoader = intfc.getClassLoader();
+        if (proxyLoader == null) {
+            ClassLoader cl = Thread.currentThread().getContextClassLoader(); // avoid use of BCP
+            proxyLoader = cl != null ? cl : ClassLoader.getSystemClassLoader();
+        }
         final Method[] methods = getSingleNameMethods(intfc);
         if (methods == null)
             throw new IllegalArgumentException("not a single-method interface: "+intfc.getName());
@@ -144,31 +163,58 @@
         for (int i = 0; i < methods.length; i++) {
             Method sm = methods[i];
             MethodType smMT = MethodType.methodType(sm.getReturnType(), sm.getParameterTypes());
-            MethodHandle checkTarget = target.asType(smMT);  // make throw WMT
+            MethodHandle checkTarget = mh.asType(smMT);  // make throw WMT
             checkTarget = checkTarget.asType(checkTarget.type().changeReturnType(Object.class));
             vaTargets[i] = checkTarget.asSpreader(Object[].class, smMT.parameterCount());
         }
-        return intfc.cast(Proxy.newProxyInstance(
-                intfc.getClassLoader(),
-                new Class<?>[]{ intfc, WrapperInstance.class },
-                new InvocationHandler() {
-                    private Object getArg(String name) {
-                        if ((Object)name == "getWrapperInstanceTarget")  return target;
-                        if ((Object)name == "getWrapperInstanceType")    return intfc;
-                        throw new AssertionError();
+        final InvocationHandler ih = new InvocationHandler() {
+                private Object getArg(String name) {
+                    if ((Object)name == "getWrapperInstanceTarget")  return target;
+                    if ((Object)name == "getWrapperInstanceType")    return intfc;
+                    throw new AssertionError();
+                }
+                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+                    for (int i = 0; i < methods.length; i++) {
+                        if (method.equals(methods[i]))
+                            return vaTargets[i].invokeExact(args);
                     }
-                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
-                        for (int i = 0; i < methods.length; i++) {
-                            if (method.equals(methods[i]))
-                                return vaTargets[i].invokeExact(args);
-                        }
-                        if (method.getDeclaringClass() == WrapperInstance.class)
-                            return getArg(method.getName());
-                        if (isObjectMethod(method))
-                            return callObjectMethod(proxy, method, args);
-                        throw new InternalError("bad proxy method: "+method);
-                    }
-                }));
+                    if (method.getDeclaringClass() == WrapperInstance.class)
+                        return getArg(method.getName());
+                    if (isObjectMethod(method))
+                        return callObjectMethod(proxy, method, args);
+                    throw new InternalError("bad proxy method: "+method);
+                }
+            };
+
+        final Object proxy;
+        if (System.getSecurityManager() != null) {
+            // sun.invoke.WrapperInstance is a restricted interface not accessible
+            // by any non-null class loader.
+            final ClassLoader loader = proxyLoader;
+            proxy = AccessController.doPrivileged(new PrivilegedAction<Object>() {
+                public Object run() {
+                    return Proxy.newProxyInstance(
+                            loader,
+                            new Class<?>[]{ intfc, WrapperInstance.class },
+                            ih);
+                }
+            });
+        } else {
+            proxy = Proxy.newProxyInstance(proxyLoader,
+                                           new Class<?>[]{ intfc, WrapperInstance.class },
+                                           ih);
+        }
+        return intfc.cast(proxy);
+    }
+
+    private static MethodHandle bindCaller(MethodHandle target, Class<?> hostClass) {
+        MethodHandle cbmh = MethodHandleImpl.bindCaller(target, hostClass);
+        if (target.isVarargsCollector()) {
+            MethodType type = cbmh.type();
+            int arity = type.parameterCount();
+            return cbmh.asVarargsCollector(type.parameterType(arity-1));
+        }
+        return cbmh;
     }
 
     /**
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java	Fri Mar 15 23:31:19 2013 -0700
@@ -598,7 +598,8 @@
         MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
             checkSecurityManager(refc, method);  // stack walk magic: do not refactor
-            return getDirectMethod(REF_invokeStatic, refc, method);
+            Class<?> callerClass = findBoundCallerClass(method);  // stack walk magic: do not refactor
+            return getDirectMethod(REF_invokeStatic, refc, method, callerClass);
         }
 
         /**
@@ -652,7 +653,8 @@
             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
             MemberName method = resolveOrFail(refKind, refc, name, type);
             checkSecurityManager(refc, method);  // stack walk magic: do not refactor
-            return getDirectMethod(refKind, refc, method);
+            Class<?> callerClass = findBoundCallerClass(method);
+            return getDirectMethod(refKind, refc, method, callerClass);
         }
         private MethodHandle findVirtualForMH(String name, MethodType type) {
             // these names require special lookups because of the implicit MethodType argument
@@ -736,7 +738,8 @@
             Lookup specialLookup = this.in(specialCaller);
             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
             checkSecurityManager(refc, method);  // stack walk magic: do not refactor
-            return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method);
+            Class<?> callerClass = findBoundCallerClass(method);
+            return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, callerClass);
         }
 
         /**
@@ -879,7 +882,8 @@
             Class<? extends Object> refc = receiver.getClass(); // may get NPE
             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
             checkSecurityManager(refc, method);  // stack walk magic: do not refactor
-            MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method);
+            Class<?> callerClass = findBoundCallerClass(method);  // stack walk magic: do not refactor
+            MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, callerClass);
             return mh.bindReceiver(receiver).setVarargs(method);
         }
 
@@ -910,8 +914,9 @@
             if (refKind == REF_invokeSpecial)
                 refKind = REF_invokeVirtual;
             assert(method.isMethod());
+            Class<?> callerClass = findBoundCallerClass(method);  // stack walk magic: do not refactor
             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
-            return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method);
+            return lookup.getDirectMethod(refKind, method.getDeclaringClass(), method, callerClass);
         }
 
         /**
@@ -940,8 +945,9 @@
             Lookup specialLookup = this.in(specialCaller);
             MemberName method = new MemberName(m, true);
             assert(method.isMethod());
+            Class<?> callerClass = findBoundCallerClass(method);  // stack walk magic: do not refactor
             // ignore m.isAccessible:  this is a new kind of access
-            return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method);
+            return specialLookup.getDirectMethod(REF_invokeSpecial, method.getDeclaringClass(), method, callerClass);
         }
 
         /**
@@ -1040,7 +1046,29 @@
         }
 
         /**
+         * Find my trustable caller class if m is a caller sensitive method.
+         * If this lookup object has private access, then the caller class is the lookupClass.
+         * Otherwise, it is the caller of the currently executing public API method (e.g., findVirtual).
+         * This is the same caller class as is used by checkSecurityManager.
+         * This function performs stack walk magic: do not refactor it.
+         */
+        Class<?> findBoundCallerClass(MemberName m) {
+            Class<?> callerClass = null;
+            if (MethodHandleNatives.isCallerSensitive(m)) {
+                // Do not refactor this to a more "logical" place, since it is stack walk magic.
+                // Note that this is the same expression as in Step 2 below in checkSecurityManager.
+                callerClass = ((allowedModes & PRIVATE) != 0
+                               ? lookupClass  // for strong access modes, no extra check
+                               // next line does stack walk magic; do not refactor:
+                               : getCallerClassAtEntryPoint(true));
+            }
+            return callerClass;
+        }
+        /**
          * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
+         * Determines a trustable caller class to compare with refc, the symbolic reference class.
+         * If this lookup object has private access, then the caller class is the lookupClass.
+         * Otherwise, it is the caller of the currently executing public API method (e.g., findVirtual).
          * This function performs stack walk magic: do not refactor it.
          */
         void checkSecurityManager(Class<?> refc, MemberName m) {
@@ -1195,22 +1223,22 @@
             return mh.viewAsType(narrowType);
         }
 
-        private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method) throws IllegalAccessException {
+        private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
             return getDirectMethodCommon(refKind, refc, method,
                     (refKind == REF_invokeSpecial ||
                         (MethodHandleNatives.refKindHasReceiver(refKind) &&
-                            restrictProtectedReceiver(method))));
+                            restrictProtectedReceiver(method))), callerClass);
         }
-        private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method) throws IllegalAccessException {
-            return getDirectMethodCommon(refKind, refc, method, false);
+        private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException {
+            return getDirectMethodCommon(refKind, refc, method, false, callerClass);
         }
         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
-                                                   boolean doRestrict) throws IllegalAccessException {
+                                                   boolean doRestrict, Class<?> callerClass) throws IllegalAccessException {
             checkMethod(refKind, refc, method);
             if (method.isMethodHandleInvoke())
                 return fakeMethodHandleInvoke(method);
             MethodHandle mh = DirectMethodHandle.make(refKind, refc, method);
-            mh = maybeBindCaller(method, mh);
+            mh = maybeBindCaller(method, mh, callerClass);
             mh = mh.setVarargs(method);
             if (doRestrict)
                 mh = restrictReceiver(method, mh, lookupClass());
@@ -1219,12 +1247,14 @@
         private MethodHandle fakeMethodHandleInvoke(MemberName method) {
             return throwException(method.getReturnType(), UnsupportedOperationException.class);
         }
-        private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh) throws IllegalAccessException {
+        private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh,
+                                             Class<?> callerClass)
+                                             throws IllegalAccessException {
             if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
                 return mh;
             Class<?> hostClass = lookupClass;
             if ((allowedModes & PRIVATE) == 0)  // caller must use full-power lookup
-                hostClass = null;
+                hostClass = callerClass;  // callerClass came from a security manager style stack walk
             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass);
             // Note: caller will apply varargs after this step happens.
             return cbmh;
@@ -1262,7 +1292,7 @@
             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
                 MemberName method = (resolved != null) ? resolved
                         : resolveOrFail(refKind, defc, name, (MethodType) type);
-                return getDirectMethod(refKind, defc, method);
+                return getDirectMethod(refKind, defc, method, lookupClass);
             } else if (refKind == REF_newInvokeSpecial) {
                 assert(name == null || name.equals("<init>"));
                 MemberName ctor = (resolved != null) ? resolved
--- a/jdk/src/share/classes/java/lang/management/ManagementFactory.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/lang/management/ManagementFactory.java	Fri Mar 15 23:31:19 2013 -0700
@@ -802,20 +802,20 @@
      */
     private static void addMXBean(final MBeanServer mbs, final PlatformManagedObject pmo) {
         // Make DynamicMBean out of MXBean by wrapping it with a StandardMBean
-        final DynamicMBean dmbean;
-        if (pmo instanceof DynamicMBean) {
-            dmbean = DynamicMBean.class.cast(pmo);
-        } else if (pmo instanceof NotificationEmitter) {
-            dmbean = new StandardEmitterMBean(pmo, null, true, (NotificationEmitter) pmo);
-        } else {
-            dmbean = new StandardMBean(pmo, null, true);
-        }
-
         try {
             AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
                 public Void run() throws InstanceAlreadyExistsException,
                                          MBeanRegistrationException,
                                          NotCompliantMBeanException {
+                    final DynamicMBean dmbean;
+                    if (pmo instanceof DynamicMBean) {
+                        dmbean = DynamicMBean.class.cast(pmo);
+                    } else if (pmo instanceof NotificationEmitter) {
+                        dmbean = new StandardEmitterMBean(pmo, null, true, (NotificationEmitter) pmo);
+                    } else {
+                        dmbean = new StandardMBean(pmo, null, true);
+                    }
+
                     mbs.registerMBean(dmbean, pmo.getObjectName());
                     return null;
                 }
--- a/jdk/src/share/classes/java/lang/reflect/Proxy.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/lang/reflect/Proxy.java	Fri Mar 15 23:31:19 2013 -0700
@@ -27,6 +27,9 @@
 
 import java.lang.ref.Reference;
 import java.lang.ref.WeakReference;
+import java.security.AccessController;
+import java.security.Permission;
+import java.security.PrivilegedAction;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
@@ -36,6 +39,9 @@
 import java.util.List;
 import java.util.WeakHashMap;
 import sun.misc.ProxyGenerator;
+import sun.reflect.Reflection;
+import sun.reflect.misc.ReflectUtil;
+import sun.security.util.SecurityConstants;
 
 /**
  * {@code Proxy} provides static methods for creating dynamic proxy
@@ -265,9 +271,69 @@
      * @param   h the invocation handler for this proxy instance
      */
     protected Proxy(InvocationHandler h) {
+        doNewInstanceCheck();
         this.h = h;
     }
 
+    private static class ProxyAccessHelper {
+        // The permission is implementation specific.
+        static final Permission PROXY_PERMISSION =
+            new ReflectPermission("proxyConstructorNewInstance");
+        // These system properties are defined to provide a short-term
+        // workaround if customers need to disable the new security checks.
+        static final boolean allowNewInstance;
+        static final boolean allowNullLoader;
+        static {
+            allowNewInstance = getBooleanProperty("sun.reflect.proxy.allowsNewInstance");
+            allowNullLoader = getBooleanProperty("sun.reflect.proxy.allowsNullLoader");
+        }
+
+        private static boolean getBooleanProperty(final String key) {
+            String s = AccessController.doPrivileged(new PrivilegedAction<String>() {
+                public String run() {
+                    return System.getProperty(key);
+                }
+            });
+            return Boolean.valueOf(s);
+        }
+
+        static boolean needsNewInstanceCheck(Class<?> proxyClass) {
+            if (!Proxy.isProxyClass(proxyClass) || allowNewInstance) {
+                return false;
+            }
+
+            if (proxyClass.getName().startsWith(ReflectUtil.PROXY_PACKAGE + ".")) {
+                // all proxy interfaces are public
+                return false;
+            }
+            for (Class<?> intf : proxyClass.getInterfaces()) {
+                if (!Modifier.isPublic(intf.getModifiers())) {
+                    return true;
+                }
+            }
+            return false;
+        }
+    }
+
+    /*
+     * Access check on a proxy class that implements any non-public interface.
+     *
+     * @throws  SecurityException if a security manager exists, and
+     *          the caller does not have the permission.
+     */
+    private void doNewInstanceCheck() {
+        SecurityManager sm = System.getSecurityManager();
+        Class<?> proxyClass = this.getClass();
+        if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(proxyClass)) {
+            try {
+                sm.checkPermission(ProxyAccessHelper.PROXY_PERMISSION);
+            } catch (SecurityException e) {
+                throw new SecurityException("Not allowed to construct a Proxy "
+                        + "instance that implements a non-public interface", e);
+            }
+        }
+    }
+
     /**
      * Returns the {@code java.lang.Class} object for a proxy class
      * given a class loader and an array of interfaces.  The proxy class
@@ -346,6 +412,51 @@
                                          Class<?>... interfaces)
         throws IllegalArgumentException
     {
+        return getProxyClass0(loader, interfaces); // stack walk magic: do not refactor
+    }
+
+    private static void checkProxyLoader(ClassLoader ccl,
+                                         ClassLoader loader)
+    {
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            if (loader == null && ccl != null) {
+                if (!ProxyAccessHelper.allowNullLoader) {
+                    sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
+                }
+            }
+        }
+    }
+
+    /*
+     * Generate a proxy class (caller-sensitive).
+     *
+     * To define a proxy class, it performs the access checks as in
+     * Class.forName (VM will invoke ClassLoader.checkPackageAccess):
+     * 1. "getClassLoader" permission check if loader == null
+     * 2. checkPackageAccess on the interfaces it implements
+     *
+     * To get a constructor and new instance of a proxy class, it performs
+     * the package access check on the interfaces it implements
+     * as in Class.getConstructor.
+     *
+     * If an interface is non-public, the proxy class must be defined by
+     * the defining loader of the interface.  If the caller's class loader
+     * is not the same as the defining loader of the interface, the VM
+     * will throw IllegalAccessError when the generated proxy class is
+     * being defined via the defineClass0 method.
+     */
+    private static Class<?> getProxyClass0(ClassLoader loader,
+                                           Class<?>... interfaces) {
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            final int CALLER_FRAME = 3; // 0: Reflection, 1: getProxyClass0 2: Proxy 3: caller
+            final Class<?> caller = Reflection.getCallerClass(CALLER_FRAME);
+            final ClassLoader ccl = caller.getClassLoader();
+            checkProxyLoader(ccl, loader);
+            ReflectUtil.checkProxyPackageAccess(ccl, interfaces);
+        }
+
         if (interfaces.length > 65535) {
             throw new IllegalArgumentException("interface limit exceeded");
         }
@@ -497,8 +608,9 @@
                 }
             }
 
-            if (proxyPkg == null) {     // if no non-public proxy interfaces,
-                proxyPkg = "";          // use the unnamed package
+            if (proxyPkg == null) {
+                // if no non-public proxy interfaces, use com.sun.proxy package
+                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
             }
 
             {
@@ -598,22 +710,46 @@
         /*
          * Look up or generate the designated proxy class.
          */
-        Class<?> cl = getProxyClass(loader, interfaces);
+        Class<?> cl = getProxyClass0(loader, interfaces); // stack walk magic: do not refactor
 
         /*
          * Invoke its constructor with the designated invocation handler.
          */
         try {
-            Constructor<?> cons = cl.getConstructor(constructorParams);
-            return cons.newInstance(new Object[] { h });
-        } catch (NoSuchMethodException |
-                 IllegalAccessException |
-                 InstantiationException |
-                 InvocationTargetException e) {
+            final Constructor<?> cons = cl.getConstructor(constructorParams);
+            final InvocationHandler ih = h;
+            SecurityManager sm = System.getSecurityManager();
+            if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) {
+                // create proxy instance with doPrivilege as the proxy class may
+                // implement non-public interfaces that requires a special permission
+                return AccessController.doPrivileged(new PrivilegedAction<Object>() {
+                    public Object run() {
+                        return newInstance(cons, ih);
+                    }
+                });
+            } else {
+                return newInstance(cons, ih);
+            }
+        } catch (NoSuchMethodException e) {
             throw new InternalError(e.toString(), e);
         }
     }
 
+    private static Object newInstance(Constructor<?> cons, InvocationHandler h) {
+        try {
+            return cons.newInstance(new Object[] {h} );
+        } catch (IllegalAccessException | InstantiationException e) {
+            throw new InternalError(e.toString(), e);
+        } catch (InvocationTargetException e) {
+            Throwable t = e.getCause();
+            if (t instanceof RuntimeException) {
+                throw (RuntimeException) t;
+            } else {
+                throw new InternalError(t.toString(), t);
+            }
+        }
+    }
+
     /**
      * Returns true if and only if the specified class was dynamically
      * generated to be a proxy class using the {@code getProxyClass}
--- a/jdk/src/share/classes/java/net/InetSocketAddress.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/net/InetSocketAddress.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2007, 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
@@ -24,9 +24,12 @@
  */
 package java.net;
 
-import java.io.ObjectInputStream;
 import java.io.IOException;
 import java.io.InvalidObjectException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamException;
+import java.io.ObjectStreamField;
 
 /**
  *
@@ -46,23 +49,105 @@
  * @see java.net.ServerSocket
  * @since 1.4
  */
-public class InetSocketAddress extends SocketAddress {
-    /* The hostname of the Socket Address
-     * @serial
-     */
-    private String hostname = null;
-    /* The IP address of the Socket Address
-     * @serial
-     */
-    private InetAddress addr = null;
-    /* The port number of the Socket Address
-     * @serial
-     */
-    private int port;
+public class InetSocketAddress
+    extends SocketAddress
+{
+    // Private implementation class pointed to by all public methods.
+    private static class InetSocketAddressHolder {
+        // The hostname of the Socket Address
+        private String hostname;
+        // The IP address of the Socket Address
+        private InetAddress addr;
+        // The port number of the Socket Address
+        private int port;
+
+        private InetSocketAddressHolder(String hostname, InetAddress addr, int port) {
+            this.hostname = hostname;
+            this.addr = addr;
+            this.port = port;
+        }
+
+        private int getPort() {
+            return port;
+        }
+
+        private InetAddress getAddress() {
+            return addr;
+        }
+
+        private String getHostName() {
+            if (hostname != null)
+                return hostname;
+            if (addr != null)
+                return addr.getHostName();
+            return null;
+        }
+
+        private String getHostString() {
+            if (hostname != null)
+                return hostname;
+            if (addr != null) {
+                if (addr.hostName != null)
+                    return addr.hostName;
+                else
+                    return addr.getHostAddress();
+            }
+            return null;
+        }
+
+        private boolean isUnresolved() {
+            return addr == null;
+        }
+
+        @Override
+        public String toString() {
+            if (isUnresolved()) {
+                return hostname + ":" + port;
+            } else {
+                return addr.toString() + ":" + port;
+            }
+        }
+
+        @Override
+        public final boolean equals(Object obj) {
+            if (obj == null || !(obj instanceof InetSocketAddressHolder))
+                return false;
+            InetSocketAddressHolder that = (InetSocketAddressHolder)obj;
+            boolean sameIP;
+            if (addr != null)
+                sameIP = addr.equals(that.addr);
+            else if (hostname != null)
+                sameIP = (that.addr == null) &&
+                    hostname.equalsIgnoreCase(that.hostname);
+            else
+                sameIP = (that.addr == null) && (that.hostname == null);
+            return sameIP && (port == that.port);
+        }
+
+        @Override
+        public final int hashCode() {
+            if (addr != null)
+                return addr.hashCode() + port;
+            if (hostname != null)
+                return hostname.toLowerCase().hashCode() + port;
+            return port;
+        }
+    }
+
+    private final transient InetSocketAddressHolder holder;
 
     private static final long serialVersionUID = 5076001401234631237L;
 
-    private InetSocketAddress() {
+    private static int checkPort(int port) {
+        if (port < 0 || port > 0xFFFF)
+            throw new IllegalArgumentException("port out of range:" + port);
+        return port;
+    }
+
+    private static String checkHost(String hostname) {
+        if (hostname == null)
+            throw new IllegalArgumentException("hostname can't be null");
+        return hostname;
     }
 
     /**
@@ -97,14 +182,10 @@
      * range of valid port values.
      */
     public InetSocketAddress(InetAddress addr, int port) {
-        if (port < 0 || port > 0xFFFF) {
-            throw new IllegalArgumentException("port out of range:" + port);
-        }
-        this.port = port;
-        if (addr == null)
-            this.addr = InetAddress.anyLocalAddress();
-        else
-            this.addr = addr;
+        holder = new InetSocketAddressHolder(
+                        null,
+                        addr == null ? InetAddress.anyLocalAddress() : addr,
+                        checkPort(port));
     }
 
     /**
@@ -132,19 +213,20 @@
      * @see     #isUnresolved()
      */
     public InetSocketAddress(String hostname, int port) {
-        if (port < 0 || port > 0xFFFF) {
-            throw new IllegalArgumentException("port out of range:" + port);
-        }
-        if (hostname == null) {
-            throw new IllegalArgumentException("hostname can't be null");
-        }
+        checkHost(hostname);
+        InetAddress addr = null;
+        String host = null;
         try {
             addr = InetAddress.getByName(hostname);
         } catch(UnknownHostException e) {
-            this.hostname = hostname;
-            addr = null;
+            host = hostname;
         }
-        this.port = port;
+        holder = new InetSocketAddressHolder(host, addr, checkPort(port));
+    }
+
+    // private constructor for creating unresolved instances
+    private InetSocketAddress(int port, String hostname) {
+        holder = new InetSocketAddressHolder(hostname, null, port);
     }
 
     /**
@@ -169,31 +251,67 @@
      * @since 1.5
      */
     public static InetSocketAddress createUnresolved(String host, int port) {
-        if (port < 0 || port > 0xFFFF) {
-            throw new IllegalArgumentException("port out of range:" + port);
-        }
-        if (host == null) {
-            throw new IllegalArgumentException("hostname can't be null");
-        }
-        InetSocketAddress s = new InetSocketAddress();
-        s.port = port;
-        s.hostname = host;
-        s.addr = null;
-        return s;
+        return new InetSocketAddress(checkPort(port), checkHost(host));
     }
 
-    private void readObject(ObjectInputStream s)
-        throws IOException, ClassNotFoundException {
-        s.defaultReadObject();
+    /**
+     * @serialField hostname String
+     * @serialField addr InetAddress
+     * @serialField port int
+     */
+    private static final ObjectStreamField[] serialPersistentFields = {
+         new ObjectStreamField("hostname", String.class),
+         new ObjectStreamField("addr", InetAddress.class),
+         new ObjectStreamField("port", int.class)};
+
+    private void writeObject(ObjectOutputStream out)
+        throws IOException
+    {
+        // Don't call defaultWriteObject()
+         ObjectOutputStream.PutField pfields = out.putFields();
+         pfields.put("hostname", holder.hostname);
+         pfields.put("addr", holder.addr);
+         pfields.put("port", holder.port);
+         out.writeFields();
+     }
+
+    private void readObject(ObjectInputStream in)
+        throws IOException, ClassNotFoundException
+    {
+        // Don't call defaultReadObject()
+        ObjectInputStream.GetField oisFields = in.readFields();
+        final String oisHostname = (String)oisFields.get("hostname", null);
+        final InetAddress oisAddr = (InetAddress)oisFields.get("addr", null);
+        final int oisPort = oisFields.get("port", -1);
 
         // Check that our invariants are satisfied
-        if (port < 0 || port > 0xFFFF) {
-            throw new InvalidObjectException("port out of range:" + port);
-        }
-
-        if (hostname == null && addr == null) {
+        checkPort(oisPort);
+        if (oisHostname == null && oisAddr == null)
             throw new InvalidObjectException("hostname and addr " +
                                              "can't both be null");
+
+        InetSocketAddressHolder h = new InetSocketAddressHolder(oisHostname,
+                                                                oisAddr,
+                                                                oisPort);
+        UNSAFE.putObject(this, FIELDS_OFFSET, h);
+    }
+
+    private void readObjectNoData()
+        throws ObjectStreamException
+    {
+        throw new InvalidObjectException("Stream data required");
+    }
+
+    private static final long FIELDS_OFFSET;
+    private static final sun.misc.Unsafe UNSAFE;
+    static {
+        try {
+            sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
+            FIELDS_OFFSET = unsafe.objectFieldOffset(
+                    InetSocketAddress.class.getDeclaredField("holder"));
+            UNSAFE = unsafe;
+        } catch (ReflectiveOperationException e) {
+            throw new Error(e);
         }
     }
 
@@ -203,7 +321,7 @@
      * @return the port number.
      */
     public final int getPort() {
-        return port;
+        return holder.getPort();
     }
 
     /**
@@ -213,7 +331,7 @@
      * @return the InetAdress or <code>null</code> if it is unresolved.
      */
     public final InetAddress getAddress() {
-        return addr;
+        return holder.getAddress();
     }
 
     /**
@@ -224,31 +342,19 @@
      * @return  the hostname part of the address.
      */
     public final String getHostName() {
-        if (hostname != null)
-            return hostname;
-        if (addr != null)
-            return addr.getHostName();
-        return null;
+        return holder.getHostName();
     }
 
     /**
      * Returns the hostname, or the String form of the address if it
      * doesn't have a hostname (it was created using a literal).
-     * This has the benefit of <b>not</b> attemptimg a reverse lookup.
+     * This has the benefit of <b>not</b> attempting a reverse lookup.
      *
      * @return the hostname, or String representation of the address.
      * @since 1.7
      */
     public final String getHostString() {
-        if (hostname != null)
-            return hostname;
-        if (addr != null) {
-            if (addr.hostName != null)
-                return addr.hostName;
-            else
-                return addr.getHostAddress();
-        }
-        return null;
+        return holder.getHostString();
     }
 
     /**
@@ -258,7 +364,7 @@
      *          an <code>InetAddress</code>.
      */
     public final boolean isUnresolved() {
-        return addr == null;
+        return holder.isUnresolved();
     }
 
     /**
@@ -269,12 +375,9 @@
      *
      * @return  a string representation of this object.
      */
+    @Override
     public String toString() {
-        if (isUnresolved()) {
-            return hostname + ":" + port;
-        } else {
-            return addr.toString() + ":" + port;
-        }
+        return holder.toString();
     }
 
     /**
@@ -297,19 +400,11 @@
      *          <code>false</code> otherwise.
      * @see java.net.InetAddress#equals(java.lang.Object)
      */
+    @Override
     public final boolean equals(Object obj) {
         if (obj == null || !(obj instanceof InetSocketAddress))
             return false;
-        InetSocketAddress sockAddr = (InetSocketAddress) obj;
-        boolean sameIP = false;
-        if (this.addr != null)
-            sameIP = this.addr.equals(sockAddr.addr);
-        else if (this.hostname != null)
-            sameIP = (sockAddr.addr == null) &&
-                this.hostname.equalsIgnoreCase(sockAddr.hostname);
-        else
-            sameIP = (sockAddr.addr == null) && (sockAddr.hostname == null);
-        return sameIP && (this.port == sockAddr.port);
+        return holder.equals(((InetSocketAddress) obj).holder);
     }
 
     /**
@@ -317,11 +412,8 @@
      *
      * @return  a hash code value for this socket address.
      */
+    @Override
     public final int hashCode() {
-        if (addr != null)
-            return addr.hashCode() + port;
-        if (hostname != null)
-            return hostname.toLowerCase().hashCode() + port;
-        return port;
+        return holder.hashCode();
     }
 }
--- a/jdk/src/share/classes/java/util/concurrent/ThreadPoolExecutor.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/util/concurrent/ThreadPoolExecutor.java	Fri Mar 15 23:31:19 2013 -0700
@@ -34,8 +34,10 @@
  */
 
 package java.util.concurrent;
-import java.util.concurrent.locks.*;
-import java.util.concurrent.atomic.*;
+import java.util.concurrent.locks.AbstractQueuedSynchronizer;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.util.*;
 
 /**
@@ -491,10 +493,15 @@
      * policy limiting the number of threads.  Even though it is not
      * treated as an error, failure to create threads may result in
      * new tasks being rejected or existing ones remaining stuck in
-     * the queue. On the other hand, no special precautions exist to
-     * handle OutOfMemoryErrors that might be thrown while trying to
-     * create threads, since there is generally no recourse from
-     * within this class.
+     * the queue.
+     *
+     * We go further and preserve pool invariants even in the face of
+     * errors such as OutOfMemoryError, that might be thrown while
+     * trying to create threads.  Such errors are rather common due to
+     * the need to allocate a native stack in Thread#start, and users
+     * will want to perform clean pool shutdown to clean up.  There
+     * will likely be enough memory available for the cleanup code to
+     * complete without encountering yet another OutOfMemoryError.
      */
     private volatile ThreadFactory threadFactory;
 
@@ -568,9 +575,13 @@
      * task execution.  This protects against interrupts that are
      * intended to wake up a worker thread waiting for a task from
      * instead interrupting a task being run.  We implement a simple
-     * non-reentrant mutual exclusion lock rather than use ReentrantLock
-     * because we do not want worker tasks to be able to reacquire the
-     * lock when they invoke pool control methods like setCorePoolSize.
+     * non-reentrant mutual exclusion lock rather than use
+     * ReentrantLock because we do not want worker tasks to be able to
+     * reacquire the lock when they invoke pool control methods like
+     * setCorePoolSize.  Additionally, to suppress interrupts until
+     * the thread actually starts running tasks, we initialize lock
+     * state to a negative value, and clear it upon start (in
+     * runWorker).
      */
     private final class Worker
         extends AbstractQueuedSynchronizer
@@ -594,6 +605,7 @@
          * @param firstTask the first task (null if none)
          */
         Worker(Runnable firstTask) {
+            setState(-1); // inhibit interrupts until runWorker
             this.firstTask = firstTask;
             this.thread = getThreadFactory().newThread(this);
         }
@@ -609,7 +621,7 @@
         // The value 1 represents the locked state.
 
         protected boolean isHeldExclusively() {
-            return getState() == 1;
+            return getState() != 0;
         }
 
         protected boolean tryAcquire(int unused) {
@@ -630,6 +642,16 @@
         public boolean tryLock()  { return tryAcquire(1); }
         public void unlock()      { release(1); }
         public boolean isLocked() { return isHeldExclusively(); }
+
+        void interruptIfStarted() {
+            Thread t;
+            if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
+                try {
+                    t.interrupt();
+                } catch (SecurityException ignore) {
+                }
+            }
+        }
     }
 
     /*
@@ -728,12 +750,8 @@
         final ReentrantLock mainLock = this.mainLock;
         mainLock.lock();
         try {
-            for (Worker w : workers) {
-                try {
-                    w.thread.interrupt();
-                } catch (SecurityException ignore) {
-                }
-            }
+            for (Worker w : workers)
+                w.interruptIfStarted();
         } finally {
             mainLock.unlock();
         }
@@ -790,19 +808,6 @@
 
     private static final boolean ONLY_ONE = true;
 
-    /**
-     * Ensures that unless the pool is stopping, the current thread
-     * does not have its interrupt set. This requires a double-check
-     * of state in case the interrupt was cleared concurrently with a
-     * shutdownNow -- if so, the interrupt is re-enabled.
-     */
-    private void clearInterruptsForTaskRun() {
-        if (runStateLessThan(ctl.get(), STOP) &&
-            Thread.interrupted() &&
-            runStateAtLeast(ctl.get(), STOP))
-            Thread.currentThread().interrupt();
-    }
-
     /*
      * Misc utilities, most of which are also exported to
      * ScheduledThreadPoolExecutor
@@ -862,12 +867,13 @@
      * Checks if a new worker can be added with respect to current
      * pool state and the given bound (either core or maximum). If so,
      * the worker count is adjusted accordingly, and, if possible, a
-     * new worker is created and started running firstTask as its
+     * new worker is created and started, running firstTask as its
      * first task. This method returns false if the pool is stopped or
      * eligible to shut down. It also returns false if the thread
-     * factory fails to create a thread when asked, which requires a
-     * backout of workerCount, and a recheck for termination, in case
-     * the existence of this worker was holding up termination.
+     * factory fails to create a thread when asked.  If the thread
+     * creation fails, either due to the thread factory returning
+     * null, or due to an exception (typically OutOfMemoryError in
+     * Thread#start), we roll back cleanly.
      *
      * @param firstTask the task the new thread should run first (or
      * null if none). Workers are created with an initial first task
@@ -910,46 +916,65 @@
             }
         }
 
-        Worker w = new Worker(firstTask);
-        Thread t = w.thread;
+        boolean workerStarted = false;
+        boolean workerAdded = false;
+        Worker w = null;
+        try {
+            final ReentrantLock mainLock = this.mainLock;
+            w = new Worker(firstTask);
+            final Thread t = w.thread;
+            if (t != null) {
+                mainLock.lock();
+                try {
+                    // Recheck while holding lock.
+                    // Back out on ThreadFactory failure or if
+                    // shut down before lock acquired.
+                    int c = ctl.get();
+                    int rs = runStateOf(c);
 
+                    if (rs < SHUTDOWN ||
+                        (rs == SHUTDOWN && firstTask == null)) {
+                        if (t.isAlive()) // precheck that t is startable
+                            throw new IllegalThreadStateException();
+                        workers.add(w);
+                        int s = workers.size();
+                        if (s > largestPoolSize)
+                            largestPoolSize = s;
+                        workerAdded = true;
+                    }
+                } finally {
+                    mainLock.unlock();
+                }
+                if (workerAdded) {
+                    t.start();
+                    workerStarted = true;
+                }
+            }
+        } finally {
+            if (! workerStarted)
+                addWorkerFailed(w);
+        }
+        return workerStarted;
+    }
+
+    /**
+     * Rolls back the worker thread creation.
+     * - removes worker from workers, if present
+     * - decrements worker count
+     * - rechecks for termination, in case the existence of this
+     *   worker was holding up termination
+     */
+    private void addWorkerFailed(Worker w) {
         final ReentrantLock mainLock = this.mainLock;
         mainLock.lock();
         try {
-            // Recheck while holding lock.
-            // Back out on ThreadFactory failure or if
-            // shut down before lock acquired.
-            int c = ctl.get();
-            int rs = runStateOf(c);
-
-            if (t == null ||
-                (rs >= SHUTDOWN &&
-                 ! (rs == SHUTDOWN &&
-                    firstTask == null))) {
-                decrementWorkerCount();
-                tryTerminate();
-                return false;
-            }
-
-            workers.add(w);
-
-            int s = workers.size();
-            if (s > largestPoolSize)
-                largestPoolSize = s;
+            if (w != null)
+                workers.remove(w);
+            decrementWorkerCount();
+            tryTerminate();
         } finally {
             mainLock.unlock();
         }
-
-        t.start();
-        // It is possible (but unlikely) for a thread to have been
-        // added to workers, but not yet started, during transition to
-        // STOP, which could result in a rare missed interrupt,
-        // because Thread.interrupt is not guaranteed to have any effect
-        // on a non-yet-started Thread (see Thread#interrupt).
-        if (runStateOf(ctl.get()) == STOP && ! t.isInterrupted())
-            t.interrupt();
-
-        return true;
     }
 
     /**
@@ -1096,15 +1121,25 @@
      * @param w the worker
      */
     final void runWorker(Worker w) {
+        Thread wt = Thread.currentThread();
         Runnable task = w.firstTask;
         w.firstTask = null;
+        w.unlock(); // allow interrupts
         boolean completedAbruptly = true;
         try {
             while (task != null || (task = getTask()) != null) {
                 w.lock();
-                clearInterruptsForTaskRun();
+                // If pool is stopping, ensure thread is interrupted;
+                // if not, ensure thread is not interrupted.  This
+                // requires a recheck in second case to deal with
+                // shutdownNow race while clearing interrupt
+                if ((runStateAtLeast(ctl.get(), STOP) ||
+                     (Thread.interrupted() &&
+                      runStateAtLeast(ctl.get(), STOP))) &&
+                    !wt.isInterrupted())
+                    wt.interrupt();
                 try {
-                    beforeExecute(w.thread, task);
+                    beforeExecute(wt, task);
                     Throwable thrown = null;
                     try {
                         task.run();
@@ -2064,3 +2099,4 @@
         }
     }
 }
+
--- a/jdk/src/share/classes/java/util/jar/JarFile.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/util/jar/JarFile.java	Fri Mar 15 23:31:19 2013 -0700
@@ -34,6 +34,7 @@
 import java.security.cert.Certificate;
 import java.security.AccessController;
 import java.security.CodeSource;
+import sun.misc.IOUtils;
 import sun.security.action.GetPropertyAction;
 import sun.security.util.ManifestEntryVerifier;
 import sun.misc.SharedSecrets;
@@ -334,6 +335,9 @@
             if (names != null) {
                 for (int i = 0; i < names.length; i++) {
                     JarEntry e = getJarEntry(names[i]);
+                    if (e == null) {
+                        throw new JarException("corrupted jar file");
+                    }
                     if (!e.isDirectory()) {
                         if (mev == null) {
                             mev = new ManifestEntryVerifier
@@ -353,6 +357,10 @@
             // treat the jar file as being unsigned
             jv = null;
             verify = false;
+            if (JarVerifier.debug != null) {
+                JarVerifier.debug.println("jarfile parsing error!");
+                ex.printStackTrace();
+            }
         }
 
         // if after initializing the verifier we have nothing
@@ -380,11 +388,9 @@
      * META-INF files.
      */
     private byte[] getBytes(ZipEntry ze) throws IOException {
-        byte[] b = new byte[(int)ze.getSize()];
-        try (DataInputStream is = new DataInputStream(super.getInputStream(ze))) {
-            is.readFully(b, 0, b.length);
+        try (InputStream is = super.getInputStream(ze)) {
+            return IOUtils.readFully(is, (int)ze.getSize(), true);
         }
-        return b;
     }
 
     /**
@@ -540,11 +546,7 @@
         if (!isKnownNotToHaveSpecialAttributes()) {
             JarEntry manEntry = getManEntry();
             if (manEntry != null) {
-                byte[] b = new byte[(int)manEntry.getSize()];
-                try (DataInputStream dis = new DataInputStream(
-                         super.getInputStream(manEntry))) {
-                    dis.readFully(b, 0, b.length);
-                }
+                byte[] b = getBytes(manEntry);
                 if (match(CLASSPATH_CHARS, b, CLASSPATH_LASTOCC, CLASSPATH_OPTOSFT))
                     hasClassPathAttribute = true;
                 if (match(PROFILE_CHARS, b, PROFILE_LASTOCC, PROFILE_OPTOSFT))
--- a/jdk/src/share/classes/java/util/logging/Level.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/util/logging/Level.java	Fri Mar 15 23:31:19 2013 -0700
@@ -24,6 +24,10 @@
  */
 
 package java.util.logging;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import java.util.ResourceBundle;
 
 /**
@@ -59,7 +63,6 @@
  */
 
 public class Level implements java.io.Serializable {
-    private static java.util.ArrayList<Level> known = new java.util.ArrayList<>();
     private static String defaultBundle = "sun.util.logging.resources.logging";
 
     /**
@@ -77,6 +80,9 @@
      */
     private final String resourceBundleName;
 
+    // localized level name
+    private String localizedLevelName;
+
     /**
      * OFF is a special level that can be used to turn off logging.
      * This level is initialized to <CODE>Integer.MAX_VALUE</CODE>.
@@ -202,9 +208,8 @@
         this.name = name;
         this.value = value;
         this.resourceBundleName = resourceBundleName;
-        synchronized (Level.class) {
-            known.add(this);
-        }
+        this.localizedLevelName = resourceBundleName == null ? name : null;
+        KnownLevel.add(this);
     }
 
     /**
@@ -236,12 +241,76 @@
      * @return localized name
      */
     public String getLocalizedName() {
+        return getLocalizedLevelName();
+    }
+
+    // package-private getLevelName() is used by the implementation
+    // instead of getName() to avoid calling the subclass's version
+    final String getLevelName() {
+        return this.name;
+    }
+
+    final synchronized String getLocalizedLevelName() {
+        if (localizedLevelName != null) {
+            return localizedLevelName;
+        }
+
         try {
             ResourceBundle rb = ResourceBundle.getBundle(resourceBundleName);
-            return rb.getString(name);
+            localizedLevelName = rb.getString(name);
         } catch (Exception ex) {
-            return name;
+            localizedLevelName = name;
+        }
+        return localizedLevelName;
+    }
+
+    // Returns a mirrored Level object that matches the given name as
+    // specified in the Level.parse method.  Returns null if not found.
+    //
+    // It returns the same Level object as the one returned by Level.parse
+    // method if the given name is a non-localized name or integer.
+    //
+    // If the name is a localized name, findLevel and parse method may
+    // return a different level value if there is a custom Level subclass
+    // that overrides Level.getLocalizedName() to return a different string
+    // than what's returned by the default implementation.
+    //
+    static Level findLevel(String name) {
+        if (name == null) {
+            throw new NullPointerException();
         }
+
+        KnownLevel level;
+
+        // Look for a known Level with the given non-localized name.
+        level = KnownLevel.findByName(name);
+        if (level != null) {
+            return level.mirroredLevel;
+        }
+
+        // Now, check if the given name is an integer.  If so,
+        // first look for a Level with the given value and then
+        // if necessary create one.
+        try {
+            int x = Integer.parseInt(name);
+            level = KnownLevel.findByValue(x);
+            if (level == null) {
+                // add new Level
+                Level levelObject = new Level(name, x);
+                level = KnownLevel.findByValue(x);
+            }
+            return level.mirroredLevel;
+        } catch (NumberFormatException ex) {
+            // Not an integer.
+            // Drop through.
+        }
+
+        level = KnownLevel.findByLocalizedLevelName(name);
+        if (level != null) {
+            return level.mirroredLevel;
+        }
+
+        return null;
     }
 
     /**
@@ -268,21 +337,15 @@
     // Serialization magic to prevent "doppelgangers".
     // This is a performance optimization.
     private Object readResolve() {
-        synchronized (Level.class) {
-            for (int i = 0; i < known.size(); i++) {
-                Level other = known.get(i);
-                if (this.name.equals(other.name) && this.value == other.value
-                        && (this.resourceBundleName == other.resourceBundleName ||
-                            (this.resourceBundleName != null &&
-                            this.resourceBundleName.equals(other.resourceBundleName)))) {
-                    return other;
-                }
-            }
-            // Woops.  Whoever sent us this object knows
-            // about a new log level.  Add it to our list.
-            known.add(this);
-            return this;
+        KnownLevel o = KnownLevel.matches(this);
+        if (o != null) {
+            return o.levelObject;
         }
+
+        // Woops.  Whoever sent us this object knows
+        // about a new log level.  Add it to our list.
+        Level level = new Level(this.name, this.value, this.resourceBundleName);
+        return level;
     }
 
     /**
@@ -296,6 +359,7 @@
      * <li>     "SEVERE"
      * <li>     "1000"
      * </ul>
+     *
      * @param  name   string to be parsed
      * @throws NullPointerException if the name is null
      * @throws IllegalArgumentException if the value is not valid.
@@ -315,12 +379,12 @@
         // Check that name is not null.
         name.length();
 
+        KnownLevel level;
+
         // Look for a known Level with the given non-localized name.
-        for (int i = 0; i < known.size(); i++) {
-            Level l = known.get(i);
-            if (name.equals(l.name)) {
-                return l;
-            }
+        level = KnownLevel.findByName(name);
+        if (level != null) {
+            return level.levelObject;
         }
 
         // Now, check if the given name is an integer.  If so,
@@ -328,14 +392,13 @@
         // if necessary create one.
         try {
             int x = Integer.parseInt(name);
-            for (int i = 0; i < known.size(); i++) {
-                Level l = known.get(i);
-                if (l.value == x) {
-                    return l;
-                }
+            level = KnownLevel.findByValue(x);
+            if (level == null) {
+                // add new Level
+                Level levelObject = new Level(name, x);
+                level = KnownLevel.findByValue(x);
             }
-            // Create a new Level.
-            return new Level(name, x);
+            return level.levelObject;
         } catch (NumberFormatException ex) {
             // Not an integer.
             // Drop through.
@@ -344,11 +407,9 @@
         // Finally, look for a known level with the given localized name,
         // in the current default locale.
         // This is relatively expensive, but not excessively so.
-        for (int i = 0; i < known.size(); i++) {
-            Level l =  known.get(i);
-            if (name.equals(l.getLocalizedName())) {
-                return l;
-            }
+        level = KnownLevel.findByLocalizedName(name);
+        if (level != null) {
+            return level.levelObject;
         }
 
         // OK, we've tried everything and failed
@@ -375,4 +436,124 @@
     public int hashCode() {
         return this.value;
     }
+
+    // KnownLevel class maintains the global list of all known levels.
+    // The API allows multiple custom Level instances of the same name/value
+    // be created. This class provides convenient methods to find a level
+    // by a given name, by a given value, or by a given localized name.
+    //
+    // KnownLevel wraps the following Level objects:
+    // 1. levelObject:   standard Level object or custom Level object
+    // 2. mirroredLevel: Level object representing the level specified in the
+    //                   logging configuration.
+    //
+    // Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods
+    // are non-final but the name and resource bundle name are parameters to
+    // the Level constructor.  Use the mirroredLevel object instead of the
+    // levelObject to prevent the logging framework to execute foreign code
+    // implemented by untrusted Level subclass.
+    //
+    // Implementation Notes:
+    // If Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods
+    // were final, the following KnownLevel implementation can be removed.
+    // Future API change should take this into consideration.
+    static final class KnownLevel {
+        private static Map<String, List<KnownLevel>> nameToLevels = new HashMap<>();
+        private static Map<Integer, List<KnownLevel>> intToLevels = new HashMap<>();
+        final Level levelObject;     // instance of Level class or Level subclass
+        final Level mirroredLevel;   // instance of Level class
+        KnownLevel(Level l) {
+            this.levelObject = l;
+            if (l.getClass() == Level.class) {
+                this.mirroredLevel = l;
+            } else {
+                this.mirroredLevel = new Level(l.name, l.value, l.resourceBundleName);
+            }
+        }
+
+        static synchronized void add(Level l) {
+            // the mirroredLevel object is always added to the list
+            // before the custom Level instance
+            KnownLevel o = new KnownLevel(l);
+            List<KnownLevel> list = nameToLevels.get(l.name);
+            if (list == null) {
+                list = new ArrayList<>();
+                nameToLevels.put(l.name, list);
+            }
+            list.add(o);
+
+            list = intToLevels.get(l.value);
+            if (list == null) {
+                list = new ArrayList<>();
+                intToLevels.put(l.value, list);
+            }
+            list.add(o);
+        }
+
+        // Returns a KnownLevel with the given non-localized name.
+        static synchronized KnownLevel findByName(String name) {
+            List<KnownLevel> list = nameToLevels.get(name);
+            if (list != null) {
+                return list.get(0);
+            }
+            return null;
+        }
+
+        // Returns a KnownLevel with the given value.
+        static synchronized KnownLevel findByValue(int value) {
+            List<KnownLevel> list = intToLevels.get(value);
+            if (list != null) {
+                return list.get(0);
+            }
+            return null;
+        }
+
+        // Returns a KnownLevel with the given localized name matching
+        // by calling the Level.getLocalizedLevelName() method (i.e. found
+        // from the resourceBundle associated with the Level object).
+        // This method does not call Level.getLocalizedName() that may
+        // be overridden in a subclass implementation
+        static synchronized KnownLevel findByLocalizedLevelName(String name) {
+            for (List<KnownLevel> levels : nameToLevels.values()) {
+                for (KnownLevel l : levels) {
+                    String lname = l.levelObject.getLocalizedLevelName();
+                    if (name.equals(lname)) {
+                        return l;
+                    }
+                }
+            }
+            return null;
+        }
+
+        // Returns a KnownLevel with the given localized name matching
+        // by calling the Level.getLocalizedName() method
+        static synchronized KnownLevel findByLocalizedName(String name) {
+            for (List<KnownLevel> levels : nameToLevels.values()) {
+                for (KnownLevel l : levels) {
+                    String lname = l.levelObject.getLocalizedName();
+                    if (name.equals(lname)) {
+                        return l;
+                    }
+                }
+            }
+            return null;
+        }
+
+        static synchronized KnownLevel matches(Level l) {
+            List<KnownLevel> list = nameToLevels.get(l.name);
+            if (list != null) {
+                for (KnownLevel level : list) {
+                    Level other = level.mirroredLevel;
+                    if (l.value == other.value &&
+                           (l.resourceBundleName == other.resourceBundleName ||
+                               (l.resourceBundleName != null &&
+                                l.resourceBundleName.equals(other.resourceBundleName)))) {
+                        return level;
+                    }
+                }
+            }
+            return null;
+        }
+    }
+
 }
--- a/jdk/src/share/classes/java/util/logging/LogManager.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/util/logging/LogManager.java	Fri Mar 15 23:31:19 2013 -0700
@@ -35,6 +35,10 @@
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.beans.PropertyChangeListener;
+import java.net.URL;
+import sun.misc.JavaAWTAccess;
+import sun.misc.SharedSecrets;
+import sun.security.action.GetPropertyAction;
 
 /**
  * There is a single global LogManager object that is used to
@@ -152,10 +156,9 @@
     // count to allow for cases where the same listener is registered many times.
     private final Map<Object,Integer> listenerMap = new HashMap<>();
 
-    // Table of named Loggers that maps names to Loggers.
-    private Hashtable<String,LoggerWeakRef> namedLoggers = new Hashtable<>();
-    // Tree of named Loggers
-    private LogNode root = new LogNode(null);
+    // LoggerContext for system loggers and user loggers
+    private final LoggerContext systemContext = new SystemLoggerContext();
+    private final LoggerContext userContext = new LoggerContext();
     private Logger rootLogger;
 
     // Have we done the primordial reading of the configuration file?
@@ -194,11 +197,12 @@
                     // Create and retain Logger for the root of the namespace.
                     manager.rootLogger = manager.new RootLogger();
                     manager.addLogger(manager.rootLogger);
+                    manager.systemContext.addLocalLogger(manager.rootLogger);
 
                     // Adding the global Logger. Doing so in the Logger.<clinit>
                     // would deadlock with the LogManager.<clinit>.
-                    Logger.getGlobal().setLogManager(manager);
-                    manager.addLogger(Logger.getGlobal());
+                    Logger.global.setLogManager(manager);
+                    manager.addLogger(Logger.global);
 
                     // We don't call readConfiguration() here, as we may be running
                     // very early in the JVM startup sequence.  Instead readConfiguration
@@ -276,14 +280,14 @@
                         return;
                     }
                     readPrimordialConfiguration = true;
+
                     try {
-                        AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
-                                public Object run() throws Exception {
+                        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
+                                public Void run() throws Exception {
                                     readConfiguration();
 
                                     // Platform loggers begin to delegate to java.util.logging.Logger
                                     sun.util.logging.PlatformLogger.redirectPlatformLoggers();
-
                                     return null;
                                 }
                             });
@@ -375,20 +379,68 @@
         }
     }
 
-    // Package-level method.
+    // Returns the LoggerContext for the user code (i.e. application or AppContext).
+    // Loggers are isolated from each AppContext.
+    private LoggerContext getUserContext() {
+        LoggerContext context = null;
+
+        SecurityManager sm = System.getSecurityManager();
+        JavaAWTAccess javaAwtAccess = SharedSecrets.getJavaAWTAccess();
+        if (sm != null && javaAwtAccess != null) {
+            synchronized (javaAwtAccess) {
+                // AppContext.getAppContext() returns the system AppContext if called
+                // from a system thread but Logger.getLogger might be called from
+                // an applet code. Instead, find the AppContext of the applet code
+                // from the execution stack.
+                Object ecx = javaAwtAccess.getExecutionContext();
+                if (ecx == null) {
+                    // fall back to AppContext.getAppContext()
+                    ecx = javaAwtAccess.getContext();
+                }
+                context = (LoggerContext)javaAwtAccess.get(ecx, LoggerContext.class);
+                if (context == null) {
+                    if (javaAwtAccess.isMainAppContext()) {
+                        context = userContext;
+                    } else {
+                        context = new LoggerContext();
+                        // during initialization, rootLogger is null when
+                        // instantiating itself RootLogger
+                        if (manager.rootLogger != null)
+                            context.addLocalLogger(manager.rootLogger);
+                    }
+                    javaAwtAccess.put(ecx, LoggerContext.class, context);
+                }
+            }
+        } else {
+            context = userContext;
+        }
+        return context;
+    }
+
+    private List<LoggerContext> contexts() {
+        List<LoggerContext> cxs = new ArrayList<>();
+        cxs.add(systemContext);
+        cxs.add(getUserContext());
+        return cxs;
+    }
+
     // Find or create a specified logger instance. If a logger has
     // already been created with the given name it is returned.
     // Otherwise a new logger instance is created and registered
     // in the LogManager global namespace.
-
     // This method will always return a non-null Logger object.
     // Synchronization is not required here. All synchronization for
     // adding a new Logger object is handled by addLogger().
-    Logger demandLogger(String name) {
+    //
+    // This method must delegate to the LogManager implementation to
+    // add a new Logger or return the one that has been added previously
+    // as a LogManager subclass may override the addLogger, getLogger,
+    // readConfiguration, and other methods.
+    Logger demandLogger(String name, String resourceBundleName) {
         Logger result = getLogger(name);
         if (result == null) {
             // only allocate the new logger once
-            Logger newLogger = new Logger(name, null);
+            Logger newLogger = new Logger(name, resourceBundleName);
             do {
                 if (addLogger(newLogger)) {
                     // We successfully added the new Logger that we
@@ -413,24 +465,249 @@
         return result;
     }
 
-    // If logger.getUseParentHandlers() returns 'true' and any of the logger's
-    // parents have levels or handlers defined, make sure they are instantiated.
-    private void processParentHandlers(Logger logger, String name) {
-        int ix = 1;
-        for (;;) {
-            int ix2 = name.indexOf(".", ix);
-            if (ix2 < 0) {
-                break;
+    Logger demandSystemLogger(String name, String resourceBundleName) {
+        // Add a system logger in the system context's namespace
+        final Logger sysLogger = systemContext.demandLogger(name, resourceBundleName);
+
+        // Add the system logger to the LogManager's namespace if not exist
+        // so that there is only one single logger of the given name.
+        // System loggers are visible to applications unless a logger of
+        // the same name has been added.
+        Logger logger;
+        do {
+            // First attempt to call addLogger instead of getLogger
+            // This would avoid potential bug in custom LogManager.getLogger
+            // implementation that adds a logger if does not exist
+            if (addLogger(sysLogger)) {
+                // successfully added the new system logger
+                logger = sysLogger;
+            } else {
+                logger = getLogger(name);
+            }
+        } while (logger == null);
+
+        // LogManager will set the sysLogger's handlers via LogManager.addLogger method.
+        if (logger != sysLogger && sysLogger.getHandlers().length == 0) {
+            // if logger already exists but handlers not set
+            final Logger l = logger;
+            AccessController.doPrivileged(new PrivilegedAction<Void>() {
+                public Void run() {
+                    for (Handler hdl : l.getHandlers()) {
+                        sysLogger.addHandler(hdl);
+                    }
+                    return null;
+                }
+            });
+        }
+        return sysLogger;
+    }
+
+    // LoggerContext maintains the logger namespace per context.
+    // The default LogManager implementation has one system context and user
+    // context.  The system context is used to maintain the namespace for
+    // all system loggers and is queried by the system code.  If a system logger
+    // doesn't exist in the user context, it'll also be added to the user context.
+    // The user context is queried by the user code and all other loggers are
+    // added in the user context.
+    static class LoggerContext {
+        // Table of named Loggers that maps names to Loggers.
+        private final Hashtable<String,LoggerWeakRef> namedLoggers = new Hashtable<>();
+        // Tree of named Loggers
+        private final LogNode root;
+
+        private LoggerContext() {
+            this.root = new LogNode(null, this);
+        }
+
+        Logger demandLogger(String name, String resourceBundleName) {
+            // a LogManager subclass may have its own implementation to add and
+            // get a Logger.  So delegate to the LogManager to do the work.
+            return manager.demandLogger(name, resourceBundleName);
+        }
+
+        synchronized Logger findLogger(String name) {
+            LoggerWeakRef ref = namedLoggers.get(name);
+            if (ref == null) {
+                return null;
+            }
+            Logger logger = ref.get();
+            if (logger == null) {
+                // Hashtable holds stale weak reference
+                // to a logger which has been GC-ed.
+                removeLogger(name);
+            }
+            return logger;
+        }
+
+        // Add a logger to this context.  This method will only set its level
+        // and process parent loggers.  It doesn't set its handlers.
+        synchronized boolean addLocalLogger(Logger logger) {
+            final String name = logger.getName();
+            if (name == null) {
+                throw new NullPointerException();
+            }
+
+            // cleanup some Loggers that have been GC'ed
+            manager.drainLoggerRefQueueBounded();
+
+            LoggerWeakRef ref = namedLoggers.get(name);
+            if (ref != null) {
+                if (ref.get() == null) {
+                    // It's possible that the Logger was GC'ed after the
+                    // drainLoggerRefQueueBounded() call above so allow
+                    // a new one to be registered.
+                    removeLogger(name);
+                } else {
+                    // We already have a registered logger with the given name.
+                    return false;
+                }
+            }
+
+            // We're adding a new logger.
+            // Note that we are creating a weak reference here.
+            ref = manager.new LoggerWeakRef(logger);
+            namedLoggers.put(name, ref);
+
+            // Apply any initial level defined for the new logger.
+            Level level = manager.getLevelProperty(name + ".level", null);
+            if (level != null) {
+                doSetLevel(logger, level);
             }
-            String pname = name.substring(0,ix2);
+
+            // instantiation of the handler is done in the LogManager.addLogger
+            // implementation as a handler class may be only visible to LogManager
+            // subclass for the custom log manager case
+            processParentHandlers(logger, name);
+
+            // Find the new node and its parent.
+            LogNode node = getNode(name);
+            node.loggerRef = ref;
+            Logger parent = null;
+            LogNode nodep = node.parent;
+            while (nodep != null) {
+                LoggerWeakRef nodeRef = nodep.loggerRef;
+                if (nodeRef != null) {
+                    parent = nodeRef.get();
+                    if (parent != null) {
+                        break;
+                    }
+                }
+                nodep = nodep.parent;
+            }
+
+            if (parent != null) {
+                doSetParent(logger, parent);
+            }
+            // Walk over the children and tell them we are their new parent.
+            node.walkAndSetParent(logger);
+            // new LogNode is ready so tell the LoggerWeakRef about it
+            ref.setNode(node);
+            return true;
+        }
+
+        void removeLogger(String name) {
+            namedLoggers.remove(name);
+        }
+
+        synchronized Enumeration<String> getLoggerNames() {
+            return namedLoggers.keys();
+        }
+
+        // If logger.getUseParentHandlers() returns 'true' and any of the logger's
+        // parents have levels or handlers defined, make sure they are instantiated.
+        private void processParentHandlers(final Logger logger, final String name) {
+            AccessController.doPrivileged(new PrivilegedAction<Void>() {
+                public Void run() {
+                    if (logger != manager.rootLogger) {
+                        boolean useParent = manager.getBooleanProperty(name + ".useParentHandlers", true);
+                        if (!useParent) {
+                            logger.setUseParentHandlers(false);
+                        }
+                    }
+                    return null;
+                }
+            });
 
-            if (getProperty(pname+".level")    != null ||
-                getProperty(pname+".handlers") != null) {
-                // This pname has a level/handlers definition.
-                // Make sure it exists.
-                demandLogger(pname);
+            int ix = 1;
+            for (;;) {
+                int ix2 = name.indexOf(".", ix);
+                if (ix2 < 0) {
+                    break;
+                }
+                String pname = name.substring(0, ix2);
+                if (manager.getProperty(pname + ".level") != null ||
+                    manager.getProperty(pname + ".handlers") != null) {
+                    // This pname has a level/handlers definition.
+                    // Make sure it exists.
+                    demandLogger(pname, null);
+                }
+                ix = ix2+1;
+            }
+        }
+
+        // Gets a node in our tree of logger nodes.
+        // If necessary, create it.
+        LogNode getNode(String name) {
+            if (name == null || name.equals("")) {
+                return root;
             }
-            ix = ix2+1;
+            LogNode node = root;
+            while (name.length() > 0) {
+                int ix = name.indexOf(".");
+                String head;
+                if (ix > 0) {
+                    head = name.substring(0, ix);
+                    name = name.substring(ix + 1);
+                } else {
+                    head = name;
+                    name = "";
+                }
+                if (node.children == null) {
+                    node.children = new HashMap<>();
+                }
+                LogNode child = node.children.get(head);
+                if (child == null) {
+                    child = new LogNode(node, this);
+                    node.children.put(head, child);
+                }
+                node = child;
+            }
+            return node;
+        }
+    }
+
+    static class SystemLoggerContext extends LoggerContext {
+        // Add a system logger in the system context's namespace as well as
+        // in the LogManager's namespace if not exist so that there is only
+        // one single logger of the given name.  System loggers are visible
+        // to applications unless a logger of the same name has been added.
+        Logger demandLogger(String name, String resourceBundleName) {
+            Logger result = findLogger(name);
+            if (result == null) {
+                // only allocate the new system logger once
+                Logger newLogger = new Logger(name, resourceBundleName);
+                do {
+                    if (addLocalLogger(newLogger)) {
+                        // We successfully added the new Logger that we
+                        // created above so return it without refetching.
+                        result = newLogger;
+                    } else {
+                        // We didn't add the new Logger that we created above
+                        // because another thread added a Logger with the same
+                        // name after our null check above and before our call
+                        // to addLogger(). We have to refetch the Logger because
+                        // addLogger() returns a boolean instead of the Logger
+                        // reference itself. However, if the thread that created
+                        // the other Logger is not holding a strong reference to
+                        // the other Logger, then it is possible for the other
+                        // Logger to be GC'ed after we saw it in addLogger() and
+                        // before we can refetch it. If it has been GC'ed then
+                        // we'll just loop around and try again.
+                        result = findLogger(name);
+                    }
+                } while (result == null);
+            }
+            return result;
         }
     }
 
@@ -439,32 +716,27 @@
     // be made based on the logging configuration, which can
     // only be modified by trusted code.
     private void loadLoggerHandlers(final Logger logger, final String name,
-                                    final String handlersPropertyName) {
+                                    final String handlersPropertyName)
+    {
         AccessController.doPrivileged(new PrivilegedAction<Object>() {
             public Object run() {
-                if (logger != rootLogger) {
-                    boolean useParent = getBooleanProperty(name + ".useParentHandlers", true);
-                    if (!useParent) {
-                        logger.setUseParentHandlers(false);
-                    }
-                }
-
                 String names[] = parseClassNames(handlersPropertyName);
                 for (int i = 0; i < names.length; i++) {
                     String word = names[i];
                     try {
                         Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word);
-                        Handler  hdl = (Handler) clz.newInstance();
-                        try {
-                            // Check if there is a property defining the
-                            // this handler's level.
-                            String levs = getProperty(word + ".level");
-                            if (levs != null) {
-                                hdl.setLevel(Level.parse(levs));
+                        Handler hdl = (Handler) clz.newInstance();
+                        // Check if there is a property defining the
+                        // this handler's level.
+                        String levs = getProperty(word + ".level");
+                        if (levs != null) {
+                            Level l = Level.findLevel(levs);
+                            if (l != null) {
+                                hdl.setLevel(l);
+                            } else {
+                                // Probably a bad level. Drop through.
+                                System.err.println("Can't set level for " + word);
                             }
-                        } catch (Exception ex) {
-                            System.err.println("Can't set level for " + word);
-                            // Probably a bad level. Drop through.
                         }
                         // Add this Handler to the logger
                         logger.addHandler(hdl);
@@ -475,7 +747,8 @@
                     }
                 }
                 return null;
-            }});
+            }
+        });
     }
 
 
@@ -520,7 +793,7 @@
             if (node != null) {
                 // if we have a LogNode, then we were a named Logger
                 // so clear namedLoggers weak ref to us
-                manager.namedLoggers.remove(name);
+                node.context.removeLogger(name);
                 name = null;  // clear our ref to the Logger's name
 
                 node.loggerRef = null;  // clear LogNode's weak ref to us
@@ -609,73 +882,22 @@
      *          false if a logger of that name already exists.
      * @exception NullPointerException if the logger name is null.
      */
-    public synchronized boolean addLogger(Logger logger) {
+    public boolean addLogger(Logger logger) {
         final String name = logger.getName();
         if (name == null) {
             throw new NullPointerException();
         }
-
-        // cleanup some Loggers that have been GC'ed
-        drainLoggerRefQueueBounded();
-
-        LoggerWeakRef ref = namedLoggers.get(name);
-        if (ref != null) {
-            if (ref.get() == null) {
-                // It's possible that the Logger was GC'ed after the
-                // drainLoggerRefQueueBounded() call above so allow
-                // a new one to be registered.
-                namedLoggers.remove(name);
-            } else {
-                // We already have a registered logger with the given name.
-                return false;
-            }
-        }
-
-        // We're adding a new logger.
-        // Note that we are creating a weak reference here.
-        ref = new LoggerWeakRef(logger);
-        namedLoggers.put(name, ref);
-
-        // Apply any initial level defined for the new logger.
-        Level level = getLevelProperty(name+".level", null);
-        if (level != null) {
-            doSetLevel(logger, level);
+        LoggerContext cx = getUserContext();
+        if (cx.addLocalLogger(logger)) {
+            // Do we have a per logger handler too?
+            // Note: this will add a 200ms penalty
+            loadLoggerHandlers(logger, name, name + ".handlers");
+            return true;
+        } else {
+            return false;
         }
-
-        // Do we have a per logger handler too?
-        // Note: this will add a 200ms penalty
-        loadLoggerHandlers(logger, name, name+".handlers");
-        processParentHandlers(logger, name);
-
-        // Find the new node and its parent.
-        LogNode node = findNode(name);
-        node.loggerRef = ref;
-        Logger parent = null;
-        LogNode nodep = node.parent;
-        while (nodep != null) {
-            LoggerWeakRef nodeRef = nodep.loggerRef;
-            if (nodeRef != null) {
-                parent = nodeRef.get();
-                if (parent != null) {
-                    break;
-                }
-            }
-            nodep = nodep.parent;
-        }
-
-        if (parent != null) {
-            doSetParent(logger, parent);
-        }
-        // Walk over the children and tell them we are their new parent.
-        node.walkAndSetParent(logger);
-
-        // new LogNode is ready so tell the LoggerWeakRef about it
-        ref.setNode(node);
-
-        return true;
     }
 
-
     // Private method to set a level on a logger.
     // If necessary, we raise privilege before doing the call.
     private static void doSetLevel(final Logger logger, final Level level) {
@@ -694,8 +916,6 @@
             }});
     }
 
-
-
     // Private method to set a parent on a logger.
     // If necessary, we raise privilege before doing the setParent call.
     private static void doSetParent(final Logger logger, final Logger parent) {
@@ -714,36 +934,6 @@
             }});
     }
 
-    // Find a node in our tree of logger nodes.
-    // If necessary, create it.
-    private LogNode findNode(String name) {
-        if (name == null || name.equals("")) {
-            return root;
-        }
-        LogNode node = root;
-        while (name.length() > 0) {
-            int ix = name.indexOf(".");
-            String head;
-            if (ix > 0) {
-                head = name.substring(0,ix);
-                name = name.substring(ix+1);
-            } else {
-                head = name;
-                name = "";
-            }
-            if (node.children == null) {
-                node.children = new HashMap<>();
-            }
-            LogNode child = node.children.get(head);
-            if (child == null) {
-                child = new LogNode(node);
-                node.children.put(head, child);
-            }
-            node = child;
-        }
-        return node;
-    }
-
     /**
      * Method to find a named logger.
      * <p>
@@ -759,18 +949,8 @@
      * @param name name of the logger
      * @return  matching logger or null if none is found
      */
-    public synchronized Logger getLogger(String name) {
-        LoggerWeakRef ref = namedLoggers.get(name);
-        if (ref == null) {
-            return null;
-        }
-        Logger logger = ref.get();
-        if (logger == null) {
-            // Hashtable holds stale weak reference
-            // to a logger which has been GC-ed.
-            namedLoggers.remove(name);
-        }
-        return logger;
+    public Logger getLogger(String name) {
+        return getUserContext().findLogger(name);
     }
 
     /**
@@ -789,8 +969,8 @@
      * <p>
      * @return  enumeration of logger name strings
      */
-    public synchronized Enumeration<String> getLoggerNames() {
-        return namedLoggers.keys();
+    public Enumeration<String> getLoggerNames() {
+        return getUserContext().getLoggerNames();
     }
 
     /**
@@ -875,20 +1055,20 @@
             // the global handlers, if they haven't been initialized yet.
             initializedGlobalHandlers = true;
         }
-        Enumeration<String> enum_ = getLoggerNames();
-        while (enum_.hasMoreElements()) {
-            String name = enum_.nextElement();
-            resetLogger(name);
+        for (LoggerContext cx : contexts()) {
+            Enumeration<String> enum_ = cx.getLoggerNames();
+            while (enum_.hasMoreElements()) {
+                String name = enum_.nextElement();
+                Logger logger = cx.findLogger(name);
+                if (logger != null) {
+                    resetLogger(logger);
+                }
+            }
         }
     }
 
-
     // Private method to reset an individual target logger.
-    private void resetLogger(String name) {
-        Logger logger = getLogger(name);
-        if (logger == null) {
-            return;
-        }
+    private void resetLogger(Logger logger) {
         // Close all the Logger's handlers.
         Handler[] targets = logger.getHandlers();
         for (int i = 0; i < targets.length; i++) {
@@ -900,6 +1080,7 @@
                 // Problems closing a handler?  Keep going...
             }
         }
+        String name = logger.getName();
         if (name != null && name.equals("")) {
             // This is the root logger.
             logger.setLevel(defaultLevel);
@@ -1065,11 +1246,8 @@
         if (val == null) {
             return defaultValue;
         }
-        try {
-            return Level.parse(val.trim());
-        } catch (Exception ex) {
-            return defaultValue;
-        }
+        Level l = Level.findLevel(val.trim());
+        return l != null ? l : defaultValue;
     }
 
     // Package private method to get a filter property.
@@ -1159,9 +1337,11 @@
         HashMap<String,LogNode> children;
         LoggerWeakRef loggerRef;
         LogNode parent;
+        final LoggerContext context;
 
-        LogNode(LogNode parent) {
+        LogNode(LogNode parent, LoggerContext context) {
             this.parent = parent;
+            this.context = context;
         }
 
         // Recursive method to walk the tree below a node and set
@@ -1188,7 +1368,6 @@
     // that we only instantiate the global handlers when they
     // are first needed.
     private class RootLogger extends Logger {
-
         private RootLogger() {
             super("", null);
             setLevel(defaultLevel);
@@ -1234,11 +1413,13 @@
                 System.err.println("Bad level value for property: " + key);
                 continue;
             }
-            Logger l = getLogger(name);
-            if (l == null) {
-                continue;
+            for (LoggerContext cx : contexts()) {
+                Logger l = cx.findLogger(name);
+                if (l == null) {
+                    continue;
+                }
+                l.setLevel(level);
             }
-            l.setLevel(level);
         }
     }
 
--- a/jdk/src/share/classes/java/util/logging/Logger.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/util/logging/Logger.java	Fri Mar 15 23:31:19 2013 -0700
@@ -27,6 +27,8 @@
 package java.util.logging;
 
 import java.lang.ref.WeakReference;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.Locale;
@@ -311,6 +313,40 @@
         }
     }
 
+    // Until all JDK code converted to call sun.util.logging.PlatformLogger
+    // (see 7054233), we need to determine if Logger.getLogger is to add
+    // a system logger or user logger.
+    //
+    // As an interim solution, if the immediate caller whose caller loader is
+    // null, we assume it's a system logger and add it to the system context.
+    // These system loggers only set the resource bundle to the given
+    // resource bundle name (rather than the default system resource bundle).
+    private static class SystemLoggerHelper {
+        static boolean disableCallerCheck = getBooleanProperty("sun.util.logging.disableCallerCheck");
+        private static boolean getBooleanProperty(final String key) {
+            String s = AccessController.doPrivileged(new PrivilegedAction<String>() {
+                public String run() {
+                    return System.getProperty(key);
+                }
+            });
+            return Boolean.valueOf(s);
+        }
+    }
+
+    private static Logger demandLogger(String name, String resourceBundleName) {
+        LogManager manager = LogManager.getLogManager();
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null && !SystemLoggerHelper.disableCallerCheck) {
+            // 0: Reflection 1: Logger.demandLogger 2: Logger.getLogger 3: caller
+            final int SKIP_FRAMES = 3;
+            Class<?> caller = sun.reflect.Reflection.getCallerClass(SKIP_FRAMES);
+            if (caller.getClassLoader() == null) {
+                return manager.demandSystemLogger(name, resourceBundleName);
+            }
+        }
+        return manager.demandLogger(name, resourceBundleName);
+    }
+
     /**
      * Find or create a logger for a named subsystem.  If a logger has
      * already been created with the given name it is returned.  Otherwise
@@ -352,8 +388,7 @@
         // would throw an IllegalArgumentException in the second call
         // because the wrapper would result in an attempt to replace
         // the existing "resourceBundleForFoo" with null.
-        LogManager manager = LogManager.getLogManager();
-        return manager.demandLogger(name);
+        return demandLogger(name, null);
     }
 
     /**
@@ -400,8 +435,7 @@
     // Synchronization is not required here. All synchronization for
     // adding a new Logger object is handled by LogManager.addLogger().
     public static Logger getLogger(String name, String resourceBundleName) {
-        LogManager manager = LogManager.getLogManager();
-        Logger result = manager.demandLogger(name);
+        Logger result = demandLogger(name, resourceBundleName);
 
         // MissingResourceException or IllegalArgumentException can be
         // thrown by setupResourceInfo().
@@ -409,6 +443,17 @@
         return result;
     }
 
+    // package-private
+    // Add a platform logger to the system context.
+    // i.e. caller of sun.util.logging.PlatformLogger.getLogger
+    static Logger getPlatformLogger(String name) {
+        LogManager manager = LogManager.getLogManager();
+
+        // all loggers in the system context will default to
+        // the system logger's resource bundle
+        Logger result = manager.demandSystemLogger(name, SYSTEM_LOGGER_RB_NAME);
+        return result;
+    }
 
     /**
      * Create an anonymous Logger.  The newly created Logger is not
@@ -561,7 +606,7 @@
     private void doLog(LogRecord lr) {
         lr.setLoggerName(name);
         String ebname = getEffectiveResourceBundleName();
-        if (ebname != null) {
+        if (ebname != null && !ebname.equals(SYSTEM_LOGGER_RB_NAME)) {
             lr.setResourceBundleName(ebname);
             lr.setResourceBundle(findResourceBundle(ebname));
         }
@@ -1538,6 +1583,23 @@
         return useParentHandlers;
     }
 
+    static final String SYSTEM_LOGGER_RB_NAME = "sun.util.logging.resources.logging";
+
+    private static ResourceBundle findSystemResourceBundle(final Locale locale) {
+        // the resource bundle is in a restricted package
+        return AccessController.doPrivileged(new PrivilegedAction<ResourceBundle>() {
+            public ResourceBundle run() {
+                try {
+                    return ResourceBundle.getBundle(SYSTEM_LOGGER_RB_NAME,
+                                                    locale,
+                                                    ClassLoader.getSystemClassLoader());
+                } catch (MissingResourceException e) {
+                    throw new InternalError(e.toString());
+                }
+            }
+        });
+    }
+
     /**
      * Private utility method to map a resource bundle name to an
      * actual resource bundle, using a simple one-entry cache.
@@ -1562,6 +1624,13 @@
             return catalog;
         }
 
+        if (name.equals(SYSTEM_LOGGER_RB_NAME)) {
+            catalog = findSystemResourceBundle(currentLocale);
+            catalogName = name;
+            catalogLocale = currentLocale;
+            return catalog;
+        }
+
         // Use the thread's context ClassLoader.  If there isn't one, use the
         // {@linkplain java.lang.ClassLoader#getSystemClassLoader() system ClassLoader}.
         ClassLoader cl = Thread.currentThread().getContextClassLoader();
--- a/jdk/src/share/classes/java/util/logging/Logging.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/util/logging/Logging.java	Fri Mar 15 23:31:19 2013 -0700
@@ -34,7 +34,7 @@
  *
  * The <tt>LoggingMXBean</tt> interface provides a standard
  * method for management access to the individual
- * java.util.Logger objects available at runtime.
+ * {@code Logger} objects available at runtime.
  *
  * @author Ron Mann
  * @author Mandy Chung
@@ -75,7 +75,7 @@
         if (level == null) {
             return EMPTY_STRING;
         } else {
-            return level.getName();
+            return level.getLevelName();
         }
     }
 
@@ -85,7 +85,6 @@
         }
 
         Logger logger = logManager.getLogger(loggerName);
-
         if (logger == null) {
             throw new IllegalArgumentException("Logger " + loggerName +
                 "does not exist");
@@ -94,7 +93,10 @@
         Level level = null;
         if (levelName != null) {
             // parse will throw IAE if logLevel is invalid
-            level = Level.parse(levelName);
+            level = Level.findLevel(levelName);
+            if (level == null) {
+                throw new IllegalArgumentException("Unknown level \"" + levelName + "\"");
+            }
         }
 
         logger.setLevel(level);
--- a/jdk/src/share/classes/java/util/logging/LoggingProxyImpl.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/util/logging/LoggingProxyImpl.java	Fri Mar 15 23:31:19 2013 -0700
@@ -37,7 +37,8 @@
 
     @Override
     public Object getLogger(String name) {
-        return Logger.getLogger(name);
+        // always create a platform logger with the resource bundle name
+        return Logger.getPlatformLogger(name);
     }
 
     @Override
@@ -92,12 +93,16 @@
 
     @Override
     public Object parseLevel(String levelName) {
-        return Level.parse(levelName);
+        Level level = Level.findLevel(levelName);
+        if (level == null) {
+            throw new IllegalArgumentException("Unknown level \"" + levelName + "\"");
+        }
+        return level;
     }
 
     @Override
     public String getLevelName(Object level) {
-        return ((Level) level).getName();
+        return ((Level) level).getLevelName();
     }
 
     @Override
--- a/jdk/src/share/classes/java/util/logging/SimpleFormatter.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/java/util/logging/SimpleFormatter.java	Fri Mar 15 23:31:19 2013 -0700
@@ -162,7 +162,7 @@
                              dat,
                              source,
                              record.getLoggerName(),
-                             record.getLevel().getLocalizedName(),
+                             record.getLevel().getLocalizedLevelName(),
                              message,
                              throwable);
     }
--- a/jdk/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/javax/management/modelmbean/RequiredModelMBean.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2008, 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
@@ -39,11 +39,13 @@
 import java.lang.reflect.InvocationTargetException;
 
 import java.lang.reflect.Method;
+import java.security.AccessControlContext;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
 
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.logging.Level;
 import java.util.Map;
 import java.util.Set;
@@ -78,6 +80,8 @@
 import javax.management.RuntimeOperationsException;
 import javax.management.ServiceNotFoundException;
 import javax.management.loading.ClassLoaderRepository;
+import sun.misc.JavaSecurityAccess;
+import sun.misc.SharedSecrets;
 
 import sun.reflect.misc.MethodUtil;
 import sun.reflect.misc.ReflectUtil;
@@ -138,6 +142,9 @@
     private boolean registered = false;
     private transient MBeanServer server = null;
 
+    private final static JavaSecurityAccess javaSecurityAccess = SharedSecrets.getJavaSecurityAccess();
+    final private AccessControlContext acc = AccessController.getContext();
+
     /*************************************/
     /* constructors                      */
     /*************************************/
@@ -1025,10 +1032,31 @@
 
             if (opClassName != null) {
                 try {
-                    final ClassLoader targetClassLoader =
-                        targetObject.getClass().getClassLoader();
-                    targetClass = Class.forName(opClassName, false,
-                                                targetClassLoader);
+                    AccessControlContext stack = AccessController.getContext();
+                    final Object obj = targetObject;
+                    final String className = opClassName;
+                    final ClassNotFoundException[] caughtException = new ClassNotFoundException[1];
+
+                    targetClass = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {
+
+                        @Override
+                        public Class<?> run() {
+                            try {
+                                ReflectUtil.checkPackageAccess(className);
+                                final ClassLoader targetClassLoader =
+                                    obj.getClass().getClassLoader();
+                                return Class.forName(className, false,
+                                                            targetClassLoader);
+                            } catch (ClassNotFoundException e) {
+                                caughtException[0] = e;
+                            }
+                            return null;
+                        }
+                    }, stack, acc);
+
+                    if (caughtException[0] != null) {
+                        throw caughtException[0];
+                    }
                 } catch (ClassNotFoundException e) {
                     final String msg =
                         "class for invoke " + opName + " not found";
@@ -1061,9 +1089,9 @@
         return result;
     }
 
-    private static Method resolveMethod(Class<?> targetClass,
+    private Method resolveMethod(Class<?> targetClass,
                                         String opMethodName,
-                                        String[] sig)
+                                        final String[] sig)
             throws ReflectionException {
         final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER);
 
@@ -1078,30 +1106,45 @@
         if (sig == null)
             argClasses = null;
         else {
+            final AccessControlContext stack = AccessController.getContext();
+            final ReflectionException[] caughtException = new ReflectionException[1];
             final ClassLoader targetClassLoader = targetClass.getClassLoader();
             argClasses = new Class<?>[sig.length];
-            for (int i = 0; i < sig.length; i++) {
-                if (tracing) {
-                    MODELMBEAN_LOGGER.logp(Level.FINER,
-                        RequiredModelMBean.class.getName(),"resolveMethod",
-                            "resolve type " + sig[i]);
-                }
-                argClasses[i] = (Class<?>) primitiveClassMap.get(sig[i]);
-                if (argClasses[i] == null) {
-                    try {
-                        argClasses[i] =
-                            Class.forName(sig[i], false, targetClassLoader);
-                    } catch (ClassNotFoundException e) {
+
+            javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Void>() {
+
+                @Override
+                public Void run() {
+                    for (int i = 0; i < sig.length; i++) {
                         if (tracing) {
                             MODELMBEAN_LOGGER.logp(Level.FINER,
-                                    RequiredModelMBean.class.getName(),
-                                    "resolveMethod",
-                                    "class not found");
+                                RequiredModelMBean.class.getName(),"resolveMethod",
+                                    "resolve type " + sig[i]);
                         }
-                        final String msg = "Parameter class not found";
-                        throw new ReflectionException(e, msg);
+                        argClasses[i] = (Class<?>) primitiveClassMap.get(sig[i]);
+                        if (argClasses[i] == null) {
+                            try {
+                                ReflectUtil.checkPackageAccess(sig[i]);
+                                argClasses[i] =
+                                    Class.forName(sig[i], false, targetClassLoader);
+                            } catch (ClassNotFoundException e) {
+                                if (tracing) {
+                                    MODELMBEAN_LOGGER.logp(Level.FINER,
+                                            RequiredModelMBean.class.getName(),
+                                            "resolveMethod",
+                                            "class not found");
+                                }
+                                final String msg = "Parameter class not found";
+                                caughtException[0] = new ReflectionException(e, msg);
+                            }
+                        }
                     }
+                    return null;
                 }
+            }, stack, acc);
+
+            if (caughtException[0] != null) {
+                throw caughtException[0];
             }
         }
 
@@ -1133,7 +1176,7 @@
     /* Find a method in RequiredModelMBean as determined by the given
        parameters.  Return null if there is none, or if the parameters
        exclude using it.  Called from invoke. */
-    private static Method findRMMBMethod(String opMethodName,
+    private Method findRMMBMethod(String opMethodName,
                                          Object targetObjectField,
                                          String opClassName,
                                          String[] sig) {
@@ -1155,19 +1198,29 @@
         if (opClassName == null)
             targetClass = rmmbClass;
         else {
-            try {
-                final ClassLoader targetClassLoader =
-                    rmmbClass.getClassLoader();
-                targetClass = Class.forName(opClassName, false,
-                                            targetClassLoader);
-                if (!rmmbClass.isAssignableFrom(targetClass))
-                    return null;
-            } catch (ClassNotFoundException e) {
-                return null;
-            }
+            AccessControlContext stack = AccessController.getContext();
+            final String className = opClassName;
+            targetClass = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {
+
+                @Override
+                public Class<?> run() {
+                    try {
+                        ReflectUtil.checkPackageAccess(className);
+                        final ClassLoader targetClassLoader =
+                            rmmbClass.getClassLoader();
+                        Class clz = Class.forName(className, false,
+                                                    targetClassLoader);
+                        if (!rmmbClass.isAssignableFrom(clz))
+                            return null;
+                        return clz;
+                    } catch (ClassNotFoundException e) {
+                        return null;
+                    }
+                }
+            }, stack, acc);
         }
         try {
-            return resolveMethod(targetClass, opMethodName, sig);
+            return targetClass != null ? resolveMethod(targetClass, opMethodName, sig) : null;
         } catch (ReflectionException e) {
             return null;
         }
@@ -1177,12 +1230,35 @@
      * Invoke the given method, and throw the somewhat unpredictable
      * appropriate exception if the method itself gets an exception.
      */
-    private Object invokeMethod(String opName, Method method,
-                                Object targetObject, Object[] opArgs)
+    private Object invokeMethod(String opName, final Method method,
+                                final Object targetObject, final Object[] opArgs)
             throws MBeanException, ReflectionException {
         try {
-            ReflectUtil.checkPackageAccess(method.getDeclaringClass());
-            return MethodUtil.invoke(method, targetObject, opArgs);
+            final Throwable[] caughtException = new Throwable[1];
+            AccessControlContext stack = AccessController.getContext();
+            Object rslt = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Object>() {
+
+                @Override
+                public Object run() {
+                    try {
+                        ReflectUtil.checkPackageAccess(method.getDeclaringClass());
+                        return MethodUtil.invoke(method, targetObject, opArgs);
+                    } catch (InvocationTargetException e) {
+                        caughtException[0] = e;
+                    } catch (IllegalAccessException e) {
+                        caughtException[0] = e;
+                    }
+                    return null;
+                }
+            }, stack, acc);
+            if (caughtException[0] != null) {
+                if (caughtException[0] instanceof Exception) {
+                    throw (Exception)caughtException[0];
+                } else if(caughtException[0] instanceof Error) {
+                    throw (Error)caughtException[0];
+                }
+            }
+            return rslt;
         } catch (RuntimeErrorException ree) {
             throw new RuntimeOperationsException(ree,
                       "RuntimeException occurred in RequiredModelMBean "+
@@ -1567,7 +1643,7 @@
                 }
 
                 // make sure response class matches type field
-                String respType = attrInfo.getType();
+                final String respType = attrInfo.getType();
                 if (response != null) {
                     String responseClass = response.getClass().getName();
                     if (!respType.equals(responseClass)) {
@@ -1590,9 +1666,31 @@
                             // inequality may come from type subclassing
                             boolean subtype;
                             try {
-                                ClassLoader cl =
-                                    response.getClass().getClassLoader();
-                                Class<?> c = Class.forName(respType, true, cl);
+                                final Class respClass = response.getClass();
+                                final Exception[] caughException = new Exception[1];
+
+                                AccessControlContext stack = AccessController.getContext();
+
+                                Class c = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {
+
+                                    @Override
+                                    public Class<?> run() {
+                                        try {
+                                            ReflectUtil.checkPackageAccess(respType);
+                                            ClassLoader cl =
+                                                respClass.getClassLoader();
+                                            return Class.forName(respType, true, cl);
+                                        } catch (Exception e) {
+                                            caughException[0] = e;
+                                        }
+                                        return null;
+                                    }
+                                }, stack, acc);
+
+                                if (caughException[0] != null) {
+                                    throw caughException[0];
+                                }
+
                                 subtype = c.isInstance(response);
                             } catch (Exception e) {
                                 subtype = false;
@@ -2745,16 +2843,37 @@
         return MBeanServerFactory.getClassLoaderRepository(server);
     }
 
-    private Class<?> loadClass(String className)
+    private Class<?> loadClass(final String className)
         throws ClassNotFoundException {
-        try {
-            return Class.forName(className);
-        } catch (ClassNotFoundException e) {
-            final ClassLoaderRepository clr =
-                getClassLoaderRepository();
-            if (clr == null) throw new ClassNotFoundException(className);
-            return clr.loadClass(className);
+        AccessControlContext stack = AccessController.getContext();
+        final ClassNotFoundException[] caughtException = new ClassNotFoundException[1];
+
+        Class c = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {
+
+            @Override
+            public Class<?> run() {
+                try {
+                    ReflectUtil.checkPackageAccess(className);
+                    return Class.forName(className);
+                } catch (ClassNotFoundException e) {
+                    final ClassLoaderRepository clr =
+                        getClassLoaderRepository();
+                    try {
+                        if (clr == null) throw new ClassNotFoundException(className);
+                        return clr.loadClass(className);
+                    } catch (ClassNotFoundException ex) {
+                        caughtException[0] = ex;
+                    }
+                }
+                return null;
+            }
+        }, stack, acc);
+
+        if (caughtException[0] != null) {
+            throw caughtException[0];
         }
+
+        return c;
     }
 
 
--- a/jdk/src/share/classes/javax/swing/JFrame.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/javax/swing/JFrame.java	Fri Mar 15 23:31:19 2013 -0700
@@ -387,13 +387,14 @@
             operation != EXIT_ON_CLOSE) {
             throw new IllegalArgumentException("defaultCloseOperation must be one of: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE, DISPOSE_ON_CLOSE, or EXIT_ON_CLOSE");
         }
+
+        if (operation == EXIT_ON_CLOSE) {
+            SecurityManager security = System.getSecurityManager();
+            if (security != null) {
+                security.checkExit(0);
+            }
+        }
         if (this.defaultCloseOperation != operation) {
-            if (operation == EXIT_ON_CLOSE) {
-                SecurityManager security = System.getSecurityManager();
-                if (security != null) {
-                    security.checkExit(0);
-                }
-            }
             int oldValue = this.defaultCloseOperation;
             this.defaultCloseOperation = operation;
             firePropertyChange("defaultCloseOperation", oldValue, operation);
--- a/jdk/src/share/classes/javax/swing/JTable.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/javax/swing/JTable.java	Fri Mar 15 23:31:19 2013 -0700
@@ -781,15 +781,11 @@
                         scrollPane.getCorner(JScrollPane.UPPER_TRAILING_CORNER);
                 if (corner == null || corner instanceof UIResource){
                     corner = null;
-                    Object componentClass = UIManager.get(
-                            "Table.scrollPaneCornerComponent");
-                    if (componentClass instanceof Class){
-                        try {
-                            corner = (Component)
-                                    ((Class)componentClass).newInstance();
-                        } catch (Exception e) {
-                            // just ignore and don't set corner
-                        }
+                    try {
+                        corner = (Component) UIManager.get(
+                                "Table.scrollPaneCornerComponent");
+                    } catch (Exception e) {
+                        // just ignore and don't set corner
                     }
                     scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER,
                             corner);
--- a/jdk/src/share/classes/javax/swing/RepaintManager.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/javax/swing/RepaintManager.java	Fri Mar 15 23:31:19 2013 -0700
@@ -27,11 +27,12 @@
 
 import java.awt.*;
 import java.awt.event.*;
-import java.awt.peer.ComponentPeer;
-import java.awt.peer.ContainerPeer;
 import java.awt.image.VolatileImage;
+import java.security.AccessControlContext;
 import java.security.AccessController;
+import java.security.PrivilegedAction;
 import java.util.*;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.applet.*;
 
 import sun.awt.AWTAccessor;
@@ -39,6 +40,8 @@
 import sun.awt.DisplayChangedListener;
 import sun.awt.SunToolkit;
 import sun.java2d.SunGraphicsEnvironment;
+import sun.misc.JavaSecurityAccess;
+import sun.misc.SharedSecrets;
 import sun.security.action.GetPropertyAction;
 
 import com.sun.java.swing.SwingUtilities3;
@@ -176,6 +179,9 @@
      */
     private final ProcessingRunnable processingRunnable;
 
+    private final static JavaSecurityAccess javaSecurityAccess =
+        SharedSecrets.getJavaSecurityAccess();
+
 
     static {
         volatileImageBufferEnabled = "true".equals(AccessController.
@@ -548,13 +554,26 @@
     // This is called from the toolkit thread when awt needs to run a
     // Runnable before we paint.
     //
-    void nativeQueueSurfaceDataRunnable(AppContext appContext, Component c,
-                                        Runnable r) {
+    void nativeQueueSurfaceDataRunnable(AppContext appContext,
+                                        final Component c, final Runnable r)
+    {
         synchronized(this) {
             if (runnableList == null) {
                 runnableList = new LinkedList<Runnable>();
             }
-            runnableList.add(r);
+            runnableList.add(new Runnable() {
+                public void run() {
+                    AccessControlContext stack = AccessController.getContext();
+                    AccessControlContext acc =
+                        AWTAccessor.getComponentAccessor().getAccessControlContext(c);
+                    javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Void>() {
+                        public Void run() {
+                            r.run();
+                            return null;
+                        }
+                    }, stack, acc);
+                }
+            });
         }
         scheduleProcessingRunnable(appContext);
     }
@@ -652,9 +671,9 @@
      * @see #addInvalidComponent
      */
     public void validateInvalidComponents() {
-        java.util.List<Component> ic;
+        final java.util.List<Component> ic;
         synchronized(this) {
-            if(invalidComponents == null) {
+            if (invalidComponents == null) {
                 return;
             }
             ic = invalidComponents;
@@ -662,7 +681,17 @@
         }
         int n = ic.size();
         for(int i = 0; i < n; i++) {
-            ic.get(i).validate();
+            final Component c = ic.get(i);
+            AccessControlContext stack = AccessController.getContext();
+            AccessControlContext acc =
+                AWTAccessor.getComponentAccessor().getAccessControlContext(c);
+            javaSecurityAccess.doIntersectionPrivilege(
+                new PrivilegedAction<Void>() {
+                    public Void run() {
+                        c.validate();
+                        return null;
+                    }
+                }, stack, acc);
         }
     }
 
@@ -740,78 +769,78 @@
         paintDirtyRegions(tmpDirtyComponents);
     }
 
-    private void paintDirtyRegions(Map<Component,Rectangle>
-                                   tmpDirtyComponents){
-        int i, count;
-        java.util.List<Component> roots;
-        Component dirtyComponent;
-
-        count = tmpDirtyComponents.size();
-        if (count == 0) {
+    private void paintDirtyRegions(
+        final Map<Component,Rectangle> tmpDirtyComponents)
+    {
+        if (tmpDirtyComponents.isEmpty()) {
             return;
         }
 
-        Rectangle rect;
-        int localBoundsX = 0;
-        int localBoundsY = 0;
-        int localBoundsH;
-        int localBoundsW;
-
-        roots = new ArrayList<Component>(count);
-
+        final java.util.List<Component> roots =
+            new ArrayList<Component>(tmpDirtyComponents.size());
         for (Component dirty : tmpDirtyComponents.keySet()) {
             collectDirtyComponents(tmpDirtyComponents, dirty, roots);
         }
 
-        count = roots.size();
+        final AtomicInteger count = new AtomicInteger(roots.size());
         painting = true;
         try {
-            for(i=0 ; i < count ; i++) {
-                dirtyComponent = roots.get(i);
-                rect = tmpDirtyComponents.get(dirtyComponent);
-                // Sometimes when RepaintManager is changed during the painting
-                // we may get null here, see #6995769 for details
-                if (rect == null) {
-                    continue;
-                }
-                localBoundsH = dirtyComponent.getHeight();
-                localBoundsW = dirtyComponent.getWidth();
+            for (int j=0 ; j < count.get(); j++) {
+                final int i = j;
+                final Component dirtyComponent = roots.get(j);
+                AccessControlContext stack = AccessController.getContext();
+                AccessControlContext acc =
+                    AWTAccessor.getComponentAccessor().getAccessControlContext(dirtyComponent);
+                javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Void>() {
+                    public Void run() {
+                        Rectangle rect = tmpDirtyComponents.get(dirtyComponent);
+                        // Sometimes when RepaintManager is changed during the painting
+                        // we may get null here, see #6995769 for details
+                        if (rect == null) {
+                            return null;
+                        }
 
-                SwingUtilities.computeIntersection(localBoundsX,
-                                                   localBoundsY,
-                                                   localBoundsW,
-                                                   localBoundsH,
-                                                   rect);
-                if (dirtyComponent instanceof JComponent) {
-                    ((JComponent)dirtyComponent).paintImmediately(
-                        rect.x,rect.y,rect.width, rect.height);
-                }
-                else if (dirtyComponent.isShowing()) {
-                    Graphics g = JComponent.safelyGetGraphics(
-                            dirtyComponent, dirtyComponent);
-                    // If the Graphics goes away, it means someone disposed of
-                    // the window, don't do anything.
-                    if (g != null) {
-                        g.setClip(rect.x, rect.y, rect.width, rect.height);
-                        try {
-                            dirtyComponent.paint(g);
-                        } finally {
-                            g.dispose();
+                        int localBoundsH = dirtyComponent.getHeight();
+                        int localBoundsW = dirtyComponent.getWidth();
+                        SwingUtilities.computeIntersection(0,
+                                                           0,
+                                                           localBoundsW,
+                                                           localBoundsH,
+                                                           rect);
+                        if (dirtyComponent instanceof JComponent) {
+                            ((JComponent)dirtyComponent).paintImmediately(
+                                rect.x,rect.y,rect.width, rect.height);
                         }
+                        else if (dirtyComponent.isShowing()) {
+                            Graphics g = JComponent.safelyGetGraphics(
+                                    dirtyComponent, dirtyComponent);
+                            // If the Graphics goes away, it means someone disposed of
+                            // the window, don't do anything.
+                            if (g != null) {
+                                g.setClip(rect.x, rect.y, rect.width, rect.height);
+                                try {
+                                    dirtyComponent.paint(g);
+                                } finally {
+                                    g.dispose();
+                                }
+                            }
+                        }
+                        // If the repaintRoot has been set, service it now and
+                        // remove any components that are children of repaintRoot.
+                        if (repaintRoot != null) {
+                            adjustRoots(repaintRoot, roots, i + 1);
+                            count.set(roots.size());
+                            paintManager.isRepaintingRoot = true;
+                            repaintRoot.paintImmediately(0, 0, repaintRoot.getWidth(),
+                                                         repaintRoot.getHeight());
+                            paintManager.isRepaintingRoot = false;
+                            // Only service repaintRoot once.
+                            repaintRoot = null;
+                        }
+
+                        return null;
                     }
-                }
-                // If the repaintRoot has been set, service it now and
-                // remove any components that are children of repaintRoot.
-                if (repaintRoot != null) {
-                    adjustRoots(repaintRoot, roots, i + 1);
-                    count = roots.size();
-                    paintManager.isRepaintingRoot = true;
-                    repaintRoot.paintImmediately(0, 0, repaintRoot.getWidth(),
-                                                 repaintRoot.getHeight());
-                    paintManager.isRepaintingRoot = false;
-                    // Only service repaintRoot once.
-                    repaintRoot = null;
-                }
+                }, stack, acc);
             }
         } finally {
             painting = false;
--- a/jdk/src/share/classes/javax/swing/SwingUtilities.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/javax/swing/SwingUtilities.java	Fri Mar 15 23:31:19 2013 -0700
@@ -356,7 +356,7 @@
                                       sourceEvent.getYOnScreen(),
                                       sourceEvent.getClickCount(),
                                       sourceEvent.isPopupTrigger(),
-                                      MouseEvent.NOBUTTON );
+                                      sourceEvent.getButton());
         }
         return newEvent;
     }
--- a/jdk/src/share/classes/javax/swing/UIDefaults.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/javax/swing/UIDefaults.java	Fri Mar 15 23:31:19 2013 -0700
@@ -677,6 +677,8 @@
         try {
             String className = (String)get(uiClassID);
             if (className != null) {
+                ReflectUtil.checkPackageAccess(className);
+
                 Class cls = (Class)get(className);
                 if (cls == null) {
                     if (uiClassLoader == null) {
--- a/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusLookAndFeel.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/NimbusLookAndFeel.java	Fri Mar 15 23:31:19 2013 -0700
@@ -159,7 +159,12 @@
 
             // Store Table ScrollPane Corner Component
             uiDefaults.put("Table.scrollPaneCornerComponent",
-                    TableScrollPaneCorner.class);
+                    new UIDefaults.ActiveValue() {
+                        @Override
+                        public Object createValue(UIDefaults table) {
+                            return new TableScrollPaneCorner();
+                        }
+                    });
 
             // Setup the settings for ToolBarSeparator which is custom
             // installed for Nimbus
--- a/jdk/src/share/classes/javax/swing/text/html/FormView.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/javax/swing/text/html/FormView.java	Fri Mar 15 23:31:19 2013 -0700
@@ -159,6 +159,10 @@
             attr.getAttribute(StyleConstants.NameAttribute);
         JComponent c = null;
         Object model = attr.getAttribute(StyleConstants.ModelAttribute);
+
+        // Remove listeners previously registered in shared model
+        // when a new UI component is replaced.  See bug 7189299.
+        removeStaleListenerForModel(model);
         if (t == HTML.Tag.INPUT) {
             c = createInputComponent(attr, model);
         } else if (t == HTML.Tag.SELECT) {
@@ -310,6 +314,63 @@
         return c;
     }
 
+    private void removeStaleListenerForModel(Object model) {
+        if (model instanceof DefaultButtonModel) {
+            // case of JButton whose model is DefaultButtonModel
+            // Need to remove stale ActionListener, ChangeListener and
+            // ItemListener that are instance of AbstractButton$Handler.
+            DefaultButtonModel buttonModel = (DefaultButtonModel) model;
+            String listenerClass = "javax.swing.AbstractButton$Handler";
+            for (ActionListener listener : buttonModel.getActionListeners()) {
+                if (listenerClass.equals(listener.getClass().getName())) {
+                    buttonModel.removeActionListener(listener);
+                }
+            }
+            for (ChangeListener listener : buttonModel.getChangeListeners()) {
+                if (listenerClass.equals(listener.getClass().getName())) {
+                    buttonModel.removeChangeListener(listener);
+                }
+            }
+            for (ItemListener listener : buttonModel.getItemListeners()) {
+                if (listenerClass.equals(listener.getClass().getName())) {
+                    buttonModel.removeItemListener(listener);
+                }
+            }
+        } else if (model instanceof AbstractListModel) {
+            // case of JComboBox and JList
+            // For JList, the stale ListDataListener is instance
+            // BasicListUI$Handler.
+            // For JComboBox, there are 2 stale ListDataListeners, which are
+            // BasicListUI$Handler and BasicComboBoxUI$Handler.
+            AbstractListModel listModel = (AbstractListModel) model;
+            String listenerClass1 =
+                    "javax.swing.plaf.basic.BasicListUI$Handler";
+            String listenerClass2 =
+                    "javax.swing.plaf.basic.BasicComboBoxUI$Handler";
+            for (ListDataListener listener : listModel.getListDataListeners()) {
+                if (listenerClass1.equals(listener.getClass().getName())
+                        || listenerClass2.equals(listener.getClass().getName()))
+                {
+                    listModel.removeListDataListener(listener);
+                }
+            }
+        } else if (model instanceof AbstractDocument) {
+            // case of JPasswordField, JTextField and JTextArea
+            // All have 2 stale DocumentListeners.
+            String listenerClass1 =
+                    "javax.swing.plaf.basic.BasicTextUI$UpdateHandler";
+            String listenerClass2 =
+                    "javax.swing.text.DefaultCaret$Handler";
+            AbstractDocument docModel = (AbstractDocument) model;
+            for (DocumentListener listener : docModel.getDocumentListeners()) {
+                if (listenerClass1.equals(listener.getClass().getName())
+                        || listenerClass2.equals(listener.getClass().getName()))
+                {
+                    docModel.removeDocumentListener(listener);
+                }
+            }
+        }
+    }
 
     /**
      * Determines the maximum span for this view along an
@@ -347,7 +408,7 @@
 
 
     /**
-     * Responsible for processeing the ActionEvent.
+     * Responsible for processing the ActionEvent.
      * If the element associated with the FormView,
      * has a type of "submit", "reset", "text" or "password"
      * then the action is processed.  In the case of a "submit"
--- a/jdk/src/share/classes/sun/applet/AppletPanel.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/applet/AppletPanel.java	Fri Mar 15 23:31:19 2013 -0700
@@ -45,6 +45,7 @@
 import java.util.Collections;
 import java.util.Locale;
 import java.util.WeakHashMap;
+import sun.awt.AWTAccessor;
 import sun.awt.AppContext;
 import sun.awt.EmbeddedFrame;
 import sun.awt.SunToolkit;
@@ -448,12 +449,12 @@
                       // to avoid deadlock.
                       try {
                           final AppletPanel p = this;
-
-                          EventQueue.invokeAndWait(new Runnable() {
-                                  public void run() {
-                                      p.validate();
-                                  }
-                              });
+                          Runnable r = new Runnable() {
+                              public void run() {
+                                  p.validate();
+                              }
+                          };
+                          AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r);
                       }
                       catch(InterruptedException ie) {
                       }
@@ -478,18 +479,19 @@
                       try {
                           final AppletPanel p = this;
                           final Applet a = applet;
-
-                          EventQueue.invokeAndWait(new Runnable() {
-                                  public void run() {
-                                      p.validate();
-                                      a.setVisible(true);
+                          Runnable r = new Runnable() {
+                              public void run() {
+                                  p.validate();
+                                  a.setVisible(true);
 
-                                      // Fix for BugTraq ID 4041703.
-                                      // Set the default focus for an applet.
-                                      if (hasInitialFocus())
-                                        setDefaultFocus();
+                                  // Fix for BugTraq ID 4041703.
+                                  // Set the default focus for an applet.
+                                  if (hasInitialFocus()) {
+                                      setDefaultFocus();
                                   }
-                              });
+                              }
+                          };
+                          AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r);
                       }
                       catch(InterruptedException ie) {
                       }
@@ -512,13 +514,12 @@
                     // to avoid deadlock.
                     try {
                         final Applet a = applet;
-
-                        EventQueue.invokeAndWait(new Runnable() {
-                                public void run()
-                                {
-                                    a.setVisible(false);
-                                }
-                            });
+                        Runnable r = new Runnable() {
+                            public void run() {
+                                a.setVisible(false);
+                            }
+                        };
+                        AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r);
                     }
                     catch(InterruptedException ie) {
                     }
@@ -570,17 +571,14 @@
                     }
                     status = APPLET_DISPOSE;
 
-                    try
-                    {
+                    try {
                         final Applet a = applet;
-
-                        EventQueue.invokeAndWait(new Runnable()
-                        {
-                            public void run()
-                            {
+                        Runnable r = new Runnable() {
+                            public void run() {
                                 remove(a);
                             }
-                        });
+                        };
+                        AWTAccessor.getEventQueueAccessor().invokeAndWait(applet, r);
                     }
                     catch(InterruptedException ie)
                     {
--- a/jdk/src/share/classes/sun/awt/AWTAccessor.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/awt/AWTAccessor.java	Fri Mar 15 23:31:19 2013 -0700
@@ -34,6 +34,8 @@
 import java.awt.event.KeyEvent;
 import java.awt.geom.Point2D;
 import java.awt.peer.ComponentPeer;
+
+import java.lang.reflect.InvocationTargetException;
 import java.security.AccessControlContext;
 
 import java.io.File;
@@ -476,6 +478,12 @@
          * appeared.
          */
         void wakeup(EventQueue eventQueue, boolean isShutdown);
+
+        /**
+         * Static in EventQueue
+         */
+        void invokeAndWait(Object source, Runnable r)
+            throws InterruptedException, InvocationTargetException;
     }
 
     /*
--- a/jdk/src/share/classes/sun/awt/AppContext.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/awt/AppContext.java	Fri Mar 15 23:31:19 2013 -0700
@@ -327,21 +327,27 @@
             // Before we return the main "system" AppContext, check to
             // see if there's an AWTSecurityManager installed.  If so,
             // allow it to choose the AppContext to return.
-            SecurityManager securityManager = System.getSecurityManager();
-            if ((securityManager != null) &&
-                (securityManager instanceof AWTSecurityManager))
-            {
-                AWTSecurityManager awtSecMgr = (AWTSecurityManager)securityManager;
-                AppContext secAppContext = awtSecMgr.getAppContext();
-                if (secAppContext != null)  {
-                    appContext = secAppContext; // Return what we're told
-                }
+            AppContext secAppContext = getExecutionAppContext();
+            if (secAppContext != null) {
+                appContext = secAppContext; // Return what we're told
             }
         }
 
         return appContext;
     }
 
+    private final static AppContext getExecutionAppContext() {
+        SecurityManager securityManager = System.getSecurityManager();
+        if ((securityManager != null) &&
+            (securityManager instanceof AWTSecurityManager))
+        {
+            AWTSecurityManager awtSecMgr = (AWTSecurityManager) securityManager;
+            AppContext secAppContext = awtSecMgr.getAppContext();
+            return secAppContext; // Return what we're told
+        }
+        return null;
+    }
+
     /**
      * Returns the main ("system") AppContext.
      *
@@ -806,6 +812,21 @@
             public boolean isMainAppContext() {
                 return (numAppContexts.get() == 1);
             }
+            public Object getContext() {
+                return getAppContext();
+            }
+            public Object getExecutionContext() {
+                return getExecutionAppContext();
+            }
+            public Object get(Object context, Object key) {
+                return ((AppContext)context).get(key);
+            }
+            public void put(Object context, Object key, Object value) {
+                ((AppContext)context).put(key, value);
+            }
+            public void remove(Object context, Object key) {
+                ((AppContext)context).remove(key);
+            }
         });
     }
 }
--- a/jdk/src/share/classes/sun/awt/EmbeddedFrame.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/awt/EmbeddedFrame.java	Fri Mar 15 23:31:19 2013 -0700
@@ -582,5 +582,8 @@
 
         public void repositionSecurityWarning() {
         }
-     }
+
+        public void emulateActivation(boolean activate) {
+        }
+    }
 } // class EmbeddedFrame
--- a/jdk/src/share/classes/sun/awt/HToolkit.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/awt/HToolkit.java	Fri Mar 15 23:31:19 2013 -0700
@@ -64,6 +64,11 @@
         throw new HeadlessException();
     }
 
+    public FramePeer createLightweightFrame(LightweightFrame target)
+        throws HeadlessException {
+        throw new HeadlessException();
+    }
+
     public FramePeer createFrame(Frame target)
         throws HeadlessException {
         throw new HeadlessException();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/awt/LightweightFrame.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.awt;
+
+import java.awt.Container;
+import java.awt.Frame;
+import java.awt.Graphics;
+import java.awt.Image;
+import java.awt.MenuBar;
+import java.awt.MenuComponent;
+import java.awt.Toolkit;
+import java.awt.peer.FramePeer;
+
+/**
+ * The class provides basic functionality for a lightweight frame
+ * implementation. A subclass is expected to provide painting to an
+ * offscreen image and access to it. Thus it can be used for lightweight
+ * embedding.
+ *
+ * @author Artem Ananiev
+ * @author Anton Tarasov
+ */
+@SuppressWarnings("serial")
+public abstract class LightweightFrame extends Frame {
+
+    /**
+     * Constructs a new, initially invisible {@code LightweightFrame}
+     * instance.
+     */
+    public LightweightFrame() {
+        setUndecorated(true);
+        setResizable(true);
+        setEnabled(true);
+    }
+
+    /**
+     * Blocks introspection of a parent window by this child.
+     *
+     * @return null
+     */
+    @Override public final Container getParent() { return null; }
+
+    @Override public Graphics getGraphics() { return null; }
+
+    @Override public final boolean isResizable() { return true; }
+
+    // Block modification of any frame attributes, since they aren't
+    // applicable for a lightweight frame.
+
+    @Override public final void setTitle(String title) {}
+    @Override public final void setIconImage(Image image) {}
+    @Override public final void setIconImages(java.util.List<? extends Image> icons) {}
+    @Override public final void setMenuBar(MenuBar mb) {}
+    @Override public final void setResizable(boolean resizable) {}
+    @Override public final void remove(MenuComponent m) {}
+    @Override public final void toFront() {}
+    @Override public final void toBack() {}
+
+    @Override public void addNotify() {
+        synchronized (getTreeLock()) {
+            if (getPeer() == null) {
+                SunToolkit stk = (SunToolkit)Toolkit.getDefaultToolkit();
+                try {
+                    setPeer(stk.createLightweightFrame(this));
+                } catch (Exception e) {
+                    throw new RuntimeException(e);
+                }
+            }
+            super.addNotify();
+        }
+    }
+
+    private void setPeer(final FramePeer p) {
+        AWTAccessor.getComponentAccessor().setPeer(this, p);
+    }
+
+    /**
+     * Requests the peer to emulate activation or deactivation of the
+     * frame. Peers should override this method if they are to implement
+     * this functionality.
+     *
+     * @param activate if <code>true</code>, activates the frame;
+     *                 otherwise, deactivates the frame
+     */
+    public void emulateActivation(boolean activate) {
+        ((FramePeer)getPeer()).emulateActivation(activate);
+    }
+
+    /**
+     * Delegates the focus grab action to the client (embedding) application.
+     * The method is called by the AWT grab machinery.
+     *
+     * @see SunToolkit#grab(java.awt.Window)
+     */
+    public abstract void grabFocus();
+
+    /**
+     * Delegates the focus ungrab action to the client (embedding) application.
+     * The method is called by the AWT grab machinery.
+     *
+     * @see SunToolkit#ungrab(java.awt.Window)
+     */
+    public abstract void ungrabFocus();
+}
--- a/jdk/src/share/classes/sun/awt/SunToolkit.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/awt/SunToolkit.java	Fri Mar 15 23:31:19 2013 -0700
@@ -131,6 +131,9 @@
     public abstract FramePeer createFrame(Frame target)
         throws HeadlessException;
 
+    public abstract FramePeer createLightweightFrame(LightweightFrame target)
+        throws HeadlessException;
+
     public abstract DialogPeer createDialog(Dialog target)
         throws HeadlessException;
 
--- a/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/awt/datatransfer/DataTransferer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1873,7 +1873,7 @@
      */
     public class ReencodingInputStream extends InputStream {
         protected BufferedReader wrapped;
-        protected final char[] in = new char[1];
+        protected final char[] in = new char[2];
         protected byte[] out;
 
         protected CharsetEncoder encoder;
@@ -1926,7 +1926,7 @@
 
             try {
                 encoder = Charset.forName(targetEncoding).newEncoder();
-                out = new byte[(int)(encoder.maxBytesPerChar() + 0.5)];
+                out = new byte[(int)(encoder.maxBytesPerChar() * 2 + 0.5)];
                 inBuf = CharBuffer.wrap(in);
                 outBuf = ByteBuffer.wrap(out);
             } catch (IllegalCharsetNameException e) {
@@ -1950,31 +1950,50 @@
             }
         }
 
+        private int readChar() throws IOException {
+            int c = wrapped.read();
+
+            if (c == -1) { // -1 is EOS
+                eos = true;
+                return -1;
+            }
+
+            // "c == 0" is not quite correct, but good enough on Windows.
+            if (numTerminators > 0 && c == 0) {
+                eos = true;
+                return -1;
+            } else if (eoln != null && matchCharArray(eoln, c)) {
+                c = '\n' & 0xFFFF;
+            }
+
+            return c;
+        }
+
         public int read() throws IOException {
             if (eos) {
                 return -1;
             }
 
             if (index >= limit) {
-                int c = wrapped.read();
-
-                if (c == -1) { // -1 is EOS
-                    eos = true;
+                // deal with supplementary characters
+                int c = readChar();
+                if (c == -1) {
                     return -1;
                 }
 
-                // "c == 0" is not quite correct, but good enough on Windows.
-                if (numTerminators > 0 && c == 0) {
-                    eos = true;
-                    return -1;
-                } else if (eoln != null && matchCharArray(eoln, c)) {
-                    c = '\n' & 0xFFFF;
+                in[0] = (char) c;
+                in[1] = 0;
+                inBuf.limit(1);
+                if (Character.isHighSurrogate((char) c)) {
+                    c = readChar();
+                    if (c != -1) {
+                        in[1] = (char) c;
+                        inBuf.limit(2);
+                    }
                 }
 
-                in[0] = (char)c;
-
                 inBuf.rewind();
-                outBuf.rewind();
+                outBuf.limit(out.length).rewind();
                 encoder.encode(inBuf, outBuf, false);
                 outBuf.flip();
                 limit = outBuf.limit();
--- a/jdk/src/share/classes/sun/awt/dnd/SunDropTargetContextPeer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/awt/dnd/SunDropTargetContextPeer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -498,7 +498,7 @@
         postDropTargetEvent(component, x, y, dropAction, actions,
                             formats, nativeCtxt,
                             SunDropTargetEvent.MOUSE_DROPPED,
-                            SunDropTargetContextPeer.DISPATCH_SYNC);
+                            !SunDropTargetContextPeer.DISPATCH_SYNC);
     }
 
     /**
--- a/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/awt/image/ByteComponentRaster.java	Fri Mar 15 23:31:19 2013 -0700
@@ -198,7 +198,7 @@
         }
         this.bandOffset = this.dataOffsets[0];
 
-        verify(false);
+        verify();
     }
 
     /**
@@ -857,38 +857,68 @@
     }
 
     /**
-     * Verify that the layout parameters are consistent with
-     * the data.  If strictCheck
-     * is false, this method will check for ArrayIndexOutOfBounds conditions.  If
-     * strictCheck is true, this method will check for additional error
-     * conditions such as line wraparound (width of a line greater than
-     * the scanline stride).
-     * @return   String   Error string, if the layout is incompatible with
-     *                    the data.  Otherwise returns null.
+     * Verify that the layout parameters are consistent with the data.
+     *
+     * The method verifies whether scanline stride and pixel stride do not
+     * cause an integer overflow during calculation of a position of the pixel
+     * in data buffer. It also verifies whether the data buffer has enough data
+     *  to correspond the raster layout attributes.
+     *
+     * @throws RasterFormatException if an integer overflow is detected,
+     * or if data buffer has not enough capacity.
      */
-    private void verify (boolean strictCheck) {
-        // Make sure data for Raster is in a legal range
-        for (int i=0; i < dataOffsets.length; i++) {
+    protected final void verify() {
+        for (int i = 0; i < dataOffsets.length; i++) {
             if (dataOffsets[i] < 0) {
-                throw new RasterFormatException("Data offsets for band "+i+
-                                                "("+dataOffsets[i]+
-                                                ") must be >= 0");
+                throw new RasterFormatException("Data offsets for band " + i
+                            + "(" + dataOffsets[i]
+                            + ") must be >= 0");
             }
         }
 
         int maxSize = 0;
         int size;
 
-        for (int i=0; i < numDataElements; i++) {
-            size = (height-1)*scanlineStride + (width-1)*pixelStride +
-                dataOffsets[i];
+        // we can be sure that width and height are greater than 0
+        if (scanlineStride < 0 ||
+            scanlineStride > (Integer.MAX_VALUE / height))
+        {
+            // integer overflow
+            throw new RasterFormatException("Incorrect scanline stride: "
+                    + scanlineStride);
+        }
+        int lastScanOffset = (height - 1) * scanlineStride;
+
+        if (pixelStride < 0 ||
+            pixelStride > (Integer.MAX_VALUE / width))
+        {
+            // integer overflow
+            throw new RasterFormatException("Incorrect pixel stride: "
+                    + pixelStride);
+        }
+        int lastPixelOffset = (width - 1) * pixelStride;
+
+        if (lastPixelOffset > (Integer.MAX_VALUE - lastScanOffset)) {
+            // integer overflow
+            throw new RasterFormatException("Incorrect raster attributes");
+        }
+        lastPixelOffset += lastScanOffset;
+
+        for (int i = 0; i < numDataElements; i++) {
+            size = lastPixelOffset + dataOffsets[i];
+            if (dataOffsets[i] > (Integer.MAX_VALUE - lastPixelOffset)) {
+                throw new RasterFormatException("Incorrect band offset: "
+                            + dataOffsets[i]);
+
+            }
+
             if (size > maxSize) {
                 maxSize = size;
             }
         }
         if (data.length < maxSize) {
-            throw new RasterFormatException("Data array too small (should be "+
-                                          maxSize+" )");
+            throw new RasterFormatException("Data array too small (should be "
+                    + maxSize + " )");
         }
     }
 
--- a/jdk/src/share/classes/sun/awt/image/ByteInterleavedRaster.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/awt/image/ByteInterleavedRaster.java	Fri Mar 15 23:31:19 2013 -0700
@@ -250,7 +250,7 @@
             }
         }
 
-        verify(false);
+        verify();
     }
 
     /**
@@ -1292,33 +1292,6 @@
         return createCompatibleWritableRaster(width,height);
     }
 
-    /**
-     * Verify that the layout parameters are consistent with
-     * the data.  If strictCheck
-     * is false, this method will check for ArrayIndexOutOfBounds conditions.  If
-     * strictCheck is true, this method will check for additional error
-     * conditions such as line wraparound (width of a line greater than
-     * the scanline stride).
-     * @return   String   Error string, if the layout is incompatible with
-     *                    the data.  Otherwise returns null.
-     */
-    private void verify (boolean strictCheck) {
-        int maxSize = 0;
-        int size;
-
-        for (int i=0; i < numDataElements; i++) {
-            size = (height-1)*scanlineStride + (width-1)*pixelStride +
-                dataOffsets[i];
-            if (size > maxSize) {
-                maxSize = size;
-            }
-        }
-        if (data.length < maxSize) {
-            throw new RasterFormatException("Data array too small (should be "+
-                                          maxSize+" )");
-        }
-    }
-
     public String toString() {
         return new String ("ByteInterleavedRaster: width = "+width+" height = "
                            + height
--- a/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/awt/image/ShortComponentRaster.java	Fri Mar 15 23:31:19 2013 -0700
@@ -198,7 +198,7 @@
         }
         this.bandOffset = this.dataOffsets[0];
 
-        verify(false);
+        verify();
     }
 
     /**
@@ -791,38 +791,67 @@
     }
 
     /**
-     * Verify that the layout parameters are consistent with
-     * the data.  If strictCheck
-     * is false, this method will check for ArrayIndexOutOfBounds conditions.  If
-     * strictCheck is true, this method will check for additional error
-     * conditions such as line wraparound (width of a line greater than
-     * the scanline stride).
-     * @return   String   Error string, if the layout is incompatible with
-     *                    the data.  Otherwise returns null.
+     * Verify that the layout parameters are consistent with the data.
+     *
+     * The method verifies whether scanline stride and pixel stride do not
+     * cause an integer overflow during calculation of a position of the pixel
+     * in data buffer. It also verifies whether the data buffer has enough data
+     *  to correspond the raster layout attributes.
+     *
+     * @throws RasterFormatException if an integer overflow is detected,
+     * or if data buffer has not enough capacity.
      */
-    private void verify (boolean strictCheck) {
-        // Make sure data for Raster is in a legal range
-        for (int i=0; i < dataOffsets.length; i++) {
+    protected final void verify() {
+        for (int i = 0; i < dataOffsets.length; i++) {
             if (dataOffsets[i] < 0) {
-                throw new RasterFormatException("Data offsets for band "+i+
-                                                "("+dataOffsets[i]+
-                                                ") must be >= 0");
+                throw new RasterFormatException("Data offsets for band " + i
+                            + "(" + dataOffsets[i]
+                            + ") must be >= 0");
             }
         }
 
         int maxSize = 0;
         int size;
 
-        for (int i=0; i < numDataElements; i++) {
-            size = (height-1)*scanlineStride + (width-1)*pixelStride +
-                dataOffsets[i];
+        // we can be sure that width and height are greater than 0
+        if (scanlineStride < 0 ||
+            scanlineStride > (Integer.MAX_VALUE / height))
+        {
+            // integer overflow
+            throw new RasterFormatException("Incorrect scanline stride: "
+                    + scanlineStride);
+        }
+        int lastScanOffset = (height - 1) * scanlineStride;
+
+        if (pixelStride < 0 ||
+            pixelStride > (Integer.MAX_VALUE / width))
+        {
+            // integer overflow
+            throw new RasterFormatException("Incorrect pixel stride: "
+                    + pixelStride);
+        }
+        int lastPixelOffset = (width - 1) * pixelStride;
+
+        if (lastPixelOffset > (Integer.MAX_VALUE - lastScanOffset)) {
+            // integer overflow
+            throw new RasterFormatException("Incorrect raster attributes");
+        }
+        lastPixelOffset += lastScanOffset;
+
+        for (int i = 0; i < numDataElements; i++) {
+            size = lastPixelOffset + dataOffsets[i];
+            if (dataOffsets[i] > (Integer.MAX_VALUE - lastPixelOffset)) {
+                throw new RasterFormatException("Incorrect band offset: "
+                            + dataOffsets[i]);
+            }
+
             if (size > maxSize) {
                 maxSize = size;
             }
         }
         if (data.length < maxSize) {
-            throw new RasterFormatException("Data array too small (should be "+
-                                          maxSize+" )");
+            throw new RasterFormatException("Data array too small (should be "
+                    + maxSize + " )");
         }
     }
 
--- a/jdk/src/share/classes/sun/awt/image/ShortInterleavedRaster.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/awt/image/ShortInterleavedRaster.java	Fri Mar 15 23:31:19 2013 -0700
@@ -171,7 +171,7 @@
               sampleModel);
         }
         this.bandOffset = this.dataOffsets[0];
-        verify(false);
+        verify();
     }
 
     /**
@@ -762,33 +762,6 @@
         return createCompatibleWritableRaster(width,height);
     }
 
-    /**
-     * Verify that the layout parameters are consistent with
-     * the data.  If strictCheck
-     * is false, this method will check for ArrayIndexOutOfBounds conditions.  If
-     * strictCheck is true, this method will check for additional error
-     * conditions such as line wraparound (width of a line greater than
-     * the scanline stride).
-     * @return   String   Error string, if the layout is incompatible with
-     *                    the data.  Otherwise returns null.
-     */
-    private void verify (boolean strictCheck) {
-        int maxSize = 0;
-        int size;
-
-        for (int i=0; i < numDataElements; i++) {
-            size = (height-1)*scanlineStride + (width-1)*pixelStride +
-                dataOffsets[i];
-            if (size > maxSize) {
-                maxSize = size;
-            }
-        }
-        if (data.length < maxSize) {
-            throw new RasterFormatException("Data array too small (should be "+
-                                          maxSize+" )");
-        }
-    }
-
     public String toString() {
         return new String ("ShortInterleavedRaster: width = "+width
                            +" height = " + height
--- a/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMS.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMS.java	Fri Mar 15 23:31:19 2013 -0700
@@ -25,29 +25,91 @@
 
 package sun.java2d.cmm.lcms;
 
-import java.awt.color.ColorSpace;
 import java.awt.color.ICC_Profile;
-import java.awt.color.CMMException;
+import java.util.Arrays;
+import java.util.HashMap;
 import sun.java2d.cmm.ColorTransform;
 import sun.java2d.cmm.PCMM;
-import sun.java2d.cmm.lcms.LCMS;
-import sun.java2d.cmm.lcms.LCMSTransform;
 
 public class LCMS implements PCMM {
 
     /* methods invoked from ICC_Profile */
-    public native long loadProfile(byte[] data);
+    @Override
+    public long loadProfile(byte[] data) {
+        long id = loadProfileNative(data);
+
+        if (id != 0L) {
+            if (profiles == null) {
+                profiles = new HashMap<>();
+            }
+            profiles.put(id, new TagCache(id));
+        }
+        return id;
+    }
 
-    public native void freeProfile(long profileID);
+    private native long loadProfileNative(byte[] data);
+
+    @Override
+    public void freeProfile(long profileID) {
+        TagCache c = profiles.remove(profileID);
+        if (c != null) {
+            c.clear();
+        }
+        if (profiles.isEmpty()) {
+            profiles = null;
+        }
+        freeProfileNative(profileID);
+    }
+
+    private native void freeProfileNative(long profileID);
 
     public native synchronized int getProfileSize(long profileID);
 
     public native synchronized void getProfileData(long profileID, byte[] data);
 
-    public native synchronized int getTagSize(long profileID, int tagSignature);
-    public native synchronized void getTagData(long profileID, int tagSignature,
-                                               byte[] data);
-    public native synchronized void setTagData(long profileID, int tagSignature,
+    @Override
+    public synchronized int getTagSize(long profileID, int tagSignature) {
+        TagCache cache = profiles.get(profileID);
+
+        if (cache ==  null) {
+            cache = new TagCache(profileID);
+            profiles.put(profileID, cache);
+        }
+
+        TagData t = cache.getTag(tagSignature);
+        return t == null ? 0 : t.getSize();
+    }
+
+    private static native byte[] getTagNative(long profileID, int signature);
+
+    @Override
+    public synchronized void getTagData(long profileID, int tagSignature,
+                                               byte[] data)
+    {
+        TagCache cache = profiles.get(profileID);
+
+        if (cache ==  null) {
+            cache = new TagCache(profileID);
+            profiles.put(profileID, cache);
+        }
+
+        TagData t = cache.getTag(tagSignature);
+        if (t != null) {
+            t.copyDataTo(data);
+        }
+    }
+
+    @Override
+    public synchronized void setTagData(long profileID, int tagSignature, byte[] data) {
+        TagCache cache = profiles.get(profileID);
+
+        if (cache != null) {
+            cache.clear();
+        }
+        setTagDataNative(profileID, tagSignature, data);
+    }
+
+    private native synchronized void setTagDataNative(long profileID, int tagSignature,
                                                byte[] data);
 
     public static native long getProfileID(ICC_Profile profile);
@@ -103,4 +165,59 @@
 
         initLCMS(LCMSTransform.class, LCMSImageLayout.class, ICC_Profile.class);
     }
+
+    private static class TagData {
+        private int signature;
+        private byte[] data;
+
+        TagData(int sig, byte[] data) {
+            this.signature = sig;
+            this.data = data;
+        }
+
+        int getSize() {
+            return data.length;
+        }
+
+        byte[] getData() {
+            return Arrays.copyOf(data, data.length);
+        }
+
+        void copyDataTo(byte[] dst) {
+            System.arraycopy(data, 0, dst, 0, data.length);
+        }
+
+        int getSignature() {
+            return signature;
+        }
+    }
+
+    private static class TagCache  {
+        private long profileID;
+        private HashMap<Integer, TagData> tags;
+
+        TagCache(long id) {
+            profileID = id;
+
+            tags = new HashMap<>();
+        }
+
+        TagData getTag(int sig) {
+            TagData t = tags.get(sig);
+            if (t == null) {
+                byte[] tagData = getTagNative(profileID, sig);
+                if (tagData != null) {
+                    t = new TagData(sig, tagData);
+                    tags.put(sig, t);
+                }
+            }
+            return t;
+        }
+
+        void clear() {
+            tags.clear();
+        }
+    }
+
+    private static HashMap<Long, TagCache> profiles;
 }
--- a/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMSImageLayout.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMSImageLayout.java	Fri Mar 15 23:31:19 2013 -0700
@@ -22,26 +22,19 @@
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
-
 package sun.java2d.cmm.lcms;
 
-import java.awt.Graphics2D;
 import java.awt.image.BufferedImage;
 import java.awt.image.ComponentColorModel;
-import java.awt.image.Raster;
-import java.awt.image.WritableRaster;
-import java.awt.image.SinglePixelPackedSampleModel;
 import java.awt.image.ComponentSampleModel;
 import java.awt.image.DataBuffer;
-import java.awt.image.DataBufferByte;
-import java.awt.image.DataBufferUShort;
-import java.awt.image.DataBufferInt;
 import java.awt.image.ColorModel;
+import java.awt.image.Raster;
+import java.awt.image.SampleModel;
 import sun.awt.image.ByteComponentRaster;
 import sun.awt.image.ShortComponentRaster;
 import sun.awt.image.IntegerComponentRaster;
 
-
 class LCMSImageLayout {
 
     public static int BYTES_SH(int x) {
@@ -49,47 +42,34 @@
     }
 
     public static int EXTRA_SH(int x) {
-        return x<<7;
+        return x << 7;
     }
 
     public static int CHANNELS_SH(int x) {
-        return x<<3;
+        return x << 3;
     }
-
-    public static final int SWAPFIRST   = 1<<14;
-
-    public static final int DOSWAP      = 1<<10;
-
+    public static final int SWAPFIRST = 1 << 14;
+    public static final int DOSWAP = 1 << 10;
     public static final int PT_RGB_8 =
-        CHANNELS_SH(3) | BYTES_SH(1);
-
+            CHANNELS_SH(3) | BYTES_SH(1);
     public static final int PT_GRAY_8 =
-        CHANNELS_SH(1) | BYTES_SH(1);
-
+            CHANNELS_SH(1) | BYTES_SH(1);
     public static final int PT_GRAY_16 =
-        CHANNELS_SH(1) | BYTES_SH(2);
-
+            CHANNELS_SH(1) | BYTES_SH(2);
     public static final int PT_RGBA_8 =
-        EXTRA_SH(1) | CHANNELS_SH(3) | BYTES_SH(1);
-
+            EXTRA_SH(1) | CHANNELS_SH(3) | BYTES_SH(1);
     public static final int PT_ARGB_8 =
-        EXTRA_SH(1) | CHANNELS_SH(3) | BYTES_SH(1) | SWAPFIRST;
-
+            EXTRA_SH(1) | CHANNELS_SH(3) | BYTES_SH(1) | SWAPFIRST;
     public static final int PT_BGR_8 =
-        DOSWAP | CHANNELS_SH(3) | BYTES_SH(1);
-
+            DOSWAP | CHANNELS_SH(3) | BYTES_SH(1);
     public static final int PT_ABGR_8 =
-        DOSWAP | EXTRA_SH(1) | CHANNELS_SH(3) | BYTES_SH(1);
-
-    public static final int PT_BGRA_8 = EXTRA_SH(1) | CHANNELS_SH(3) |
-        BYTES_SH(1) | DOSWAP | SWAPFIRST;
-
-    public static final int DT_BYTE     = 0;
-    public static final int DT_SHORT    = 1;
-    public static final int DT_INT      = 2;
-    public static final int DT_DOUBLE   = 3;
-
-
+            DOSWAP | EXTRA_SH(1) | CHANNELS_SH(3) | BYTES_SH(1);
+    public static final int PT_BGRA_8 = EXTRA_SH(1) | CHANNELS_SH(3)
+            | BYTES_SH(1) | DOSWAP | SWAPFIRST;
+    public static final int DT_BYTE = 0;
+    public static final int DT_SHORT = 1;
+    public static final int DT_INT = 2;
+    public static final int DT_DOUBLE = 3;
     boolean isIntPacked = false;
     int pixelType;
     int dataType;
@@ -98,25 +78,30 @@
     int nextRowOffset;
     int offset;
 
+    /* This flag indicates whether the image can be processed
+     * at once by doTransfrom() native call. Otherwise, the
+     * image is processed scan by scan.
+     */
+    private boolean imageAtOnce = false;
     Object dataArray;
+
     private LCMSImageLayout(int np, int pixelType, int pixelSize) {
         this.pixelType = pixelType;
         width = np;
         height = 1;
-        nextRowOffset = np*pixelSize;
+        nextRowOffset = np * pixelSize;
         offset = 0;
     }
 
     private LCMSImageLayout(int width, int height, int pixelType,
-                            int pixelSize) {
+            int pixelSize) {
         this.pixelType = pixelType;
         this.width = width;
         this.height = height;
-        nextRowOffset = width*pixelSize;
+        nextRowOffset = width * pixelSize;
         offset = 0;
     }
 
-
     public LCMSImageLayout(byte[] data, int np, int pixelType, int pixelSize) {
         this(np, pixelType, pixelSize);
         dataType = DT_BYTE;
@@ -135,102 +120,218 @@
         dataArray = data;
     }
 
-    public LCMSImageLayout(double[] data, int np, int pixelType, int pixelSize)
-    {
+    public LCMSImageLayout(double[] data, int np, int pixelType, int pixelSize) {
         this(np, pixelType, pixelSize);
         dataType = DT_DOUBLE;
         dataArray = data;
     }
 
-    public LCMSImageLayout(BufferedImage image) {
-        ShortComponentRaster shortRaster;
-        IntegerComponentRaster intRaster;
-        ByteComponentRaster byteRaster;
+    private LCMSImageLayout() {
+    }
+
+    /* This method creates a layout object for given image.
+     * Returns null if the image is not supported by current implementation.
+     */
+    public static LCMSImageLayout createImageLayout(BufferedImage image) {
+        LCMSImageLayout l = new LCMSImageLayout();
+
         switch (image.getType()) {
             case BufferedImage.TYPE_INT_RGB:
-                pixelType = PT_ARGB_8;
-                isIntPacked = true;
+                l.pixelType = PT_ARGB_8;
+                l.isIntPacked = true;
                 break;
             case BufferedImage.TYPE_INT_ARGB:
-                pixelType = PT_ARGB_8;
-                isIntPacked = true;
+                l.pixelType = PT_ARGB_8;
+                l.isIntPacked = true;
                 break;
             case BufferedImage.TYPE_INT_BGR:
-                pixelType = PT_ABGR_8;
-                isIntPacked = true;
+                l.pixelType = PT_ABGR_8;
+                l.isIntPacked = true;
                 break;
             case BufferedImage.TYPE_3BYTE_BGR:
-                pixelType = PT_BGR_8;
+                l.pixelType = PT_BGR_8;
                 break;
             case BufferedImage.TYPE_4BYTE_ABGR:
-                pixelType = PT_ABGR_8;
+                l.pixelType = PT_ABGR_8;
                 break;
             case BufferedImage.TYPE_BYTE_GRAY:
-                pixelType = PT_GRAY_8;
+                l.pixelType = PT_GRAY_8;
                 break;
             case BufferedImage.TYPE_USHORT_GRAY:
-                pixelType = PT_GRAY_16;
+                l.pixelType = PT_GRAY_16;
                 break;
             default:
-            // TODO: Add support for some images having
-            // SinglePixelPackedModel and ComponentSampleModel
-                throw new IllegalArgumentException(
-                    "CMMImageLayout - bad image type passed to constructor");
+                /* ColorConvertOp creates component images as
+                 * default destination, so this kind of images
+                 * has to be supported.
+                 */
+                ColorModel cm = image.getColorModel();
+                if (cm instanceof ComponentColorModel) {
+                    ComponentColorModel ccm = (ComponentColorModel) cm;
+
+                    // verify whether the component size is fine
+                    int[] cs = ccm.getComponentSize();
+                    for (int s : cs) {
+                        if (s != 8) {
+                            return null;
+                        }
+                    }
+
+                    return createImageLayout(image.getRaster());
+
+                }
+                return null;
         }
 
-        width = image.getWidth();
-        height = image.getHeight();
+        l.width = image.getWidth();
+        l.height = image.getHeight();
 
         switch (image.getType()) {
             case BufferedImage.TYPE_INT_RGB:
             case BufferedImage.TYPE_INT_ARGB:
             case BufferedImage.TYPE_INT_BGR:
-                intRaster = (IntegerComponentRaster)image.getRaster();
-                nextRowOffset = intRaster.getScanlineStride()*4;
-                offset = intRaster.getDataOffset(0)*4;
-                dataArray = intRaster.getDataStorage();
-                dataType = DT_INT;
+                do {
+                    IntegerComponentRaster intRaster = (IntegerComponentRaster)
+                            image.getRaster();
+                    l.nextRowOffset = intRaster.getScanlineStride() * 4;
+                    l.offset = intRaster.getDataOffset(0) * 4;
+                    l.dataArray = intRaster.getDataStorage();
+                    l.dataType = DT_INT;
+
+                    if (l.nextRowOffset == l.width * 4 * intRaster.getPixelStride()) {
+                        l.imageAtOnce = true;
+                    }
+                } while (false);
                 break;
 
             case BufferedImage.TYPE_3BYTE_BGR:
             case BufferedImage.TYPE_4BYTE_ABGR:
-                byteRaster = (ByteComponentRaster)image.getRaster();
-                nextRowOffset = byteRaster.getScanlineStride();
-                int firstBand = image.getSampleModel().getNumBands() - 1;
-                offset = byteRaster.getDataOffset(firstBand);
-                dataArray = byteRaster.getDataStorage();
-                dataType = DT_BYTE;
+                do {
+                    ByteComponentRaster byteRaster = (ByteComponentRaster)
+                            image.getRaster();
+                    l.nextRowOffset = byteRaster.getScanlineStride();
+                    int firstBand = image.getSampleModel().getNumBands() - 1;
+                    l.offset = byteRaster.getDataOffset(firstBand);
+                    l.dataArray = byteRaster.getDataStorage();
+                    l.dataType = DT_BYTE;
+                    if (l.nextRowOffset == l.width * byteRaster.getPixelStride()) {
+                        l.imageAtOnce = true;
+                    }
+                } while (false);
                 break;
 
             case BufferedImage.TYPE_BYTE_GRAY:
-                byteRaster = (ByteComponentRaster)image.getRaster();
-                nextRowOffset = byteRaster.getScanlineStride();
-                offset = byteRaster.getDataOffset(0);
-                dataArray = byteRaster.getDataStorage();
-                dataType = DT_BYTE;
+                do {
+                    ByteComponentRaster byteRaster = (ByteComponentRaster)
+                            image.getRaster();
+                    l.nextRowOffset = byteRaster.getScanlineStride();
+                    l.offset = byteRaster.getDataOffset(0);
+                    l.dataArray = byteRaster.getDataStorage();
+                    l.dataType = DT_BYTE;
+
+                    if (l.nextRowOffset == l.width * byteRaster.getPixelStride()) {
+                        l.imageAtOnce = true;
+                    }
+                } while (false);
                 break;
 
             case BufferedImage.TYPE_USHORT_GRAY:
-                shortRaster = (ShortComponentRaster)image.getRaster();
-                nextRowOffset = shortRaster.getScanlineStride()*2;
-                offset = shortRaster.getDataOffset(0) * 2;
-                dataArray = shortRaster.getDataStorage();
-                dataType = DT_SHORT;
+                do {
+                    ShortComponentRaster shortRaster = (ShortComponentRaster)
+                            image.getRaster();
+                    l.nextRowOffset = shortRaster.getScanlineStride() * 2;
+                    l.offset = shortRaster.getDataOffset(0) * 2;
+                    l.dataArray = shortRaster.getDataStorage();
+                    l.dataType = DT_SHORT;
+
+                    if (l.nextRowOffset == l.width * 2 * shortRaster.getPixelStride()) {
+                        l.imageAtOnce = true;
+                    }
+                } while (false);
                 break;
+            default:
+                return null;
+        }
+        return l;
+    }
+
+    private static enum BandOrder {
+        DIRECT,
+        INVERTED,
+        ARBITRARY,
+        UNKNOWN;
+
+        public static BandOrder getBandOrder(int[] bandOffsets) {
+            BandOrder order = UNKNOWN;
+
+            int numBands = bandOffsets.length;
+
+            for (int i = 0; (order != ARBITRARY) && (i < bandOffsets.length); i++) {
+                switch (order) {
+                    case UNKNOWN:
+                        if (bandOffsets[i] == i) {
+                            order = DIRECT;
+                        } else if (bandOffsets[i] == (numBands - 1 - i)) {
+                            order = INVERTED;
+                        } else {
+                            order = ARBITRARY;
+                        }
+                        break;
+                    case DIRECT:
+                        if (bandOffsets[i] != i) {
+                            order = ARBITRARY;
+                        }
+                        break;
+                    case INVERTED:
+                        if (bandOffsets[i] != (numBands - 1 - i)) {
+                            order = ARBITRARY;
+                        }
+                        break;
+                }
+            }
+            return order;
         }
     }
 
-    public static boolean isSupported(BufferedImage image) {
-        switch (image.getType()) {
-            case BufferedImage.TYPE_INT_RGB:
-            case BufferedImage.TYPE_INT_ARGB:
-            case BufferedImage.TYPE_INT_BGR:
-            case BufferedImage.TYPE_3BYTE_BGR:
-            case BufferedImage.TYPE_4BYTE_ABGR:
-            case BufferedImage.TYPE_BYTE_GRAY:
-            case BufferedImage.TYPE_USHORT_GRAY:
-                return true;
+    public static LCMSImageLayout createImageLayout(Raster r) {
+        LCMSImageLayout l = new LCMSImageLayout();
+        if (r instanceof ByteComponentRaster) {
+            ByteComponentRaster br = (ByteComponentRaster)r;
+
+            ComponentSampleModel csm = (ComponentSampleModel)r.getSampleModel();
+
+            l.pixelType = CHANNELS_SH(br.getNumBands()) | BYTES_SH(1);
+
+            int[] bandOffsets = csm.getBandOffsets();
+            BandOrder order = BandOrder.getBandOrder(bandOffsets);
+
+            int firstBand = 0;
+            switch (order) {
+                case INVERTED:
+                    l.pixelType |= DOSWAP;
+                    firstBand  = csm.getNumBands() - 1;
+                    break;
+                case DIRECT:
+                    // do nothing
+                    break;
+                default:
+                    // unable to create the image layout;
+                    return null;
+            }
+
+            l.nextRowOffset = br.getScanlineStride();
+            l.offset = br.getDataOffset(firstBand);
+            l.dataArray = br.getDataStorage();
+            l.dataType = DT_BYTE;
+
+            l.width = br.getWidth();
+            l.height = br.getHeight();
+
+            if (l.nextRowOffset == l.width * br.getPixelStride()) {
+                l.imageAtOnce = true;
+            }
+            return l;
         }
-        return false;
+        return null;
     }
 }
--- a/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMSTransform.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/java2d/cmm/lcms/LCMSTransform.java	Fri Mar 15 23:31:19 2013 -0700
@@ -161,13 +161,18 @@
     }
 
     public void colorConvert(BufferedImage src, BufferedImage dst) {
-        if (LCMSImageLayout.isSupported(src) &&
-            LCMSImageLayout.isSupported(dst))
-        {
-            doTransform(new LCMSImageLayout(src), new LCMSImageLayout(dst));
-            return;
+        LCMSImageLayout srcIL, dstIL;
+
+        dstIL = LCMSImageLayout.createImageLayout(dst);
+
+        if (dstIL != null) {
+            srcIL = LCMSImageLayout.createImageLayout(src);
+            if (srcIL != null) {
+                doTransform(srcIL, dstIL);
+                return;
+            }
         }
-        LCMSImageLayout srcIL, dstIL;
+
         Raster srcRas = src.getRaster();
         WritableRaster dstRas = dst.getRaster();
         ColorModel srcCM = src.getColorModel();
@@ -439,6 +444,14 @@
     public void colorConvert(Raster src, WritableRaster dst) {
 
         LCMSImageLayout srcIL, dstIL;
+        dstIL = LCMSImageLayout.createImageLayout(dst);
+        if (dstIL != null) {
+            srcIL = LCMSImageLayout.createImageLayout(src);
+            if (srcIL != null) {
+                doTransform(srcIL, dstIL);
+                return;
+            }
+        }
         // Can't pass src and dst directly to CMM, so process per scanline
         SampleModel srcSM = src.getSampleModel();
         SampleModel dstSM = dst.getSampleModel();
--- a/jdk/src/share/classes/sun/misc/JavaAWTAccess.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/misc/JavaAWTAccess.java	Fri Mar 15 23:31:19 2013 -0700
@@ -26,6 +26,14 @@
 package sun.misc;
 
 public interface JavaAWTAccess {
+    public Object getContext();
+    public Object getExecutionContext();
+
+    public Object get(Object context, Object key);
+    public void put(Object context, Object key, Object value);
+    public void remove(Object context, Object key);
+
+    // convenience methods whose context is the object returned by getContext()
     public Object get(Object key);
     public void put(Object key, Object value);
     public void remove(Object key);
--- a/jdk/src/share/classes/sun/net/httpserver/ChunkedInputStream.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/net/httpserver/ChunkedInputStream.java	Fri Mar 15 23:31:19 2013 -0700
@@ -41,8 +41,12 @@
 
     private boolean needToReadHeader = true;
 
-    static char CR = '\r';
-    static char LF = '\n';
+    final static char CR = '\r';
+    final static char LF = '\n';
+    /*
+     * Maximum chunk header size of 2KB + 2 bytes for CRLF
+     */
+    private final static int MAX_CHUNK_HEADER_SIZE = 2050;
 
     private int numeric (char[] arr, int nchars) throws IOException {
         assert arr.length >= nchars;
@@ -73,10 +77,14 @@
         char[] len_arr = new char [16];
         int len_size = 0;
         boolean end_of_len = false;
+        int read = 0;
 
         while ((c=in.read())!= -1) {
             char ch = (char) c;
-            if (len_size == len_arr.length -1) {
+            read++;
+            if ((len_size == len_arr.length -1) ||
+                (read > MAX_CHUNK_HEADER_SIZE))
+            {
                 throw new IOException ("invalid chunk header");
             }
             if (gotCR) {
--- a/jdk/src/share/classes/sun/net/www/http/ChunkedInputStream.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/net/www/http/ChunkedInputStream.java	Fri Mar 15 23:31:19 2013 -0700
@@ -125,6 +125,11 @@
      */
     private boolean closed;
 
+    /*
+     * Maximum chunk header size of 2KB + 2 bytes for CRLF
+     */
+    private final static int MAX_CHUNK_HEADER_SIZE = 2050;
+
     /**
      * State to indicate that next field should be :-
      *  chunk-size [ chunk-extension ] CRLF
@@ -290,6 +295,10 @@
                             break;
                         }
                         pos++;
+                        if ((pos - rawPos) >= MAX_CHUNK_HEADER_SIZE) {
+                            error = true;
+                            throw new IOException("Chunk header too long");
+                        }
                     }
                     if (pos >= rawCount) {
                         return;
--- a/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java	Fri Mar 15 23:31:19 2013 -0700
@@ -421,7 +421,7 @@
 
         synchronized (writeLock) {
             ensureOpen();
-            InetSocketAddress isa = (InetSocketAddress)target;
+            InetSocketAddress isa = Net.checkAddress(target);
             InetAddress ia = isa.getAddress();
             if (ia == null)
                 throw new IOException("Target address not resolved");
@@ -432,9 +432,9 @@
                     SecurityManager sm = System.getSecurityManager();
                     if (sm != null) {
                         if (ia.isMulticastAddress()) {
-                            sm.checkMulticast(isa.getAddress());
+                            sm.checkMulticast(ia);
                         } else {
-                            sm.checkConnect(isa.getAddress().getHostAddress(),
+                            sm.checkConnect(ia.getHostAddress(),
                                             isa.getPort());
                         }
                     }
@@ -454,7 +454,7 @@
                     return 0;
                 writerThread = NativeThread.current();
                 do {
-                    n = send(fd, src, target);
+                    n = send(fd, src, isa);
                 } while ((n == IOStatus.INTERRUPTED) && isOpen());
 
                 synchronized (stateLock) {
@@ -471,7 +471,7 @@
         }
     }
 
-    private int send(FileDescriptor fd, ByteBuffer src, SocketAddress target)
+    private int send(FileDescriptor fd, ByteBuffer src, InetSocketAddress target)
         throws IOException
     {
         if (src instanceof DirectBuffer)
@@ -502,7 +502,7 @@
     }
 
     private int sendFromNativeBuffer(FileDescriptor fd, ByteBuffer bb,
-                                            SocketAddress target)
+                                     InetSocketAddress target)
         throws IOException
     {
         int pos = bb.position();
@@ -514,7 +514,7 @@
         int written;
         try {
             written = send0(preferIPv6, fd, ((DirectBuffer)bb).address() + pos,
-                            rem, target);
+                            rem, target.getAddress(), target.getPort());
         } catch (PortUnreachableException pue) {
             if (isConnected())
                 throw pue;
@@ -1116,8 +1116,8 @@
                                 boolean connected)
         throws IOException;
 
-    private native int send0(boolean preferIPv6, FileDescriptor fd, long address, int len,
-                             SocketAddress sa)
+    private native int send0(boolean preferIPv6, FileDescriptor fd, long address,
+                             int len, InetAddress addr, int port)
         throws IOException;
 
     static {
--- a/jdk/src/share/classes/sun/print/RasterPrinterJob.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/print/RasterPrinterJob.java	Fri Mar 15 23:31:19 2013 -0700
@@ -527,9 +527,92 @@
         }
     }
 
+    private PageFormat attributeToPageFormat(PrintService service,
+                                               PrintRequestAttributeSet attSet) {
+        PageFormat page = defaultPage();
+
+        if (service == null) {
+            return page;
+        }
+
+        OrientationRequested orient = (OrientationRequested)
+                                      attSet.get(OrientationRequested.class);
+        if (orient == null) {
+            orient = (OrientationRequested)
+                    service.getDefaultAttributeValue(OrientationRequested.class);
+        }
+        if (orient == OrientationRequested.REVERSE_LANDSCAPE) {
+            page.setOrientation(PageFormat.REVERSE_LANDSCAPE);
+        } else if (orient == OrientationRequested.LANDSCAPE) {
+            page.setOrientation(PageFormat.LANDSCAPE);
+        } else {
+            page.setOrientation(PageFormat.PORTRAIT);
+        }
+
+        Media media = (Media)attSet.get(Media.class);
+        if (media == null) {
+            media =
+                (Media)service.getDefaultAttributeValue(Media.class);
+        }
+        if (!(media instanceof MediaSizeName)) {
+            media = MediaSizeName.NA_LETTER;
+        }
+        MediaSize size =
+            MediaSize.getMediaSizeForName((MediaSizeName)media);
+        if (size == null) {
+            size = MediaSize.NA.LETTER;
+        }
+        Paper paper = new Paper();
+        float dim[] = size.getSize(1); //units == 1 to avoid FP error
+        double w = Math.rint((dim[0]*72.0)/Size2DSyntax.INCH);
+        double h = Math.rint((dim[1]*72.0)/Size2DSyntax.INCH);
+        paper.setSize(w, h);
+        MediaPrintableArea area =
+             (MediaPrintableArea)
+             attSet.get(MediaPrintableArea.class);
+        double ix, iw, iy, ih;
+
+        if (area != null) {
+            // Should pass in same unit as updatePageAttributes
+            // to avoid rounding off errors.
+            ix = Math.rint(
+                           area.getX(MediaPrintableArea.INCH) * DPI);
+            iy = Math.rint(
+                           area.getY(MediaPrintableArea.INCH) * DPI);
+            iw = Math.rint(
+                           area.getWidth(MediaPrintableArea.INCH) * DPI);
+            ih = Math.rint(
+                           area.getHeight(MediaPrintableArea.INCH) * DPI);
+        }
+        else {
+            if (w >= 72.0 * 6.0) {
+                ix = 72.0;
+                iw = w - 2 * 72.0;
+            } else {
+                ix = w / 6.0;
+                iw = w * 0.75;
+            }
+            if (h >= 72.0 * 6.0) {
+                iy = 72.0;
+                ih = h - 2 * 72.0;
+            } else {
+                iy = h / 6.0;
+                ih = h * 0.75;
+            }
+        }
+        paper.setImageableArea(ix, iy, iw, ih);
+        page.setPaper(paper);
+        return page;
+    }
 
     protected void updatePageAttributes(PrintService service,
                                         PageFormat page) {
+        updateAttributesWithPageFormat(service, page, this.attributes);
+    }
+
+    protected void updateAttributesWithPageFormat(PrintService service,
+                                        PageFormat page,
+                                        PrintRequestAttributeSet attributes) {
         if (service == null || page == null) {
             return;
         }
@@ -659,6 +742,18 @@
             throw new HeadlessException();
         }
 
+        DialogTypeSelection dlg =
+            (DialogTypeSelection)attributes.get(DialogTypeSelection.class);
+
+        // Check for native, note that default dialog is COMMON.
+        if (dlg == DialogTypeSelection.NATIVE) {
+            PrintService pservice = getPrintService();
+            PageFormat page = pageDialog(attributeToPageFormat(pservice,
+                                                               attributes));
+            updateAttributesWithPageFormat(pservice, page, attributes);
+            return page;
+        }
+
         final GraphicsConfiguration gc =
             GraphicsEnvironment.getLocalGraphicsEnvironment().
             getDefaultScreenDevice().getDefaultConfiguration();
@@ -698,77 +793,7 @@
                 attributes.remove(amCategory);
             }
             attributes.addAll(newas);
-
-            PageFormat page = defaultPage();
-
-            OrientationRequested orient =
-                (OrientationRequested)
-                attributes.get(OrientationRequested.class);
-            int pfOrient =  PageFormat.PORTRAIT;
-            if (orient != null) {
-                if (orient == OrientationRequested.REVERSE_LANDSCAPE) {
-                    pfOrient = PageFormat.REVERSE_LANDSCAPE;
-                } else if (orient == OrientationRequested.LANDSCAPE) {
-                    pfOrient = PageFormat.LANDSCAPE;
-                }
-            }
-            page.setOrientation(pfOrient);
-
-            Media media = (Media)attributes.get(Media.class);
-            if (media == null) {
-                media =
-                    (Media)service.getDefaultAttributeValue(Media.class);
-            }
-            if (!(media instanceof MediaSizeName)) {
-                media = MediaSizeName.NA_LETTER;
-            }
-            MediaSize size =
-                MediaSize.getMediaSizeForName((MediaSizeName)media);
-            if (size == null) {
-                size = MediaSize.NA.LETTER;
-            }
-            Paper paper = new Paper();
-            float dim[] = size.getSize(1); //units == 1 to avoid FP error
-            double w = Math.rint((dim[0]*72.0)/Size2DSyntax.INCH);
-            double h = Math.rint((dim[1]*72.0)/Size2DSyntax.INCH);
-            paper.setSize(w, h);
-            MediaPrintableArea area =
-                (MediaPrintableArea)
-                attributes.get(MediaPrintableArea.class);
-            double ix, iw, iy, ih;
-
-            if (area != null) {
-                // Should pass in same unit as updatePageAttributes
-                // to avoid rounding off errors.
-                ix = Math.rint(
-                               area.getX(MediaPrintableArea.INCH) * DPI);
-                iy = Math.rint(
-                               area.getY(MediaPrintableArea.INCH) * DPI);
-                iw = Math.rint(
-                               area.getWidth(MediaPrintableArea.INCH) * DPI);
-                ih = Math.rint(
-                               area.getHeight(MediaPrintableArea.INCH) * DPI);
-            }
-            else {
-                if (w >= 72.0 * 6.0) {
-                    ix = 72.0;
-                    iw = w - 2 * 72.0;
-                } else {
-                    ix = w / 6.0;
-                    iw = w * 0.75;
-                }
-                if (h >= 72.0 * 6.0) {
-                    iy = 72.0;
-                    ih = h - 2 * 72.0;
-                } else {
-                    iy = h / 6.0;
-                    ih = h * 0.75;
-                }
-            }
-            paper.setImageableArea(ix, iy, iw, ih);
-            page.setPaper(paper);
-
-            return page;
+            return attributeToPageFormat(service, attributes);
         } else {
             return null;
         }
@@ -795,7 +820,6 @@
             throw new HeadlessException();
         }
 
-
         DialogTypeSelection dlg =
             (DialogTypeSelection)attributes.get(DialogTypeSelection.class);
 
@@ -816,7 +840,6 @@
 
         }
 
-
         /* A security check has already been performed in the
          * java.awt.print.printerJob.getPrinterJob method.
          * So by the time we get here, it is OK for the current thread
--- a/jdk/src/share/classes/sun/reflect/misc/MethodUtil.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/reflect/misc/MethodUtil.java	Fri Mar 15 23:31:19 2013 -0700
@@ -252,6 +252,12 @@
     public static Object invoke(Method m, Object obj, Object[] params)
         throws InvocationTargetException, IllegalAccessException {
         if (m.getDeclaringClass().equals(AccessController.class) ||
+           (m.getDeclaringClass().equals(java.lang.invoke.MethodHandles.class)
+            && m.getName().equals("lookup")) ||
+           (m.getDeclaringClass().equals(java.lang.invoke.MethodHandles.Lookup.class)
+            && (m.getName().startsWith("find") ||
+                m.getName().startsWith("bind") ||
+                m.getName().startsWith("unreflect"))) ||
             m.getDeclaringClass().equals(Method.class))
             throw new InvocationTargetException(
                 new UnsupportedOperationException("invocation not supported"));
--- a/jdk/src/share/classes/sun/reflect/misc/ReflectUtil.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/reflect/misc/ReflectUtil.java	Fri Mar 15 23:31:19 2013 -0700
@@ -178,4 +178,31 @@
 
         return !isAncestor(from, to);
     }
+
+    /**
+     * Access check on the interfaces that a proxy class implements and throw
+     * {@code SecurityException} if it accesses a restricted package.
+     *
+     * @param ccl the caller's class loader
+     * @param interfaces the list of interfaces that a proxy class implements
+     *
+     * @see Proxy#checkProxyAccess
+     */
+    public static void checkProxyPackageAccess(ClassLoader ccl,
+                                               Class<?>... interfaces)
+    {
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            for (Class<?> intf : interfaces) {
+                ClassLoader cl = intf.getClassLoader();
+                if (needsPackageAccessCheck(ccl, cl)) {
+                    checkPackageAccess(intf);
+                }
+            }
+        }
+    }
+
+    // Note that bytecode instrumentation tools may exclude 'sun.*'
+    // classes but not generated proxy classes and so keep it in com.sun.*
+    public static final String PROXY_PACKAGE = "com.sun.proxy";
 }
--- a/jdk/src/share/classes/sun/rmi/transport/proxy/CGIHandler.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/rmi/transport/proxy/CGIHandler.java	Fri Mar 15 23:31:19 2013 -0700
@@ -153,7 +153,7 @@
                     returnServerError(e.getMessage());
                 }
             else
-                returnClientError("invalid command: " + command);
+                returnClientError("invalid command.");
         } catch (Exception e) {
             returnServerError("internal error: " + e.getMessage());
         }
@@ -225,7 +225,7 @@
         try {
             port = Integer.parseInt(param);
         } catch (NumberFormatException e) {
-            throw new CGIClientException("invalid port number: " + param);
+            throw new CGIClientException("invalid port number.");
         }
         if (port <= 0 || port > 0xFFFF)
             throw new CGIClientException("invalid port: " + port);
@@ -293,11 +293,14 @@
                     "unexpected EOF reading server response");
 
             if (line.toLowerCase().startsWith(key)) {
-                // if contentLengthFound is true
-                // we should probably do something here
-                responseContentLength =
-                    Integer.parseInt(line.substring(key.length()).trim());
-                contentLengthFound = true;
+                if (contentLengthFound) {
+                    throw new CGIServerException(
+                            "Multiple Content-length entries found.");
+                } else {
+                    responseContentLength =
+                        Integer.parseInt(line.substring(key.length()).trim());
+                    contentLengthFound = true;
+                }
             }
         } while ((line.length() != 0) &&
                  (line.charAt(0) != '\r') && (line.charAt(0) != '\n'));
--- a/jdk/src/share/classes/sun/rmi/transport/proxy/HttpInputStream.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/rmi/transport/proxy/HttpInputStream.java	Fri Mar 15 23:31:19 2013 -0700
@@ -70,11 +70,14 @@
                 throw new EOFException();
 
             if (line.toLowerCase().startsWith(key)) {
-                // if contentLengthFound is true
-                // we should probably do something here
-                bytesLeft =
-                    Integer.parseInt(line.substring(key.length()).trim());
-                contentLengthFound = true;
+                if (contentLengthFound) {
+                    throw new IOException(
+                            "Multiple Content-length entries found.");
+                } else {
+                    bytesLeft =
+                        Integer.parseInt(line.substring(key.length()).trim());
+                    contentLengthFound = true;
+                }
             }
 
             // The idea here is to go past the first blank line.
--- a/jdk/src/share/classes/sun/security/pkcs11/P11KeyAgreement.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11KeyAgreement.java	Fri Mar 15 23:31:19 2013 -0700
@@ -37,6 +37,7 @@
 import static sun.security.pkcs11.TemplateManager.*;
 import sun.security.pkcs11.wrapper.*;
 import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
+import sun.security.util.KeyUtil;
 
 /**
  * KeyAgreement implementation class. This class currently supports
@@ -134,6 +135,10 @@
         BigInteger p, g, y;
         if (key instanceof DHPublicKey) {
             DHPublicKey dhKey = (DHPublicKey)key;
+
+            // validate the Diffie-Hellman public key
+            KeyUtil.validate(dhKey);
+
             y = dhKey.getY();
             DHParameterSpec params = dhKey.getParams();
             p = params.getP();
@@ -145,6 +150,10 @@
             try {
                 DHPublicKeySpec spec = kf.engineGetKeySpec(
                         key, DHPublicKeySpec.class);
+
+                // validate the Diffie-Hellman public key
+                KeyUtil.validate(spec);
+
                 y = spec.getY();
                 p = spec.getP();
                 g = spec.getG();
--- a/jdk/src/share/classes/sun/security/ssl/CipherBox.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/CipherBox.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -392,7 +392,8 @@
      * uniformly use the bad_record_mac alert to hide the specific type of
      * the error.
      */
-    int decrypt(byte[] buf, int offset, int len) throws BadPaddingException {
+    int decrypt(byte[] buf, int offset, int len,
+            int tagLen) throws BadPaddingException {
         if (cipher == null) {
             return len;
         }
@@ -416,9 +417,10 @@
                         System.out);
                 } catch (IOException e) { }
             }
+
             if (blockSize != 0) {
-                newLen = removePadding(buf, offset, newLen,
-                             blockSize, protocolVersion);
+                newLen = removePadding(
+                    buf, offset, newLen, tagLen, blockSize, protocolVersion);
 
                 if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
                     if (newLen < blockSize) {
@@ -448,7 +450,7 @@
      *
      *  @see decrypt(byte[], int, int)
      */
-    int decrypt(ByteBuffer bb) throws BadPaddingException {
+    int decrypt(ByteBuffer bb, int tagLen) throws BadPaddingException {
 
         int len = bb.remaining();
 
@@ -471,7 +473,6 @@
             }
 
             if (debug != null && Debug.isOn("plaintext")) {
-                bb.position(pos);
                 try {
                     HexDumpEncoder hd = new HexDumpEncoder();
 
@@ -479,7 +480,8 @@
                         "Padded plaintext after DECRYPTION:  len = "
                         + newLen);
 
-                    hd.encodeBuffer(bb, System.out);
+                    hd.encodeBuffer(
+                        (ByteBuffer)bb.duplicate().position(pos), System.out);
                 } catch (IOException e) { }
             }
 
@@ -488,7 +490,8 @@
              */
             if (blockSize != 0) {
                 bb.position(pos);
-                newLen = removePadding(bb, blockSize, protocolVersion);
+                newLen = removePadding(
+                    bb, tagLen, blockSize, protocolVersion);
 
                 if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
                     if (newLen < blockSize) {
@@ -590,6 +593,65 @@
         return newlen;
     }
 
+    /*
+     * A constant-time check of the padding.
+     *
+     * NOTE that we are checking both the padding and the padLen bytes here.
+     *
+     * The caller MUST ensure that the len parameter is a positive number.
+     */
+    private static int[] checkPadding(
+            byte[] buf, int offset, int len, byte pad) {
+
+        if (len <= 0) {
+            throw new RuntimeException("padding len must be positive");
+        }
+
+        // An array of hits is used to prevent Hotspot optimization for
+        // the purpose of a constant-time check.
+        int[] results = {0, 0};    // {missed #, matched #}
+        for (int i = 0; i <= 256;) {
+            for (int j = 0; j < len && i <= 256; j++, i++) {     // j <= i
+                if (buf[offset + j] != pad) {
+                    results[0]++;       // mismatched padding data
+                } else {
+                    results[1]++;       // matched padding data
+                }
+            }
+        }
+
+        return results;
+    }
+
+    /*
+     * A constant-time check of the padding.
+     *
+     * NOTE that we are checking both the padding and the padLen bytes here.
+     *
+     * The caller MUST ensure that the bb parameter has remaining.
+     */
+    private static int[] checkPadding(ByteBuffer bb, byte pad) {
+
+        if (!bb.hasRemaining()) {
+            throw new RuntimeException("hasRemaining() must be positive");
+        }
+
+        // An array of hits is used to prevent Hotspot optimization for
+        // the purpose of a constant-time check.
+        int[] results = {0, 0};    // {missed #, matched #}
+        bb.mark();
+        for (int i = 0; i <= 256; bb.reset()) {
+            for (; bb.hasRemaining() && i <= 256; i++) {
+                if (bb.get() != pad) {
+                    results[0]++;       // mismatched padding data
+                } else {
+                    results[1]++;       // matched padding data
+                }
+            }
+        }
+
+        return results;
+    }
 
     /*
      * Typical TLS padding format for a 64 bit block cipher is as follows:
@@ -602,86 +664,95 @@
      * as it makes the data a multiple of the block size
      */
     private static int removePadding(byte[] buf, int offset, int len,
-            int blockSize, ProtocolVersion protocolVersion)
-            throws BadPaddingException {
+            int tagLen, int blockSize,
+            ProtocolVersion protocolVersion) throws BadPaddingException {
+
         // last byte is length byte (i.e. actual padding length - 1)
         int padOffset = offset + len - 1;
-        int pad = buf[padOffset] & 0x0ff;
+        int padLen = buf[padOffset] & 0xFF;
 
-        int newlen = len - (pad + 1);
-        if (newlen < 0) {
-            throw new BadPaddingException("Padding length invalid: " + pad);
+        int newLen = len - (padLen + 1);
+        if ((newLen - tagLen) < 0) {
+            // If the buffer is not long enough to contain the padding plus
+            // a MAC tag, do a dummy constant-time padding check.
+            //
+            // Note that it is a dummy check, so we won't care about what is
+            // the actual padding data.
+            checkPadding(buf, offset, len, (byte)(padLen & 0xFF));
+
+            throw new BadPaddingException("Invalid Padding length: " + padLen);
         }
 
+        // The padding data should be filled with the padding length value.
+        int[] results = checkPadding(buf, offset + newLen,
+                        padLen + 1, (byte)(padLen & 0xFF));
         if (protocolVersion.v >= ProtocolVersion.TLS10.v) {
-            for (int i = 1; i <= pad; i++) {
-                int val = buf[padOffset - i] & 0xff;
-                if (val != pad) {
-                    throw new BadPaddingException
-                                        ("Invalid TLS padding: " + val);
-                }
+            if (results[0] != 0) {          // padding data has invalid bytes
+                throw new BadPaddingException("Invalid TLS padding data");
             }
         } else { // SSLv3
             // SSLv3 requires 0 <= length byte < block size
             // some implementations do 1 <= length byte <= block size,
             // so accept that as well
             // v3 does not require any particular value for the other bytes
-            if (pad > blockSize) {
-                throw new BadPaddingException("Invalid SSLv3 padding: " + pad);
+            if (padLen > blockSize) {
+                throw new BadPaddingException("Invalid SSLv3 padding");
             }
         }
-        return newlen;
+        return newLen;
     }
 
     /*
      * Position/limit is equal the removed padding.
      */
     private static int removePadding(ByteBuffer bb,
-            int blockSize, ProtocolVersion protocolVersion)
-            throws BadPaddingException {
+            int tagLen, int blockSize,
+            ProtocolVersion protocolVersion) throws BadPaddingException {
 
         int len = bb.remaining();
         int offset = bb.position();
 
         // last byte is length byte (i.e. actual padding length - 1)
         int padOffset = offset + len - 1;
-        int pad = bb.get(padOffset) & 0x0ff;
+        int padLen = bb.get(padOffset) & 0xFF;
 
-        int newlen = len - (pad + 1);
-        if (newlen < 0) {
-            throw new BadPaddingException("Padding length invalid: " + pad);
+        int newLen = len - (padLen + 1);
+        if ((newLen - tagLen) < 0) {
+            // If the buffer is not long enough to contain the padding plus
+            // a MAC tag, do a dummy constant-time padding check.
+            //
+            // Note that it is a dummy check, so we won't care about what is
+            // the actual padding data.
+            checkPadding(bb.duplicate(), (byte)(padLen & 0xFF));
+
+            throw new BadPaddingException("Invalid Padding length: " + padLen);
         }
 
-        /*
-         * We could zero the padding area, but not much useful
-         * information there.
-         */
+        // The padding data should be filled with the padding length value.
+        int[] results = checkPadding(
+                (ByteBuffer)bb.duplicate().position(offset + newLen),
+                (byte)(padLen & 0xFF));
         if (protocolVersion.v >= ProtocolVersion.TLS10.v) {
-            bb.put(padOffset, (byte)0);         // zero the padding.
-            for (int i = 1; i <= pad; i++) {
-                int val = bb.get(padOffset - i) & 0xff;
-                if (val != pad) {
-                    throw new BadPaddingException
-                                        ("Invalid TLS padding: " + val);
-                }
+            if (results[0] != 0) {          // padding data has invalid bytes
+                throw new BadPaddingException("Invalid TLS padding data");
             }
         } else { // SSLv3
             // SSLv3 requires 0 <= length byte < block size
             // some implementations do 1 <= length byte <= block size,
             // so accept that as well
             // v3 does not require any particular value for the other bytes
-            if (pad > blockSize) {
-                throw new BadPaddingException("Invalid SSLv3 padding: " + pad);
+            if (padLen > blockSize) {
+                throw new BadPaddingException("Invalid SSLv3 padding");
             }
         }
 
         /*
          * Reset buffer limit to remove padding.
          */
-        bb.position(offset + newlen);
-        bb.limit(offset + newlen);
+        bb.position(offset + newLen);
+        bb.limit(offset + newLen);
 
-        return newlen;
+        return newLen;
     }
 
     /*
@@ -708,4 +779,45 @@
     boolean isCBCMode() {
         return isCBCMode;
     }
+
+    /**
+     * Is the cipher null?
+     *
+     * @return true if the cipher is null, false otherwise.
+     */
+    boolean isNullCipher() {
+        return cipher == null;
+    }
+
+    /**
+     * Sanity check the length of a fragment before decryption.
+     *
+     * In CBC mode, check that the fragment length is one or multiple times
+     * of the block size of the cipher suite, and is at least one (one is the
+     * smallest size of padding in CBC mode) bigger than the tag size of the
+     * MAC algorithm except the explicit IV size for TLS 1.1 or later.
+     *
+     * In non-CBC mode, check that the fragment length is not less than the
+     * tag size of the MAC algorithm.
+     *
+     * @return true if the length of a fragment matches above requirements
+     */
+    boolean sanityCheck(int tagLen, int fragmentLen) {
+        if (!isCBCMode) {
+            return fragmentLen >= tagLen;
+        }
+
+        if ((fragmentLen % blockSize) == 0) {
+            int minimal = tagLen + 1;
+            minimal = (minimal >= blockSize) ? minimal : blockSize;
+            if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
+                minimal += blockSize;   // plus the size of the explicit IV
+            }
+
+            return (fragmentLen >= minimal);
+        }
+
+        return false;
+    }
+
 }
--- a/jdk/src/share/classes/sun/security/ssl/CipherSuite.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/CipherSuite.java	Fri Mar 15 23:31:19 2013 -0700
@@ -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
@@ -549,9 +549,18 @@
         // size of the MAC value (and MAC key) in bytes
         final int size;
 
-        MacAlg(String name, int size) {
+        // block size of the underlying hash algorithm
+        final int hashBlockSize;
+
+        // minimal padding size of the underlying hash algorithm
+        final int minimalPaddingSize;
+
+        MacAlg(String name, int size,
+                int hashBlockSize, int minimalPaddingSize) {
             this.name = name;
             this.size = size;
+            this.hashBlockSize = hashBlockSize;
+            this.minimalPaddingSize = minimalPaddingSize;
         }
 
         /**
@@ -596,11 +605,11 @@
                         new BulkCipher(CIPHER_AES,     32, 16, true);
 
     // MACs
-    final static MacAlg M_NULL = new MacAlg("NULL", 0);
-    final static MacAlg M_MD5  = new MacAlg("MD5", 16);
-    final static MacAlg M_SHA  = new MacAlg("SHA", 20);
-    final static MacAlg M_SHA256  = new MacAlg("SHA256", 32);
-    final static MacAlg M_SHA384  = new MacAlg("SHA384", 48);
+    final static MacAlg M_NULL    = new MacAlg("NULL",     0,   0,   0);
+    final static MacAlg M_MD5     = new MacAlg("MD5",     16,  64,   9);
+    final static MacAlg M_SHA     = new MacAlg("SHA",     20,  64,   9);
+    final static MacAlg M_SHA256  = new MacAlg("SHA256",  32,  64,   9);
+    final static MacAlg M_SHA384  = new MacAlg("SHA384",  48, 128,  17);
 
     /**
      * PRFs (PseudoRandom Function) from TLS specifications.
--- a/jdk/src/share/classes/sun/security/ssl/ClientHandshaker.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/ClientHandshaker.java	Fri Mar 15 23:31:19 2013 -0700
@@ -129,9 +129,8 @@
      */
     @Override
     void processMessage(byte type, int messageLen) throws IOException {
-        if (state > type
-                && (type != HandshakeMessage.ht_hello_request
-                    && state != HandshakeMessage.ht_client_hello)) {
+        if (state >= type
+                && (type != HandshakeMessage.ht_hello_request)) {
             throw new SSLProtocolException(
                     "Handshake message sequence violation, " + type);
         }
@@ -194,8 +193,12 @@
                 }
                 break;
             case K_DH_ANON:
-                this.serverKeyExchange(new DH_ServerKeyExchange(
+                try {
+                    this.serverKeyExchange(new DH_ServerKeyExchange(
                                                 input, protocolVersion));
+                } catch (GeneralSecurityException e) {
+                    throwSSLException("Server key", e);
+                }
                 break;
             case K_DHE_DSS:
             case K_DHE_RSA:
@@ -921,7 +924,7 @@
         case K_DHE_RSA:
         case K_DHE_DSS:
         case K_DH_ANON:
-            preMasterSecret = dh.getAgreedSecret(serverDH);
+            preMasterSecret = dh.getAgreedSecret(serverDH, true);
             break;
         case K_ECDHE_RSA:
         case K_ECDHE_ECDSA:
--- a/jdk/src/share/classes/sun/security/ssl/DHClientKeyExchange.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/DHClientKeyExchange.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2007, 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,7 +29,7 @@
 import java.io.IOException;
 import java.io.PrintStream;
 import java.math.BigInteger;
-
+import javax.net.ssl.SSLHandshakeException;
 
 /*
  * Message used by clients to send their Diffie-Hellman public
@@ -51,7 +51,7 @@
     private byte dh_Yc[];               // 1 to 2^16 -1 bytes
 
     BigInteger getClientPublicKey() {
-        return new BigInteger(1, dh_Yc);
+        return dh_Yc == null ? null : new BigInteger(1, dh_Yc);
     }
 
     /*
@@ -73,7 +73,14 @@
      * but that's what the protocol spec requires.)
      */
     DHClientKeyExchange(HandshakeInStream input) throws IOException {
-        dh_Yc = input.getBytes16();
+        if (input.available() >= 2) {
+            dh_Yc = input.getBytes16();
+        } else {
+            // currently, we don't support cipher suites that requires
+            // implicit public key of client.
+            throw new SSLHandshakeException(
+                    "Unsupported implicit client DiffieHellman public key");
+        }
     }
 
     @Override
@@ -87,7 +94,9 @@
 
     @Override
     void send(HandshakeOutStream s) throws IOException {
-        s.putBytes16(dh_Yc);
+        if (dh_Yc != null && dh_Yc.length != 0) {
+            s.putBytes16(dh_Yc);
+        }
     }
 
     @Override
--- a/jdk/src/share/classes/sun/security/ssl/DHCrypt.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/DHCrypt.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2008, 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
@@ -28,12 +28,15 @@
 
 import java.math.BigInteger;
 import java.security.*;
-
+import java.io.IOException;
+import javax.net.ssl.SSLHandshakeException;
 import javax.crypto.SecretKey;
 import javax.crypto.KeyAgreement;
 import javax.crypto.interfaces.DHPublicKey;
 import javax.crypto.spec.*;
 
+import sun.security.util.KeyUtil;
+
 /**
  * This class implements the Diffie-Hellman key exchange algorithm.
  * D-H means combining your private key with your partners public key to
@@ -54,7 +57,8 @@
  *  . if we are server, call DHCrypt(keyLength,random). This generates
  *    an ephemeral keypair of the request length.
  *  . if we are client, call DHCrypt(modulus, base, random). This
- *    generates an ephemeral keypair using the parameters specified by the server.
+ *    generates an ephemeral keypair using the parameters specified by
+ *    the server.
  *  . send parameters and public value to remote peer
  *  . receive peers ephemeral public key
  *  . call getAgreedSecret() to calculate the shared secret
@@ -83,6 +87,9 @@
     // public component of our key, X = (g ^ x) mod p
     private BigInteger publicValue;             // X (aka y)
 
+    // the times to recove from failure if public key validation
+    private static int MAX_FAILOVER_TIMES = 2;
+
     /**
      * Generate a Diffie-Hellman keypair of the specified size.
      */
@@ -90,9 +97,12 @@
         try {
             KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("DiffieHellman");
             kpg.initialize(keyLength, random);
-            KeyPair kp = kpg.generateKeyPair();
-            privateKey = kp.getPrivate();
-            DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());
+
+            DHPublicKeySpec spec = generateDHPublicKeySpec(kpg);
+            if (spec == null) {
+                throw new RuntimeException("Could not generate DH keypair");
+            }
+
             publicValue = spec.getY();
             modulus = spec.getP();
             base = spec.getG();
@@ -115,20 +125,25 @@
             KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("DiffieHellman");
             DHParameterSpec params = new DHParameterSpec(modulus, base);
             kpg.initialize(params, random);
-            KeyPair kp = kpg.generateKeyPair();
-            privateKey = kp.getPrivate();
-            DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());
+
+            DHPublicKeySpec spec = generateDHPublicKeySpec(kpg);
+            if (spec == null) {
+                throw new RuntimeException("Could not generate DH keypair");
+            }
+
             publicValue = spec.getY();
         } catch (GeneralSecurityException e) {
             throw new RuntimeException("Could not generate DH keypair", e);
         }
     }
 
+
     static DHPublicKeySpec getDHPublicKeySpec(PublicKey key) {
         if (key instanceof DHPublicKey) {
             DHPublicKey dhKey = (DHPublicKey)key;
             DHParameterSpec params = dhKey.getParams();
-            return new DHPublicKeySpec(dhKey.getY(), params.getP(), params.getG());
+            return new DHPublicKeySpec(dhKey.getY(),
+                                    params.getP(), params.getG());
         }
         try {
             KeyFactory factory = JsseJce.getKeyFactory("DH");
@@ -166,17 +181,32 @@
      * <P>It is illegal to call this member function if the private key
      * has not been set (or generated).
      *
-     * @param peerPublicKey the peer's public key.
-     * @returns the secret, which is an unsigned big-endian integer
-     *  the same size as the Diffie-Hellman modulus.
+     * @param  peerPublicKey the peer's public key.
+     * @param  keyIsValidated whether the {@code peerPublicKey} has beed
+     *         validated
+     * @return the secret, which is an unsigned big-endian integer
+     *         the same size as the Diffie-Hellman modulus.
      */
-    SecretKey getAgreedSecret(BigInteger peerPublicValue) {
+    SecretKey getAgreedSecret(BigInteger peerPublicValue,
+            boolean keyIsValidated) throws IOException {
         try {
             KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
             DHPublicKeySpec spec =
                         new DHPublicKeySpec(peerPublicValue, modulus, base);
             PublicKey publicKey = kf.generatePublic(spec);
             KeyAgreement ka = JsseJce.getKeyAgreement("DiffieHellman");
+
+            // validate the Diffie-Hellman public key
+            if (!keyIsValidated &&
+                    !KeyUtil.isOracleJCEProvider(ka.getProvider().getName())) {
+                try {
+                    KeyUtil.validate(spec);
+                } catch (InvalidKeyException ike) {
+                    // prefer handshake_failure alert to internal_error alert
+                    throw new SSLHandshakeException(ike.getMessage());
+                }
+            }
+
             ka.init(privateKey);
             ka.doPhase(publicKey, true);
             return ka.generateSecret("TlsPremasterSecret");
@@ -185,4 +215,33 @@
         }
     }
 
+    // Generate and validate DHPublicKeySpec
+    private DHPublicKeySpec generateDHPublicKeySpec(KeyPairGenerator kpg)
+            throws GeneralSecurityException {
+
+        boolean doExtraValiadtion =
+                    (!KeyUtil.isOracleJCEProvider(kpg.getProvider().getName()));
+        for (int i = 0; i <= MAX_FAILOVER_TIMES; i++) {
+            KeyPair kp = kpg.generateKeyPair();
+            privateKey = kp.getPrivate();
+            DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic());
+
+            // validate the Diffie-Hellman public key
+            if (doExtraValiadtion) {
+                try {
+                    KeyUtil.validate(spec);
+                } catch (InvalidKeyException ivke) {
+                    if (i == MAX_FAILOVER_TIMES) {
+                        throw ivke;
+                    }
+                    // otherwise, ignore the exception and try the next one
+                    continue;
+                }
+            }
+
+            return spec;
+        }
+
+        return null;
+    }
 }
--- a/jdk/src/share/classes/sun/security/ssl/EngineInputRecord.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/EngineInputRecord.java	Fri Mar 15 23:31:19 2013 -0700
@@ -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
@@ -178,71 +178,6 @@
     }
 
     /*
-     * Verifies and removes the MAC value.  Returns true if
-     * the MAC checks out OK.
-     *
-     * On entry:
-     *     position = beginning of app/MAC data
-     *     limit = end of MAC data.
-     *
-     * On return:
-     *     position = beginning of app data
-     *     limit = end of app data
-     */
-    boolean checkMAC(MAC signer, ByteBuffer bb) {
-        if (internalData) {
-            return checkMAC(signer);
-        }
-
-        int len = signer.MAClen();
-        if (len == 0) { // no mac
-            return true;
-        }
-
-        /*
-         * Grab the original limit
-         */
-        int lim = bb.limit();
-
-        /*
-         * Delineate the area to apply a MAC on.
-         */
-        int macData = lim - len;
-        bb.limit(macData);
-
-        byte[] mac = signer.compute(contentType(), bb);
-
-        if (len != mac.length) {
-            throw new RuntimeException("Internal MAC error");
-        }
-
-        /*
-         * Delineate the MAC values, position was already set
-         * by doing the compute above.
-         *
-         * We could zero the MAC area, but not much useful information
-         * there anyway.
-         */
-        bb.position(macData);
-        bb.limit(lim);
-
-        try {
-            for (int i = 0; i < len; i++) {
-                if (bb.get() != mac[i]) {  // No BB.equals(byte []); !
-                    return false;
-                }
-            }
-            return true;
-        } finally {
-            /*
-             * Position to the data.
-             */
-            bb.rewind();
-            bb.limit(macData);
-        }
-    }
-
-    /*
      * Pass the data down if it's internally cached, otherwise
      * do it here.
      *
@@ -251,21 +186,164 @@
      * If external data(app), return a new ByteBuffer with data to
      * process.
      */
-    ByteBuffer decrypt(CipherBox box, ByteBuffer bb)
-            throws BadPaddingException {
+    ByteBuffer decrypt(MAC signer,
+            CipherBox box, ByteBuffer bb) throws BadPaddingException {
 
         if (internalData) {
-            decrypt(box);
+            decrypt(signer, box);   // MAC is checked during decryption
             return tmpBB;
         }
 
-        box.decrypt(bb);
-        bb.rewind();
+        BadPaddingException reservedBPE = null;
+        int tagLen = signer.MAClen();
+        int cipheredLength = bb.remaining();
+
+        if (!box.isNullCipher()) {
+            // sanity check length of the ciphertext
+            if (!box.sanityCheck(tagLen, cipheredLength)) {
+                throw new BadPaddingException(
+                    "ciphertext sanity check failed");
+            }
+
+            try {
+                // Note that the CipherBox.decrypt() does not change
+                // the capacity of the buffer.
+                box.decrypt(bb, tagLen);
+            } catch (BadPaddingException bpe) {
+                // RFC 2246 states that decryption_failed should be used
+                // for this purpose. However, that allows certain attacks,
+                // so we just send bad record MAC. We also need to make
+                // sure to always check the MAC to avoid a timing attack
+                // for the same issue. See paper by Vaudenay et al and the
+                // update in RFC 4346/5246.
+                //
+                // Failover to message authentication code checking.
+                reservedBPE = bpe;
+            } finally {
+                bb.rewind();
+            }
+        }
+
+        if (tagLen != 0) {
+            int macOffset = bb.limit() - tagLen;
+
+            // Note that although it is not necessary, we run the same MAC
+            // computation and comparison on the payload for both stream
+            // cipher and CBC block cipher.
+            if (bb.remaining() < tagLen) {
+                // negative data length, something is wrong
+                if (reservedBPE == null) {
+                    reservedBPE = new BadPaddingException("bad record");
+                }
+
+                // set offset of the dummy MAC
+                macOffset = cipheredLength - tagLen;
+                bb.limit(cipheredLength);
+            }
+
+            // Run MAC computation and comparison on the payload.
+            if (checkMacTags(contentType(), bb, signer, false)) {
+                if (reservedBPE == null) {
+                    reservedBPE = new BadPaddingException("bad record MAC");
+                }
+            }
+
+            // Run MAC computation and comparison on the remainder.
+            //
+            // It is only necessary for CBC block cipher.  It is used to get a
+            // constant time of MAC computation and comparison on each record.
+            if (box.isCBCMode()) {
+                int remainingLen = calculateRemainingLen(
+                                        signer, cipheredLength, macOffset);
+
+                // NOTE: here we use the InputRecord.buf because I did not find
+                // an effective way to work on ByteBuffer when its capacity is
+                // less than remainingLen.
+
+                // NOTE: remainingLen may be bigger (less than 1 block of the
+                // hash algorithm of the MAC) than the cipheredLength. However,
+                // We won't need to worry about it because we always use a
+                // maximum buffer for every record.  We need a change here if
+                // we use small buffer size in the future.
+                if (remainingLen > buf.length) {
+                    // unlikely to happen, just a placehold
+                    throw new RuntimeException(
+                        "Internal buffer capacity error");
+                }
+
+                // Won't need to worry about the result on the remainder. And
+                // then we won't need to worry about what's actual data to
+                // check MAC tag on.  We start the check from the header of the
+                // buffer so that we don't need to construct a new byte buffer.
+                checkMacTags(contentType(), buf, 0, remainingLen, signer, true);
+            }
+
+            bb.limit(macOffset);
+        }
+
+        // Is it a failover?
+        if (reservedBPE != null) {
+            throw reservedBPE;
+        }
 
         return bb.slice();
     }
 
     /*
+     * Run MAC computation and comparison
+     *
+     * Please DON'T change the content of the ByteBuffer parameter!
+     */
+    private static boolean checkMacTags(byte contentType, ByteBuffer bb,
+            MAC signer, boolean isSimulated) {
+
+        int tagLen = signer.MAClen();
+        int lim = bb.limit();
+        int macData = lim - tagLen;
+
+        bb.limit(macData);
+        byte[] hash = signer.compute(contentType, bb, isSimulated);
+        if (hash == null || tagLen != hash.length) {
+            // Something is wrong with MAC implementation.
+            throw new RuntimeException("Internal MAC error");
+        }
+
+        bb.position(macData);
+        bb.limit(lim);
+        try {
+            int[] results = compareMacTags(bb, hash);
+            return (results[0] != 0);
+        } finally {
+            bb.rewind();
+            bb.limit(macData);
+        }
+    }
+
+    /*
+     * A constant-time comparison of the MAC tags.
+     *
+     * Please DON'T change the content of the ByteBuffer parameter!
+     */
+    private static int[] compareMacTags(ByteBuffer bb, byte[] tag) {
+
+        // An array of hits is used to prevent Hotspot optimization for
+        // the purpose of a constant-time check.
+        int[] results = {0, 0};     // {missed #, matched #}
+
+        // The caller ensures there are enough bytes available in the buffer.
+        // So we won't need to check the remaining of the buffer.
+        for (int i = 0; i < tag.length; i++) {
+            if (bb.get() != tag[i]) {
+                results[0]++;       // mismatched bytes
+            } else {
+                results[1]++;       // matched bytes
+            }
+        }
+
+        return results;
+    }
+
+    /*
      * Override the actual write below.  We do things this way to be
      * consistent with InputRecord.  InputRecord may try to write out
      * data to the peer, and *then* throw an Exception.  This forces
--- a/jdk/src/share/classes/sun/security/ssl/EngineOutputRecord.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/EngineOutputRecord.java	Fri Mar 15 23:31:19 2013 -0700
@@ -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
@@ -118,7 +118,7 @@
             throws IOException {
 
         if (signer.MAClen() != 0) {
-            byte[] hash = signer.compute(contentType(), bb);
+            byte[] hash = signer.compute(contentType(), bb, false);
 
             /*
              * position was advanced to limit in compute above.
--- a/jdk/src/share/classes/sun/security/ssl/HandshakeMessage.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/HandshakeMessage.java	Fri Mar 15 23:31:19 2013 -0700
@@ -41,12 +41,14 @@
 
 import javax.crypto.KeyGenerator;
 import javax.crypto.SecretKey;
+import javax.crypto.spec.DHPublicKeySpec;
 
 import javax.net.ssl.*;
 
 import sun.security.internal.spec.TlsPrfParameterSpec;
 import sun.security.ssl.CipherSuite.*;
 import static sun.security.ssl.CipherSuite.PRF.*;
+import sun.security.util.KeyUtil;
 
 /**
  * Many data structures are involved in the handshake messages.  These
@@ -712,6 +714,7 @@
         this.protocolVersion = protocolVersion;
         this.preferableSignatureAlgorithm = null;
 
+        // The DH key has been validated in the constructor of DHCrypt.
         setValues(obj);
         signature = null;
     }
@@ -728,6 +731,7 @@
 
         this.protocolVersion = protocolVersion;
 
+        // The DH key has been validated in the constructor of DHCrypt.
         setValues(obj);
 
         Signature sig;
@@ -754,7 +758,8 @@
      * DH_anon key exchange
      */
     DH_ServerKeyExchange(HandshakeInStream input,
-            ProtocolVersion protocolVersion) throws IOException {
+            ProtocolVersion protocolVersion)
+            throws IOException, GeneralSecurityException {
 
         this.protocolVersion = protocolVersion;
         this.preferableSignatureAlgorithm = null;
@@ -762,6 +767,10 @@
         dh_p = input.getBytes16();
         dh_g = input.getBytes16();
         dh_Ys = input.getBytes16();
+        KeyUtil.validate(new DHPublicKeySpec(new BigInteger(1, dh_Ys),
+                                             new BigInteger(1, dh_p),
+                                             new BigInteger(1, dh_g)));
+
         signature = null;
     }
 
@@ -782,6 +791,9 @@
         dh_p = input.getBytes16();
         dh_g = input.getBytes16();
         dh_Ys = input.getBytes16();
+        KeyUtil.validate(new DHPublicKeySpec(new BigInteger(1, dh_Ys),
+                                             new BigInteger(1, dh_p),
+                                             new BigInteger(1, dh_g)));
 
         // read the signature and hash algorithm
         if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
--- a/jdk/src/share/classes/sun/security/ssl/InputRecord.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/InputRecord.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -133,44 +133,174 @@
         return handshakeHash;
     }
 
-    /*
-     * Verify and remove the MAC ... used for all records.
-     */
-    boolean checkMAC(MAC signer) {
-        int len = signer.MAClen();
-        if (len == 0) { // no mac
-            return true;
+    void decrypt(MAC signer, CipherBox box) throws BadPaddingException {
+
+        BadPaddingException reservedBPE = null;
+        int tagLen = signer.MAClen();
+        int cipheredLength = count - headerSize;
+
+        if (!box.isNullCipher()) {
+            // sanity check length of the ciphertext
+            if (!box.sanityCheck(tagLen, cipheredLength)) {
+                throw new BadPaddingException(
+                    "ciphertext sanity check failed");
+            }
+
+            try {
+                // Note that the CipherBox.decrypt() does not change
+                // the capacity of the buffer.
+                count = headerSize +
+                        box.decrypt(buf, headerSize, cipheredLength, tagLen);
+            } catch (BadPaddingException bpe) {
+                // RFC 2246 states that decryption_failed should be used
+                // for this purpose. However, that allows certain attacks,
+                // so we just send bad record MAC. We also need to make
+                // sure to always check the MAC to avoid a timing attack
+                // for the same issue. See paper by Vaudenay et al and the
+                // update in RFC 4346/5246.
+                //
+                // Failover to message authentication code checking.
+                reservedBPE = bpe;
+            }
         }
 
-        int offset = count - len;
+        if (tagLen != 0) {
+            int macOffset = count - tagLen;
+            int contentLen = macOffset - headerSize;
+
+            // Note that although it is not necessary, we run the same MAC
+            // computation and comparison on the payload for both stream
+            // cipher and CBC block cipher.
+            if (contentLen < 0) {
+                // negative data length, something is wrong
+                if (reservedBPE == null) {
+                    reservedBPE = new BadPaddingException("bad record");
+                }
+
+                // set offset of the dummy MAC
+                macOffset = headerSize + cipheredLength - tagLen;
+                contentLen = macOffset - headerSize;
+            }
+
+            count -= tagLen;  // Set the count before any MAC checking
+                              // exception occurs, so that the following
+                              // process can read the actual decrypted
+                              // content (minus the MAC) in the fragment
+                              // if necessary.
 
-        if (offset < headerSize) {
-            // data length would be negative, something is wrong
-            return false;
+            // Run MAC computation and comparison on the payload.
+            if (checkMacTags(contentType(),
+                    buf, headerSize, contentLen, signer, false)) {
+                if (reservedBPE == null) {
+                    reservedBPE = new BadPaddingException("bad record MAC");
+                }
+            }
+
+            // Run MAC computation and comparison on the remainder.
+            //
+            // It is only necessary for CBC block cipher.  It is used to get a
+            // constant time of MAC computation and comparison on each record.
+            if (box.isCBCMode()) {
+                int remainingLen = calculateRemainingLen(
+                                        signer, cipheredLength, contentLen);
+
+                // NOTE: remainingLen may be bigger (less than 1 block of the
+                // hash algorithm of the MAC) than the cipheredLength. However,
+                // We won't need to worry about it because we always use a
+                // maximum buffer for every record.  We need a change here if
+                // we use small buffer size in the future.
+                if (remainingLen > buf.length) {
+                    // unlikely to happen, just a placehold
+                    throw new RuntimeException(
+                        "Internal buffer capacity error");
+                }
+
+                // Won't need to worry about the result on the remainder. And
+                // then we won't need to worry about what's actual data to
+                // check MAC tag on.  We start the check from the header of the
+                // buffer so that we don't need to construct a new byte buffer.
+                checkMacTags(contentType(), buf, 0, remainingLen, signer, true);
+            }
         }
 
-        byte[] mac = signer.compute(contentType(), buf,
-            headerSize, offset - headerSize);
+        // Is it a failover?
+        if (reservedBPE != null) {
+            throw reservedBPE;
+        }
+    }
 
-        if (len != mac.length) {
+    /*
+     * Run MAC computation and comparison
+     *
+     * Please DON'T change the content of the byte buffer parameter!
+     */
+    static boolean checkMacTags(byte contentType, byte[] buffer,
+            int offset, int contentLen, MAC signer, boolean isSimulated) {
+
+        int tagLen = signer.MAClen();
+        byte[] hash = signer.compute(
+                contentType, buffer, offset, contentLen, isSimulated);
+        if (hash == null || tagLen != hash.length) {
+            // Something is wrong with MAC implementation.
             throw new RuntimeException("Internal MAC error");
         }
 
-        for (int i = 0; i < len; i++) {
-            if (buf[offset + i] != mac[i]) {
-                return false;
+        int[] results = compareMacTags(buffer, offset + contentLen, hash);
+        return (results[0] != 0);
+    }
+
+    /*
+     * A constant-time comparison of the MAC tags.
+     *
+     * Please DON'T change the content of the byte buffer parameter!
+     */
+    private static int[] compareMacTags(
+            byte[] buffer, int offset, byte[] tag) {
+
+        // An array of hits is used to prevent Hotspot optimization for
+        // the purpose of a constant-time check.
+        int[] results = {0, 0};    // {missed #, matched #}
+
+        // The caller ensures there are enough bytes available in the buffer.
+        // So we won't need to check the length of the buffer.
+        for (int i = 0; i < tag.length; i++) {
+            if (buffer[offset + i] != tag[i]) {
+                results[0]++;       // mismatched bytes
+            } else {
+                results[1]++;       // matched bytes
             }
         }
-        count -= len;
-        return true;
+
+        return results;
     }
 
-    void decrypt(CipherBox box) throws BadPaddingException {
-        int len = count - headerSize;
-        count = headerSize + box.decrypt(buf, headerSize, len);
+    /*
+     * Calculate the length of a dummy buffer to run MAC computation
+     * and comparison on the remainder.
+     *
+     * The caller MUST ensure that the fullLen is not less than usedLen.
+     */
+    static int calculateRemainingLen(
+            MAC signer, int fullLen, int usedLen) {
+
+        int blockLen = signer.hashBlockLen();
+        int minimalPaddingLen = signer.minimalPaddingLen();
+
+        // (blockLen - minimalPaddingLen) is the maximum message size of
+        // the last block of hash function operation. See FIPS 180-4, or
+        // MD5 specification.
+        fullLen += 13 - (blockLen - minimalPaddingLen);
+        usedLen += 13 - (blockLen - minimalPaddingLen);
+
+        // Note: fullLen is always not less than usedLen, and blockLen
+        // is always bigger than minimalPaddingLen, so we don't worry
+        // about negative values. 0x01 is added to the result to ensure
+        // that the return value is positive.  The extra one byte does
+        // not impact the overall MAC compression function evaluations.
+        return 0x01 + (int)(Math.ceil(fullLen/(1.0d * blockLen)) -
+                Math.ceil(usedLen/(1.0d * blockLen))) * signer.hashBlockLen();
     }
 
-
     /*
      * Well ... hello_request messages are _never_ hashed since we can't
      * know when they'd appear in the sequence.
--- a/jdk/src/share/classes/sun/security/ssl/MAC.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/MAC.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,8 +43,8 @@
  * provide integrity protection for SSL messages.  The MAC is actually
  * one of several keyed hashes, as associated with the cipher suite and
  * protocol version.  (SSL v3.0 uses one construct, TLS uses another.)
- *
- * <P>NOTE: MAC computation is the only place in the SSL protocol that the
+ * <P>
+ * NOTE: MAC computation is the only place in the SSL protocol that the
  * sequence number is used.  It's also reset to zero with each change of
  * a cipher spec, so this is the only place this state is needed.
  *
@@ -58,6 +58,9 @@
     // Value of the null MAC is fixed
     private static final byte nullMAC[] = new byte[0];
 
+    // internal identifier for the MAC algorithm
+    private final MacAlg        macAlg;
+
     // stuff defined by the kind of MAC algorithm
     private final int           macSize;
 
@@ -82,6 +85,7 @@
 
     private MAC() {
         macSize = 0;
+        macAlg = M_NULL;
         mac = null;
         block = null;
     }
@@ -91,6 +95,7 @@
      */
     MAC(MacAlg macAlg, ProtocolVersion protocolVersion, SecretKey key)
             throws NoSuchAlgorithmException, InvalidKeyException {
+        this.macAlg = macAlg;
         this.macSize = macAlg.size;
 
         String algorithm;
@@ -128,15 +133,31 @@
     }
 
     /**
+     * Returns the hash function block length of the MAC alorithm.
+     */
+    int hashBlockLen() {
+        return macAlg.hashBlockSize;
+    }
+
+    /**
+     * Returns the hash function minimal padding length of the MAC alorithm.
+     */
+    int minimalPaddingLen() {
+        return macAlg.minimalPaddingSize;
+    }
+
+    /**
      * Computes and returns the MAC for the data in this byte array.
      *
      * @param type record type
      * @param buf compressed record on which the MAC is computed
      * @param offset start of compressed record data
      * @param len the size of the compressed record
+     * @param isSimulated if true, simulate the the MAC computation
      */
-    final byte[] compute(byte type, byte buf[], int offset, int len) {
-        return compute(type, null, buf, offset, len);
+    final byte[] compute(byte type, byte buf[],
+            int offset, int len, boolean isSimulated) {
+        return compute(type, null, buf, offset, len, isSimulated);
     }
 
     /**
@@ -149,9 +170,10 @@
      * @param type record type
      * @param bb a ByteBuffer in which the position and limit
      *          demarcate the data to be MAC'd.
+     * @param isSimulated if true, simulate the the MAC computation
      */
-    final byte[] compute(byte type, ByteBuffer bb) {
-        return compute(type, bb, null, 0, bb.remaining());
+    final byte[] compute(byte type, ByteBuffer bb, boolean isSimulated) {
+        return compute(type, bb, null, 0, bb.remaining(), isSimulated);
     }
 
     /**
@@ -204,18 +226,21 @@
      * or buf/offset/len.
      */
     private byte[] compute(byte type, ByteBuffer bb, byte[] buf,
-            int offset, int len) {
+            int offset, int len, boolean isSimulated) {
 
         if (macSize == 0) {
             return nullMAC;
         }
 
-        block[BLOCK_OFFSET_TYPE] = type;
-        block[block.length - 2]  = (byte)(len >> 8);
-        block[block.length - 1]  = (byte)(len     );
+        // MUST NOT increase the sequence number for a simulated computation.
+        if (!isSimulated) {
+            block[BLOCK_OFFSET_TYPE] = type;
+            block[block.length - 2]  = (byte)(len >> 8);
+            block[block.length - 1]  = (byte)(len     );
 
-        mac.update(block);
-        incrementSequenceNumber();
+            mac.update(block);
+            incrementSequenceNumber();
+        }
 
         // content
         if (bb != null) {
--- a/jdk/src/share/classes/sun/security/ssl/OutputRecord.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/OutputRecord.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -205,7 +205,7 @@
         }
         if (signer.MAClen() != 0) {
             byte[] hash = signer.compute(contentType, buf,
-                    headerSize, count - headerSize);
+                    headerSize, count - headerSize, false);
             write(hash);
         }
     }
--- a/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java	Fri Mar 15 23:31:19 2013 -0700
@@ -34,7 +34,7 @@
 import javax.net.ssl.*;
 
 import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec;
-import sun.security.util.KeyLength;
+import sun.security.util.KeyUtil;
 
 /**
  * This is the client key exchange message (CLIENT --> SERVER) used with
@@ -191,7 +191,7 @@
                         "unable to get the plaintext of the premaster secret");
                 }
 
-                int keySize = KeyLength.getKeySize(secretKey);
+                int keySize = KeyUtil.getKeySize(secretKey);
                 if (keySize > 0 && keySize != 384) {       // 384 = 48 * 8
                     if (debug != null && Debug.isOn("handshake")) {
                         System.out.println(
--- a/jdk/src/share/classes/sun/security/ssl/SSLEngineImpl.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/SSLEngineImpl.java	Fri Mar 15 23:31:19 2013 -0700
@@ -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
@@ -958,35 +958,15 @@
              * throw a fatal alert if the integrity check fails.
              */
             try {
-                decryptedBB = inputRecord.decrypt(readCipher, readBB);
+                decryptedBB = inputRecord.decrypt(readMAC, readCipher, readBB);
             } catch (BadPaddingException e) {
-                // RFC 2246 states that decryption_failed should be used
-                // for this purpose. However, that allows certain attacks,
-                // so we just send bad record MAC. We also need to make
-                // sure to always check the MAC to avoid a timing attack
-                // for the same issue. See paper by Vaudenay et al.
-                //
-                // rewind the BB if necessary.
-                readBB.rewind();
-
-                inputRecord.checkMAC(readMAC, readBB);
-
-                // use the same alert types as for MAC failure below
                 byte alertType = (inputRecord.contentType() ==
                     Record.ct_handshake) ?
                         Alerts.alert_handshake_failure :
                         Alerts.alert_bad_record_mac;
-                fatal(alertType, "Invalid padding", e);
+                fatal(alertType, e.getMessage(), e);
             }
 
-            if (!inputRecord.checkMAC(readMAC, decryptedBB)) {
-                if (inputRecord.contentType() == Record.ct_handshake) {
-                    fatal(Alerts.alert_handshake_failure,
-                        "bad handshake record MAC");
-                } else {
-                    fatal(Alerts.alert_bad_record_mac, "bad record MAC");
-                }
-            }
 
             // if (!inputRecord.decompress(c))
             //     fatal(Alerts.alert_decompression_failure,
--- a/jdk/src/share/classes/sun/security/ssl/SSLSocketImpl.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/SSLSocketImpl.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -986,29 +986,13 @@
              * throw a fatal alert if the integrity check fails.
              */
             try {
-                r.decrypt(readCipher);
+                r.decrypt(readMAC, readCipher);
             } catch (BadPaddingException e) {
-                // RFC 2246 states that decryption_failed should be used
-                // for this purpose. However, that allows certain attacks,
-                // so we just send bad record MAC. We also need to make
-                // sure to always check the MAC to avoid a timing attack
-                // for the same issue. See paper by Vaudenay et al.
-                r.checkMAC(readMAC);
-                // use the same alert types as for MAC failure below
                 byte alertType = (r.contentType() == Record.ct_handshake)
                                         ? Alerts.alert_handshake_failure
                                         : Alerts.alert_bad_record_mac;
-                fatal(alertType, "Invalid padding", e);
+                fatal(alertType, e.getMessage(), e);
             }
-            if (!r.checkMAC(readMAC)) {
-                if (r.contentType() == Record.ct_handshake) {
-                    fatal(Alerts.alert_handshake_failure,
-                        "bad handshake record MAC");
-                } else {
-                    fatal(Alerts.alert_bad_record_mac, "bad record MAC");
-                }
-            }
-
 
             // if (!r.decompress(c))
             //     fatal(Alerts.alert_decompression_failure,
--- a/jdk/src/share/classes/sun/security/ssl/ServerHandshaker.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/ServerHandshaker.java	Fri Mar 15 23:31:19 2013 -0700
@@ -150,7 +150,7 @@
         // In SSLv3 and TLS, messages follow strictly increasing
         // numerical order _except_ for one annoying special case.
         //
-        if ((state > type)
+        if ((state >= type)
                 && (state != HandshakeMessage.ht_client_key_exchange
                     && type != HandshakeMessage.ht_certificate_verify)) {
             throw new SSLProtocolException(
@@ -250,13 +250,15 @@
         }
 
         //
-        // Move the state machine forward except for that annoying
-        // special case.  This means that clients could send extra
-        // cert verify messages; not a problem so long as all of
-        // them actually check out.
+        // Move state machine forward if the message handling
+        // code didn't already do so
         //
-        if (state < type && type != HandshakeMessage.ht_certificate_verify) {
-            state = type;
+        if (state < type) {
+            if(type == HandshakeMessage.ht_certificate_verify) {
+                state = type + 2;    // an annoying special case
+            } else {
+                state = type;
+            }
         }
     }
 
@@ -1406,7 +1408,7 @@
         if (debug != null && Debug.isOn("handshake")) {
             mesg.print(System.out);
         }
-        return dh.getAgreedSecret(mesg.getClientPublicKey());
+        return dh.getAgreedSecret(mesg.getClientPublicKey(), false);
     }
 
     private SecretKey clientKeyExchange(ECDHClientKeyExchange mesg)
--- a/jdk/src/share/classes/sun/security/ssl/SignatureAndHashAlgorithm.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/ssl/SignatureAndHashAlgorithm.java	Fri Mar 15 23:31:19 2013 -0700
@@ -38,7 +38,7 @@
 import java.util.Collections;
 import java.util.ArrayList;
 
-import sun.security.util.KeyLength;
+import sun.security.util.KeyUtil;
 
 /**
  * Signature and hash algorithm.
@@ -274,7 +274,7 @@
              * If key size is less than 512, the  digest length should be
              * less than or equal to 20 bytes.
              */
-            int keySize = KeyLength.getKeySize(signingKey);
+            int keySize = KeyUtil.getKeySize(signingKey);
             if (keySize >= 768) {
                 maxDigestLength = HashAlgorithm.SHA512.length;
             } else if ((keySize >= 512) && (keySize < 768)) {
--- a/jdk/src/share/classes/sun/security/util/DerIndefLenConverter.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/util/DerIndefLenConverter.java	Fri Mar 15 23:31:19 2013 -0700
@@ -325,6 +325,10 @@
             }
         }
 
+        if (unresolved != 0) {
+            throw new IOException("not all indef len BER resolved");
+        }
+
         newData = new byte[dataSize + numOfTotalLenBytes + unused];
         dataPos=0; newDataPos=0; index=0;
 
--- a/jdk/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/util/DisabledAlgorithmConstraints.java	Fri Mar 15 23:31:19 2013 -0700
@@ -440,7 +440,7 @@
 
         // Does this key constraint disable the specified key?
         public boolean disables(Key key) {
-            int size = KeyLength.getKeySize(key);
+            int size = KeyUtil.getKeySize(key);
 
             if (size == 0) {
                 return true;    // we don't allow any key of size 0.
--- a/jdk/src/share/classes/sun/security/util/KeyLength.java	Fri Mar 15 19:30:28 2013 +0530
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,91 +0,0 @@
-/*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.security.util;
-
-import java.security.Key;
-import java.security.PrivilegedAction;
-import java.security.AccessController;
-import java.security.interfaces.ECKey;
-import java.security.interfaces.RSAKey;
-import java.security.interfaces.DSAKey;
-import javax.crypto.SecretKey;
-import javax.crypto.interfaces.DHKey;
-
-/**
- * A utility class to get key length
- */
-public final class KeyLength {
-
-    /**
-     * Returns the key size of the given key object in bits.
-     *
-     * @param key the key object, cannot be null
-     * @return the key size of the given key object in bits, or -1 if the
-     *       key size is not accessible
-     */
-    final public static int getKeySize(Key key) {
-        int size = -1;
-
-        if (key instanceof Length) {
-            try {
-                Length ruler = (Length)key;
-                size = ruler.length();
-            } catch (UnsupportedOperationException usoe) {
-                // ignore the exception
-            }
-
-            if (size >= 0) {
-                return size;
-            }
-        }
-
-        // try to parse the length from key specification
-        if (key instanceof SecretKey) {
-            SecretKey sk = (SecretKey)key;
-            String format = sk.getFormat();
-            if ("RAW".equals(format) && sk.getEncoded() != null) {
-                size = (sk.getEncoded().length * 8);
-            }   // Otherwise, it may be a unextractable key of PKCS#11, or
-                // a key we are not able to handle.
-        } else if (key instanceof RSAKey) {
-            RSAKey pubk = (RSAKey)key;
-            size = pubk.getModulus().bitLength();
-        } else if (key instanceof ECKey) {
-            ECKey pubk = (ECKey)key;
-            size = pubk.getParams().getOrder().bitLength();
-        } else if (key instanceof DSAKey) {
-            DSAKey pubk = (DSAKey)key;
-            size = pubk.getParams().getP().bitLength();
-        } else if (key instanceof DHKey) {
-            DHKey pubk = (DHKey)key;
-            size = pubk.getParams().getP().bitLength();
-        }   // Otherwise, it may be a unextractable key of PKCS#11, or
-            // a key we are not able to handle.
-
-        return size;
-    }
-}
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/security/util/KeyUtil.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,204 @@
+/*
+ * 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.util;
+
+import java.security.Key;
+import java.security.PrivilegedAction;
+import java.security.AccessController;
+import java.security.InvalidKeyException;
+import java.security.interfaces.ECKey;
+import java.security.interfaces.RSAKey;
+import java.security.interfaces.DSAKey;
+import java.security.spec.KeySpec;
+import javax.crypto.SecretKey;
+import javax.crypto.interfaces.DHKey;
+import javax.crypto.interfaces.DHPublicKey;
+import javax.crypto.spec.DHParameterSpec;
+import javax.crypto.spec.DHPublicKeySpec;
+import java.math.BigInteger;
+
+/**
+ * A utility class to get key length, valiate keys, etc.
+ */
+public final class KeyUtil {
+
+    /**
+     * Returns the key size of the given key object in bits.
+     *
+     * @param key the key object, cannot be null
+     * @return the key size of the given key object in bits, or -1 if the
+     *       key size is not accessible
+     */
+    public static final int getKeySize(Key key) {
+        int size = -1;
+
+        if (key instanceof Length) {
+            try {
+                Length ruler = (Length)key;
+                size = ruler.length();
+            } catch (UnsupportedOperationException usoe) {
+                // ignore the exception
+            }
+
+            if (size >= 0) {
+                return size;
+            }
+        }
+
+        // try to parse the length from key specification
+        if (key instanceof SecretKey) {
+            SecretKey sk = (SecretKey)key;
+            String format = sk.getFormat();
+            if ("RAW".equals(format) && sk.getEncoded() != null) {
+                size = (sk.getEncoded().length * 8);
+            }   // Otherwise, it may be a unextractable key of PKCS#11, or
+                // a key we are not able to handle.
+        } else if (key instanceof RSAKey) {
+            RSAKey pubk = (RSAKey)key;
+            size = pubk.getModulus().bitLength();
+        } else if (key instanceof ECKey) {
+            ECKey pubk = (ECKey)key;
+            size = pubk.getParams().getOrder().bitLength();
+        } else if (key instanceof DSAKey) {
+            DSAKey pubk = (DSAKey)key;
+            size = pubk.getParams().getP().bitLength();
+        } else if (key instanceof DHKey) {
+            DHKey pubk = (DHKey)key;
+            size = pubk.getParams().getP().bitLength();
+        }   // Otherwise, it may be a unextractable key of PKCS#11, or
+            // a key we are not able to handle.
+
+        return size;
+    }
+
+    /**
+     * Returns whether the key is valid or not.
+     * <P>
+     * Note that this method is only apply to DHPublicKey at present.
+     *
+     * @param  publicKey
+     *         the key object, cannot be null
+     *
+     * @throws NullPointerException if {@code publicKey} is null
+     * @throws InvalidKeyException if {@code publicKey} is invalid
+     */
+    public static final void validate(Key key)
+            throws InvalidKeyException {
+        if (key == null) {
+            throw new NullPointerException(
+                "The key to be validated cannot be null");
+        }
+
+        if (key instanceof DHPublicKey) {
+            validateDHPublicKey((DHPublicKey)key);
+        }
+    }
+
+
+    /**
+     * Returns whether the key spec is valid or not.
+     * <P>
+     * Note that this method is only apply to DHPublicKeySpec at present.
+     *
+     * @param  keySpec
+     *         the key spec object, cannot be null
+     *
+     * @throws NullPointerException if {@code keySpec} is null
+     * @throws InvalidKeyException if {@code keySpec} is invalid
+     */
+    public static final void validate(KeySpec keySpec)
+            throws InvalidKeyException {
+        if (keySpec == null) {
+            throw new NullPointerException(
+                "The key spec to be validated cannot be null");
+        }
+
+        if (keySpec instanceof DHPublicKeySpec) {
+            validateDHPublicKey((DHPublicKeySpec)keySpec);
+        }
+    }
+
+    /**
+     * Returns whether the specified provider is Oracle provider or not.
+     * <P>
+     * Note that this method is only apply to SunJCE and SunPKCS11 at present.
+     *
+     * @param  providerName
+     *         the provider name
+     * @return true if, and only if, the provider of the specified
+     *         {@code providerName} is Oracle provider
+     */
+    public static final boolean isOracleJCEProvider(String providerName) {
+        return providerName != null && (providerName.equals("SunJCE") ||
+                                        providerName.startsWith("SunPKCS11"));
+    }
+
+    /**
+     * Returns whether the Diffie-Hellman public key is valid or not.
+     *
+     * Per RFC 2631 and NIST SP800-56A, the following algorithm is used to
+     * validate Diffie-Hellman public keys:
+     * 1. Verify that y lies within the interval [2,p-1]. If it does not,
+     *    the key is invalid.
+     * 2. Compute y^q mod p. If the result == 1, the key is valid.
+     *    Otherwise the key is invalid.
+     */
+    private static void validateDHPublicKey(DHPublicKey publicKey)
+            throws InvalidKeyException {
+        DHParameterSpec paramSpec = publicKey.getParams();
+
+        BigInteger p = paramSpec.getP();
+        BigInteger g = paramSpec.getG();
+        BigInteger y = publicKey.getY();
+
+        validateDHPublicKey(p, g, y);
+    }
+
+    private static void validateDHPublicKey(DHPublicKeySpec publicKeySpec)
+            throws InvalidKeyException {
+        validateDHPublicKey(publicKeySpec.getP(),
+            publicKeySpec.getG(), publicKeySpec.getY());
+    }
+
+    private static void validateDHPublicKey(BigInteger p,
+            BigInteger g, BigInteger y) throws InvalidKeyException {
+
+        // For better interoperability, the interval is limited to [2, p-2].
+        BigInteger leftOpen = BigInteger.ONE;
+        BigInteger rightOpen = p.subtract(BigInteger.ONE);
+        if (y.compareTo(leftOpen) <= 0) {
+            throw new InvalidKeyException(
+                    "Diffie-Hellman public key is too small");
+        }
+        if (y.compareTo(rightOpen) >= 0) {
+            throw new InvalidKeyException(
+                    "Diffie-Hellman public key is too large");
+        }
+
+        // Don't bother to check against the y^q mod p if safe primes are used.
+    }
+}
+
--- a/jdk/src/share/classes/sun/security/util/UntrustedCertificates.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/classes/sun/security/util/UntrustedCertificates.java	Fri Mar 15 23:31:19 2013 -0700
@@ -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
@@ -737,5 +737,111 @@
         "B8WfedLHjFW/TMcnXlEWKz4=\n" +
         "-----END CERTIFICATE-----");
 
+        //
+        // Revoked DigiCert code signing certificates used to sign malware
+        //
+
+        // Subject: CN=Buster Paper Comercial Ltda,
+        //          O=Buster Paper Comercial Ltda,
+        //          L=S?o Jos? Dos Campos,
+        //          ST=S?o Paulo,
+        //          C=BR
+        // Issuer:  CN=DigiCert Assured ID Code Signing CA-1,
+        //          OU=www.digicert.com,
+        //          O=DigiCert Inc,
+        //          C=US
+        // Serial:  07:b4:4c:db:ff:fb:78:de:05:f4:26:16:72:a6:73:12
+        add("buster-paper-comercial-ltda-72A67312",
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIIGwzCCBaugAwIBAgIQB7RM2//7eN4F9CYWcqZzEjANBgkqhkiG9w0BAQUFADBv\n" +
+        "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" +
+        "d3cuZGlnaWNlcnQuY29tMS4wLAYDVQQDEyVEaWdpQ2VydCBBc3N1cmVkIElEIENv\n" +
+        "ZGUgU2lnbmluZyBDQS0xMB4XDTEzMDExNzAwMDAwMFoXDTE0MDEyMjEyMDAwMFow\n" +
+        "gY4xCzAJBgNVBAYTAkJSMRMwEQYDVQQIDApTw6NvIFBhdWxvMR4wHAYDVQQHDBVT\n" +
+        "w6NvIEpvc8OpIERvcyBDYW1wb3MxJDAiBgNVBAoTG0J1c3RlciBQYXBlciBDb21l\n" +
+        "cmNpYWwgTHRkYTEkMCIGA1UEAxMbQnVzdGVyIFBhcGVyIENvbWVyY2lhbCBMdGRh\n" +
+        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzO0l6jWIpEfO2oUpVHpL\n" +
+        "HETj5lzivNb0S9jKHgGJax917czh81PnGTxwxFXd6gLJuy/XFHvmiSi8g8jzlymn\n" +
+        "2Ji5zQ3CPaz7nomJokSUDlMVJ2qYWtctw4jrdjuI4qtn+koXXUFkWjkf8h8251I4\n" +
+        "tUs7S49HE2Go5owCYP3byajj7fsFAYR/Xb7TdVtndkZsUB/YgOjHovyACjouaNCi\n" +
+        "mDiRyQ6zLLjZGiyeD65Yiseuhp5b8/BL5h1p7w76QYMYMVQNAdtDKut2R8MBpuWf\n" +
+        "Ny7Eoi0x/gm1p9X5Rcl5aN7K0G4UtTAJKbkuUfXddsyFoM0Nx8uo8SgNQ8Y/X5Jx\n" +
+        "BwIDAQABo4IDOTCCAzUwHwYDVR0jBBgwFoAUe2jOKarAF75JeuHlP9an90WPNTIw\n" +
+        "HQYDVR0OBBYEFFLZ3n5nt/Eer7n1bvtOqMb1qKO5MA4GA1UdDwEB/wQEAwIHgDAT\n" +
+        "BgNVHSUEDDAKBggrBgEFBQcDAzBzBgNVHR8EbDBqMDOgMaAvhi1odHRwOi8vY3Js\n" +
+        "My5kaWdpY2VydC5jb20vYXNzdXJlZC1jcy0yMDExYS5jcmwwM6AxoC+GLWh0dHA6\n" +
+        "Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9hc3N1cmVkLWNzLTIwMTFhLmNybDCCAcQGA1Ud\n" +
+        "IASCAbswggG3MIIBswYJYIZIAYb9bAMBMIIBpDA6BggrBgEFBQcCARYuaHR0cDov\n" +
+        "L3d3dy5kaWdpY2VydC5jb20vc3NsLWNwcy1yZXBvc2l0b3J5Lmh0bTCCAWQGCCsG\n" +
+        "AQUFBwICMIIBVh6CAVIAQQBuAHkAIAB1AHMAZQAgAG8AZgAgAHQAaABpAHMAIABD\n" +
+        "AGUAcgB0AGkAZgBpAGMAYQB0AGUAIABjAG8AbgBzAHQAaQB0AHUAdABlAHMAIABh\n" +
+        "AGMAYwBlAHAAdABhAG4AYwBlACAAbwBmACAAdABoAGUAIABEAGkAZwBpAEMAZQBy\n" +
+        "AHQAIABDAFAALwBDAFAAUwAgAGEAbgBkACAAdABoAGUAIABSAGUAbAB5AGkAbgBn\n" +
+        "ACAAUABhAHIAdAB5ACAAQQBnAHIAZQBlAG0AZQBuAHQAIAB3AGgAaQBjAGgAIABs\n" +
+        "AGkAbQBpAHQAIABsAGkAYQBiAGkAbABpAHQAeQAgAGEAbgBkACAAYQByAGUAIABp\n" +
+        "AG4AYwBvAHIAcABvAHIAYQB0AGUAZAAgAGgAZQByAGUAaQBuACAAYgB5ACAAcgBl\n" +
+        "AGYAZQByAGUAbgBjAGUALjCBggYIKwYBBQUHAQEEdjB0MCQGCCsGAQUFBzABhhho\n" +
+        "dHRwOi8vb2NzcC5kaWdpY2VydC5jb20wTAYIKwYBBQUHMAKGQGh0dHA6Ly9jYWNl\n" +
+        "cnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEFzc3VyZWRJRENvZGVTaWduaW5nQ0Et\n" +
+        "MS5jcnQwDAYDVR0TAQH/BAIwADANBgkqhkiG9w0BAQUFAAOCAQEAPTTQvpOIikXI\n" +
+        "hTLnNbajaFRR5GhQpTzUNgBfF9VYSlNw/wMjpGsrh5RxaJCip52jbehmTgjMRhft\n" +
+        "jRYyml44PAVsCcR9uEoDpCZYpI1fHI1R+F8jd1C9rqprbSwwOG4xlg4SmvTHYs6e\n" +
+        "gBItQ/1p9XY+Sf4Wv1qOuOFL1qvV/5VyR2zdlOQCmKCeMgxt6a/tHLBDiAA67D44\n" +
+        "/vfdoNJl0CU2It0PO60jdCPFNWIRcxL+OSDqAoePeUC7xQ+JsTEIxuUE8+d6w6fc\n" +
+        "BV2mYb1flh22t46GLjh4gyo7xw3aL6L0L0jzlTT6IcEw6NIbaPbIKj/npQnHobYj\n" +
+        "XMuKLxbh7g==\n" +
+        "-----END CERTIFICATE-----");
+
+        // Subject: CN=BUSTER ASSISTENCIA TECNICA ELETRONICA LTDA - ME,
+        //          O=BUSTER ASSISTENCIA TECNICA ELETRONICA LTDA - ME,
+        //          L=S?o Paulo,
+        //          ST=S?o Paulo,
+        //          C=BR
+        // Issuer:  CN=DigiCert Assured ID Code Signing CA-1,
+        //          OU=www.digicert.com,
+        //          O=DigiCert Inc,
+        //          C=US
+        // Serial:  0a:38:9b:95:ee:73:6d:d1:3b:c0:ed:74:3f:d7:4d:2f
+        add("buster-assistencia-tecnica-electronica-ltda-3FD74D2F",
+        "-----BEGIN CERTIFICATE-----\n" +
+        "MIIG4DCCBcigAwIBAgIQCjible5zbdE7wO10P9dNLzANBgkqhkiG9w0BAQUFADBv\n" +
+        "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" +
+        "d3cuZGlnaWNlcnQuY29tMS4wLAYDVQQDEyVEaWdpQ2VydCBBc3N1cmVkIElEIENv\n" +
+        "ZGUgU2lnbmluZyBDQS0xMB4XDTEyMTEwOTAwMDAwMFoXDTEzMTExNDEyMDAwMFow\n" +
+        "gasxCzAJBgNVBAYTAkJSMRMwEQYDVQQIDApTw6NvIFBhdWxvMRMwEQYDVQQHDApT\n" +
+        "w6NvIFBhdWxvMTgwNgYDVQQKEy9CVVNURVIgQVNTSVNURU5DSUEgVEVDTklDQSBF\n" +
+        "TEVUUk9OSUNBIExUREEgLSBNRTE4MDYGA1UEAxMvQlVTVEVSIEFTU0lTVEVOQ0lB\n" +
+        "IFRFQ05JQ0EgRUxFVFJPTklDQSBMVERBIC0gTUUwggEiMA0GCSqGSIb3DQEBAQUA\n" +
+        "A4IBDwAwggEKAoIBAQDAqNeEs5/B2CTXGjTOkUIdu6jV6qulOZwdw4sefHWYj1UR\n" +
+        "4z6zPk9kjpUgbnb402RFq88QtfInwddZ/wXn9OxMtDd/3TnC7HrhNS7ga79ZFL2V\n" +
+        "JnmzKHum2Yvh0q82QEJ9tHBR2X9VdKpUIH08Zs3k6cWWM1H0YX0cxA/HohhesQJW\n" +
+        "kwJ3urOIJiH/HeByDk8a1NS8safcCxk5vxvW4WvCg43iT09LeHY5Aa8abKw8lqVb\n" +
+        "0tD5ZSIjdmdj3TT1U37iAHLLRM2DXbxfdbhouUX1c5U1ZHAMA67HwjKiseOiDaHj\n" +
+        "NUGbC37C+cgbc9VVM/cURD8WvS0Kj6fQv7F2QtJDAgMBAAGjggM5MIIDNTAfBgNV\n" +
+        "HSMEGDAWgBR7aM4pqsAXvkl64eU/1qf3RY81MjAdBgNVHQ4EFgQU88EXKAyDsh30\n" +
+        "o9+Gu9a4xUy+FSMwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMD\n" +
+        "MHMGA1UdHwRsMGowM6AxoC+GLWh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9hc3N1\n" +
+        "cmVkLWNzLTIwMTFhLmNybDAzoDGgL4YtaHR0cDovL2NybDQuZGlnaWNlcnQuY29t\n" +
+        "L2Fzc3VyZWQtY3MtMjAxMWEuY3JsMIIBxAYDVR0gBIIBuzCCAbcwggGzBglghkgB\n" +
+        "hv1sAwEwggGkMDoGCCsGAQUFBwIBFi5odHRwOi8vd3d3LmRpZ2ljZXJ0LmNvbS9z\n" +
+        "c2wtY3BzLXJlcG9zaXRvcnkuaHRtMIIBZAYIKwYBBQUHAgIwggFWHoIBUgBBAG4A\n" +
+        "eQAgAHUAcwBlACAAbwBmACAAdABoAGkAcwAgAEMAZQByAHQAaQBmAGkAYwBhAHQA\n" +
+        "ZQAgAGMAbwBuAHMAdABpAHQAdQB0AGUAcwAgAGEAYwBjAGUAcAB0AGEAbgBjAGUA\n" +
+        "IABvAGYAIAB0AGgAZQAgAEQAaQBnAGkAQwBlAHIAdAAgAEMAUAAvAEMAUABTACAA\n" +
+        "YQBuAGQAIAB0AGgAZQAgAFIAZQBsAHkAaQBuAGcAIABQAGEAcgB0AHkAIABBAGcA\n" +
+        "cgBlAGUAbQBlAG4AdAAgAHcAaABpAGMAaAAgAGwAaQBtAGkAdAAgAGwAaQBhAGIA\n" +
+        "aQBsAGkAdAB5ACAAYQBuAGQAIABhAHIAZQAgAGkAbgBjAG8AcgBwAG8AcgBhAHQA\n" +
+        "ZQBkACAAaABlAHIAZQBpAG4AIABiAHkAIAByAGUAZgBlAHIAZQBuAGMAZQAuMIGC\n" +
+        "BggrBgEFBQcBAQR2MHQwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0\n" +
+        "LmNvbTBMBggrBgEFBQcwAoZAaHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0Rp\n" +
+        "Z2lDZXJ0QXNzdXJlZElEQ29kZVNpZ25pbmdDQS0xLmNydDAMBgNVHRMBAf8EAjAA\n" +
+        "MA0GCSqGSIb3DQEBBQUAA4IBAQAei1QmiXepje8OIfo/WonD4MIXgpPr2dfRaquQ\n" +
+        "A8q63OpTRSveyqdQDCSPpDRF/nvO1Y30yksZvIH1tNBsW5LBdxAKN3lFdBlqBwtE\n" +
+        "Q3jHc0KVVYRJ0FBaGE/PJHmRajscdAhYIcMPhTga0u0tDK+wOHEq3993dfl6yHjA\n" +
+        "XHU2iW5pnk75ZoE39zALD5eKXT8ZXrET5c3XUFJKWA+XuGmdmyzqo0Au49PanBv9\n" +
+        "UlZnabYfqoMArqMS0tGSX4cGgi9/2E+pHG9BX4sFW+ZDumroOA2pxyMWEKjxePEL\n" +
+        "zCOfhbsRWdMLYepauaNZOIMZXmFwcrIl0TGMkTAtATz+XmZc\n" +
+        "-----END CERTIFICATE-----");
+
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/swing/JLightweightFrame.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,250 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.swing;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.EventQueue;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.Rectangle;
+import java.awt.image.BufferedImage;
+import java.awt.image.DataBufferInt;
+
+import javax.swing.JLayeredPane;
+import javax.swing.JPanel;
+import javax.swing.JRootPane;
+import javax.swing.LayoutFocusTraversalPolicy;
+import javax.swing.RootPaneContainer;
+
+import sun.awt.LightweightFrame;
+
+/**
+ * The frame serves as a lightweight container which paints its content
+ * to an offscreen image and provides access to the image's data via the
+ * {@link LightweightContent} interface. Note, that it may not be shown
+ * as a standalone toplevel frame. Its purpose is to provide functionality
+ * for lightweight embedding.
+ *
+ * @author Artem Ananiev
+ * @author Anton Tarasov
+ */
+public final class JLightweightFrame extends LightweightFrame implements RootPaneContainer {
+
+    private final JRootPane rootPane = new JRootPane();
+
+    private LightweightContent content;
+
+    private Component component;
+    private JPanel contentPane;
+
+    private BufferedImage bbImage;
+
+    /**
+     * Constructs a new, initially invisible {@code JLightweightFrame}
+     * instance.
+     */
+    public JLightweightFrame() {
+        super();
+        add(rootPane, BorderLayout.CENTER);
+        setBackground(new Color(0, 0, 0, 0));
+        setFocusTraversalPolicy(new LayoutFocusTraversalPolicy());
+    }
+
+    /**
+     * Sets the {@link LightweightContent} instance for this frame.
+     * The {@code JComponent} object returned by the
+     * {@link LightweightContent#getComponent()} method is immediately
+     * added to the frame's content pane.
+     *
+     * @param content the {@link LightweightContent} instance
+     */
+    public void setContent(LightweightContent content) {
+        this.content = content;
+        this.component = content.getComponent();
+
+        initInterior();
+    }
+
+    @Override
+    public Graphics getGraphics() {
+        if (bbImage == null) return null;
+
+        Graphics2D g = bbImage.createGraphics();
+        g.setBackground(getBackground());
+        g.setColor(getForeground());
+        g.setFont(getFont());
+        return g;
+    }
+
+    /**
+     * {@inheritDoc}
+     *
+     * @see LightweightContent#focusGrabbed()
+     */
+    @Override
+    public void grabFocus() {
+        if (content != null) content.focusGrabbed();
+    }
+
+    /**
+     * {@inheritDoc}
+     *
+     * @see LightweightContent#focusUngrabbed()
+     */
+    @Override
+    public void ungrabFocus() {
+        if (content != null) content.focusUngrabbed();
+    }
+
+    private void initInterior() {
+        contentPane = new JPanel() {
+            @Override
+            public void paint(Graphics g) {
+                content.paintLock();
+                try {
+                    super.paint(g);
+
+                    final Rectangle clip = g.getClipBounds() != null ?
+                            g.getClipBounds() : new Rectangle(0, 0, contentPane.getWidth(), contentPane.getHeight());
+
+                    clip.x = Math.max(0, clip.x);
+                    clip.y = Math.max(0, clip.y);
+                    clip.width = Math.min(contentPane.getWidth(), clip.width);
+                    clip.height = Math.min(contentPane.getHeight(), clip.height);
+
+                    EventQueue.invokeLater(new Runnable() {
+                        @Override
+                        public void run() {
+                            content.imageUpdated(clip.x, clip.y, clip.width, clip.height);
+                        }
+                    });
+                } finally {
+                    content.paintUnlock();
+                }
+            }
+            @Override
+            protected boolean isPaintingOrigin() {
+                return true;
+            }
+        };
+        contentPane.setLayout(new BorderLayout());
+        contentPane.add(component);
+        setContentPane(contentPane);
+    }
+
+    @SuppressWarnings("deprecation")
+    @Override public void reshape(int x, int y, int width, int height) {
+        super.reshape(x, y, width, height);
+
+        if (width == 0 || height == 0) {
+            return;
+        }
+
+        content.paintLock();
+        try {
+            if ((bbImage == null) || (width != bbImage.getWidth()) || (height != bbImage.getHeight())) {
+                boolean createBB = true;
+                int newW = width;
+                int newH = height;
+                if (bbImage != null) {
+                    int oldW = bbImage.getWidth();
+                    int oldH = bbImage.getHeight();
+                    if ((oldW >= newW) && (oldH >= newH)) {
+                        createBB = false;
+                    } else {
+                        if (oldW >= newW) {
+                            newW = oldW;
+                        } else {
+                            newW = Math.max((int)(oldW * 1.2), width);
+                        }
+                        if (oldH >= newH) {
+                            newH = oldH;
+                        } else {
+                            newH = Math.max((int)(oldH * 1.2), height);
+                        }
+                    }
+                }
+                if (createBB) {
+                    BufferedImage oldBB = bbImage;
+                    bbImage = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB_PRE);
+                    if (oldBB != null) {
+                        Graphics g = bbImage.getGraphics();
+                        try {
+                            g.drawImage(oldBB, 0, 0, newW, newH, null);
+                        } finally {
+                            g.dispose();
+                            oldBB.flush();
+                        }
+                    }
+                    DataBufferInt dataBuf = (DataBufferInt)bbImage.getRaster().getDataBuffer();
+                    content.imageBufferReset(dataBuf.getData(), 0, 0, width, height, bbImage.getWidth());
+                } else {
+                    content.imageReshaped(0, 0, width, height);
+                }
+            }
+        } finally {
+            content.paintUnlock();
+        }
+    }
+
+    @Override
+    public JRootPane getRootPane() {
+        return rootPane;
+    }
+
+    @Override
+    public void setContentPane(Container contentPane) {
+        getRootPane().setContentPane(contentPane);
+    }
+
+    @Override
+    public Container getContentPane() {
+        return getRootPane().getContentPane();
+    }
+
+    @Override
+    public void setLayeredPane(JLayeredPane layeredPane) {
+        getRootPane().setLayeredPane(layeredPane);
+    }
+
+    @Override
+    public JLayeredPane getLayeredPane() {
+        return getRootPane().getLayeredPane();
+    }
+
+    @Override
+    public void setGlassPane(Component glassPane) {
+        getRootPane().setGlassPane(glassPane);
+    }
+
+    @Override
+    public Component getGlassPane() {
+        return getRootPane().getGlassPane();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/sun/swing/LightweightContent.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.swing;
+
+import javax.swing.JComponent;
+
+/**
+ * The interface by means of which the {@link JLightweightFrame} class
+ * communicates to its client application.
+ * <p>
+ * The client application implements this interface so it can response
+ * to requests and process notifications from {@code JLightweightFrame}.
+ * An implementation of this interface is associated with a {@code
+ * JLightweightFrame} instance via the {@link JLightweightFrame#setContent}
+ * method.
+ *
+ * A hierarchy of components contained in the {@code JComponent} instance
+ * returned by the {@link #getComponent} method should not contain any
+ * heavyweight components, otherwise {@code JLightweightFrame} may fail
+ * to paint it.
+ *
+ * @author Artem Ananiev
+ * @author Anton Tarasov
+ * @author Jim Graham
+ */
+public interface LightweightContent {
+
+    /**
+     * The client application overrides this method to return the {@code
+     * JComponent} instance which the {@code JLightweightFrame} container
+     * will paint as its lightweight content. A hierarchy of components
+     * contained in this component should not contain any heavyweight objects.
+     *
+     * @return the component to paint
+     */
+    public JComponent getComponent();
+
+    /**
+     * {@code JLightweightFrame} calls this method to notify the client
+     * application that it acquires the paint lock. The client application
+     * should implement the locking mechanism in order to synchronize access
+     * to the content image data, shared between {@code JLightweightFrame}
+     * and the client application.
+     *
+     * @see #paintUnlock
+     */
+    public void paintLock();
+
+    /**
+     * {@code JLightweightFrame} calls this method to notify the client
+     * application that it releases the paint lock. The client application
+     * should implement the locking mechanism in order to synchronize access
+     * to the content image data, shared between {@code JLightweightFrame}
+     * and the client application.
+     *
+     * @see #paintLock
+     */
+    public void paintUnlock();
+
+    /**
+     * {@code JLightweightFrame} calls this method to notify the client
+     * application that a new data buffer has been set as a content pixel
+     * buffer. Typically this occurs when a buffer of a larger size is
+     * created in response to a content resize event. The method reports
+     * a reference to the pixel data buffer, the content image bounds
+     * within the buffer and the line stride of the buffer. These values
+     * have the following correlation.
+     * <p>
+     * The {@code width} and {@code height} matches the size of the content
+     * (the component returned from the {@link #getComponent} method). The
+     * {@code x} and {@code y} is the origin of the content, {@code (0, 0)}
+     * in the coordinate space of the content, appearing at
+     * {@code data[y * linestride + x]} in the buffer. All indices
+     * {@code data[(y + j) * linestride + (x + i)]} where
+     * {@code (0 <= i < width)} and {@code (0 <= j < height)} will represent
+     * valid pixel data, {@code (i, j)} in the coordinate space of the content.
+     *
+     * @param data the content pixel data buffer of INT_ARGB_PRE type
+     * @param x the x coordinate of the image
+     * @param y the y coordinate of the image
+     * @param width the width of the image
+     * @param height the height of the image
+     * @param linestride the line stride of the pixel buffer
+     */
+    public void imageBufferReset(int[] data,
+                                 int x, int y,
+                                 int width, int height,
+                                 int linestride);
+
+    /**
+     * {@code JLightweightFrame} calls this method to notify the client
+     * application that the content image bounds have been changed within the
+     * image's pixel buffer.
+     *
+     * @param x the x coordinate of the image
+     * @param y the y coordinate of the image
+     * @param width the width of the image
+     * @param height the height of the image
+     *
+     * @see #imageBufferReset
+     */
+    public void imageReshaped(int x, int y, int width, int height);
+
+    /**
+     * {@code JLightweightFrame} calls this method to notify the client
+     * application that a part of the content image, or the whole image has
+     * been updated. The method reports bounds of the rectangular dirty region.
+     * The {@code dirtyX} and {@code dirtyY} is the origin of the dirty
+     * rectangle, which is relative to the origin of the content, appearing
+     * at {@code data[(y + dirtyY] * linestride + (x + dirtyX)]} in the pixel
+     * buffer (see {@link #imageBufferReset}). All indices
+     * {@code data[(y + dirtyY + j) * linestride + (x + dirtyX + i)]} where
+     * {@code (0 <= i < dirtyWidth)} and {@code (0 <= j < dirtyHeight)}
+     * will represent valid pixel data, {@code (i, j)} in the coordinate space
+     * of the dirty rectangle.
+     *
+     * @param dirtyX the x coordinate of the dirty rectangle,
+     *        relative to the image origin
+     * @param dirtyY the y coordinate of the dirty rectangle,
+     *        relative to the image origin
+     * @param dirtyWidth the width of the dirty rectangle
+     * @param dirtyHeight the height of the dirty rectangle
+     *
+     * @see #imageBufferReset
+     * @see #imageReshaped
+     */
+    public void imageUpdated(int dirtyX, int dirtyY,
+                             int dirtyWidth, int dirtyHeight);
+
+    /**
+     * {@code JLightweightFrame} calls this method to notify the client
+     * application that the frame has grabbed focus.
+     */
+    public void focusGrabbed();
+
+    /**
+     * {@code JLightweightFrame} calls this method to notify the client
+     * application that the frame has ungrabbed focus.
+     */
+    public void focusUngrabbed();
+}
--- a/jdk/src/share/demo/java2d/J2DBench/build.xml	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/demo/java2d/J2DBench/build.xml	Fri Mar 15 23:31:19 2013 -0700
@@ -52,7 +52,7 @@
     <javac debug="flase" source="1.5" target="1.5" srcdir="${src}" destdir="${build}"/>
   </target>
 
-  <target name="run" depends="dist" 
+  <target name="run" depends="dist"
     description="run J2DBench" >
     <java jar="${dist}/J2DBench.jar"
        fork="true"
@@ -60,7 +60,7 @@
     </java>
   </target>
 
-  <target name="analyze" depends="dist" 
+  <target name="analyze" depends="dist"
     description="run J2DAnalyzer" >
     <java jar="${dist}/J2DAnalyzer.jar"
        fork="true"
@@ -80,6 +80,10 @@
     <copy todir="${build}/j2dbench/tests/iio/images">
       <fileset dir="${resources}/images" />
     </copy>
+    <mkdir dir="${build}/j2dbench/tests/cmm/images"/>
+    <copy todir="${build}/j2dbench/tests/cmm/images">
+      <fileset dir="${resources}/cmm_images" />
+    </copy>
   </target>
 
   <target name="dist" depends="compile, resources"
@@ -88,14 +92,14 @@
     <mkdir dir="${dist}"/>
 
     <!-- Put everything in ${build} into the J2DBench.jar file -->
-    <jar jarfile="${dist}/J2DBench.jar" basedir="${build}" 
+    <jar jarfile="${dist}/J2DBench.jar" basedir="${build}"
         excludes="j2dbench/report/**" >
       <manifest>
         <attribute name="Built-By" value="${user.name}"/>
 	<attribute name="Main-Class" value="j2dbench.J2DBench"/>
       </manifest>
     </jar>
-    <jar jarfile="${dist}/J2DAnalyzer.jar" basedir="${build}" 
+    <jar jarfile="${dist}/J2DAnalyzer.jar" basedir="${build}"
         includes="j2dbench/report/**" >
       <manifest>
         <attribute name="Built-By" value="${user.name}"/>
Binary file jdk/src/share/demo/java2d/J2DBench/resources/cmm_images/img_icc_large.jpg has changed
Binary file jdk/src/share/demo/java2d/J2DBench/resources/cmm_images/img_icc_medium.jpg has changed
Binary file jdk/src/share/demo/java2d/J2DBench/resources/cmm_images/img_icc_small.jpg has changed
--- a/jdk/src/share/demo/java2d/J2DBench/src/j2dbench/tests/cmm/ColorConversionTests.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/demo/java2d/J2DBench/src/j2dbench/tests/cmm/ColorConversionTests.java	Fri Mar 15 23:31:19 2013 -0700
@@ -51,6 +51,7 @@
 
         DataConversionTests.init();
         ColorConvertOpTests.init();
+        EmbeddedProfileTests.init();
     }
 
     protected ColorConversionTests(Group parent, String nodeName, String description) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/demo/java2d/J2DBench/src/j2dbench/tests/cmm/EmbeddedProfileTests.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2013, 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 java.awt.image.BufferedImage;
+import java.io.IOException;
+import java.net.URL;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReader;
+import javax.imageio.stream.ImageInputStream;
+
+/* This benchmark verifies how changes in cmm library affects image decoding */
+public class EmbeddedProfileTests extends ColorConversionTests {
+
+    protected static Group grpRoot;
+    protected static Group grpOptionsRoot;
+
+    protected static Option inputImages;
+
+    public static void init() {
+        grpRoot = new Group(colorConvRoot, "embed", "Embedded Profile Tests");
+
+        grpOptionsRoot = new Group(grpRoot, "embedOptions", "Options");
+
+        inputImages = createImageList();
+
+        new ReadImageTest();
+    }
+
+    private static enum IccImageResource {
+        SMALL("images/img_icc_small.jpg", "512x512", "Small: 512x512"),
+        MEDIUM("images/img_icc_medium.jpg", "2048x2048", "Medium: 2048x2048"),
+        LARGE("images/img_icc_large.jpg", "4096x4096", "Large: 4096x4096");
+
+        private IccImageResource(String file, String name, String description) {
+            this.url = CMMTests.class.getResource(file);
+            this.abbrev = name;
+            this.description = description;
+        }
+
+        public final URL url;
+        public final String abbrev;
+        public final String description;
+    }
+
+    private static Option createImageList() {
+        IccImageResource[] images = IccImageResource.values();
+
+        int num = images.length;
+
+        String[] names = new String[num];
+        String[] abbrev = new String[num];
+        String[] descr = new String[num];
+
+        for (int i = 0; i < num; i++) {
+            names[i] = images[i].toString();
+            abbrev[i] = images[i].abbrev;
+            descr[i] = images[i].description;
+        }
+
+         Option list = new Option.ObjectList(grpOptionsRoot,
+                "Images", "Input Images",
+                names, images, abbrev, descr, 1);
+
+         return list;
+    }
+
+    public EmbeddedProfileTests(Group parent, String nodeName, String description) {
+        super(parent, nodeName, description);
+        addDependencies(grpOptionsRoot, true);
+    }
+
+    private static class Context {
+        URL input;
+
+        public Context(TestEnvironment env, Result res) {
+
+            IccImageResource icc_input = (IccImageResource)
+                    env.getModifier(inputImages);
+
+            input = icc_input.url;
+        }
+    }
+
+     public Object initTest(TestEnvironment env, Result res) {
+        return new Context(env, res);
+    }
+
+    public void cleanupTest(TestEnvironment env, Object o) {
+        Context ctx = (Context)o;
+        ctx.input = null;
+    }
+
+    private static class ReadImageTest extends EmbeddedProfileTests {
+        public ReadImageTest() {
+            super(grpRoot, "embd_img_read", "ImageReader.read()");
+        }
+
+        public void runTest(Object octx, int numReps) {
+            final Context ctx = (Context)octx;
+            final URL url = ctx.input;
+            ImageInputStream iis = null;
+            ImageReader reader = null;
+
+            try {
+                iis = ImageIO.createImageInputStream(url.openStream());
+                reader = ImageIO.getImageReaders(iis).next();
+            } catch (IOException e) {
+                throw new RuntimeException("Unable to run the becnhmark", e);
+            }
+
+            do {
+                try {
+                    reader.setInput(iis);
+                    BufferedImage img = reader.read(0);
+                    reader.reset();
+
+                    iis = ImageIO.createImageInputStream(url.openStream());
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+            } while (--numReps >= 0);
+        }
+    }
+}
--- a/jdk/src/share/lib/security/java.security-linux	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/lib/security/java.security-linux	Fri Mar 15 23:31:19 2013 -0700
@@ -145,7 +145,19 @@
 # passed to checkPackageAccess unless the
 # corresponding RuntimePermission ("accessClassInPackage."+package) has
 # been granted.
-package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
+package.access=sun.,\
+               com.sun.xml.internal.bind.,\
+               com.sun.xml.internal.org.jvnet.staxex.,\
+               com.sun.xml.internal.ws.,\
+               com.sun.imageio.,\
+               com.sun.istack.internal.,\
+               com.sun.jmx.,\
+               com.sun.proxy.,\
+               com.sun.org.apache.xerces.internal.utils.,\
+               com.sun.org.apache.xalan.internal.utils.,\
+               com.sun.org.glassfish.external.,\
+               com.sun.org.glassfish.gmbal.,\
+	       jdk.internal.
 
 #
 # List of comma-separated packages that start with or equal this string
@@ -157,7 +169,19 @@
 # by default, none of the class loaders supplied with the JDK call
 # checkPackageDefinition.
 #
-package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
+package.definition=sun.,\
+                   com.sun.xml.internal.bind.,\
+                   com.sun.xml.internal.org.jvnet.staxex.,\
+                   com.sun.xml.internal.ws.,\
+                   com.sun.imageio.,\
+                   com.sun.istack.internal.,\
+                   com.sun.jmx.,\
+                   com.sun.proxy.,\
+                   com.sun.org.apache.xerces.internal.utils.,\
+                   com.sun.org.apache.xalan.internal.utils.,\
+                   com.sun.org.glassfish.external.,\
+                   com.sun.org.glassfish.gmbal.,\
+		   jdk.internal.
 
 #
 # Determines whether this properties file can be appended to
--- a/jdk/src/share/lib/security/java.security-macosx	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/lib/security/java.security-macosx	Fri Mar 15 23:31:19 2013 -0700
@@ -146,7 +146,20 @@
 # passed to checkPackageAccess unless the
 # corresponding RuntimePermission ("accessClassInPackage."+package) has
 # been granted.
-package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,apple.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
+package.access=sun.,\
+               com.sun.xml.internal.bind.,\
+               com.sun.xml.internal.org.jvnet.staxex.,\
+               com.sun.xml.internal.ws.,\
+               com.sun.imageio.,\
+               com.sun.istack.internal.,\
+               com.sun.jmx.,\
+               com.sun.proxy.,\
+               com.sun.org.apache.xerces.internal.utils.,\
+               com.sun.org.apache.xalan.internal.utils.,\
+               com.sun.org.glassfish.external.,\
+               com.sun.org.glassfish.gmbal.,\
+	       jdk.internal.,\
+               apple.
 
 #
 # List of comma-separated packages that start with or equal this string
@@ -158,7 +171,20 @@
 # by default, none of the class loaders supplied with the JDK call
 # checkPackageDefinition.
 #
-package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,apple.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
+package.definition=sun.,\
+                   com.sun.xml.internal.bind.,\
+                   com.sun.xml.internal.org.jvnet.staxex.,\
+                   com.sun.xml.internal.ws.,\
+                   com.sun.imageio.,\
+                   com.sun.istack.internal.,\
+                   com.sun.jmx.,\
+                   com.sun.proxy.,\
+                   com.sun.org.apache.xerces.internal.utils.,\
+                   com.sun.org.apache.xalan.internal.utils.,\
+                   com.sun.org.glassfish.external.,\
+                   com.sun.org.glassfish.gmbal.,\
+		   jdk.internal.,\
+                   apple.
 
 #
 # Determines whether this properties file can be appended to
--- a/jdk/src/share/lib/security/java.security-solaris	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/lib/security/java.security-solaris	Fri Mar 15 23:31:19 2013 -0700
@@ -147,7 +147,19 @@
 # passed to checkPackageAccess unless the
 # corresponding RuntimePermission ("accessClassInPackage."+package) has
 # been granted.
-package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
+package.access=sun.,\
+               com.sun.xml.internal.bind.,\
+               com.sun.xml.internal.org.jvnet.staxex.,\
+               com.sun.xml.internal.ws.,\
+               com.sun.imageio.,\
+               com.sun.istack.internal.,\
+               com.sun.jmx.,\
+               com.sun.proxy.,\
+               com.sun.org.apache.xerces.internal.utils.,\
+               com.sun.org.apache.xalan.internal.utils.,\
+               com.sun.org.glassfish.external.,\
+               com.sun.org.glassfish.gmbal.,\
+	       jdk.internal.
 
 #
 # List of comma-separated packages that start with or equal this string
@@ -159,7 +171,19 @@
 # by default, none of the class loaders supplied with the JDK call
 # checkPackageDefinition.
 #
-package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
+package.definition=sun.,\
+                   com.sun.xml.internal.bind.,\
+                   com.sun.xml.internal.org.jvnet.staxex.,\
+                   com.sun.xml.internal.ws.,\
+                   com.sun.imageio.,\
+                   com.sun.istack.internal.,\
+                   com.sun.jmx.,\
+                   com.sun.proxy.,\
+                   com.sun.org.apache.xerces.internal.utils.,\
+                   com.sun.org.apache.xalan.internal.utils.,\
+                   com.sun.org.glassfish.external.,\
+                   com.sun.org.glassfish.gmbal.,\
+		   jdk.internal.
 
 #
 # Determines whether this properties file can be appended to
--- a/jdk/src/share/lib/security/java.security-windows	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/lib/security/java.security-windows	Fri Mar 15 23:31:19 2013 -0700
@@ -146,7 +146,19 @@
 # passed to checkPackageAccess unless the
 # corresponding RuntimePermission ("accessClassInPackage."+package) has
 # been granted.
-package.access=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
+package.access=sun.,\
+               com.sun.xml.internal.bind.,\
+               com.sun.xml.internal.org.jvnet.staxex.,\
+               com.sun.xml.internal.ws.,\
+               com.sun.imageio.,\
+               com.sun.istack.internal.,\
+               com.sun.jmx.,\
+               com.sun.proxy.,\
+               com.sun.org.apache.xerces.internal.utils.,\
+               com.sun.org.apache.xalan.internal.utils.,\
+               com.sun.org.glassfish.external.,\
+               com.sun.org.glassfish.gmbal.,\
+	       jdk.internal.
 
 #
 # List of comma-separated packages that start with or equal this string
@@ -158,7 +170,19 @@
 # by default, none of the class loaders supplied with the JDK call
 # checkPackageDefinition.
 #
-package.definition=sun.,com.sun.xml.internal.ws.,com.sun.xml.internal.bind.,com.sun.imageio.,com.sun.org.apache.xerces.internal.utils.,com.sun.org.apache.xalan.internal.utils.,com.sun.org.glassfish.external.,com.sun.org.glassfish.gmbal.,jdk.internal.
+package.definition=sun.,\
+                   com.sun.xml.internal.bind.,\
+                   com.sun.xml.internal.org.jvnet.staxex.,\
+                   com.sun.xml.internal.ws.,\
+                   com.sun.imageio.,\
+                   com.sun.istack.internal.,\
+                   com.sun.jmx.,\
+                   com.sun.proxy.,\
+                   com.sun.org.apache.xerces.internal.utils.,\
+                   com.sun.org.apache.xalan.internal.utils.,\
+                   com.sun.org.glassfish.external.,\
+                   com.sun.org.glassfish.gmbal.,\
+		   jdk.internal.
 
 #
 # Determines whether this properties file can be appended to
--- a/jdk/src/share/native/com/sun/java/util/jar/pack/bands.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/com/sun/java/util/jar/pack/bands.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -187,6 +187,10 @@
 
 entry* band::getRefCommon(cpindex* ix_, bool nullOKwithCaller) {
   CHECK_0;
+  if (ix_ == NULL) {
+      abort("no index");
+      return NULL;
+  }
   assert(ix_->ixTag == ixTag
          || ((ixTag == CONSTANT_All ||
               ixTag == CONSTANT_LoadableValue ||
--- a/jdk/src/share/native/com/sun/java/util/jar/pack/bands.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/com/sun/java/util/jar/pack/bands.h	Fri Mar 15 23:31:19 2013 -0700
@@ -99,8 +99,8 @@
 
   int    getByte()  { assert(ix == null); return vs[0].getByte(); }
   int    getInt()   { assert(ix == null); return vs[0].getInt(); }
-  entry* getRefN()  { assert(ix != null); return getRefCommon(ix, true); }
-  entry* getRef()   { assert(ix != null); return getRefCommon(ix, false); }
+  entry* getRefN()  { return getRefCommon(ix, true); }
+  entry* getRef()   { return getRefCommon(ix, false); }
   entry* getRefUsing(cpindex* ix2)
                     { assert(ix == null); return getRefCommon(ix2, true); }
   entry* getRefCommon(cpindex* ix, bool nullOK);
--- a/jdk/src/share/native/com/sun/java/util/jar/pack/jni.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/com/sun/java/util/jar/pack/jni.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -50,6 +50,7 @@
 static jmethodID currentInstMID;
 static jmethodID readInputMID;
 static jclass    NIclazz;
+static jmethodID getUnpackerPtrMID;
 
 static char* dbg = null;
 
@@ -60,8 +61,8 @@
 
 static unpacker* get_unpacker(JNIEnv *env, jobject pObj, bool noCreate=false) {
   unpacker* uPtr;
-  uPtr = (unpacker*)jlong2ptr(env->GetLongField(pObj, unpackerPtrFID));
-  //fprintf(stderr, "get_unpacker(%p) uPtr=%p\n", pObj, uPtr);
+  jlong p = env->CallLongMethod(pObj, getUnpackerPtrMID);
+  uPtr = (unpacker*)jlong2ptr(p);
   if (uPtr == null) {
     if (noCreate)  return null;
     uPtr = new unpacker();
@@ -94,11 +95,15 @@
   if (env == null)
     return null;
   jobject pObj = env->CallStaticObjectMethod(NIclazz, currentInstMID);
-  //fprintf(stderr, "get_unpacker() pObj=%p\n", pObj);
-  if (pObj == null)
-    return null;
-  // Got pObj and env; now do it the easy way.
-  return get_unpacker(env, pObj);
+  //fprintf(stderr, "get_unpacker0() pObj=%p\n", pObj);
+  if (pObj != null) {
+    // Got pObj and env; now do it the easy way.
+    return get_unpacker(env, pObj);
+  }
+  // this should really not happen, if it does something is seriously
+  // wrong throw an exception
+  THROW_IOE(ERROR_INTERNAL);
+  return null;
 }
 
 static void free_unpacker(JNIEnv *env, jobject pObj, unpacker* uPtr) {
@@ -127,18 +132,23 @@
 
 JNIEXPORT void JNICALL
 Java_com_sun_java_util_jar_pack_NativeUnpack_initIDs(JNIEnv *env, jclass clazz) {
+#ifndef PRODUCT
   dbg = getenv("DEBUG_ATTACH");
   while( dbg != null) { sleep(10); }
+#endif
   NIclazz = (jclass) env->NewGlobalRef(clazz);
   unpackerPtrFID = env->GetFieldID(clazz, "unpackerPtr", "J");
   currentInstMID = env->GetStaticMethodID(clazz, "currentInstance",
                                           "()Ljava/lang/Object;");
   readInputMID = env->GetMethodID(clazz, "readInputFn",
                                   "(Ljava/nio/ByteBuffer;J)J");
+  getUnpackerPtrMID = env->GetMethodID(clazz, "getUnpackerPtr", "()J");
+
   if (unpackerPtrFID == null ||
       currentInstMID == null ||
       readInputMID == null ||
-      NIclazz == null) {
+      NIclazz == null ||
+      getUnpackerPtrMID == null) {
     THROW_IOE("cannot init class members");
   }
 }
@@ -146,8 +156,13 @@
 JNIEXPORT jlong JNICALL
 Java_com_sun_java_util_jar_pack_NativeUnpack_start(JNIEnv *env, jobject pObj,
                                    jobject pBuf, jlong offset) {
-  unpacker* uPtr = get_unpacker(env, pObj);
-
+  // try to get the unpacker pointer the hard way first, we do this to ensure
+  // valid object pointers and env is intact, if not now is good time to bail.
+  unpacker* uPtr = get_unpacker();
+  //fprintf(stderr, "start(%p) uPtr=%p initializing\n", pObj, uPtr);
+  if (uPtr == null) {
+      return -1;
+  }
   // redirect our io to the default log file or whatever.
   uPtr->redirect_stdio();
 
@@ -163,7 +178,12 @@
     else
       { buf = (char*)buf + (size_t)offset; buflen -= (size_t)offset; }
   }
-
+  // before we start off we make sure there is no other error by the time we
+  // get here
+  if (uPtr->aborting()) {
+    THROW_IOE(uPtr->get_abort_message());
+    return 0;
+  }
   uPtr->start(buf, buflen);
   if (uPtr->aborting()) {
     THROW_IOE(uPtr->get_abort_message());
@@ -230,11 +250,14 @@
 
   // We have fetched all the files.
   // Now swallow up any remaining input.
-  if (uPtr->input_remaining() == 0)
+  if (uPtr->input_remaining() == 0) {
     return null;
-  else
-    return env->NewDirectByteBuffer(uPtr->input_scan(),
-                                    uPtr->input_remaining());
+  } else {
+    bytes remaining_bytes;
+    remaining_bytes.malloc(uPtr->input_remaining());
+    remaining_bytes.copyFrom(uPtr->input_scan(), uPtr->input_remaining());
+    return env->NewDirectByteBuffer(remaining_bytes.ptr, remaining_bytes.len);
+  }
 }
 
 JNIEXPORT jlong JNICALL
--- a/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -281,11 +281,13 @@
 }
 
 inline cpindex* cpool::getFieldIndex(entry* classRef) {
+  if (classRef == NULL) { abort("missing class reference"); return NULL; }
   assert(classRef->tagMatches(CONSTANT_Class));
   assert((uint)classRef->inord < (uint)tag_count[CONSTANT_Class]);
   return &member_indexes[classRef->inord*2+0];
 }
 inline cpindex* cpool::getMethodIndex(entry* classRef) {
+  if (classRef == NULL) { abort("missing class reference"); return NULL; }
   assert(classRef->tagMatches(CONSTANT_Class));
   assert((uint)classRef->inord < (uint)tag_count[CONSTANT_Class]);
   return &member_indexes[classRef->inord*2+1];
@@ -1291,6 +1293,7 @@
     entry& e = cpMap[i];
     e.refs = U_NEW(entry*, e.nrefs = 2);
     e.refs[0] = cp_band1.getRef();
+    CHECK;
     e.refs[1] = cp_band2.getRef();
     CHECK;
   }
@@ -1371,6 +1374,7 @@
       entry& e = cpMap[i];
       e.refs = U_NEW(entry*, e.nrefs = 1);
       e.refs[0] = cp_MethodType.getRef();
+      CHECK;
   }
 }
 
@@ -2106,6 +2110,7 @@
     int    attrc   = ADH_BYTE_CONTEXT(header);
     int    idx     = ADH_BYTE_INDEX(header);
     entry* name    = attr_definition_name.getRef();
+    CHECK;
     entry* layout  = attr_definition_layout.getRef();
     CHECK;
     attr_defs[attrc].defineLayout(idx, name, layout->value.b.strval());
@@ -2210,7 +2215,9 @@
     if (ics[i].name == NO_ENTRY_YET) {
       // Long form.
       ics[i].outer = ic_outer_class.getRefN();
+      CHECK;
       ics[i].name  = ic_name.getRefN();
+      CHECK;
     } else {
       // Fill in outer and name based on inner.
       bytes& n = ics[i].inner->value.b;
@@ -2733,6 +2740,7 @@
           e = b.getRefUsing(cp.getKQIndex());
         else
           e = b.getRefN();
+        CHECK;
         switch (b.le_len) {
         case 0: break;
         case 1: putu1ref(e); break;
@@ -3121,7 +3129,7 @@
 
 void unpacker::read_bands() {
   byte* rp0 = rp;
-
+  CHECK;
   read_file_header();
   CHECK;
 
@@ -3883,10 +3891,12 @@
 // packed file and len is the length of the buffer.
 // If null, the callback is used to fill an internal buffer.
 void unpacker::start(void* packptr, size_t len) {
+  CHECK;
   NOT_PRODUCT(debug_u = this);
   if (packptr != null && len != 0) {
     inbytes.set((byte*) packptr, len);
   }
+  CHECK;
   read_bands();
 }
 
@@ -4018,6 +4028,7 @@
     NOT_PRODUCT(bc_superfield.setIndex(null));
     NOT_PRODUCT(bc_supermethod.setIndex(null));
   }
+  CHECK;
 
   for (int curIP = 0; ; curIP++) {
     int curPC = (int)(wpoffset() - codeBase);
@@ -4131,7 +4142,8 @@
         int coding = bc_initref.getInt();
         // Find the nth overloading of <init> in classRef.
         entry*   ref = null;
-        cpindex* ix = (classRef == null)? null: cp.getMethodIndex(classRef);
+        cpindex* ix = cp.getMethodIndex(classRef);
+        CHECK;
         for (int j = 0, which_init = 0; ; j++) {
           ref = (ix == null)? null: ix->get(j);
           if (ref == null)  break;  // oops, bad input
@@ -4414,6 +4426,7 @@
       case ADH_BYTE(ATTR_CONTEXT_CLASS, CLASS_ATTR_EnclosingMethod):
         aname = cp.sym[cpool::s_EnclosingMethod];
         putref(class_EnclosingMethod_RC.getRefN());
+        CHECK_0;
         putref(class_EnclosingMethod_RDN.getRefN());
         break;
 
@@ -4432,6 +4445,7 @@
         putu2(count = method_Exceptions_N.getInt());
         for (j = 0; j < count; j++) {
           putref(method_Exceptions_RC.getRefN());
+          CHECK_0;
         }
         break;
 
@@ -4464,16 +4478,18 @@
             // (253)     [(1)(2)(2)]
             // (254)     [(1)(2)(2)(2)]
             putu2(code_StackMapTable_offset.getInt());
+            CHECK_0;
             for (int k = (tag - 251); k > 0; k--) {
               put_stackmap_type();
+              CHECK_0;
             }
           } else {
             // (255)     [(1)NH[(2)]NH[(2)]]
             putu2(code_StackMapTable_offset.getInt());
             putu2(j2 = code_StackMapTable_local_N.getInt());
-            while (j2-- > 0)  put_stackmap_type();
+            while (j2-- > 0) {put_stackmap_type(); CHECK_0;}
             putu2(j2 = code_StackMapTable_stack_N.getInt());
-            while (j2-- > 0)  put_stackmap_type();
+            while (j2-- > 0)  {put_stackmap_type(); CHECK_0;}
           }
         }
         break;
@@ -4497,7 +4513,9 @@
           bii    += code_LocalVariableTable_span_O.getInt();
           putu2(to_bci(bii) - bci);
           putref(code_LocalVariableTable_name_RU.getRefN());
+          CHECK_0;
           putref(code_LocalVariableTable_type_RS.getRefN());
+          CHECK_0;
           putu2(code_LocalVariableTable_slot.getInt());
         }
         break;
@@ -4512,7 +4530,9 @@
           bii    += code_LocalVariableTypeTable_span_O.getInt();
           putu2(to_bci(bii) - bci);
           putref(code_LocalVariableTypeTable_name_RU.getRefN());
+          CHECK_0;
           putref(code_LocalVariableTypeTable_type_RS.getRefN());
+          CHECK_0;
           putu2(code_LocalVariableTypeTable_slot.getInt());
         }
         break;
@@ -4540,7 +4560,7 @@
         break;
       }
     }
-
+    CHECK_0;
     if (aname == null) {
       // Unparse a compressor-defined attribute.
       layout_definition* lo = ad.getLayout(idx);
@@ -4696,7 +4716,9 @@
       flags &= ~ACC_IC_LONG_FORM;  // clear high bit if set to get clean zero
       extra_ic.flags = flags;
       extra_ic.outer = class_InnerClasses_outer_RCN.getRefN();
+      CHECK_0;
       extra_ic.name  = class_InnerClasses_name_RUN.getRefN();
+      CHECK_0;
       // Detect if this is an exact copy of the global tuple.
       if (global_ic != null) {
         if (global_ic->flags != extra_ic.flags ||
@@ -4806,6 +4828,7 @@
   julong indexMask = ad.flagIndexMask();
 
   cur_class = class_this.getRef();
+  CHECK;
   cur_super = class_super.getRef();
   CHECK;
 
@@ -4819,6 +4842,7 @@
   putu2(num = class_interface_count.getInt());
   for (i = 0; i < num; i++) {
     putref(class_interface.getRef());
+    CHECK;
   }
 
   write_members(class_field_count.getInt(),  ATTR_CONTEXT_FIELD);
--- a/jdk/src/share/native/sun/awt/image/awt_parseImage.c	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/awt/image/awt_parseImage.c	Fri Mar 15 23:31:19 2013 -0700
@@ -114,6 +114,62 @@
     return status;
 }
 
+/* Verifies whether the channel offsets are sane and correspond to the type of
+ * the raster.
+ *
+ * Return value:
+ *     0: Failure: channel offsets are invalid
+ *     1: Success
+ */
+static int checkChannelOffsets(RasterS_t *rasterP, int dataArrayLength) {
+    int i, lastPixelOffset, lastScanOffset;
+    switch (rasterP->rasterType) {
+    case COMPONENT_RASTER_TYPE:
+        if (!SAFE_TO_MULT(rasterP->height, rasterP->scanlineStride)) {
+            return 0;
+        }
+        if (!SAFE_TO_MULT(rasterP->width, rasterP->pixelStride)) {
+            return 0;
+        }
+
+        lastScanOffset = (rasterP->height - 1) * rasterP->scanlineStride;
+        lastPixelOffset = (rasterP->width - 1) * rasterP->pixelStride;
+
+
+        if (!SAFE_TO_ADD(lastPixelOffset, lastScanOffset)) {
+            return 0;
+        }
+
+        lastPixelOffset += lastScanOffset;
+
+        for (i = 0; i < rasterP->numDataElements; i++) {
+            int off = rasterP->chanOffsets[i];
+            int size = lastPixelOffset + off;
+
+            if (off < 0 || !SAFE_TO_ADD(lastPixelOffset, off)) {
+                return 0;
+            }
+
+            if (size < lastPixelOffset || size >= dataArrayLength) {
+                // an overflow, or insufficient buffer capacity
+                return 0;
+            }
+        }
+        return 1;
+    case BANDED_RASTER_TYPE:
+        // NB:caller does not support the banded rasters yet,
+        // so this branch of the code must be re-defined in
+        // order to provide valid criteria for the data offsets
+        // verification, when/if banded rasters will be supported.
+        // At the moment, we prohibit banded rasters as well.
+        return 0;
+    default:
+        // PACKED_RASTER_TYPE: does not support channel offsets
+        // UNKNOWN_RASTER_TYPE: should not be used, likely indicates an error
+        return 0;
+    }
+}
+
 /* Parse the raster.  All of the raster information is returned in the
  * rasterP structure.
  *
@@ -125,7 +181,6 @@
 int awt_parseRaster(JNIEnv *env, jobject jraster, RasterS_t *rasterP) {
     jobject joffs = NULL;
     /* int status;*/
-    int isDiscrete = TRUE;
 
     if (JNU_IsNull(env, jraster)) {
         JNU_ThrowNullPointerException(env, "null Raster object");
@@ -155,6 +210,9 @@
         return -1;
     }
 
+    // make sure that the raster type is initialized
+    rasterP->rasterType = UNKNOWN_RASTER_TYPE;
+
     if (rasterP->numBands <= 0 ||
         rasterP->numBands > MAX_NUMBANDS)
     {
@@ -165,9 +223,14 @@
         return 0;
     }
 
+    rasterP->sppsm.isUsed = 0;
+
     if ((*env)->IsInstanceOf(env, rasterP->jsampleModel,
        (*env)->FindClass(env,"java/awt/image/SinglePixelPackedSampleModel"))) {
         jobject jmask, joffs, jnbits;
+
+        rasterP->sppsm.isUsed = 1;
+
         rasterP->sppsm.maxBitSize = (*env)->GetIntField(env,
                                                         rasterP->jsampleModel,
                                                         g_SPPSMmaxBitID);
@@ -254,7 +317,6 @@
         }
         rasterP->chanOffsets[0] = (*env)->GetIntField(env, jraster, g_BPRdataBitOffsetID);
         rasterP->dataType = BYTE_DATA_TYPE;
-        isDiscrete = FALSE;
     }
     else {
         rasterP->type = sun_awt_image_IntegerComponentRaster_TYPE_CUSTOM;
@@ -265,7 +327,19 @@
         return 0;
     }
 
-    if (isDiscrete) {
+    // do basic validation of the raster structure
+    if (rasterP->width <= 0 || rasterP->height <= 0 ||
+        rasterP->pixelStride <= 0 || rasterP->scanlineStride <= 0)
+    {
+        // invalid raster
+        return -1;
+    }
+
+    // channel (data) offsets
+    switch (rasterP->rasterType) {
+    case COMPONENT_RASTER_TYPE:
+    case BANDED_RASTER_TYPE: // note that this routine does not support banded rasters at the moment
+        // get channel (data) offsets
         rasterP->chanOffsets = NULL;
         if (SAFE_TO_ALLOC_2(rasterP->numDataElements, sizeof(jint))) {
             rasterP->chanOffsets =
@@ -278,10 +352,21 @@
         }
         (*env)->GetIntArrayRegion(env, joffs, 0, rasterP->numDataElements,
                                   rasterP->chanOffsets);
+        if (rasterP->jdata == NULL) {
+            // unable to verify the raster
+            return -1;
+        }
+        // verify whether channel offsets look sane
+        if (!checkChannelOffsets(rasterP, (*env)->GetArrayLength(env, rasterP->jdata))) {
+            return -1;
+        }
+        break;
+    default:
+        ; // PACKED_RASTER_TYPE does not use the channel offsets.
     }
 
-    /* additioanl check for sppsm fields validity: make sure that
-     * size of raster samples doesn't exceed the data type cpacity.
+    /* additional check for sppsm fields validity: make sure that
+     * size of raster samples doesn't exceed the data type capacity.
      */
     if (rasterP->dataType > UNKNOWN_DATA_TYPE && /* data type has been recognized */
         rasterP->sppsm.maxBitSize > 0 && /* raster has SPP sample model */
@@ -696,6 +781,21 @@
     }
     else if (cmodelP->cmType == DIRECT_CM_TYPE || cmodelP->cmType == PACKED_CM_TYPE) {
         int i;
+
+        /* do some sanity check first: make sure that
+         * - sample model is SinglePixelPackedSampleModel
+         * - number of bands in the raster corresponds to the number
+         *   of color components in the color model
+         */
+        if (!rasterP->sppsm.isUsed ||
+            rasterP->numBands != cmodelP->numComponents)
+        {
+            /* given raster is not compatible with the color model,
+             * so the operation has to be aborted.
+             */
+            return -1;
+        }
+
         if (cmodelP->maxNbits > 8) {
             hintP->needToExpand = TRUE;
             hintP->expandToNbits = cmodelP->maxNbits;
--- a/jdk/src/share/native/sun/awt/image/awt_parseImage.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/awt/image/awt_parseImage.h	Fri Mar 15 23:31:19 2013 -0700
@@ -95,6 +95,7 @@
     jint offsets[MAX_NUMBANDS];
     jint nBits[MAX_NUMBANDS];
     jint  maxBitSize;
+    jint isUsed; // flag to indicate whether the raster sample model is SPPSM
 } SPPSampleModelS_t;
 
 /* Struct that holds information for the Raster object */
--- a/jdk/src/share/native/sun/awt/medialib/safe_alloc.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/awt/medialib/safe_alloc.h	Fri Mar 15 23:31:19 2013 -0700
@@ -41,5 +41,10 @@
     (((w) > 0) && ((h) > 0) && ((sz) > 0) &&                               \
      (((0xffffffffu / ((juint)(w))) / ((juint)(h))) > ((juint)(sz))))
 
+#define SAFE_TO_MULT(a, b) \
+    (((a) > 0) && ((b) >= 0) && ((0x7fffffff / (a)) > (b)))
+
+#define SAFE_TO_ADD(a, b) \
+    (((a) >= 0) && ((b) >= 0) && ((0x7fffffff - (a)) > (b)))
 
 #endif // __SAFE_ALLOC_H__
--- a/jdk/src/share/native/sun/awt/splashscreen/splashscreen_jpeg.c	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/awt/splashscreen/splashscreen_jpeg.c	Fri Mar 15 23:31:19 2013 -0700
@@ -133,6 +133,10 @@
     ImageFormat srcFormat;
 
     jpeg_read_header(cinfo, TRUE);
+
+    // SplashScreen jpeg converter expects data in RGB format only
+    cinfo->out_color_space = JCS_RGB;
+
     jpeg_start_decompress(cinfo);
 
     SplashCleanup(splash);
--- a/jdk/src/share/native/sun/font/layout/LookupProcessor.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/font/layout/LookupProcessor.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -125,6 +125,10 @@
     }
 
     const LookupTable *lookupTable = lookupListTable->getLookupTable(lookupTableIndex);
+    if (lookupTable == NULL) {
+        success = LE_INTERNAL_ERROR;
+        return 0;
+    }
     le_uint16 lookupFlags = SWAPW(lookupTable->lookupFlags);
     GlyphIterator tempIterator(*glyphIterator, lookupFlags);
     le_uint32 delta = applyLookupTable(lookupTable, &tempIterator, fontInstance, success);
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/LCMS.c	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/LCMS.c	Fri Mar 15 23:31:19 2013 -0700
@@ -117,6 +117,7 @@
 static jfieldID IL_nextRowOffset_fID;
 static jfieldID IL_width_fID;
 static jfieldID IL_height_fID;
+static jfieldID IL_imageAtOnce_fID;
 static jfieldID PF_ID_fID;
 
 JavaVM *javaVM;
@@ -237,7 +238,7 @@
  * Method:    loadProfile
  * Signature: ([B)J
  */
-JNIEXPORT jlong JNICALL Java_sun_java2d_cmm_lcms_LCMS_loadProfile
+JNIEXPORT jlong JNICALL Java_sun_java2d_cmm_lcms_LCMS_loadProfileNative
   (JNIEnv *env, jobject obj, jbyteArray data)
 {
     jbyte* dataArray;
@@ -284,7 +285,7 @@
  * Method:    freeProfile
  * Signature: (J)V
  */
-JNIEXPORT void JNICALL Java_sun_java2d_cmm_lcms_LCMS_freeProfile
+JNIEXPORT void JNICALL Java_sun_java2d_cmm_lcms_LCMS_freeProfileNative
   (JNIEnv *env, jobject obj, jlong id)
 {
     storeID_t sProf;
@@ -369,48 +370,22 @@
 static cmsBool _setHeaderInfo(cmsHPROFILE pf, jbyte* pBuffer, jint bufferSize);
 static cmsBool _writeCookedTag(cmsHPROFILE pfTarget, cmsTagSignature sig, jbyte *pData, jint size);
 
-/*
- * Class:     sun_java2d_cmm_lcms_LCMS
- * Method:    getTagSize
- * Signature: (JI)I
- */
-JNIEXPORT jint JNICALL Java_sun_java2d_cmm_lcms_LCMS_getTagSize
-  (JNIEnv *env, jobject obj, jlong id, jint tagSig)
-{
-    storeID_t sProf;
-    TagSignature_t sig;
-    jint result = -1;
-
-    sProf.j = id;
-    sig.j = tagSig;
-
-    if (tagSig == SigHead) {
-        result = sizeof(cmsICCHeader);
-    } else {
-      if (cmsIsTag(sProf.pf, sig.cms)) {
-          result = cmsReadRawTag(sProf.pf, sig.cms, NULL, 0);
-        } else {
-            JNU_ThrowByName(env, "java/awt/color/CMMException",
-                            "ICC profile tag not found");
-        }
-    }
-
-    return result;
-}
 
 /*
  * Class:     sun_java2d_cmm_lcms_LCMS
  * Method:    getTagData
  * Signature: (JI[B)V
  */
-JNIEXPORT void JNICALL Java_sun_java2d_cmm_lcms_LCMS_getTagData
-  (JNIEnv *env, jobject obj, jlong id, jint tagSig, jbyteArray data)
+JNIEXPORT jbyteArray JNICALL Java_sun_java2d_cmm_lcms_LCMS_getTagNative
+  (JNIEnv *env, jobject obj, jlong id, jint tagSig)
 {
     storeID_t sProf;
     TagSignature_t sig;
     cmsInt32Number tagSize;
 
-    jbyte* dataArray;
+    jbyte* dataArray = NULL;
+    jbyteArray data = NULL;
+
     jint bufSize;
 
     sProf.j = id;
@@ -419,12 +394,14 @@
     if (tagSig == SigHead) {
         cmsBool status;
 
-        bufSize =(*env)->GetArrayLength(env, data);
+        // allocate java array
+        bufSize = sizeof(cmsICCHeader);
+        data = (*env)->NewByteArray(env, bufSize);
 
-        if (bufSize < sizeof(cmsICCHeader)) {
-           JNU_ThrowByName(env, "java/awt/color/CMMException",
-                            "Insufficient buffer capacity");
-           return;
+        if (data == NULL) {
+            JNU_ThrowByName(env, "java/awt/color/CMMException",
+                            "Unable to allocate buffer");
+            return NULL;
         }
 
         dataArray = (*env)->GetByteArrayElements (env, data, 0);
@@ -432,7 +409,7 @@
         if (dataArray == NULL) {
            JNU_ThrowByName(env, "java/awt/color/CMMException",
                             "Unable to get buffer");
-           return;
+           return NULL;
         }
 
         status = _getHeaderInfo(sProf.pf, dataArray, bufSize);
@@ -442,9 +419,10 @@
         if (!status) {
             JNU_ThrowByName(env, "java/awt/color/CMMException",
                             "ICC Profile header not found");
+            return NULL;
         }
 
-        return;
+        return data;
     }
 
     if (cmsIsTag(sProf.pf, sig.cms)) {
@@ -452,16 +430,15 @@
     } else {
         JNU_ThrowByName(env, "java/awt/color/CMMException",
                         "ICC profile tag not found");
-        return;
+        return NULL;
     }
 
-    // verify data buffer capacity
-    bufSize = (*env)->GetArrayLength(env, data);
-
-    if (tagSize < 0 || 0 > bufSize || tagSize > bufSize) {
+    // allocate java array
+    data = (*env)->NewByteArray(env, tagSize);
+    if (data == NULL) {
         JNU_ThrowByName(env, "java/awt/color/CMMException",
-                        "Insufficient buffer capacity.");
-        return;
+                        "Unable to allocate buffer");
+        return NULL;
     }
 
     dataArray = (*env)->GetByteArrayElements (env, data, 0);
@@ -469,7 +446,7 @@
     if (dataArray == NULL) {
         JNU_ThrowByName(env, "java/awt/color/CMMException",
                         "Unable to get buffer");
-        return;
+        return NULL;
     }
 
     bufSize = cmsReadRawTag(sProf.pf, sig.cms, dataArray, tagSize);
@@ -479,8 +456,9 @@
     if (bufSize != tagSize) {
         JNU_ThrowByName(env, "java/awt/color/CMMException",
                         "Can not get tag data.");
+        return NULL;
     }
-    return;
+    return data;
 }
 
 /*
@@ -488,7 +466,7 @@
  * Method:    setTagData
  * Signature: (JI[B)V
  */
-JNIEXPORT void JNICALL Java_sun_java2d_cmm_lcms_LCMS_setTagData
+JNIEXPORT void JNICALL Java_sun_java2d_cmm_lcms_LCMS_setTagDataNative
   (JNIEnv *env, jobject obj, jlong id, jint tagSig, jbyteArray data)
 {
     storeID_t sProf;
@@ -586,6 +564,7 @@
     char* inputRow;
     char* outputRow;
     jobject srcData, dstData;
+    jboolean srcAtOnce = JNI_FALSE, dstAtOnce = JNI_FALSE;
 
     srcOffset = (*env)->GetIntField (env, src, IL_offset_fID);
     srcNextRowOffset = (*env)->GetIntField (env, src, IL_nextRowOffset_fID);
@@ -594,6 +573,9 @@
     width = (*env)->GetIntField (env, src, IL_width_fID);
     height = (*env)->GetIntField (env, src, IL_height_fID);
 
+    srcAtOnce = (*env)->GetBooleanField(env, src, IL_imageAtOnce_fID);
+    dstAtOnce = (*env)->GetBooleanField(env, dst, IL_imageAtOnce_fID);
+
     sTrans.j = (*env)->GetLongField (env, trans, Trans_ID_fID);
 
     if (sTrans.xf == NULL) {
@@ -625,10 +607,14 @@
     inputRow = (char*)inputBuffer + srcOffset;
     outputRow = (char*)outputBuffer + dstOffset;
 
-    for (i = 0; i < height; i++) {
-        cmsDoTransform(sTrans.xf, inputRow, outputRow, width);
-        inputRow += srcNextRowOffset;
-        outputRow += dstNextRowOffset;
+    if (srcAtOnce && dstAtOnce) {
+        cmsDoTransform(sTrans.xf, inputRow, outputRow, width * height);
+    } else {
+        for (i = 0; i < height; i++) {
+            cmsDoTransform(sTrans.xf, inputRow, outputRow, width);
+            inputRow += srcNextRowOffset;
+            outputRow += dstNextRowOffset;
+        }
     }
 
     releaseILData(env, inputBuffer, srcDType, srcData);
@@ -670,6 +656,7 @@
     IL_width_fID = (*env)->GetFieldID (env, IL, "width", "I");
     IL_height_fID = (*env)->GetFieldID (env, IL, "height", "I");
     IL_offset_fID = (*env)->GetFieldID (env, IL, "offset", "I");
+    IL_imageAtOnce_fID = (*env)->GetFieldID (env, IL, "imageAtOnce", "Z");
     IL_nextRowOffset_fID = (*env)->GetFieldID (env, IL, "nextRowOffset", "I");
 
     PF_ID_fID = (*env)->GetFieldID (env, Pf, "ID", "J");
--- a/jdk/src/share/native/sun/java2d/loops/AnyByteBinary.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/java2d/loops/AnyByteBinary.h	Fri Mar 15 23:31:19 2013 -0700
@@ -153,7 +153,10 @@
     jint PREFIX ## rgb;
 
 #define InitByteBinaryAlphaLoadData(TYPE, PREFIX, pRasInfo) \
-    PREFIX ## Lut = (pRasInfo)->lutBase
+    do { \
+        PREFIX ## Lut = (pRasInfo)->lutBase; \
+        PREFIX ## rgb = 0; \
+    } while (0)
 
 #define LoadAlphaFromByteBinaryFor4ByteArgb(TYPE, pRas, PREFIX, COMP_PREFIX) \
     do { \
--- a/jdk/src/share/native/sun/java2d/loops/ByteIndexed.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/java2d/loops/ByteIndexed.h	Fri Mar 15 23:31:19 2013 -0700
@@ -202,7 +202,10 @@
     jint PREFIX ## rgb;
 
 #define InitByteIndexedAlphaLoadData(PREFIX, pRasInfo) \
-    PREFIX ## Lut = (pRasInfo)->lutBase
+    do { \
+        PREFIX ## Lut = (pRasInfo)->lutBase; \
+        PREFIX ## rgb = 0; \
+    } while (0)
 
 #define LoadAlphaFromByteIndexedFor4ByteArgb(pRas, PREFIX, COMP_PREFIX) \
     do { \
--- a/jdk/src/share/native/sun/java2d/loops/IntArgb.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/java2d/loops/IntArgb.h	Fri Mar 15 23:31:19 2013 -0700
@@ -122,7 +122,8 @@
 #define DeclareIntArgbAlphaLoadData(PREFIX) \
     jint PREFIX;
 
-#define InitIntArgbAlphaLoadData(PREFIX, pRasInfo)
+#define InitIntArgbAlphaLoadData(PREFIX, pRasInfo) \
+    PREFIX = 0
 
 #define LoadAlphaFromIntArgbFor4ByteArgb(pRas, PREFIX, COMP_PREFIX) \
     do { \
--- a/jdk/src/share/native/sun/java2d/loops/IntArgbBm.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/java2d/loops/IntArgbBm.h	Fri Mar 15 23:31:19 2013 -0700
@@ -133,7 +133,8 @@
 #define DeclareIntArgbBmAlphaLoadData(PREFIX) \
     jint PREFIX;
 
-#define InitIntArgbBmAlphaLoadData(PREFIX, pRasInfo)
+#define InitIntArgbBmAlphaLoadData(PREFIX, pRasInfo) \
+    PREFIX = 0
 
 #define LoadAlphaFromIntArgbBmFor4ByteArgb(pRas, PREFIX, COMP_PREFIX) \
     do { \
--- a/jdk/src/share/native/sun/java2d/loops/IntArgbPre.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/java2d/loops/IntArgbPre.h	Fri Mar 15 23:31:19 2013 -0700
@@ -153,7 +153,8 @@
 #define DeclareIntArgbPreAlphaLoadData(PREFIX) \
     jint PREFIX;
 
-#define InitIntArgbPreAlphaLoadData(PREFIX, pRasInfo)
+#define InitIntArgbPreAlphaLoadData(PREFIX, pRasInfo) \
+    PREFIX = 0
 
 #define LoadAlphaFromIntArgbPreFor4ByteArgb(pRas, PREFIX, COMP_PREFIX) \
     do { \
--- a/jdk/src/share/native/sun/java2d/loops/TransformHelper.c	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/java2d/loops/TransformHelper.c	Fri Mar 15 23:31:19 2013 -0700
@@ -353,6 +353,9 @@
         pInterpFunc = pBicubicFunc;
         maxlinepix = LINE_SIZE / 16;
         break;
+    default:
+        // Should not happen, but just in case.
+        return;
     }
 
     srcInfo.bounds.x1 = sx1;
--- a/jdk/src/share/native/sun/java2d/loops/Ushort4444Argb.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/java2d/loops/Ushort4444Argb.h	Fri Mar 15 23:31:19 2013 -0700
@@ -120,7 +120,8 @@
 #define DeclareUshort4444ArgbAlphaLoadData(PREFIX) \
     jint PREFIX;
 
-#define InitUshort4444ArgbAlphaLoadData(PREFIX, pRasInfo)
+#define InitUshort4444ArgbAlphaLoadData(PREFIX, pRasInfo) \
+    PREFIX = 0
 
 #define LoadAlphaFromUshort4444ArgbFor4ByteArgb(pRas, PREFIX, COMP_PREFIX) \
     do { \
--- a/jdk/src/share/native/sun/java2d/loops/UshortIndexed.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/share/native/sun/java2d/loops/UshortIndexed.h	Fri Mar 15 23:31:19 2013 -0700
@@ -170,7 +170,10 @@
     jint PREFIX ## rgb;
 
 #define InitUshortIndexedAlphaLoadData(PREFIX, pRasInfo) \
-    PREFIX ## Lut = (pRasInfo)->lutBase
+    do { \
+        PREFIX ## Lut = (pRasInfo)->lutBase; \
+        PREFIX ## rgb = 0; \
+    } while (0)
 
 #define LoadAlphaFromUshortIndexedFor4ByteArgb(pRas, PREFIX, COMP_PREFIX) \
     do { \
--- a/jdk/src/solaris/classes/sun/awt/X11/XFramePeer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/solaris/classes/sun/awt/X11/XFramePeer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -641,4 +641,6 @@
     public Rectangle getBoundsPrivate() {
         return getBounds();
     }
+
+    public void emulateActivation(boolean doActivate) {}
 }
--- a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java	Fri Mar 15 23:31:19 2013 -0700
@@ -419,6 +419,10 @@
         return peer;
     }
 
+    public FramePeer createLightweightFrame(LightweightFrame target) {
+        return null;
+    }
+
     public FramePeer createFrame(Frame target) {
         FramePeer peer = new XFramePeer(target);
         targetCreatedPeer(target, peer);
--- a/jdk/src/solaris/classes/sun/nio/ch/sctp/SctpChannelImpl.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/solaris/classes/sun/nio/ch/sctp/SctpChannelImpl.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1026,13 +1026,21 @@
                                      boolean unordered,
                                      int ppid)
             throws IOException {
+        InetAddress addr = null;     // no preferred address
+        int port = 0;
+        if (target != null) {
+            InetSocketAddress isa = Net.checkAddress(target);
+            addr = isa.getAddress();
+            port = isa.getPort();
+        }
+
         int pos = bb.position();
         int lim = bb.limit();
         assert (pos <= lim);
         int rem = (pos <= lim ? lim - pos : 0);
 
-        int written = send0(fd, ((DirectBuffer)bb).address() + pos,
-                            rem, target, -1 /*121*/, streamNumber, unordered, ppid);
+        int written = send0(fd, ((DirectBuffer)bb).address() + pos, rem, addr,
+                            port, -1 /*121*/, streamNumber, unordered, ppid);
         if (written > 0)
             bb.position(pos + written);
         return written;
@@ -1091,7 +1099,7 @@
             long address, int length, boolean peek) throws IOException;
 
     static native int send0(int fd, long address, int length,
-            SocketAddress target, int assocId, int streamNumber,
+            InetAddress addr, int port, int assocId, int streamNumber,
             boolean unordered, int ppid) throws IOException;
 
     private static native int checkConnect(FileDescriptor fd, boolean block,
--- a/jdk/src/solaris/classes/sun/nio/ch/sctp/SctpMultiChannelImpl.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/solaris/classes/sun/nio/ch/sctp/SctpMultiChannelImpl.java	Fri Mar 15 23:31:19 2013 -0700
@@ -889,13 +889,20 @@
                                      boolean unordered,
                                      int ppid)
             throws IOException {
+        InetAddress addr = null;     // no preferred address
+        int port = 0;
+        if (target != null) {
+            InetSocketAddress isa = Net.checkAddress(target);
+            addr = isa.getAddress();
+            port = isa.getPort();
+        }
         int pos = bb.position();
         int lim = bb.limit();
         assert (pos <= lim);
         int rem = (pos <= lim ? lim - pos : 0);
 
-        int written = send0(fd, ((DirectBuffer)bb).address() + pos,
-                            rem, target, assocId, streamNumber, unordered, ppid);
+        int written = send0(fd, ((DirectBuffer)bb).address() + pos, rem, addr,
+                            port, assocId, streamNumber, unordered, ppid);
         if (written > 0)
             bb.position(pos + written);
         return written;
@@ -976,13 +983,14 @@
     private static int send0(int fd,
                              long address,
                              int length,
-                             SocketAddress target,
+                             InetAddress addr,
+                             int port,
                              int assocId,
                              int streamNumber,
                              boolean unordered,
                              int ppid)
             throws IOException {
-        return SctpChannelImpl.send0(fd, address, length, target, assocId,
+        return SctpChannelImpl.send0(fd, address, length, addr, port, assocId,
                 streamNumber, unordered, ppid);
     }
 
--- a/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c	Fri Mar 15 23:31:19 2013 -0700
@@ -46,8 +46,6 @@
 
 #include "sun_nio_ch_DatagramChannelImpl.h"
 
-static jfieldID isa_addrID;     /* address in java.net.InetSocketAddress */
-static jfieldID isa_portID;     /* port in java.net.InetSocketAddress */
 static jfieldID dci_senderID;   /* sender in sun.nio.ch.DatagramChannelImpl */
 static jfieldID dci_senderAddrID; /* sender InetAddress in sun.nio.ch.DatagramChannelImpl */
 static jfieldID dci_senderPortID; /* sender port in sun.nio.ch.DatagramChannelImpl */
@@ -61,9 +59,6 @@
     isa_class = (*env)->NewGlobalRef(env, clazz);
     isa_ctorID = (*env)->GetMethodID(env, clazz, "<init>",
                                      "(Ljava/net/InetAddress;I)V");
-    isa_addrID = (*env)->GetFieldID(env, clazz, "addr",
-                                    "Ljava/net/InetAddress;");
-    isa_portID = (*env)->GetFieldID(env, clazz, "port", "I");
 
     clazz = (*env)->FindClass(env, "sun/nio/ch/DatagramChannelImpl");
     dci_senderID = (*env)->GetFieldID(env, clazz, "sender",
@@ -212,15 +207,13 @@
 JNIEXPORT jint JNICALL
 Java_sun_nio_ch_DatagramChannelImpl_send0(JNIEnv *env, jobject this,
                                           jboolean preferIPv6, jobject fdo, jlong address,
-                                            jint len, jobject dest)
+                                          jint len, jobject destAddress, jint destPort)
 {
     jint fd = fdval(env, fdo);
     void *buf = (void *)jlong_to_ptr(address);
     SOCKADDR sa;
     int sa_len = SOCKADDR_LEN;
     jint n = 0;
-    jobject destAddress = (*env)->GetObjectField(env, dest, isa_addrID);
-    jint destPort = (*env)->GetIntField(env, dest, isa_portID);
 
     if (len > MAX_PACKET_LEN) {
         len = MAX_PACKET_LEN;
--- a/jdk/src/solaris/native/sun/nio/ch/sctp/SctpChannelImpl.c	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/solaris/native/sun/nio/ch/sctp/SctpChannelImpl.c	Fri Mar 15 23:31:19 2013 -0700
@@ -67,8 +67,6 @@
 static jmethodID spc_ctrID;    /* sun.nio.ch.sctp.PeerAddressChanged.<init>  */
 static jclass    ss_class;     /* sun.nio.ch.sctp.Shutdown                   */
 static jmethodID ss_ctrID;     /* sun.nio.ch.sctp.Shutdown.<init>            */
-static jfieldID  isa_addrID;   /* java.net.InetSocketAddress.addr            */
-static jfieldID  isa_portID;   /* java.net.InetSocketAddress.port            */
 
 /* defined in SctpNet.c */
 jobject SockAddrToInetSocketAddress(JNIEnv* env, struct sockaddr* addr);
@@ -138,13 +136,6 @@
     CHECK_NULL(ss_class);
     ss_ctrID = (*env)->GetMethodID(env, cls, "<init>", "(I)V");
     CHECK_NULL(ss_ctrID);
-
-    /* InetSocketAddress */
-    cls = (*env)->FindClass(env, "java/net/InetSocketAddress");
-    CHECK_NULL(cls);
-    isa_addrID = (*env)->GetFieldID(env, cls, "addr", "Ljava/net/InetAddress;");
-    CHECK_NULL(isa_addrID);
-    isa_portID = (*env)->GetFieldID(env, cls, "port", "I");
 }
 
 void getControlData
@@ -509,12 +500,12 @@
 /*
  * Class:     sun_nio_ch_sctp_SctpChannelImpl
  * Method:    send0
- * Signature: (IJILjava/net/SocketAddress;IIZI)I
+ * Signature: (IJILjava/net/InetAddress;IIIZI)I
  */
 JNIEXPORT jint JNICALL Java_sun_nio_ch_sctp_SctpChannelImpl_send0
   (JNIEnv *env, jclass klass, jint fd, jlong address, jint length,
-   jobject saTarget, jint assocId, jint streamNumber, jboolean unordered,
-   jint ppid) {
+   jobject targetAddress, jint targetPort, jint assocId, jint streamNumber,
+   jboolean unordered, jint ppid) {
     SOCKADDR sa;
     int sa_len = sizeof(sa);
     ssize_t rv = 0;
@@ -526,17 +517,13 @@
     struct controlData cdata[1];
 
     /* SctpChannel:
-     *    saTarget may contain the preferred address or NULL to use primary,
+     *    targetAddress may contain the preferred address or NULL to use primary,
      *    assocId will always be -1
      * SctpMultiChannell:
-     *    Setup new association, saTarget will contain address, assocId = -1
-     *    Association already existing, assocId != -1, saTarget = preferred addr
+     *    Setup new association, targetAddress will contain address, assocId = -1
+     *    Association already existing, assocId != -1, targetAddress = preferred addr
      */
-    if (saTarget != NULL /*&& assocId <= 0*/) {
-
-        jobject targetAddress = (*env)->GetObjectField(env, saTarget, isa_addrID);
-        jint targetPort = (*env)->GetIntField(env, saTarget, isa_portID);
-
+    if (targetAddress != NULL /*&& assocId <= 0*/) {
         if (NET_InetAddressToSockaddr(env, targetAddress, targetPort,
                                       (struct sockaddr *)&sa,
                                       &sa_len, JNI_TRUE) != 0) {
--- a/jdk/src/windows/bin/java_md.c	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/windows/bin/java_md.c	Fri Mar 15 23:31:19 2013 -0700
@@ -101,7 +101,6 @@
 /* funtion in awt.dll (src/windows/native/sun/java2d/d3d/D3DPipelineManager.cpp) */
 #define D3D_PRELOAD_FUNC "preloadD3D"
 
-
 /* Extracts value of a parameter with the specified name
  * from command line argument (returns pointer in the argument).
  * Returns NULL if the argument does not contains the parameter.
@@ -276,7 +275,8 @@
 #endif
 #ifdef CRT_DLL
         if (GetJREPath(crtpath, MAXPATHLEN)) {
-            if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") + JLI_StrLen(CRT_DLL) >= MAXPATHLEN) {
+            if (JLI_StrLen(crtpath) + JLI_StrLen("\\bin\\") +
+                    JLI_StrLen(CRT_DLL) >= MAXPATHLEN) {
                 JLI_ReportErrorMessage(JRE_ERROR11);
                 return JNI_FALSE;
             }
@@ -347,7 +347,8 @@
     if (JLI_StrChr(jvmtype, '/') || JLI_StrChr(jvmtype, '\\')) {
         JLI_Snprintf(jvmpath, jvmpathsize, "%s\\" JVM_DLL, jvmtype);
     } else {
-        JLI_Snprintf(jvmpath, jvmpathsize, "%s\\bin\\%s\\" JVM_DLL, jrepath, jvmtype);
+        JLI_Snprintf(jvmpath, jvmpathsize, "%s\\bin\\%s\\" JVM_DLL,
+                     jrepath, jvmtype);
     }
     if (stat(jvmpath, &s) == 0) {
         return JNI_TRUE;
@@ -525,6 +526,37 @@
     }
     return (counts * 1000 * 1000)/counterFrequency.QuadPart;
 }
+/*
+ * windows snprintf does not guarantee a null terminator in the buffer,
+ * if the computed size is equal to or greater than the buffer size,
+ * as well as error conditions. This function guarantees a null terminator
+ * under all these conditions. An unreasonable buffer or size will return
+ * an error value. Under all other conditions this function will return the
+ * size of the bytes actually written minus the null terminator, similar
+ * to ansi snprintf api. Thus when calling this function the caller must
+ * ensure storage for the null terminator.
+ */
+int
+JLI_Snprintf(char* buffer, size_t size, const char* format, ...) {
+    int rc;
+    va_list vl;
+    if (size == 0 || buffer == NULL)
+        return -1;
+    buffer[0] = '\0';
+    va_start(vl, format);
+    rc = vsnprintf(buffer, size, format, vl);
+    va_end(vl);
+    /* force a null terminator, if something is amiss */
+    if (rc < 0) {
+        /* apply ansi semantics */
+        buffer[size - 1] = '\0';
+        return size;
+    } else if (rc == size) {
+        /* force a null terminator */
+        buffer[size - 1] = '\0';
+    }
+    return rc;
+}
 
 void
 JLI_ReportErrorMessage(const char* fmt, ...) {
@@ -880,7 +912,7 @@
  */
 void
 ExecJRE(char *jre, char **argv) {
-    int     len;
+    jint     len;
     char    path[MAXPATHLEN + 1];
 
     const char *progname = GetProgramName();
@@ -1417,7 +1449,10 @@
         // we add the indicator
         tlen = 1 + JLI_StrLen(strv[i]) + 1;
         nargv[i] = (char *) JLI_MemAlloc(tlen);
-        JLI_Snprintf(nargv[i], tlen, "%c%s", arg_expand ? 'T' : 'F', strv[i]);
+        if (JLI_Snprintf(nargv[i], tlen, "%c%s", arg_expand ? 'T' : 'F',
+                         strv[i]) < 0) {
+            return NULL;
+        }
         JLI_TraceLauncher("%s\n", nargv[i]);
     }
 
--- a/jdk/src/windows/classes/sun/awt/windows/WComponentPeer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/windows/classes/sun/awt/windows/WComponentPeer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -488,14 +488,15 @@
                     try {
                         replaceSurfaceData();
                     } catch (InvalidPipeException e) {
-                    // REMIND : what do we do if our surface creation failed?
+                        // REMIND : what do we do if our surface creation failed?
                     }
                 }
             }
         };
+        Component c = (Component)target;
         // Fix 6255371.
-        if (!PaintEventDispatcher.getPaintEventDispatcher().queueSurfaceDataReplacing((Component)target, r)) {
-            postEvent(new InvocationEvent(Toolkit.getDefaultToolkit(), r));
+        if (!PaintEventDispatcher.getPaintEventDispatcher().queueSurfaceDataReplacing(c, r)) {
+            postEvent(new InvocationEvent(c, r));
         }
     }
 
@@ -618,7 +619,7 @@
     }
 
     public void disposeLater() {
-        postEvent(new InvocationEvent(Toolkit.getDefaultToolkit(), new Runnable() {
+        postEvent(new InvocationEvent(target, new Runnable() {
             public void run() {
                 dispose();
             }
--- a/jdk/src/windows/classes/sun/awt/windows/WEmbeddedFrame.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/windows/classes/sun/awt/windows/WEmbeddedFrame.java	Fri Mar 15 23:31:19 2013 -0700
@@ -27,6 +27,7 @@
 
 import sun.awt.*;
 import java.awt.*;
+import java.awt.event.InvocationEvent;
 import java.awt.peer.ComponentPeer;
 import java.awt.image.*;
 import sun.awt.image.ByteInterleavedRaster;
@@ -226,17 +227,19 @@
     }
 
     @SuppressWarnings("deprecation")
-    public void synthesizeWindowActivation(final boolean doActivate) {
-        if (!doActivate || EventQueue.isDispatchThread()) {
-            ((WEmbeddedFramePeer)getPeer()).synthesizeWmActivate(doActivate);
+    public void synthesizeWindowActivation(final boolean activate) {
+        if (!activate || EventQueue.isDispatchThread()) {
+            ((WFramePeer)getPeer()).emulateActivation(activate);
         } else {
             // To avoid focus concurrence b/w IE and EmbeddedFrame
             // activation is postponed by means of posting it to EDT.
-            EventQueue.invokeLater(new Runnable() {
-                    public void run() {
-                        ((WEmbeddedFramePeer)getPeer()).synthesizeWmActivate(true);
-                    }
-                });
+            Runnable r = new Runnable() {
+                public void run() {
+                    ((WFramePeer)getPeer()).emulateActivation(true);
+                }
+            };
+            WToolkit.postEvent(WToolkit.targetToAppContext(this),
+                               new InvocationEvent(this, r));
         }
     }
 
--- a/jdk/src/windows/classes/sun/awt/windows/WEmbeddedFramePeer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/windows/classes/sun/awt/windows/WEmbeddedFramePeer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -65,8 +65,6 @@
 
     public native Rectangle getBoundsPrivate();
 
-    public native void synthesizeWmActivate(boolean doActivate);
-
     @Override
     public boolean isAccelCapable() {
         // REMIND: Temp workaround for issues with using HW acceleration
--- a/jdk/src/windows/classes/sun/awt/windows/WFramePeer.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/windows/classes/sun/awt/windows/WFramePeer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -200,4 +200,11 @@
     public Rectangle getBoundsPrivate() {
         return getBounds();
     }
+
+    // TODO: implement it in peers. WLightweightFramePeer may implement lw version.
+    public void emulateActivation(boolean activate) {
+        synthesizeWmActivate(activate);
+    }
+
+    private native void synthesizeWmActivate(boolean activate);
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/windows/classes/sun/awt/windows/WLightweightFramePeer.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.awt.windows;
+
+import java.awt.Component;
+import java.awt.Graphics;
+import java.awt.event.ComponentEvent;
+import java.awt.event.MouseEvent;
+
+import sun.awt.LightweightFrame;
+
+public class WLightweightFramePeer extends WFramePeer {
+
+    public WLightweightFramePeer(LightweightFrame target) {
+        super(target);
+    }
+
+    private LightweightFrame getLwTarget() {
+        return (LightweightFrame)target;
+    }
+
+    @Override
+    public Graphics getGraphics() {
+        return getLwTarget().getGraphics();
+    }
+
+    @Override
+    public void show() {
+        super.show();
+        postEvent(new ComponentEvent((Component)getTarget(), ComponentEvent.COMPONENT_SHOWN));
+    }
+
+    @Override
+    public void hide() {
+        super.hide();
+        postEvent(new ComponentEvent((Component)getTarget(), ComponentEvent.COMPONENT_HIDDEN));
+    }
+
+    @Override
+    public void reshape(int x, int y, int width, int height) {
+        super.reshape(x, y, width, height);
+        postEvent(new ComponentEvent((Component) getTarget(), ComponentEvent.COMPONENT_MOVED));
+        postEvent(new ComponentEvent((Component) getTarget(), ComponentEvent.COMPONENT_RESIZED));
+    }
+
+    @Override
+    public void handleEvent(java.awt.AWTEvent e) {
+        if (e.getID() == MouseEvent.MOUSE_PRESSED) {
+            emulateActivation(true);
+        }
+        super.handleEvent(e);
+    }
+
+    @Override
+    public void grab() {
+        getLwTarget().grabFocus();
+    }
+
+    @Override
+    public void ungrab() {
+        getLwTarget().ungrabFocus();
+    }
+}
--- a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java	Fri Mar 15 23:31:19 2013 -0700
@@ -37,6 +37,7 @@
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import sun.awt.AWTAutoShutdown;
+import sun.awt.LightweightFrame;
 import sun.awt.SunToolkit;
 import sun.awt.Win32GraphicsDevice;
 import sun.awt.Win32GraphicsEnvironment;
@@ -398,6 +399,12 @@
         return peer;
     }
 
+    public FramePeer createLightweightFrame(LightweightFrame target) {
+        FramePeer peer = new WLightweightFramePeer(target);
+        targetCreatedPeer(target, peer);
+        return peer;
+    }
+
     public CanvasPeer createCanvas(Canvas target) {
         CanvasPeer peer = new WCanvasPeer(target);
         targetCreatedPeer(target, peer);
--- a/jdk/src/windows/native/sun/nio/ch/DatagramChannelImpl.c	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/windows/native/sun/nio/ch/DatagramChannelImpl.c	Fri Mar 15 23:31:19 2013 -0700
@@ -34,8 +34,6 @@
 #include "net_util.h"
 #include <winsock2.h>
 
-static jfieldID isa_addrID;     /* address in java.net.InetSocketAddress */
-static jfieldID isa_portID;     /* port in java.net.InetSocketAddress */
 static jfieldID dci_senderID;   /* sender in sun.nio.ch.DatagramChannelImpl */
 static jfieldID dci_senderAddrID; /* sender InetAddress in sun.nio.ch.DatagramChannelImpl */
 static jfieldID dci_senderPortID; /* sender port in sun.nio.ch.DatagramChannelImpl */
@@ -50,9 +48,6 @@
     isa_class = (*env)->NewGlobalRef(env, clazz);
     isa_ctorID = (*env)->GetMethodID(env, clazz, "<init>",
                                      "(Ljava/net/InetAddress;I)V");
-    isa_addrID = (*env)->GetFieldID(env, clazz, "addr",
-                                    "Ljava/net/InetAddress;");
-    isa_portID = (*env)->GetFieldID(env, clazz, "port", "I");
 
     clazz = (*env)->FindClass(env, "sun/nio/ch/DatagramChannelImpl");
     dci_senderID = (*env)->GetFieldID(env, clazz, "sender",
@@ -214,15 +209,14 @@
 JNIEXPORT jint JNICALL
 Java_sun_nio_ch_DatagramChannelImpl_send0(JNIEnv *env, jobject this,
                                           jboolean preferIPv6, jobject fdo,
-                                          jlong address, jint len, jobject dest)
+                                          jlong address, jint len,
+                                          jobject destAddress, jint destPort)
 {
     jint fd = fdval(env, fdo);
     void *buf = (void *)jlong_to_ptr(address);
     SOCKETADDRESS sa;
     int sa_len;
     jint rv = 0;
-    jobject destAddress = (*env)->GetObjectField(env, dest, isa_addrID);
-    jint destPort = (*env)->GetIntField(env, dest, isa_portID);
 
     if (NET_InetAddressToSockaddr(env, destAddress, destPort,
                                   (struct sockaddr *)&sa,
--- a/jdk/src/windows/native/sun/windows/awt_Frame.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/windows/native/sun/windows/awt_Frame.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -105,6 +105,7 @@
     m_parentWnd = NULL;
     menuBar = NULL;
     m_isEmbedded = FALSE;
+    m_isLightweight = FALSE;
     m_ignoreWmSize = FALSE;
     m_isMenuDropped = FALSE;
     m_isInputMethodWindow = FALSE;
@@ -170,14 +171,13 @@
              * area of the browser is a Java Frame for parenting purposes, but
              * really a Windows child window
              */
+            BOOL isEmbeddedInstance = FALSE;
+            BOOL isEmbedded = FALSE;
             cls = env->FindClass("sun/awt/EmbeddedFrame");
-            if (cls == NULL) {
-                return NULL;
+            if (cls) {
+                isEmbeddedInstance = env->IsInstanceOf(target, cls);
             }
             INT_PTR handle;
-            jboolean isEmbeddedInstance = env->IsInstanceOf(target, cls);
-            jboolean isEmbedded = FALSE;
-
             if (isEmbeddedInstance) {
                 handle = static_cast<INT_PTR>(env->GetLongField(target, AwtFrame::handleID));
                 if (handle != 0) {
@@ -186,6 +186,13 @@
             }
             frame->m_isEmbedded = isEmbedded;
 
+            BOOL isLightweight = FALSE;
+            cls = env->FindClass("sun/awt/LightweightFrame");
+            if (cls) {
+                isLightweight = env->IsInstanceOf(target, cls);
+            }
+            frame->m_isLightweight = isLightweight;
+
             if (isEmbedded) {
                 hwndParent = (HWND)handle;
                 RECT rect;
@@ -230,6 +237,23 @@
                                  rect.bottom-rect.top);
                 frame->InitPeerGraphicsConfig(env, self);
                 AwtToolkit::GetInstance().RegisterEmbedderProcessId(hwndParent);
+            } else if (isLightweight) {
+                frame->m_isUndecorated = true;
+                frame->m_peerObject = env->NewGlobalRef(self);
+                frame->RegisterClass();
+
+                DWORD exStyle = 0;
+                DWORD style = WS_POPUP;
+
+                frame->CreateHWnd(env, L"",
+                                  style,
+                                  exStyle,
+                                  0, 0, 0, 0,
+                                  0,
+                                  NULL,
+                                  ::GetSysColor(COLOR_WINDOWTEXT),
+                                  ::GetSysColor(COLOR_WINDOWFRAME),
+                                  self);
             } else {
                 jint state = env->CallIntMethod(self, AwtFrame::getExtendedStateMID);
                 DWORD exStyle;
@@ -345,16 +369,20 @@
         case WM_SETFOCUS:
             if (sm_inSynthesizeFocus) break; // pass it up the WindowProc chain
 
-            if (!sm_suppressFocusAndActivation && IsEmbeddedFrame()) {
-                AwtSetActiveWindow();
+            if (!sm_suppressFocusAndActivation) {
+                if (IsLightweightFrame() || IsEmbeddedFrame()) {
+                    AwtSetActiveWindow();
+                }
             }
             mr = mrConsume;
             break;
         case WM_KILLFOCUS:
             if (sm_inSynthesizeFocus) break; // pass it up the WindowProc chain
 
-            if (!sm_suppressFocusAndActivation && IsEmbeddedFrame()) {
-                AwtWindow::SynthesizeWmActivate(FALSE, GetHWnd(), NULL);
+            if (!sm_suppressFocusAndActivation) {
+                if (IsLightweightFrame() || IsEmbeddedFrame()) {
+                    AwtWindow::SynthesizeWmActivate(FALSE, GetHWnd(), NULL);
+                }
 
             } else if (sm_restoreFocusAndActivation) {
                 if (AwtComponent::GetFocusedWindow() != NULL) {
@@ -640,6 +668,10 @@
     HWND hwnd = GetHWnd();
     JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 
+    if (IsLightweightFrame()) {
+        return;
+    }
+
     DTRACE_PRINTLN3("AwtFrame::Show:%s%s%s",
                   m_iconic ? " iconic" : "",
                   m_zoomed ? " zoomed" : "",
@@ -992,6 +1024,9 @@
         // b) focus is requested to some of the frame's child.
         m_actualFocusedWindow = NULL;
     }
+    if (IsLightweightFrame()) {
+        return TRUE;
+    }
     return AwtWindow::AwtSetActiveWindow(isMouseEventCause);
 }
 
@@ -1873,7 +1908,7 @@
 }
 
 JNIEXPORT void JNICALL
-Java_sun_awt_windows_WEmbeddedFramePeer_synthesizeWmActivate(JNIEnv *env, jobject self, jboolean doActivate)
+Java_sun_awt_windows_WFramePeer_synthesizeWmActivate(JNIEnv *env, jobject self, jboolean doActivate)
 {
     TRY;
 
--- a/jdk/src/windows/native/sun/windows/awt_Frame.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/windows/native/sun/windows/awt_Frame.h	Fri Mar 15 23:31:19 2013 -0700
@@ -72,6 +72,8 @@
 
     /* Returns whether this frame is embedded in an external native frame. */
     INLINE BOOL IsEmbeddedFrame() { return m_isEmbedded; }
+    /* Returns whether this frame is lightweight. */
+    INLINE virtual BOOL IsLightweightFrame() { return m_isLightweight; }
 
     INLINE BOOL IsSimpleWindow() { return FALSE; }
 
@@ -169,6 +171,9 @@
     /* The frame is an EmbeddedFrame. */
     BOOL m_isEmbedded;
 
+    /* The frame is a LightweightFrame */
+    BOOL m_isLightweight;
+
     /* used so that calls to ::MoveWindow in SetMenuBar don't propogate
        because they are immediately followed by calls to Component.resize */
     BOOL m_ignoreWmSize;
--- a/jdk/src/windows/native/sun/windows/awt_TextComponent.cpp	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/windows/native/sun/windows/awt_TextComponent.cpp	Fri Mar 15 23:31:19 2013 -0700
@@ -53,14 +53,12 @@
  * AwtTextComponent fields
  */
 
-/* java.awt.TextComponent fields */
-jfieldID AwtTextComponent::canAccessClipboardID;
-
-
 /************************************************************************
  * AwtTextComponent methods
  */
 
+jmethodID AwtTextComponent::canAccessClipboardMID;
+
 AwtTextComponent::AwtTextComponent() {
     m_synthetic = FALSE;
     m_lStartPos = -1;
@@ -367,8 +365,7 @@
         }
         jobject target = GetTarget(env);
         jboolean canAccessClipboard =
-            env->GetBooleanField(target,
-                                 AwtTextComponent::canAccessClipboardID);
+            env->CallBooleanMethod (target, AwtTextComponent::canAccessClipboardMID);
         env->DeleteLocalRef(target);
         return (canAccessClipboard) ? mrDoDefault : mrConsume;
     }
@@ -854,12 +851,13 @@
 {
     TRY;
 
-    cls = env->FindClass("java/awt/TextComponent");
-    if (cls != NULL) {
-        AwtTextComponent::canAccessClipboardID =
-            env->GetFieldID(cls, "canAccessClipboard", "Z");
-        DASSERT(AwtTextComponent::canAccessClipboardID != NULL);
-    }
+    jclass textComponentClassID = env->FindClass("java/awt/TextComponent");
+    AwtTextComponent::canAccessClipboardMID =
+        env->GetMethodID(textComponentClassID,
+        "canAccessClipboard", "()Z");
+    env->DeleteLocalRef(textComponentClassID);
+
+    DASSERT(AwtTextComponent::canAccessClipboardMID != NULL);
 
     CATCH_BAD_ALLOC;
 }
--- a/jdk/src/windows/native/sun/windows/awt_TextComponent.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/windows/native/sun/windows/awt_TextComponent.h	Fri Mar 15 23:31:19 2013 -0700
@@ -42,8 +42,7 @@
 
 class AwtTextComponent : public AwtComponent {
 public:
-    /* java.awt.TextComponent canAccessClipboard field ID */
-    static jfieldID canAccessClipboardID;
+    static jmethodID canAccessClipboardMID;
 
     AwtTextComponent();
 
--- a/jdk/src/windows/native/sun/windows/awt_Window.h	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/src/windows/native/sun/windows/awt_Window.h	Fri Mar 15 23:31:19 2013 -0700
@@ -143,6 +143,7 @@
     INLINE HICON GetHIcon() {return m_hIcon;};
     INLINE HICON GetHIconSm() {return m_hIconSm;};
     INLINE BOOL IsIconInherited() {return m_iconInherited;};
+    INLINE virtual BOOL IsLightweightFrame() {return FALSE;}
 
     /* Post events to the EventQueue */
     void SendComponentEvent(jint eventId);
@@ -193,8 +194,10 @@
 
     // Execute on Toolkit only.
     INLINE static LRESULT SynthesizeWmActivate(BOOL doActivate, HWND targetHWnd, HWND oppositeHWnd) {
+        AwtWindow *win = static_cast<AwtWindow*>(AwtComponent::GetComponent(targetHWnd));
         if (doActivate &&
-            (!::IsWindowVisible(targetHWnd) || ::IsIconic(::GetAncestor(targetHWnd, GA_ROOT))))
+            (!::IsWindowVisible(targetHWnd) || ::IsIconic(::GetAncestor(targetHWnd, GA_ROOT))) &&
+            (win == NULL || !win->IsLightweightFrame()))
         {
             // The activation is rejected if either:
             // - The toplevel is not visible
--- a/jdk/test/Makefile	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/test/Makefile	Fri Mar 15 23:31:19 2013 -0700
@@ -513,6 +513,7 @@
           javax/script \
 	  java/sql javax/sql \
           javax/smartcardio \
+	  javax/xml/soap \
 	  javax/xml/ws com/sun/internal/ws \
 	  jdk/asm \
 	  com/sun/org/apache/xerces \
--- a/jdk/test/ProblemList.txt	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/test/ProblemList.txt	Fri Mar 15 23:31:19 2013 -0700
@@ -330,6 +330,23 @@
 # 8007410
 tools/launcher/FXLauncherTest.java                              linux-all
 
+# 8004172
+sun/tools/jstat/jstatGcCapacityOutput1.sh                       generic-all
+sun/tools/jstat/jstatGcCauseOutput1.sh                          generic-all
+sun/tools/jstat/jstatGcOldOutput1.sh                            generic-all
+sun/tools/jstat/jstatGcOutput1.sh                               generic-all
+sun/tools/jstat/jstatGcPermCapacityOutput1.sh                   generic-all
+sun/tools/jstat/jstatLineCounts1.sh                             generic-all
+sun/tools/jstat/jstatLineCounts2.sh                             generic-all
+sun/tools/jstat/jstatLineCounts3.sh                             generic-all
+sun/tools/jstat/jstatLineCounts4.sh                             generic-all
+sun/tools/jstat/jstatOptions1.sh                                generic-all
+sun/tools/jstat/jstatTimeStamp1.sh                              generic-all
+sun/tools/jstatd/jstatdExternalRegistry.sh                      generic-all
+sun/tools/jstatd/jstatdDefaults.sh                              generic-all
+sun/tools/jstatd/jstatdPort.sh                                  generic-all
+sun/tools/jstatd/jstatdServerName.sh                            generic-all
+
 ############################################################################
 
 # jdk_jdi
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/List/MouseDraggedOutCauseScrollingTest/MouseDraggedOutCauseScrollingTest.html	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,43 @@
+<html>
+<!--
+  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 6243382 8006070
+  @summary Dragging of mouse outside of a List and Choice area don't work properly on XAWT
+  @author Dmitry.Cherepanov@SUN.COM area=awt.list
+  @run applet/manual=yesno MouseDraggedOutCauseScrollingTest.html
+  -->
+<head>
+<title> ManualYesNoTest </title>
+</head>
+<body>
+
+<h1>ManualYesNoTest<br>Bug ID: </h1>
+
+<p> See the dialog box (usually in upper left corner) for instructions</p>
+
+<APPLET CODE="MouseDraggedOutCauseScrollingTest.class" WIDTH=200 HEIGHT=200></APPLET>
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/List/MouseDraggedOutCauseScrollingTest/MouseDraggedOutCauseScrollingTest.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,246 @@
+/*
+ * 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 6243382 8006070
+  @summary Dragging of mouse outside of a List and Choice area don't work properly on XAWT
+  @author Dmitry.Cherepanov@SUN.COM area=awt.list
+  @run applet/manual=yesno MouseDraggedOutCauseScrollingTest.html
+*/
+
+import java.applet.Applet;
+import java.awt.*;
+
+public class MouseDraggedOutCauseScrollingTest extends Applet
+{
+    Choice choice;
+    List singleList;
+    List multipleList;
+
+    public void init()
+    {
+        this.setLayout (new GridLayout (1, 3));
+
+        choice = new Choice();
+        singleList = new List(3, false);
+        multipleList = new List(3, true);
+
+        choice.add("Choice");
+        for (int i = 1; i < 100; i++){
+            choice.add(""+i);
+        }
+
+        singleList.add("Single list");
+        for (int i = 1; i < 100; i++)
+            singleList.add(""+i);
+
+        multipleList.add("Multiple list");
+        for (int i = 1; i < 100; i++)
+            multipleList.add(""+i);
+
+        this.add(choice);
+        this.add(singleList);
+        this.add(multipleList);
+
+        String toolkitName = Toolkit.getDefaultToolkit().getClass().getName();
+        if (!toolkitName.equals("sun.awt.X11.XToolkit")) {
+            String[] instructions =
+            {
+                "This test is not applicable to the current platform. Press PASS"
+            };
+            Sysout.createDialogWithInstructions( instructions );
+        } else {
+            String[] instructions =
+            {
+                "0) Please note, that this is only Motif/XAWT test. At first, make the applet active",
+                "1.1) Click on the choice",
+                "1.2) Press the left button of the mouse and keep on any item of the choice, for example 5",
+                "1.3) Drag mouse out of the area of the unfurled list, at the same time hold the X coordinate of the mouse position about the same",
+                "1.4) To make sure, that when the Y coordinate of the mouse position higher of the upper bound of the list then scrolling UP of the list and selected item changes on the upper. If not, the test failed",
+                "1.5) To make sure, that when the Y coordinate of the mouse position under of the lower bound of the list then scrolling DOWN of the list and selected item changes on the lower. If not, the test failed",
+                "-----------------------------------",
+                "2.1) Click on the single list",
+                "2.2) Press the left button of the mouse and keep on any item of the list, for example 5",
+                "2.3) Drag mouse out of the area of the unfurled list, at the same time hold the X coordinate of the mouse position about the same",
+                "2.4) To make sure, that when the Y coordinate of the mouse position higher of the upper bound of the list then scrolling UP of the list and selected item changes on the upper. If not, the test failed",
+                "2.5) To make sure, that when the Y coordinate of the mouse position under of the lower bound of the list then scrolling DOWN of the list and selected item changes on the lower. If not, the test failed",
+                "-----------------------------------",
+                "3.1) Click on the multiple list",
+                "3.2) Press the left button of the mouse and keep on any item of the list, for example 5",
+                "3.3) Drag mouse out of the area of the unfurled list, at the same time hold the X coordinate of the mouse position about the same",
+                "3.4) To make sure, that when the Y coordinate of the mouse position higher of the upper bound of the list then scrolling of the list NO OCCURED and selected item NO CHANGES on the upper. If not, the test failed",
+                "3.5) To make sure, that when the Y coordinate of the mouse position under of the lower bound of the list then scrolling of the list NO OCCURED and selected item NO CHANGES on the lower. If not, the test failed",
+                "4) Test passed."
+            };
+            Sysout.createDialogWithInstructions( instructions );
+        }
+
+    }//End  init()
+
+    public void start ()
+    {
+        setSize (400,100);
+        setVisible(true);
+        validate();
+
+    }// start()
+
+}// class ManualYesNoTest
+
+/****************************************************
+ Standard Test Machinery
+ DO NOT modify anything below -- it's a standard
+  chunk of code whose purpose is to make user
+  interaction uniform, and thereby make it simpler
+  to read and understand someone else's test.
+ ****************************************************/
+
+/**
+ This is part of the standard test machinery.
+ It creates a dialog (with the instructions), and is the interface
+  for sending text messages to the user.
+ To print the instructions, send an array of strings to Sysout.createDialog
+  WithInstructions method.  Put one line of instructions per array entry.
+ To display a message for the tester to see, simply call Sysout.println
+  with the string to be displayed.
+ This mimics System.out.println but works within the test harness as well
+  as standalone.
+ */
+
+class Sysout
+{
+    private static TestDialog dialog;
+
+    public static void createDialogWithInstructions( String[] instructions )
+    {
+        dialog = new TestDialog( new Frame(), "Instructions" );
+        dialog.printInstructions( instructions );
+        dialog.setVisible(true);
+        println( "Any messages for the tester will display here." );
+    }
+
+    public static void createDialog( )
+    {
+        dialog = new TestDialog( new Frame(), "Instructions" );
+        String[] defInstr = { "Instructions will appear here. ", "" } ;
+        dialog.printInstructions( defInstr );
+        dialog.setVisible(true);
+        println( "Any messages for the tester will display here." );
+    }
+
+
+    public static void printInstructions( String[] instructions )
+    {
+        dialog.printInstructions( instructions );
+    }
+
+
+    public static void println( String messageIn )
+    {
+        dialog.displayMessage( messageIn );
+    }
+
+}// Sysout  class
+
+/**
+  This is part of the standard test machinery.  It provides a place for the
+   test instructions to be displayed, and a place for interactive messages
+   to the user to be displayed.
+  To have the test instructions displayed, see Sysout.
+  To have a message to the user be displayed, see Sysout.
+  Do not call anything in this dialog directly.
+  */
+class TestDialog extends Dialog
+{
+
+    TextArea instructionsText;
+    TextArea messageText;
+    int maxStringLength = 80;
+
+    //DO NOT call this directly, go through Sysout
+    public TestDialog( Frame frame, String name )
+    {
+        super( frame, name );
+        int scrollBoth = TextArea.SCROLLBARS_BOTH;
+        instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
+        add( "North", instructionsText );
+
+        messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
+        add("Center", messageText);
+
+        pack();
+
+        setVisible(true);
+    }// TestDialog()
+
+    //DO NOT call this directly, go through Sysout
+    public void printInstructions( String[] instructions )
+    {
+        //Clear out any current instructions
+        instructionsText.setText( "" );
+
+        //Go down array of instruction strings
+
+        String printStr, remainingStr;
+        for( int i=0; i < instructions.length; i++ )
+        {
+            //chop up each into pieces maxSringLength long
+            remainingStr = instructions[ i ];
+            while( remainingStr.length() > 0 )
+            {
+                //if longer than max then chop off first max chars to print
+                if( remainingStr.length() >= maxStringLength )
+                {
+                    //Try to chop on a word boundary
+                    int posOfSpace = remainingStr.
+                        lastIndexOf( ' ', maxStringLength - 1 );
+
+                    if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
+
+                    printStr = remainingStr.substring( 0, posOfSpace + 1 );
+                    remainingStr = remainingStr.substring( posOfSpace + 1 );
+                }
+                //else just print
+                else
+                {
+                    printStr = remainingStr;
+                    remainingStr = "";
+                }
+
+                instructionsText.append( printStr + "\n" );
+
+            }// while
+
+        }// for
+
+    }//printInstructions()
+
+    //DO NOT call this directly, go through Sysout
+    public void displayMessage( String messageIn )
+    {
+        messageText.append( messageIn + "\n" );
+        System.out.println(messageIn);
+    }
+
+}// TestDialog  class
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Modal/ModalDialogMultiscreenTest/ModalDialogMultiscreenTest.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,441 @@
+/*
+ * 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 6430802 8008379
+  @summary WM should not hang after show()/close()
+  @author anthony.petrov@sun.com: area=awt.modal
+  @run main/manual ModalDialogMultiscreenTest
+*/
+
+
+/**
+ * ModalDialogMultiscreenTest.java
+ *
+ * summary: Tests whether a WM will hang on show()/close() a modal dialog in multiscreen mode
+ */
+
+import java.awt.*;
+import java.awt.event.*;
+import javax.swing.*;
+
+
+public class ModalDialogMultiscreenTest
+{
+
+    private static class ButtonActionListener implements ActionListener {
+        JFrame frame;
+        JDialog dialog;
+        public ButtonActionListener(JFrame frame, JDialog dialog) {
+            this.frame = frame;
+            this.dialog = dialog;
+        }
+        public void actionPerformed(ActionEvent e) {
+            dialog.setLocationRelativeTo(frame);
+            dialog.setVisible(true);
+        }
+    }
+    public static class TestDialog extends JDialog {
+        public TestDialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc) {
+            super(owner, title, modal, gc);
+            setSize(200, 100);
+            JButton button = new JButton("Close");
+            button.addActionListener(new ActionListener() {
+                public void actionPerformed(ActionEvent e) {
+                    dispose();
+                }
+            });
+            getContentPane().add(button);
+        }
+    }
+
+    private static void init()
+    {
+        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+        GraphicsDevice[] gs = ge.getScreenDevices();
+
+        Sysout.createDialog( );
+
+        if (gs.length < 2) {
+            System.out.println("Not multi-head environment, test not valid!");
+            ModalDialogMultiscreenTest.pass( );
+        }
+
+        String[] instructions =
+        {
+            "The test should be run on a multi-head X (non-xinerama) systems.",
+            "Otherwise click the Pass button right now.",
+            "You will see an open Frame on each screen your system has.",
+            "The frame has an 'Open dialog' button.",
+            "Clicking the button opens a modal dialog with a Close button.",
+            "The test procedure:",
+            "1. Open a dialog and close it with appropriate buttons.",
+            "2. Switch to another screen ($ DISPLAY=X.Y xprop)",
+            "3. Repeat steps 1-2 several times (about 3*<number-of-screens>)",
+            "If the test doesn't cause the window manager to hang, it's passed."
+        };
+        Sysout.printInstructions( instructions );
+
+
+        for (int i = 0; i < gs.length; i++) {
+            JFrame frame = new JFrame("Frame "+i,gs[i].getDefaultConfiguration());
+            JButton button = new JButton("Open Dialog");
+            button.setMinimumSize(new Dimension(200, 100));
+            button.setPreferredSize(new Dimension(200, 100));
+            button.setSize(new Dimension(200, 100));
+            button.addActionListener(new ButtonActionListener(frame, new TestDialog(frame, "Dialog #"+i, true, gs[i].getDefaultConfiguration())));
+            frame.getContentPane().add(button);
+            frame.pack();
+            frame.setVisible(true);
+        }
+
+    }//End  init()
+
+
+    //ap203012: NO MORE CHANGES BELOW THIS LINE
+
+
+
+    /*****************************************************
+     * Standard Test Machinery Section
+     * DO NOT modify anything in this section -- it's a
+     * standard chunk of code which has all of the
+     * synchronisation necessary for the test harness.
+     * By keeping it the same in all tests, it is easier
+     * to read and understand someone else's test, as
+     * well as insuring that all tests behave correctly
+     * with the test harness.
+     * There is a section following this for test-defined
+     * classes
+     ******************************************************/
+    private static boolean theTestPassed = false;
+    private static boolean testGeneratedInterrupt = false;
+    private static String failureMessage = "";
+
+    private static Thread mainThread = null;
+
+    private static int sleepTime = 300000;
+
+    public static void main( String args[] ) throws InterruptedException
+    {
+        mainThread = Thread.currentThread();
+        try
+        {
+            init();
+        }
+        catch( TestPassedException e )
+        {
+            //The test passed, so just return from main and harness will
+            // interepret this return as a pass
+            return;
+        }
+        //At this point, neither test passed nor test failed has been
+        // called -- either would have thrown an exception and ended the
+        // test, so we know we have multiple threads.
+
+        //Test involves other threads, so sleep and wait for them to
+        // called pass() or fail()
+        try
+        {
+            Thread.sleep( sleepTime );
+            //Timed out, so fail the test
+            throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" );
+        }
+        catch (InterruptedException e)
+        {
+            if( ! testGeneratedInterrupt ) throw e;
+
+            //reset flag in case hit this code more than once for some reason (just safety)
+            testGeneratedInterrupt = false;
+            if ( theTestPassed == false )
+            {
+                throw new RuntimeException( failureMessage );
+            }
+        }
+
+    }//main
+
+    public static synchronized void setTimeoutTo( int seconds )
+    {
+        sleepTime = seconds * 1000;
+    }
+
+    public static synchronized void pass()
+    {
+        Sysout.println( "The test passed." );
+        Sysout.println( "The test is over, hit  Ctl-C to stop Java VM" );
+        //first check if this is executing in main thread
+        if ( mainThread == Thread.currentThread() )
+        {
+            //Still in the main thread, so set the flag just for kicks,
+            // and throw a test passed exception which will be caught
+            // and end the test.
+            theTestPassed = true;
+            throw new TestPassedException();
+        }
+        //pass was called from a different thread, so set the flag and interrupt
+        // the main thead.
+        theTestPassed = true;
+        testGeneratedInterrupt = true;
+        mainThread.interrupt();
+    }//pass()
+
+    public static synchronized void fail()
+    {
+        //test writer didn't specify why test failed, so give generic
+        fail( "it just plain failed! :-)" );
+    }
+
+    public static synchronized void fail( String whyFailed )
+    {
+        Sysout.println( "The test failed: " + whyFailed );
+        Sysout.println( "The test is over, hit  Ctl-C to stop Java VM" );
+        //check if this called from main thread
+        if ( mainThread == Thread.currentThread() )
+        {
+            //If main thread, fail now 'cause not sleeping
+            throw new RuntimeException( whyFailed );
+        }
+        theTestPassed = false;
+        testGeneratedInterrupt = true;
+        failureMessage = whyFailed;
+        mainThread.interrupt();
+    }//fail()
+
+}// class ModalDialogMultiscreenTest
+
+//This exception is used to exit from any level of call nesting
+// when it's determined that the test has passed, and immediately
+// end the test.
+class TestPassedException extends RuntimeException
+{
+}
+
+//*********** End Standard Test Machinery Section **********
+
+
+//************ Begin classes defined for the test ****************
+
+// make listeners in a class defined here, and instantiate them in init()
+
+/* Example of a class which may be written as part of a test
+class NewClass implements anInterface
+ {
+   static int newVar = 0;
+
+   public void eventDispatched(AWTEvent e)
+    {
+      //Counting events to see if we get enough
+      eventCount++;
+
+      if( eventCount == 20 )
+       {
+         //got enough events, so pass
+
+         ModalDialogMultiscreenTest.pass();
+       }
+      else if( tries == 20 )
+       {
+         //tried too many times without getting enough events so fail
+
+         ModalDialogMultiscreenTest.fail();
+       }
+
+    }// eventDispatched()
+
+ }// NewClass class
+
+*/
+
+
+//************** End classes defined for the test *******************
+
+
+
+
+/****************************************************
+ Standard Test Machinery
+ DO NOT modify anything below -- it's a standard
+  chunk of code whose purpose is to make user
+  interaction uniform, and thereby make it simpler
+  to read and understand someone else's test.
+ ****************************************************/
+
+/**
+ This is part of the standard test machinery.
+ It creates a dialog (with the instructions), and is the interface
+  for sending text messages to the user.
+ To print the instructions, send an array of strings to Sysout.createDialog
+  WithInstructions method.  Put one line of instructions per array entry.
+ To display a message for the tester to see, simply call Sysout.println
+  with the string to be displayed.
+ This mimics System.out.println but works within the test harness as well
+  as standalone.
+ */
+
+class Sysout
+{
+    private static TestDialog dialog;
+
+    public static void createDialogWithInstructions( String[] instructions )
+    {
+        dialog = new TestDialog( new Frame(), "Instructions" );
+        dialog.printInstructions( instructions );
+        dialog.setVisible(true);
+        println( "Any messages for the tester will display here." );
+    }
+
+    public static void createDialog( )
+    {
+        dialog = new TestDialog( new Frame(), "Instructions" );
+        String[] defInstr = { "Instructions will appear here. ", "" } ;
+        dialog.printInstructions( defInstr );
+        dialog.setVisible(true);
+        println( "Any messages for the tester will display here." );
+    }
+
+
+    public static void printInstructions( String[] instructions )
+    {
+        dialog.printInstructions( instructions );
+    }
+
+
+    public static void println( String messageIn )
+    {
+        dialog.displayMessage( messageIn );
+    }
+
+}// Sysout  class
+
+/**
+  This is part of the standard test machinery.  It provides a place for the
+   test instructions to be displayed, and a place for interactive messages
+   to the user to be displayed.
+  To have the test instructions displayed, see Sysout.
+  To have a message to the user be displayed, see Sysout.
+  Do not call anything in this dialog directly.
+  */
+class TestDialog extends Dialog implements ActionListener
+{
+
+    TextArea instructionsText;
+    TextArea messageText;
+    int maxStringLength = 80;
+    Panel  buttonP = new Panel();
+    Button passB = new Button( "pass" );
+    Button failB = new Button( "fail" );
+
+    //DO NOT call this directly, go through Sysout
+    public TestDialog( Frame frame, String name )
+    {
+        super( frame, name );
+        int scrollBoth = TextArea.SCROLLBARS_BOTH;
+        instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
+        add( "North", instructionsText );
+
+        messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
+        add("Center", messageText);
+
+        passB = new Button( "pass" );
+        passB.setActionCommand( "pass" );
+        passB.addActionListener( this );
+        buttonP.add( "East", passB );
+
+        failB = new Button( "fail" );
+        failB.setActionCommand( "fail" );
+        failB.addActionListener( this );
+        buttonP.add( "West", failB );
+
+        add( "South", buttonP );
+        pack();
+
+        setVisible(true);
+    }// TestDialog()
+
+    //DO NOT call this directly, go through Sysout
+    public void printInstructions( String[] instructions )
+    {
+        //Clear out any current instructions
+        instructionsText.setText( "" );
+
+        //Go down array of instruction strings
+
+        String printStr, remainingStr;
+        for( int i=0; i < instructions.length; i++ )
+        {
+            //chop up each into pieces maxSringLength long
+            remainingStr = instructions[ i ];
+            while( remainingStr.length() > 0 )
+            {
+                //if longer than max then chop off first max chars to print
+                if( remainingStr.length() >= maxStringLength )
+                {
+                    //Try to chop on a word boundary
+                    int posOfSpace = remainingStr.
+                        lastIndexOf( ' ', maxStringLength - 1 );
+
+                    if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
+
+                    printStr = remainingStr.substring( 0, posOfSpace + 1 );
+                    remainingStr = remainingStr.substring( posOfSpace + 1 );
+                }
+                //else just print
+                else
+                {
+                    printStr = remainingStr;
+                    remainingStr = "";
+                }
+
+                instructionsText.append( printStr + "\n" );
+
+            }// while
+
+        }// for
+
+    }//printInstructions()
+
+    //DO NOT call this directly, go through Sysout
+    public void displayMessage( String messageIn )
+    {
+        messageText.append( messageIn + "\n" );
+        System.out.println(messageIn);
+    }
+
+    //catch presses of the passed and failed buttons.
+    //simply call the standard pass() or fail() static methods of
+    //ModalDialogMultiscreenTest
+    public void actionPerformed( ActionEvent e )
+    {
+        if( e.getActionCommand() == "pass" )
+        {
+            ModalDialogMultiscreenTest.pass();
+        }
+        else
+        {
+            ModalDialogMultiscreenTest.fail();
+        }
+    }
+
+}// TestDialog  class
--- a/jdk/test/java/awt/Modal/WsDisabledStyle/Winkey/Winkey.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/test/java/awt/Modal/WsDisabledStyle/Winkey/Winkey.java	Fri Mar 15 23:31:19 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2008, 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
@@ -22,8 +22,8 @@
  */
 
 /*
-  @test %I% %E%
-  @bug 6572263 6571808
+  @test
+  @bug 6572263 6571808 8005920
   @summary  PIT:FileDialog minimized to taskbar(through 'Show Desktop')selecting the fileDialog using windowList
   @author dmitry.cherepanov: area=awt.modal
   @run main/manual Winkey
@@ -48,12 +48,14 @@
 
         String[] instructions =
         {
+            " 0. This test is for MS Windows only, if you use other OS, press \"pass\" button.",
             " 1. there is a frame with a 'show modal' button, ",
             " 2. press the button to show a modal dialog, ",
             " 3. the modal dialog will be shown over the frame, ",
             " 4. please verify that all (5.1, 5.2.1, 5.2.2) the following tests pass: ",
             " ",
             " 5.1. press combination Windows Key and M key to minimize all windows, ",
+            "      note that the modal dialog and modal blocked windows are NOT minimized",
             " 5.2. press combination Windows Key and D key to show desktop, ",
             "      5.2.1. restore the dialog by choosing this one in the ALT-TAB list, ",
             "      5.2.2. restore the dialog by mouse click on taskbar (on java or any other item)",
--- a/jdk/test/java/beans/Introspector/Test7192955.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/test/java/beans/Introspector/Test7192955.java	Fri Mar 15 23:31:19 2013 -0700
@@ -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,17 +23,20 @@
 
 /*
  * @test
- * @bug 7192955
+ * @bug 7192955 8000183
  * @summary Tests that all properties are bound
  * @author Sergey Malenkov
  */
 
+import java.beans.IntrospectionException;
+import java.beans.Introspector;
 import java.beans.PropertyChangeListener;
+import java.beans.PropertyDescriptor;
 import java.util.List;
 
 public class Test7192955 {
 
-    public static void main(String[] args) {
+    public static void main(String[] args) throws IntrospectionException {
         if (!BeanUtils.findPropertyDescriptor(MyBean.class, "test").isBound()) {
             throw new Error("a simple property is not bound");
         }
@@ -43,6 +46,12 @@
         if (!BeanUtils.findPropertyDescriptor(MyBean.class, "readOnly").isBound()) {
             throw new Error("a read-only property is not bound");
         }
+        PropertyDescriptor[] pds = Introspector.getBeanInfo(MyBean.class, BaseBean.class).getPropertyDescriptors();
+        for (PropertyDescriptor pd : pds) {
+            if (pd.getName().equals("test") && pd.isBound()) {
+                throw new Error("a simple property is bound without superclass");
+            }
+        }
     }
 
     public static class BaseBean {
--- a/jdk/test/java/nio/channels/DatagramChannel/SendToUnresolved.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/test/java/nio/channels/DatagramChannel/SendToUnresolved.java	Fri Mar 15 23:31:19 2013 -0700
@@ -42,7 +42,7 @@
         try {
             dc.send(bb, sa);
             throw new RuntimeException("Expected exception not thrown");
-        } catch (IOException e) {
+        } catch (IOException | UnresolvedAddressException e) {
             // Correct result
         }
         dc.close();
--- a/jdk/test/java/rmi/server/RMIClassLoader/loadProxyClasses/security.policy	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/test/java/rmi/server/RMIClassLoader/loadProxyClasses/security.policy	Fri Mar 15 23:31:19 2013 -0700
@@ -13,6 +13,7 @@
     permission java.io.FilePermission ".${/}-", "read,write,delete";
 
     permission java.lang.RuntimePermission "createClassLoader";
+    permission java.lang.RuntimePermission "getClassLoader";
     permission java.lang.RuntimePermission "setContextClassLoader";
 
     // used by TestLibrary to determine test environment
--- a/jdk/test/java/rmi/testlibrary/JavaVM.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/test/java/rmi/testlibrary/JavaVM.java	Fri Mar 15 23:31:19 2013 -0700
@@ -110,6 +110,14 @@
         return TestLibrary.getExtraProperty("jcov.options","");
     }
 
+    public void start(Runnable runnable) throws IOException {
+        if (runnable == null) {
+            throw new NullPointerException("Runnable cannot be null.");
+        }
+
+        start();
+        new JavaVMCallbackHandler(runnable).start();
+    }
 
     /**
      * Exec the VM as specified in this object's constructor.
@@ -183,4 +191,35 @@
         start();
         return waitFor();
     }
+
+    /**
+     * Handles calling the callback.
+     */
+    private class JavaVMCallbackHandler extends Thread {
+        Runnable runnable;
+
+        JavaVMCallbackHandler(Runnable runnable) {
+            this.runnable = runnable;
+        }
+
+
+        /**
+         * Wait for the Process to terminate and notify the callback.
+         */
+        @Override
+        public void run() {
+            if (vm != null) {
+                try {
+                    vm.waitFor();
+                } catch(InterruptedException ie) {
+                    // Restore the interrupted status
+                    Thread.currentThread().interrupt();
+                }
+            }
+
+            if (runnable != null) {
+                runnable.run();
+            }
+        }
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/logging/CustomLogManager.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.*;
+import java.util.*;
+import java.util.logging.*;
+
+/*
+ * Custom LogManager implementation to verify that the implementation delegates
+ * to the LogManager subclass to register both system logger and user logger.
+ *
+ * The LogManager implementation is the one configuring the logger's property
+ * such as level, handler, etc.
+ */
+public class CustomLogManager extends LogManager {
+    static LogManager INSTANCE;
+    Map<String,Logger> namedLoggers = new HashMap<>();
+    Properties props = initConfig();
+    public CustomLogManager() {
+        if (INSTANCE != null) {
+            throw new RuntimeException("CustomLogManager already created");
+        }
+        INSTANCE = this;
+    }
+
+    public synchronized boolean addLogger(Logger logger) {
+        String name = logger.getName();
+        if (namedLoggers.containsKey(name)) {
+            return false;
+        }
+        namedLoggers.put(name, logger);
+        // set level
+        if (props.get(name + ".level") != null) {
+            logger.setLevel(Level.parse(props.getProperty(name + ".level")));
+        }
+        // add handlers
+        if (props.get(name + ".handlers") != null && logger.getHandlers().length == 0) {
+            logger.addHandler(new CustomHandler());
+        }
+        // add parent loggers
+        int ix = 1;
+        for (;;) {
+            int ix2 = name.indexOf(".", ix);
+            if (ix2 < 0) {
+                break;
+            }
+            String pname = name.substring(0, ix2);
+            if (props.get(pname + ".level") != null ||
+                props.get(pname + ".handlers") != null) {
+                // This pname has a level/handlers definition.
+                // Make sure it exists.
+                //
+                // The test doesn't set the parent for simplicity.
+                if (!namedLoggers.containsKey(pname)) {
+                    Logger.getLogger(pname);
+                }
+            }
+            ix = ix2 + 1;
+        }
+        return true;
+    }
+
+    public synchronized Logger getLogger(String name) {
+        return namedLoggers.get(name);
+    }
+
+    public synchronized Enumeration<String> getLoggerNames() {
+        return Collections.enumeration(namedLoggers.keySet());
+    }
+
+    public String getProperty(String name) {
+        return props.getProperty(name);
+    }
+
+    public void readConfiguration() {
+        // do nothing
+    }
+
+    public void readConfiguration(InputStream ins) {
+        // do nothing
+    }
+
+    private Properties initConfig() {
+        Properties props = new Properties();
+        props.put(".level", "CONFIG");
+        props.put("CustomLogManagerTest.level", "WARNING");
+        props.put("CustomLogManagerTest.handlers", "CustomLogManager$CustomHandler");
+        props.put("SimpleLogManager.level", "INFO");
+        props.put("SimpleLogManager.handlers", "CustomLogManager$CustomHandler");
+        props.put("CustomLogManager$CustomHandler.level", "WARNING");
+        props.put(".handlers", "CustomLogManager$CustomHandler");
+        props.put("org.foo.bar.level", "SEVERE");
+        props.put("org.foo.handlers", "CustomLogManager$CustomHandler");
+        props.put("org.openjdk.level", "SEVERE");
+        props.put("org.openjdk.handlers", "CustomLogManager$CustomHandler");
+        props.put("org.openjdk.core.level", "INFO");
+
+        return props;
+    }
+
+    public static void checkLogger(String name) {
+        checkLogger(name, null);
+    }
+
+    public static void checkLogger(String name, String resourceBundleName) {
+        Logger logger = INSTANCE.getLogger(name);
+        if (logger == null) {
+            throw new RuntimeException("Logger \"" + name + "\" not exist");
+        }
+        System.out.format("Logger \"%s\" level=%s handlers=%s resourcebundle=%s%n",
+            name, logger.getLevel(),
+            Arrays.toString(logger.getHandlers()),
+            logger.getResourceBundleName());
+        String rb = logger.getResourceBundleName();
+        if (rb != resourceBundleName && (rb == null || rb.equals(resourceBundleName))) {
+            throw new RuntimeException("Logger \"" + name +
+                "\" unexpected resource bundle: " + rb);
+        }
+
+        String value = INSTANCE.getProperty(name + ".level");
+        String level = logger.getLevel() != null ? logger.getLevel().getName() : null;
+        if (level != value && (level == null || level.equals(value))) {
+            throw new RuntimeException("Logger \"" + name + "\" unexpected level: " + level);
+        }
+
+        Handler[] handlers = logger.getHandlers();
+        String hdl = INSTANCE.getProperty(name + ".handlers");
+        if ((hdl == null && handlers.length != 0) ||
+            (hdl != null && handlers.length != 1)) {
+            throw new RuntimeException("Logger \"" + name + "\" unexpected handler: " +
+                Arrays.toString(handlers));
+        }
+        checkParents(name);
+    }
+
+    private static void checkParents(String name) {
+        int ix = 1;
+        for (;;) {
+            int ix2 = name.indexOf(".", ix);
+            if (ix2 < 0) {
+                break;
+            }
+            String pname = name.substring(0, ix2);
+            if (INSTANCE.getProperty(pname + ".level") != null ||
+                INSTANCE.getProperty(pname + ".handlers") != null) {
+                // This pname has a level/handlers definition.
+                // Make sure it exists.
+                checkLogger(pname);
+            }
+            ix = ix2 + 1;
+        }
+    }
+
+    // only CustomLogManager can create an instance of CustomHandler
+    private class CustomHandler extends StreamHandler {
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/logging/CustomLogManagerTest.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.*;
+import java.util.*;
+
+import java.util.logging.*;
+import sun.util.logging.PlatformLogger;
+
+/*
+ * @test
+ * @bug 8005615
+ * @summary Add loggers to custom log manager
+ *
+ * @compile -XDignore.symbol.file CustomLogManagerTest.java CustomLogManager.java
+ * @run main/othervm -Djava.util.logging.manager=CustomLogManager CustomLogManagerTest
+ */
+public class CustomLogManagerTest {
+    private static final String RESOURCE_BUNDLE = "sun.util.logging.resources.logging";
+    public static void main(String[] args) {
+        String mgr = System.getProperty("java.util.logging.manager");
+        if (!mgr.equals("CustomLogManager")) {
+            throw new RuntimeException("java.util.logging.manager not set");
+        }
+
+        Logger.getLogger(CustomLogManagerTest.class.getName());
+        Logger.getLogger("org.foo.Foo");
+        Logger.getLogger("org.foo.bar.Foo", RESOURCE_BUNDLE);
+        // platform logger will be set with the default system resource bundle
+        PlatformLogger.getLogger("org.openjdk.core.logger");
+
+        if (LogManager.getLogManager() != CustomLogManager.INSTANCE) {
+             throw new RuntimeException(LogManager.getLogManager() + " not CustomLogManager");
+        }
+
+        CustomLogManager.checkLogger(CustomLogManagerTest.class.getName());
+        CustomLogManager.checkLogger("org.foo.Foo");
+        CustomLogManager.checkLogger("org.foo.bar.Foo", RESOURCE_BUNDLE);
+        CustomLogManager.checkLogger(Logger.GLOBAL_LOGGER_NAME);
+        CustomLogManager.checkLogger("");
+        CustomLogManager.checkLogger("org.openjdk.core.logger", RESOURCE_BUNDLE);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/logging/SimpleLogManager.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.util.*;
+import java.util.logging.*;
+import sun.util.logging.PlatformLogger;
+
+/*
+ * @test
+ * @bug 8005615
+ * @summary A LogManager subclass overrides its own implementation of named
+ *          logger (see the subclassing information in the Logger class specification)
+ *
+ * @compile -XDignore.symbol.file CustomLogManager.java SimpleLogManager.java
+ * @run main/othervm -Djava.util.logging.manager=SimpleLogManager SimpleLogManager
+ */
+public class SimpleLogManager extends CustomLogManager {
+    public static void main(String[] args) {
+        String classname = System.getProperty("java.util.logging.manager");
+        if (!classname.equals("SimpleLogManager")) {
+            throw new RuntimeException("java.util.logging.manager not set");
+        }
+
+        Logger logger = Logger.getLogger(SimpleLogManager.class.getName());
+        Logger.getLogger("org.foo.bar.Foo");
+
+        // a platform logger used by the system code is just a Logger instance.
+        PlatformLogger.getLogger("org.openjdk.core.logger");
+
+        LogManager mgr = LogManager.getLogManager();
+        if (mgr != CustomLogManager.INSTANCE || !(mgr instanceof SimpleLogManager)) {
+             throw new RuntimeException(LogManager.getLogManager() + " not SimpleLogManager");
+        }
+
+        checkCustomLogger(SimpleLogManager.class.getName(), null);
+        checkCustomLogger("org.foo.bar.Foo", null);
+        checkCustomLogger("org.openjdk.core.logger", "sun.util.logging.resources.logging");
+
+        // ## The LogManager.demandLogger method does not handle custom log manager
+        // ## that overrides the getLogger method to return a custom logger
+        // ## (see the test case in 8005640).  Logger.getLogger may return
+        // ## a Logger instance but LogManager overrides it with a custom Logger
+        // ## instance like this case.
+        //
+        // However, the specification of LogManager and Logger subclassing is
+        // not clear whether this is supported or not.  The following check
+        // just captures the current behavior.
+        if (logger instanceof CustomLogger) {
+            throw new RuntimeException(logger + " not CustomLogger");
+        }
+    }
+
+    private static void checkCustomLogger(String name, String resourceBundleName) {
+        CustomLogManager.checkLogger(name, resourceBundleName);
+        Logger logger1 = Logger.getLogger(name);
+        Logger logger2 = LogManager.getLogManager().getLogger(name);
+        if (logger1 != logger2) {
+            throw new RuntimeException(logger1 + " != " + logger2);
+        }
+        if (!(logger1 instanceof CustomLogger)) {
+            throw new RuntimeException(logger1 + " not CustomLogger");
+        }
+    }
+
+    /*
+     * This SimpleLogManager overrides the addLogger method to replace
+     * the given logger with a custom logger.
+     *
+     * It's unclear what the recommended way to use custom logger is.
+     * A LogManager subclass might override the getLogger method to return
+     * a custom Logger and create a new custom logger if not exist so that
+     * Logger.getLogger() can return a custom Logger instance but that violates
+     * the LogManager.getLogger() spec which should return null if not found.
+     */
+    public synchronized boolean addLogger(Logger logger) {
+        String name = logger.getName();
+        if (namedLoggers.containsKey(name)) {
+            return false;
+        }
+        CustomLogger newLogger = new CustomLogger(logger);
+        super.addLogger(newLogger);
+        return true;
+    }
+
+    public class CustomLogger extends Logger {
+        CustomLogger(Logger logger) {
+            super(logger.getName(), logger.getResourceBundleName());
+        }
+        CustomLogger(String name) {
+            super(name, null);
+        }
+    }
+}
--- a/jdk/test/javax/management/remote/mandatory/subjectDelegation/SubjectDelegation2Test.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/test/javax/management/remote/mandatory/subjectDelegation/SubjectDelegation2Test.java	Fri Mar 15 23:31:19 2013 -0700
@@ -119,9 +119,6 @@
             System.out.println("Create SimpleStandard MBean");
             SimpleStandard s = new SimpleStandard("monitorRole");
             mbs.registerMBean(s, new ObjectName("MBeans:type=SimpleStandard"));
-            // Set Security Manager
-            //
-            System.setSecurityManager(new SecurityManager());
             // Create Properties containing the username/password entries
             //
             Properties props = new Properties();
@@ -132,6 +129,9 @@
             HashMap env = new HashMap();
             env.put("jmx.remote.authenticator",
                     new JMXPluggableAuthenticator(props));
+            // Set Security Manager
+            //
+            System.setSecurityManager(new SecurityManager());
             // Create an RMI connector server
             //
             System.out.println("Create an RMI connector server");
--- a/jdk/test/javax/management/remote/mandatory/subjectDelegation/SubjectDelegation3Test.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/test/javax/management/remote/mandatory/subjectDelegation/SubjectDelegation3Test.java	Fri Mar 15 23:31:19 2013 -0700
@@ -120,9 +120,6 @@
             System.out.println("Create SimpleStandard MBean");
             SimpleStandard s = new SimpleStandard("delegate");
             mbs.registerMBean(s, new ObjectName("MBeans:type=SimpleStandard"));
-            // Set Security Manager
-            //
-            System.setSecurityManager(new SecurityManager());
             // Create Properties containing the username/password entries
             //
             Properties props = new Properties();
@@ -133,6 +130,9 @@
             HashMap env = new HashMap();
             env.put("jmx.remote.authenticator",
                     new JMXPluggableAuthenticator(props));
+            // Set Security Manager
+            //
+            System.setSecurityManager(new SecurityManager());
             // Create an RMI connector server
             //
             System.out.println("Create an RMI connector server");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/swing/text/html/7189299/bug7189299.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * Portions Copyright (c) 2013 IBM Corporation
+ */
+import java.awt.BorderLayout;
+import java.awt.Toolkit;
+
+import java.awt.event.ActionListener;
+import javax.swing.DefaultButtonModel;
+import javax.swing.JEditorPane;
+import javax.swing.JFrame;
+import javax.swing.SwingUtilities;
+import javax.swing.text.StyleConstants;
+import javax.swing.text.StyleContext;
+import javax.swing.text.html.HTMLEditorKit;
+import sun.awt.SunToolkit;
+
+
+/*
+ * @test
+ * @bug 8008289
+ * @summary Shared ButtonModel instance should deregister previous listeners.
+ * @author Frank Ding
+ */
+public class bug7189299 {
+
+    private static JEditorPane html;
+    private static JFrame frame;
+
+    private static void setup() {
+        /**
+         * Note the input type is not restricted to "submit". Types "image",
+         * "checkbox", "radio" have the same problem.
+         */
+        html = new JEditorPane("text/html",
+                "<html><body><form action=\"http://localhost.cgi\">"
+                        + "<input type=submit name=submit value=\"submit\"/>"
+                        + "</form></body></html>");
+        frame = new JFrame();
+        frame.setLayout(new BorderLayout());
+        frame.add(html, BorderLayout.CENTER);
+        frame.setSize(200, 100);
+        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+        frame.setVisible(true);
+    }
+
+    private static void doTest() {
+        /*
+         * Calling updateComponentTreeUI creates a new FormView instance with
+         * its own associated JButton instance. The same DefaultButtonModel
+         * instance is used for both FormView's.
+         *
+         * The action listeners associated with (the JButton for) the first
+         * FormView should be unregistered from this common DefaultButtonModel,
+         * such that only those for the new FormView remain.
+         */
+        SwingUtilities.updateComponentTreeUI(html);
+    }
+
+    private static void verifySingleDefaultButtonModelListener() {
+        HTMLEditorKit htmlEditorKit = (HTMLEditorKit) html.getEditorKit();
+        StyleContext.NamedStyle style = ((StyleContext.NamedStyle) htmlEditorKit
+                .getInputAttributes());
+        DefaultButtonModel model = ((DefaultButtonModel) style
+                .getAttribute(StyleConstants.ModelAttribute));
+        ActionListener[] listeners = model.getActionListeners();
+        int actionListenerNum = listeners.length;
+        if (actionListenerNum != 1) {
+            throw new RuntimeException(
+                    "Expected single ActionListener object registered with "
+                    + "DefaultButtonModel; found " + actionListenerNum
+                    + " listeners registered.");
+        }
+
+        int changeListenerNum = model.getChangeListeners().length;
+        if (changeListenerNum != 1) {
+            throw new RuntimeException(
+                    "Expected at most one ChangeListener object registered "
+                    + "with DefaultButtonModel; found " + changeListenerNum
+                    + " listeners registered.");
+        }
+        int itemListenerNum = model.getItemListeners().length;
+        if (itemListenerNum != 1) {
+            throw new RuntimeException(
+                    "Expected at most one ItemListener object registered "
+                    + "with DefaultButtonModel; found " + itemListenerNum
+                    + " listeners registered.");
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        final SunToolkit toolkit = ((SunToolkit) Toolkit.getDefaultToolkit());
+
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                setup();
+            }
+        });
+        toolkit.realSync();
+        SwingUtilities.invokeAndWait(new Runnable() {
+
+            @Override
+            public void run() {
+                try {
+                    verifySingleDefaultButtonModelListener();
+                    doTest();
+                    verifySingleDefaultButtonModelListener();
+                } finally {
+                    frame.dispose();
+                }
+            }
+        });
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/awt/datatransfer/SuplementaryCharactersTransferTest.java	Fri Mar 15 23:31:19 2013 -0700
@@ -0,0 +1,165 @@
+/*
+ * 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 6877495
+   @summary JTextField and JTextArea does not support supplementary characters
+   @author Alexander Scherbatiy
+   @run main SuplementaryCharactersTransferTest
+*/
+
+
+import java.io.*;
+import java.util.*;
+import java.awt.*;
+import java.awt.datatransfer.*;
+import sun.awt.datatransfer.*;
+import sun.awt.datatransfer.DataTransferer.ReencodingInputStream;
+
+public class SuplementaryCharactersTransferTest {
+
+    public static final long TEXT_FORMAT = 13;
+
+    public static void main(String[] args) throws Exception {
+
+        DataTransferer dataTransferer = new TestDataTransferer();
+        dataTransferer.registerTextFlavorProperties("UNICODE TEXT", "utf-16le", "\r\n", "2");
+        ByteTransferable transferable = new ByteTransferable();
+        ReencodingInputStream is = dataTransferer.new ReencodingInputStream(transferable.getByteInputStream(), TEXT_FORMAT,
+                DataTransferer.getTextCharset(transferable.getDataFlavor()), transferable);
+
+        byte[] bytes = transferable.getBytes();
+        byte[] result = new byte[bytes.length];
+
+        is.read(result);
+
+        for (int i = 0; i < bytes.length; i++) {
+            if (bytes[i] != result[i]) {
+                throw new RuntimeException("Characters are not equal!");
+            }
+        }
+
+    }
+
+    static class ByteTransferable implements Transferable, ClipboardOwner {
+
+        private final DataFlavor dataFlavor;
+
+        public ByteTransferable() throws Exception {
+            dataFlavor = DataFlavor.getTextPlainUnicodeFlavor();
+        }
+
+        public DataFlavor getDataFlavor() {
+            return dataFlavor;
+        }
+
+        public DataFlavor[] getTransferDataFlavors() {
+            return new DataFlavor[]{dataFlavor};
+        }
+
+        public boolean isDataFlavorSupported(DataFlavor flavor) {
+            return flavor.equals(dataFlavor);
+        }
+
+        public byte[] getBytes() {
+            return new byte[]{97, 0, 64, -40, 32, -36, 98, 0};
+        }
+
+        public InputStream getByteInputStream() {
+            return new ByteArrayInputStream(getBytes());
+        }
+
+        public Object getTransferData(DataFlavor flavor)
+                throws UnsupportedFlavorException, IOException {
+            if (flavor.equals(dataFlavor)) {
+                return getByteInputStream();
+            } else {
+                throw new UnsupportedFlavorException(flavor);
+            }
+        }
+
+        public void lostOwnership(Clipboard clipboard, Transferable contents) {
+        }
+    }
+
+    static class TestDataTransferer extends DataTransferer {
+
+        @Override
+        public String getDefaultUnicodeEncoding() {
+            throw new UnsupportedOperationException("Not supported yet.");
+        }
+
+        @Override
+        public boolean isLocaleDependentTextFormat(long format) {
+            return false;
+        }
+
+        @Override
+        public boolean isFileFormat(long format) {
+            throw new UnsupportedOperationException("Not supported yet.");
+        }
+
+        @Override
+        public boolean isImageFormat(long format) {
+            throw new UnsupportedOperationException("Not supported yet.");
+        }
+
+        @Override
+        protected Long getFormatForNativeAsLong(String str) {
+            return TEXT_FORMAT;
+        }
+
+        @Override
+        protected String getNativeForFormat(long format) {
+            throw new UnsupportedOperationException("Not supported yet.");
+        }
+
+        @Override
+        protected ByteArrayOutputStream convertFileListToBytes(
+                ArrayList<String> fileList) throws IOException {
+            throw new UnsupportedOperationException("Not supported yet.");
+        }
+
+        @Override
+        protected String[] dragQueryFile(byte[] bytes) {
+            throw new UnsupportedOperationException("Not supported yet.");
+        }
+
+        @Override
+        protected Image platformImageBytesOrStreamToImage(InputStream str,
+                byte[] bytes, long format) throws IOException {
+            throw new UnsupportedOperationException("Not supported yet.");
+        }
+
+        @Override
+        protected byte[] imageToPlatformBytes(Image image, long format)
+                throws IOException {
+            throw new UnsupportedOperationException("Not supported yet.");
+        }
+
+        @Override
+        public ToolkitThreadBlockedHandler getToolkitThreadBlockedHandler() {
+            throw new UnsupportedOperationException("Not supported yet.");
+        }
+    }
+}
\ No newline at end of file
--- a/jdk/test/sun/security/mscapi/ShortRSAKeyWithinTLS.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/test/sun/security/mscapi/ShortRSAKeyWithinTLS.java	Fri Mar 15 23:31:19 2013 -0700
@@ -29,7 +29,7 @@
 import javax.net.ssl.*;
 import java.lang.reflect.*;
 
-import sun.security.util.KeyLength;
+import sun.security.util.KeyUtil;
 
 public class ShortRSAKeyWithinTLS {
 
@@ -175,13 +175,13 @@
             privateKey = (PrivateKey)ks.getKey(keyAlias, null);
             publicKey = (PublicKey)ks.getCertificate(keyAlias).getPublicKey();
 
-            int privateKeySize = KeyLength.getKeySize(privateKey);
+            int privateKeySize = KeyUtil.getKeySize(privateKey);
             if (privateKeySize != keySize) {
                 throw new Exception("Expected key size is " + keySize +
                         ", but the private key size is " + privateKeySize);
             }
 
-            int publicKeySize = KeyLength.getKeySize(publicKey);
+            int publicKeySize = KeyUtil.getKeySize(publicKey);
             if (publicKeySize != keySize) {
                 throw new Exception("Expected key size is " + keySize +
                         ", but the public key size is " + publicKeySize);
--- a/jdk/test/tools/launcher/ToolsOpts.java	Fri Mar 15 19:30:28 2013 +0530
+++ b/jdk/test/tools/launcher/ToolsOpts.java	Fri Mar 15 23:31:19 2013 -0700
@@ -23,6 +23,7 @@
 
 /*
  * @test
+ * @bug 8002091
  * @summary Test options patterns for javac,javah,javap and javadoc using
  * javac as a test launcher. Create a dummy javac and intercept options to check
  * reception of options as passed through the launcher without having to launch
--- a/langtools/.hgtags	Fri Mar 15 19:30:28 2013 +0530
+++ b/langtools/.hgtags	Fri Mar 15 23:31:19 2013 -0700
@@ -201,3 +201,4 @@
 89c66415168925dffe492356ff893ff248bb5603 jdk8-b77
 af8417e590f4e76e0dfed09e71239fb102ef0d43 jdk8-b78
 56dfafbb9e1ad7548a4415316dc003296fb498cb jdk8-b79
+a8227c61768499dac847ea718af6719027c949f2 jdk8-b80